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
0b3524994502a7a53b5fbfe955aa745e6ad3299e
Add documentation to js utilities
corehq/apps/export/static/export/js/utils.js
corehq/apps/export/static/export/js/utils.js
hqDefine('export/js/utils.js', function () { var getTagCSSClass = function(tag) { var constants = hqImport('export/js/const.js'); var cls = 'label'; if (tag === constants.TAG_DELETED) { return cls + ' label-warning'; } else { return cls + ' label-default'; } }; var redirect = function(url) { window.location.href = url; }; var animateToEl = function(toElementSelector, callback) { $('html, body').animate({ scrollTop: $(toElementSelector).offset().top + 'px', }, 'slow', undefined, callback); }; var readablePath = function(pathNodes) { return _.map(pathNodes, function(pathNode) { return pathNode.name(); }).join('.') }; var customPathToNodes = function(customPathString) { var models = hqImport('export/js/models.js'); var parts = customPathString.split('.'); return _.map(parts, function(part) { return new models.PathNode({ name: part, is_repeat: false, doc_type: 'PathNode', }); }); }; return { getTagCSSClass: getTagCSSClass, redirect: redirect, animateToEl: animateToEl, readablePath: readablePath, customPathToNodes: customPathToNodes, }; });
JavaScript
0
@@ -625,166 +625,821 @@ -var readablePath = function(pathNodes) %7B%0A return _.map(pathNodes, function(pathNode) %7B%0A return pathNode.name();%0A %7D).join('.')%0A %7D;%0A +/**%0A * readablePath%0A *%0A * Takes an array of PathNodes and converts them to a string dot path.%0A *%0A * @param %7BArray%7D pathNodes - An array of PathNodes to be converted to a string%0A * dot path.%0A * @returns %7Bstring%7D A string dot path that represents the array of PathNodes%0A */%0A var readablePath = function(pathNodes) %7B%0A return _.map(pathNodes, function(pathNode) %7B%0A return pathNode.name();%0A %7D).join('.')%0A %7D;%0A%0A /**%0A * customPathToNodes%0A *%0A * This function takes a string path like form.meta.question and%0A * returns the equivalent path in an array of PathNodes.%0A *%0A * @param %7Bstring%7D customPathString - A string dot path to be converted%0A * to PathNodes.%0A * @returns %7BArray%7D Returns an array of PathNodes.%0A */ %0A
b90d886e4128252b01779dc753251c7db79de320
simplify scale factor logic
src/components/containers/zoom-helpers.js
src/components/containers/zoom-helpers.js
import { Selection, Collection } from "victory-core"; import { throttle, isFunction } from "lodash"; const Helpers = { /** * Generates a new domain scaled by factor and constrained by the original domain. * @param {[Number, Number]} currentDomain The domain to be scaled. * @param {[Number, Number]} originalDomain The original domain for the data set. * @param {Number} factor The delta to translate by * @return {[Number, Number]} The scale domain */ scale(currentDomain, originalDomain, factor) { const [fromBound, toBound] = originalDomain; const [from, to] = currentDomain; const range = Math.abs(from - to); const midpoint = +from + (range / 2); const newRange = (range * Math.abs(factor)) / 2; const minDomain = Collection.containsDates(originalDomain) ? [ new Date(midpoint - 4), new Date(midpoint) ] : // 4ms is standard browser date precision [ midpoint - 1 / Number.MAX_SAFE_INTEGER, midpoint ]; const newDomain = [ Collection.getMaxValue([midpoint - newRange, fromBound]), Collection.getMinValue([midpoint + newRange, toBound]) ]; return Math.abs(minDomain[1] - minDomain[0]) > Math.abs(newDomain[1] - newDomain[0]) ? minDomain : newDomain; }, /** * Generate a new domain translated by the delta and constrained by the original domain. * @param {[Number, Number]} currentDomain The domain to be translated. * @param {[Number, Number]} originalDomain The original domain for the data set. * @param {Number} delta The delta to translate by * @return {[Number, Number]} The translated domain */ pan(currentDomain, originalDomain, delta) { const [fromCurrent, toCurrent] = currentDomain.map((val) => +val); const [fromOriginal, toOriginal] = originalDomain.map((val) => +val); const lowerBound = fromCurrent + delta; const upperBound = toCurrent + delta; let newDomain; if (lowerBound > fromOriginal && upperBound < toOriginal) { newDomain = [lowerBound, upperBound]; } else if (lowerBound < fromOriginal) { // Clamp to lower limit const dx = toCurrent - fromCurrent; newDomain = [fromOriginal, fromOriginal + dx]; } else if (upperBound > toOriginal) { // Clamp to upper limit const dx = toCurrent - fromCurrent; newDomain = [toOriginal - dx, toOriginal]; } else { newDomain = currentDomain; } return Collection.containsDates(currentDomain) || Collection.containsDates(originalDomain) ? newDomain.map((val) => new Date(val)) : newDomain; }, getDomainScale(domain, scale) { const {x: [from, to]} = domain; const rangeX = scale.x.range(); const plottableWidth = Math.abs(rangeX[0] - rangeX[1]); return plottableWidth / (to - from); }, handleAnimation(ctx) { const getTimer = isFunction(ctx.getTimer) && ctx.getTimer.bind(ctx); if (getTimer && isFunction(getTimer().bypassAnimation)) { getTimer().bypassAnimation(); return isFunction(getTimer().resumeAnimation) ? () => getTimer().resumeAnimation() : undefined; } }, onMouseDown(evt, targetProps) { evt.preventDefault(); const originalDomain = targetProps.originalDomain || targetProps.domain; const currentDomain = targetProps.currentDomain || targetProps.zoomDomain || originalDomain; const {x} = Selection.getSVGEventCoordinates(evt); return [{ target: "parent", mutation: () => { return { startX: x, domain: currentDomain, cachedZoomDomain: targetProps.zoomDomain, originalDomain, currentDomain, panning: true, parentControlledProps: ["domain"] }; } }]; }, onMouseUp() { return [{ target: "parent", mutation: () => { return {panning: false}; } }]; }, onMouseLeave() { return [{ target: "parent", mutation: () => { return {panning: false}; } }]; }, onMouseMove(evt, targetProps, eventKey, ctx) { // eslint-disable-line max-params if (targetProps.panning) { const { scale, startX, onDomainChange, domain, zoomDomain } = targetProps; const {x} = Selection.getSVGEventCoordinates(evt); const originalDomain = targetProps.originalDomain || domain; const lastDomain = targetProps.currentDomain || targetProps.zoomDomain || originalDomain; const calculatedDx = (startX - x) / this.getDomainScale(lastDomain, scale); const nextXDomain = this.pan(lastDomain.x, originalDomain.x, calculatedDx); const currentDomain = { x: nextXDomain, y: originalDomain.y }; const resumeAnimation = this.handleAnimation(ctx); if (isFunction(onDomainChange)) { onDomainChange(currentDomain); } return [{ target: "parent", callback: resumeAnimation, mutation: () => { return { parentControlledProps: ["domain"], domain: currentDomain, currentDomain, originalDomain, cachedZoomDomain: zoomDomain }; } }]; } }, onWheel(evt, targetProps, eventKey, ctx) { // eslint-disable-line max-params, max-statements if (!targetProps.allowZoom) { return {}; } const { onDomainChange, domain, zoomDomain } = targetProps; const originalDomain = targetProps.originalDomain || domain; const lastDomain = targetProps.currentDomain || zoomDomain || originalDomain; const {x} = lastDomain; const xBounds = originalDomain.x; const delta = evt.deltaY / 300; // TODO: Check scale factor const maxDelta = delta > 0 ? 0.75 : -0.75; // TODO: Check max scale factor const factor = Math.abs(delta) > 1 ? 1 + maxDelta : 1 + delta; const nextXDomain = this.scale(x, xBounds, factor); const currentDomain = { x: nextXDomain, y: originalDomain.y }; const resumeAnimation = this.handleAnimation(ctx); if (isFunction(onDomainChange)) { onDomainChange(currentDomain); } return [{ target: "parent", callback: resumeAnimation, mutation: () => { return { domain: currentDomain, currentDomain, originalDomain, cachedZoomDomain: zoomDomain, parentControlledProps: ["domain"], panning: false }; } }]; } }; export default { onMouseDown: Helpers.onMouseDown.bind(Helpers), onMouseUp: Helpers.onMouseUp.bind(Helpers), onMouseLeave: Helpers.onMouseLeave.bind(Helpers), onMouseMove: throttle(Helpers.onMouseMove.bind(Helpers), 16, {leading: true}), onWheel: throttle(Helpers.onWheel.bind(Helpers), 16, {leading: true}) };
JavaScript
0.005012
@@ -5191,24 +5191,8 @@ rams -, max-statements %0A @@ -5532,21 +5532,20 @@ const -delta +sign = evt.d @@ -5554,42 +5554,21 @@ taY -/ 300; // TODO: Check scale factor +%3E 0 ? 1 : -1; %0A @@ -5578,43 +5578,58 @@ nst -maxD +d elta = -delta %3E 0 ? 0.75 : - +Math.min(Math.abs(evt.deltaY / 300), 0.75 +) ; // @@ -5645,12 +5645,8 @@ eck -max scal @@ -5658,75 +5658,8 @@ tor%0A - const factor = Math.abs(delta) %3E 1 ? 1 + maxDelta : 1 + delta;%0A @@ -5701,22 +5701,32 @@ Bounds, -factor +1 + sign * delta );%0A c
6d562c9dbbb2e68860c8b0922819af64981d4908
Fix linting issues for 5d6f9e049884e55d84554b5c2523e24af3bab7e0
commands/serverinfo.js
commands/serverinfo.js
"use strict"; const { Command } = require("sosamba"); class ServerCommand extends Command { constructor(...args) { super(...args, { name: "serverinfo", description: "Shows the information about the server." }); } async run(ctx) { const embed = { author: { name: ctx.guild.name }, thumbnail: { url: ctx.guild.iconURL }, fields: [{ name: await ctx.t("MEMBERS"), value: await ctx.t("MEMBER_COUNT", ctx.guild.memberCount), inline: true }, { name: await ctx.t("OWNER"), value: this.sosamba.getTag(ctx.guild.members.get(ctx.guild.ownerID)), inline: true }, { name: await ctx.t("GUILD_VERIFICATION_LEVEL"), value: await this.getGuildVerification(ctx), inline: true }, { name: await ctx.t("REQUIRES_ADMIN_MFA"), value: ctx.guild.mfaLevel === 1 ? await ctx.t("YES") : await ctx.t("NO"), inline: true }, { name: await ctx.t("ROLES"), value: await ctx.t("ROLE_COUNT", ctx.guild.roles.size), inline: true }, { name: await ctx.t("EXPLICIT_FILTERING"), value: await this.getExplicitContent(ctx), inline: true }, { name: await ctx.t("DEFAULT_NOTIFICATIONS"), value: ctx.guild.defaultNotifications === 1 ? await ctx.t("ONLY_MENTIONS") : await ctx.t("ALL_MESSAGES"), inline: true }, { name: "Features", value: await (async () => { let featureStr = ""; if (ctx.guild.features.includes("INVITE_SPLASH")) featureStr += ":cityscape: This server can have an invite splash\n"; if (ctx.guild.features.includes("VIP_REGIONS")) featureStr += ":loud_sound: This server has access to higher-quality voice servers\n"; // Please, someone who has access to vanity URLs, if anything breaks, tell me if (ctx.guild.features.includes("VANITY_URL")) featureStr += `:link: This server can have a ${ctx.guild.vanityURL ? "[" : ""}vanity URL${ctx.guild.vanityURL ? `](https://discord.gg/${ctx.guild.vanityURL})` : ""}\n`; if (ctx.guild.features.includes("VERIFIED")) featureStr += ":white_check_mark: This server is verified\n"; if (ctx.guild.features.includes("PARTNERED")) featureStr += ":star: This server is partnered with Discord\n"; if (ctx.guild.features.includes("COMMERCE")) featureStr += ":moneybag: This server has access to commerce features (store channels, for example)\n"; if (ctx.guild.features.includes("NEWS")) featureStr += ":newspaper: This server can have announcement channels\n"; if (ctx.guild.features.includes("LURKABLE")) featureStr += ":eyes: This server is lurkable\n"; if (ctx.guild.features.includes("DISCOVERABLE")) featureStr += ":mag: This server can be found in the server discovery menu\n"; if (ctx.guild.features.includes("FEATURABLE")) featureStr += ":star2: This server can be featured in the server discovery menu\n"; if (ctx.guild.features.includes("ANIMATED_ICON")) featureStr += ":mountain: This server can have an animated icon\n"; if (ctx.guild.features.includes("BANNER")) featureStr += ":sunrise_over_mountains: This server can have a banner\n"; return featureStr || await ctx.t("NONE"); })() }], description: ` **ID**: ${ctx.guild.id} **${await ctx.t("VOICE_REGION")}**: ${ctx.guild.region} **${await ctx.t("AFK_TIMEOUT")}**: ${await ctx.t("AFK_MINUTES", ctx.guild.afkTimeout)} **Nitro Boosters**: ${ctx.guild.premiumSubscriptionCount} (Level ${ctx.guild.premiumTier})`, image: { url: `https://cdn.discordapp.com/splashes/${ctx.guild.id}/${ctx.guild.splash}.png?size=2048` }, footer: { text: await ctx.t("CREATED_ON") }, timestamp: new Date(ctx.guild.createdAt), color: 0x008800 }; await ctx.send({ embed }); } async getGuildVerification(ctx) { switch (ctx.guild.verificationLevel) { case 0: return await ctx.t("GUILD_VERIFICATION_NONE"); case 1: return await ctx.t("GUILD_VERIFICATION_LOW"); case 2: return await ctx.t("GUILD_VERIFICATION_MEDIUM"); case 3: return "(╯°□°)╯︵ ┻━┻" + await ctx.t("GUILD_VERIFICATION_TABLEFLIP"); case 4: return "┻━┻ ミヽ(ಠ益ಠ)ノ彡┻━┻ " + await ctx.t("GUILD_VERIFICATION_ULTRATABLEFLIP"); } } async getExplicitContent(ctx) { switch (ctx.guild.explicitContentFilter) { case 0: return await ctx.t("EXPLICIT_FILTERING_OFF"); case 1: return await ctx.t("EXPLICIT_FILTERING_NOROLE"); case 2: return await ctx.t("EXPLICIT_FILTERING_ON"); } } } module.exports = ServerCommand;
JavaScript
0.000021
@@ -4925,36 +4925,32 @@ ) %7B%0A - case 0:%0A @@ -4929,36 +4929,32 @@ case 0:%0A - retu @@ -5001,36 +5001,32 @@ );%0A%0A - case 1:%0A @@ -5005,36 +5005,32 @@ case 1:%0A - retu @@ -5076,36 +5076,32 @@ );%0A%0A - case 2:%0A @@ -5080,36 +5080,32 @@ case 2:%0A - retu @@ -5162,20 +5162,16 @@ - case 3:%0A @@ -5166,20 +5166,16 @@ case 3:%0A - @@ -5260,20 +5260,16 @@ - case 4:%0A @@ -5264,20 +5264,16 @@ case 4:%0A - @@ -5463,36 +5463,32 @@ ) %7B%0A - case 0:%0A @@ -5467,36 +5467,32 @@ case 0:%0A - retu @@ -5530,28 +5530,24 @@ ING_OFF%22);%0A%0A - case @@ -5554,36 +5554,32 @@ 1:%0A - return await ctx @@ -5616,36 +5616,32 @@ );%0A%0A - case 2:%0A @@ -5620,36 +5620,32 @@ case 2:%0A - retu
ba8968e7fae1089d5b59328f53d8c80d916f99d4
Add xmlHttpRequest to sen user info to RailsAPI
options.js
options.js
document.addEventListener('DOMContentLoaded', function() { restore_options(); userRailsOauth(); document.getElementById('myonoffswitch').addEventListener('click', save_options); }); function save_options() { var twitterSwitch = document.getElementById("twitterOn").checked; var faceBookSwitch = document.getElementById("facebookOn").checked; var fbFloorSwitch = document.getElementById("facebookCharFloor").checked; var alwaysUrlSwitch = document.getElementById("alwaysAddUrl").checked; chrome.storage.sync.set({ twitterOn: tw, facebookOn: fb, facebookCharFloor: fbFloor, alwaysAddUrl: url }, function() { var status = document.getElementById('status'); status.textContent = 'Options saved!'; setTimeout(function() { status.textContent = ''; }, 750); }); } function restore_options() { chrome.storage.sync.get({ //send key value pairs of user's changed options to update. Make async. }, function(items) { //Luke Kedz wrote this callback. It should act like a switch..case for checked //boxes. document.getElementById("twitterOn").checked = items.twitterOn; document.getElementById("facebookOn").checked = items.facebookOn; document.getElementById("facebookCharFloor").checked = items.facebookCharFloor; document.getElementById("alwaysAddUrl").checked = items.alwaysAddUrl; }); }; function userRailsOauth() { chrome.identity.getProfileUserInfo(function(userInfo) { }); };
JavaScript
0
@@ -1457,16 +1457,317 @@ Info) %7B%0A + var message = JSON.stringify(userInfo);%0A%0A var xml = new XMLHttpRequest();%0A xml.open(%22POST%22, %22http://localhost:3000/api/users%22, true);%0A xml.setRequestHeader(%22Content-Type%22, %22application/x-www-form-urlencoded%22);%0A xml.setRequestHeader(%22Accept%22, %22application/json%22);%0A xml.send(message); %0A %7D);%0A%7D @@ -1760,16 +1760,17 @@ sage);%0A %7D);%0A%7D;%0A +%0A
229a2361882dabf7ef67c171a2259fa3ef9d0610
Remove user creation from passport functionality.
config/passport.js
config/passport.js
var passport = require('passport'); var BasicStrategy = require("passport-http").BasicStrategy; var utils = require("../lib/utils"); var nconf = require('./nconf.js'); var Adapter = require(nconf.get('RIPPLE_DATAMODEL_ADAPTER')); var adapter = new Adapter(); passport.use(new BasicStrategy( function(username, password, done) { if (username == 'admin') { if (password && (password == nconf.get('KEY'))) { return done(null, { admin: true }); } else { return done('Invalid admin key'); } } else { adapter.getUser({ name: username }, function(err, user) { if (err) { return done(err) } if (user) { if (!utils.verifyPassword(password, user.salt, user.password_hash)) { return done(null, false) } return done(null, user); } else { adapter.createUser({ name: username, password: password }, function(err, user) { // if there are no errors, allow addtional logic to be executed return err ? done(err, user) : done(null, user); }); } }) } } )) module.exports = passport;
JavaScript
0
@@ -833,237 +833,41 @@ -adapter.createUser(%7B name: username, password: password %7D, function(err, user) %7B%0A // if there are no errors, allow addtional logic to be executed%0A return err ? done(err, user) : done(null, user);%0A %7D +return done('invalid credentials' );%0A
4e1ea79fe47f7502854ec855cc7aaa98f720d8ea
remove async/await from non test files
lib/bulk.js
lib/bulk.js
const mongodb = require('mongodb'); const maxBulkSize = 1000; const oid = mongodb.ObjectID.createPk; class Bulk { constructor(colName, ordered, connect, opts) { this.colName = colName; this.ordered = ordered; this.connect = connect; opts = opts || { writeConcern: { w: 1 } }; this.writeConcern = opts.writeConcern || { w: 1 }; this.cmds = []; this.cmdKeys = { insert: 'nInserted', delete: 'nRemoved', update: 'nUpserted' } } ensureCommand(cmdName, bulkCollection) { if (this.currentCmd && (!this.currentCmd[cmdName] || this.currentCmd[bulkCollection].length === maxBulkSize)) { this.cmds.push(this.currentCmd); this.currentCmd = null; } if (!this.currentCmd) { this.currentCmd = { [cmdName]: this.colName, [bulkCollection]: [], ordered: this.ordered, writeConcern: this.writeConcern } } return this.currentCmd; } find(q) { let upsert = false; const remove = (limit) => { const cmd = this.ensureCommand('delete', 'deletes'); cmd.deletes.push({ q, limit }); } const update = (u, multi) => { const cmd = this.ensureCommand('update', 'updates'); cmd.updates.push({ q, u, multi, upsert }) } return new FindSyntax({ update, upsert(upsertValue) { upsert = upsertValue }, remove }); } insert(doc) { const cmd = this.ensureCommand('insert', 'documents'); doc._id = doc._id || oid(); cmd.documents.push(doc); } async execute() { this.pushCurrentCmd(); const result = { writeErrors: [ ], writeConcernErrors: [ ], nInserted: 0, nUpserted: 0, nMatched: 0, nModified: 0, nRemoved: 0, upserted: [ ] } const connection = await this.connect(); for (const cmd of this.cmds) { const cmdResult = await connection.command(cmd); const cmdKey = Object.keys(cmd)[0]; result[this.cmdKeys[cmdKey]] += cmdResult.n; } result.ok = 1 return result; } pushCurrentCmd() { if (this.currentCmd) { this.cmds.push(this.currentCmd) } } tojson() { if (this.currentCmd) { this.cmds.push(this.currentCmd); } const obj = { nInsertOps: 0, nUpdateOps: 0, nRemoveOps: 0, nBatches: this.cmds.length } this.cmds.forEach(function (cmd) { if (cmd.update) { obj.nUpdateOps += cmd.updates.length } else if (cmd.insert) { obj.nInsertOps += cmd.documents.length } else if (cmd.delete) { obj.nRemoveOps += cmd.deletes.length } }) return obj } toString () { return JSON.stringify(this.tojson()) } } class FindSyntax { constructor(cmds) { this.cmds = cmds; } upsert() { this.cmds.upsert(true); return this; } remove() { this.cmds.remove(0); } removeOne() { this.cmds.remove(1); } update(updObj) { this.cmds.update(updObj, true); } updateOne(updObj) { this.cmds.update(updObj, false); } replaceOne(updObj) { this.updateOne(updObj); } } module.exports = Bulk;
JavaScript
0
@@ -1547,14 +1547,8 @@ %0A%0A -async exec @@ -1554,18 +1554,16 @@ cute() %7B - %0A thi @@ -1616,33 +1616,32 @@ writeErrors: %5B - %5D,%0A writeCo @@ -1654,17 +1654,16 @@ rrors: %5B - %5D,%0A @@ -1776,17 +1776,16 @@ d: %5B - %5D%0A %7D%0A %0A @@ -1776,26 +1776,24 @@ d: %5B%5D%0A %7D%0A - %0A const c @@ -1795,90 +1795,25 @@ nst -connection = await this.connect();%0A%0A for (const cmd of this.cmds) %7B%0A const +setResult = (cmd, cmd @@ -1822,42 +1822,14 @@ sult +) = - await connection.command(cmd);%0A +%3E %7B %0A @@ -1921,24 +1921,201 @@ t.n;%0A %7D%0A%0A + return this%0A .connect()%0A .then(connection =%3E each(this.cmds, cmd =%3E connection.command(cmd).then(cmdResult =%3E setResult(cmd, cmdResult))))%0A .then(() =%3E %7B%0A result.o @@ -2119,18 +2119,23 @@ t.ok = 1 +; %0A%0A + retu @@ -2145,16 +2145,26 @@ result;%0A + %7D);%0A %7D%0A%0A p @@ -3235,16 +3235,297 @@ %0A %7D%0A%7D%0A%0A +// TODO: This implementation is a bit whacky recursive implementation. PR anyone?%0Afunction each(cmds, executeCmd, idx) %7B%0A idx = idx %7C%7C 0;%0A%0A if (idx %3C cmds.length) %7B%0A return executeCmd(cmds%5Bidx%5D).then(() =%3E each(cmds, executeCmd, idx + 1));%0A %7D%0A%0A return Promise.resolve();%0A%7D%0A%0A module.e
93d2b691bdeaa54fe744e85655a1bae91c511cb8
Convert fetchMessage to messages.fetch
src/util/pageControls.js
src/util/pageControls.js
const log = require('./logger.js') class PageContainer { constructor () { this.messageList = {} } async nextPage (message) { if (this.messageList[message.id].currentPage + 1 > this.messageList[message.id].pages.length - 1) return this.messageList[message.id].currentPage++ const pageMsg = this.messageList[message.id] try { const m = await message.channel.fetchMessage(message.id) await m.edit({ embed: pageMsg.pages[pageMsg.currentPage] }) } catch (err) { log.command.warning('pageControls nextPage', err, message.channel) } } async prevPage (message) { if (this.messageList[message.id].currentPage - 1 < 0) return this.messageList[message.id].currentPage-- const pageMsg = this.messageList[message.id] try { const m = await message.channel.fetchMessage(message.id) await m.edit({ embed: pageMsg.pages[pageMsg.currentPage] }) } catch (err) { log.command.warning('pageControls prevpage', err, message.channel) } } } const pageMsgs = new PageContainer() exports.add = (msgId, pages) => { pageMsgs.messageList[msgId] = { currentPage: 0, pages: pages } } exports.nextPage = message => pageMsgs.nextPage(message) exports.prevPage = message => pageMsgs.prevPage(message) exports.has = id => pageMsgs.messageList[id]
JavaScript
0.999999
@@ -97,24 +97,87 @@ t = %7B%7D%0A %7D%0A%0A + /**%0A * @param %7Bimport('discord.js').Message%7D message%0A */%0A async next @@ -185,32 +185,32 @@ age (message) %7B%0A - if (this.mes @@ -443,36 +443,38 @@ age.channel. -fetchMessage +messages.fetch (message.id) @@ -644,16 +644,79 @@ %7D%0A %7D%0A%0A + /**%0A * @param %7Bimport('discord.js').Message%7D message%0A */%0A async @@ -950,20 +950,22 @@ nel. -fetchMessage +messages.fetch (mes
dbc04f487d03e8742da37725a032341f422b665e
break out the text function and add some more text
demo/demo.js
demo/demo.js
window.onload = function() { // Create a new Animator that is attached to the page's canvas element var animator = CandidCanvas.createAnimator(document.getElementById('canvas')); animator.addScenes(Scene1.get(), Scene2.get()); animator.loop(); addEventHandlers(animator); }; function addEventHandlers(anim) { document.getElementById("play").addEventListener('click', function() { anim.play(); }); document.getElementById("pause").addEventListener('click', function() { anim.pause(); }); document.getElementById("loop").addEventListener('click', function() { anim.loop(); }); document.getElementById("stop").addEventListener('click', function() { anim.reset(); }); } var Scene1 = { get: function() { // Create a new scene that will last 10 seconds var scene = CandidCanvas.createScene({ duration: 3000 }); // Add an element that draws the background for each tick scene.addElement(General.getDrawBackground("#080808")); // Add an element that draws a rotating circle scene.addElement(Scene1.getCircleDraw(180, 540, 50, "#D2EC4C")); // Add an element that draws another rotating circle scene.addElement(Scene1.getCircleDraw(0, 360, 40, "#4CCDED")); // Finally, one more circle, but rotate it faster scene.addElement(Scene1.getCircleDraw(90, 810, 30, "#F39B3E")); return scene; }, // This function builds a function that will be used as a scene element // that draws circle. The scene element will behave differently, depending // on the params that are passed to function that builds the element. // // See the usage above for different parameters being passed in to build // slightly different scene elements. getCircleDraw: function (startAngle, endAngle, circleRadius, color) { var totalAngleChange = endAngle - startAngle; var rotationRadius = 150; return function(anim) { var ctx = anim.context(); var scene = anim.currentScene(); var rotationAmt = (totalAngleChange / scene.duration()) * scene.timeElapsed(); var currentAngle = startAngle + rotationAmt; var point = Scene1.getCoordsFromAngle(rotationRadius, currentAngle); ctx.fillStyle = color; ctx.beginPath(); ctx.arc(200 + point.x, 200 + point.y, circleRadius, 0, Math.PI * 2, true); ctx.fill(); }; }, getCoordsFromAngle: function (radius, angle) { var angleInRads = angle * (Math.PI / 180); return { x: radius * Math.cos(angleInRads), y: radius * Math.sin(angleInRads) }; } }; var Scene2 = { get: function() { var scene = CandidCanvas.createScene({duration: 2000}); scene.addElements(General.getDrawBackground("#95E681"), Scene2.drawText, Scene2.drawStatus); return scene; }, // A function to draw some text to the screen drawText: function(anim) { var ctx = anim.context(); ctx.restore(); ctx.save(); ctx.fillStyle = "#FFF"; ctx.font = "60px Helvetica"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText("SCENE 2", 200, 200); ctx.restore(); ctx.save(); }, drawStatus: function(anim) { var startX = 0; var endX = 400; var y = 350; var changeX = endX - startX; var scene = anim.currentScene(); var ctx = anim.context(); ctx.restore(); ctx.save(); ctx.strokeStyle = "#515F4D"; ctx.lineWidth = 5; ctx.beginPath(); ctx.moveTo(startX, y); var xPos = (changeX / scene.duration()) * scene.timeElapsed(); ctx.lineTo(xPos, y); ctx.stroke(); ctx.restore(); ctx.save(); } }; var General = { // This function builds a function that will be used to draw the background // for an animation. getDrawBackground: function(color) { return function(anim) { var ctx = anim.context(); ctx.restore(); ctx.save(); ctx.fillStyle = color; ctx.fillRect(0, 0, 400, 400); ctx.restore(); ctx.save(); }; } };
JavaScript
0.000001
@@ -998,24 +998,135 @@ 080808%22));%0A%0A + // Add an element that draws some text in the middle of the screen%0A scene.addElement(Scene1.drawText);%0A%0A // Add a @@ -1156,32 +1156,32 @@ rotating circle%0A - scene.addEle @@ -2671,24 +2671,112 @@ eInRads) %7D;%0A + %7D,%0A%0A drawText: function(anim) %7B%0A General.drawText(anim.context(), %22Scene 1%22, 20);%0A %7D%0A%7D;%0A%0Avar @@ -3036,371 +3036,8 @@ %7D,%0A%0A - // A function to draw some text to the screen%0A drawText: function(anim) %7B%0A var ctx = anim.context();%0A ctx.restore();%0A ctx.save();%0A%0A ctx.fillStyle = %22#FFF%22;%0A ctx.font = %2260px Helvetica%22;%0A ctx.textAlign = %22center%22;%0A ctx.textBaseline = %22middle%22;%0A%0A ctx.fillText(%22SCENE 2%22, 200, 200);%0A%0A ctx.restore();%0A ctx.save();%0A %7D,%0A%0A dr @@ -3511,16 +3511,104 @@ save();%0A + %7D,%0A%0A drawText: function(anim) %7B%0A General.drawText(anim.context(), %22SCENE 2%22, 60);%0A %7D%0A%7D;%0A%0A @@ -3968,22 +3968,360 @@ save();%0A - %7D;%0A + %7D,%0A%0A // draw some text to the screen%0A drawText: function(ctx, text, fontSize) %7B%0A ctx.restore();%0A ctx.save();%0A%0A ctx.fillStyle = %22#FFF%22;%0A ctx.font = fontSize + %22px Helvetica%22;%0A ctx.textAlign = %22center%22;%0A ctx.textBaseline = %22middle%22;%0A%0A ctx.fillText(text, 200, 200);%0A%0A ctx.restore();%0A ctx.save();%0A %7D%0A%7D;%0A
54b545bf36d00606996a62ae0dfa0bda2995f0db
add logging
fbm/routes/fbm.js
fbm/routes/fbm.js
var express = require('express'); var conf = require('configure'); var parser = require('body-parser'); var router = express.Router(); router.use(parser.json()); router.route('/') .get(function (req, res) { if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === conf.fb.verify_token) { console.log(conf.fbm.desc + ' - Validating webhook'); res.status(200).send(req.query['hub.challenge']); } else { console.error(conf.fbm.desc + ' - Failed validation. Make sure the validation tokens match.'); res.sendStatus(403); } }) .post(function (req, res) { var data = req.body; console.log('Req:' + req.body); // Make sure this is a page subscription if (data.object === 'page') { // Iterate over each entry - there may be multiple if batched data.entry.forEach(function(entry) { console.log('Entry:' + entry); var pageID = entry.id; var timeOfEvent = entry.time; // Iterate over each messaging event entry.messaging.forEach(function(event) { if (event.message) { receivedMessage(event); } else { console.log(conf.fbm.desc + ' - Webhook received unknown event: ', event); } }); }); // Assume all went well. // // You must send back a 200, within 20 seconds, to let us know // you've successfully received the callback. Otherwise, the request // will time out and we will keep trying to resend. res.sendStatus(200); } }); module.exports = router; function receivedMessage(event) { // Putting a stub for now, we'll expand it in the following steps console.log(conf.fbm.desc + ' - Message data: ', event.message); }
JavaScript
0.000001
@@ -721,19 +721,39 @@ g('Req:' - + +);%0A console.log( req.body @@ -1004,19 +1004,47 @@ 'Entry:' - + +);%0A console.log( entry);%0A
96a152c1d496e6b25720d9dfe805d8b823800025
Remove scene causes no error anymore
src/components/fixture-list-item/index.js
src/components/fixture-list-item/index.js
import { LitElement, html } from 'lit-element' import { links } from '../../styles/links.js' /* * A fixture list item */ class FixtureListItem extends LitElement { static get properties() { return { fixture: { type: Object } } } render() { const { fixture } = this return html` ${links} <div> <a href="/fixture/${fixture.id}">${fixture.name}</a> </div> ` } } customElements.define('fixture-list-item', FixtureListItem)
JavaScript
0.000001
@@ -277,16 +277,76 @@ = this%0A%0A + if (fixture === undefined) %7B%0A return html%60%60%0A %7D%0A%0A retu
0f8217e25ae0bb4aba6733600f742181a63615a5
Fix linting issues for 08775e56d21ae043e0a8e8ea9a4993a15fb173d0
commands/serverinfo.js
commands/serverinfo.js
"use strict"; const { Command } = require("sosamba"); class ServerCommand extends Command { constructor(...args) { super(...args, { name: "serverinfo", description: "Shows the information about the server." }); } async run(ctx) { const embed = { author: { name: ctx.guild.name }, thumbnail: { url: ctx.guild.iconURL }, fields: [{ name: await ctx.t("MEMBERS"), value: await ctx.t("MEMBER_COUNT", ctx.guild.memberCount), inline: true }, { name: await ctx.t("OWNER"), value: this.sosamba.getTag(ctx.guild.members.get(ctx.guild.ownerID)), inline: true }, { name: await ctx.t("GUILD_VERIFICATION_LEVEL"), value: await this.getGuildVerification(ctx), inline: true }, { name: await ctx.t("REQUIRES_ADMIN_MFA"), value: ctx.guild.mfaLevel == 1 ? await ctx.t("YES") : await ctx.t("NO"), inline: true }, { name: await ctx.t("ROLES"), value: await ctx.t("ROLE_COUNT", ctx.guild.roles.size), inline: true }, { name: await ctx.t("EXPLICIT_FILTERING"), value: await this.getExplicitContent(ctx), inline: true }, { name: await ctx.t("DEFAULT_NOTIFICATIONS"), value: ctx.guild.defaultNotifications == 1 ? await ctx.t("ONLY_MENTIONS") : await ctx.t("ALL_MESSAGES"), inline: true }, { name: "Features", value: await (async () => { let featureStr = ""; if (ctx.guild.features.includes("INVITE_SPLASH")) featureStr += ":cityscape: This server can have an invite splash\n" if (ctx.guild.features.includes("VIP_REGIONS")) featureStr += ":loud_sound: This server has access to higher-quality voice servers\n"; if (ctx.guild.features.includes("VANITY_URL")) featureStr += ":link: This server can have a vanity URL\n"; if (ctx.guild.features.includes("VERIFIED")) featureStr += ":white_check_mark: This server is verified\n"; if (ctx.guild.features.includes("PARTNERED")) featureStr += ":star: This server is partnered with Discord\n"; if (ctx.guild.features.includes("COMMERCE")) featureStr += ":moneybag: This server has access to commerce features (store channels, for example)\n"; if (ctx.guild.features.includes("NEWS")) featureStr += ":newspaper: This server can have announcement channels\n"; if (ctx.guild.features.includes("LURKABLE")) featureStr += ":eyes: This server is lurkable\n"; if (ctx.guild.features.includes("DISCOVERABLE")) featureStr += ":mag: This server can be found in the server discovery menu\n"; if (ctx.guild.features.includes("FEATURABLE")) featureStr += ":star2: This server can be featured in the server discovery menu\n"; if (ctx.guild.features.includes("ANIMATED_ICON")) featureStr += ":mountain: This server can have an animated icon\n"; if (ctx.guild.features.includes("BANNER")) featureStr += ":sunrise_over_mountains: This server can have a banner\n"; return featureStr || await ctx.t("NONE") })() }], description: ` **ID**: ${ctx.guild.id} **${await ctx.t("VOICE_REGION")}**: ${ctx.guild.region} **${await ctx.t("AFK_TIMEOUT")}**: ${await ctx.t("AFK_MINUTES", ctx.guild.afkTimeout)}`, image: { url: `https://cdn.discordapp.com/splashes/${ctx.guild.id}/${ctx.guild.splash}.png?size=2048` }, footer: { text: await ctx.t("CREATED_ON") }, timestamp: new Date(ctx.guild.createdAt), color: 0x008800 }; await ctx.send({embed}); } async getGuildVerification(ctx) { switch (ctx.guild.verificationLevel) { case 0: return await ctx.t("GUILD_VERIFICATION_NONE"); case 1: return await ctx.t("GUILD_VERIFICATION_LOW"); case 2: return await ctx.t("GUILD_VERIFICATION_MEDIUM"); case 3: return "(╯°□°)╯︵ ┻━┻" + await ctx.t("GUILD_VERIFICATION_TABLEFLIP"); case 4: return "┻━┻ ミヽ(ಠ益ಠ)ノ彡┻━┻ " + await ctx.t("GUILD_VERIFICATION_ULTRATABLEFLIP"); } } async getExplicitContent(ctx) { switch (ctx.guild.explicitContentFilter) { case 0: return await ctx.t("EXPLICIT_FILTERING_OFF"); case 1: return await ctx.t("EXPLICIT_FILTERING_NOROLE"); case 2: return await ctx.t("EXPLICIT_FILTERING_ON"); } } } module.exports = ServerCommand;
JavaScript
0.000004
@@ -2053,16 +2053,17 @@ plash%5Cn%22 +; %0A @@ -3647,16 +3647,17 @@ (%22NONE%22) +; %0A
51eae1b75843e7c9e0ecdbc68357abdf433d7293
Change to jquery function callback
demo/demo.js
demo/demo.js
(function() { 'use strict'; var $window = $(window); function resizeLists() { var $categories = $('#categories'), $styles = $('#styles'); $categories.css('max-height', $window.height() / 4); $categories.perfectScrollbar('update'); $styles.height($window.height() - $styles.position().top - 20); $styles.perfectScrollbar('update'); } function selectCategory(category) { $('#languages div').each(function(i, div) { var $div = $(div); if ($div.hasClass(category)) { var code = $div.find('code'); if (!code.hasClass('hljs')) { hljs.highlightBlock(code.get(0)); } $div.show(); } else { $div.hide(); } }); $(document).scrollTop(0); } function categoryKey(c) { return c === 'common' ? '' : c === 'misc' ? 'z' : c === 'all' ? 'zz' : c; } function initCategories() { var categories = {}, $categoryContainer = $('#categories'); $('#languages div').each(function(i, div) { if (!div.className) { div.className += 'misc'; } div.className += ' all'; div.className.split(' ').forEach(function(c) { categories[c] = (categories[c] || 0) + 1; }); }); var category_names = Object.keys(categories); category_names.sort(function(a, b) { a = categoryKey(a); b = categoryKey(b); return a < b ? -1 : a > b ? 1 : 0; }); category_names.forEach(function(c) { $categoryContainer.append('<li data-category="' + c + '">' + c + ' (' + categories[c] +')</li>'); }); $('#categories li').click(function(e) { $('#categories li').removeClass('current'); $(this).addClass('current'); selectCategory($(this).data('category')); }); $('#categories li:first-child').click(); $categoryContainer.perfectScrollbar(); } function selectStyle(style) { $('link[title]').each(function(i, link) { link.disabled = (link.title != style); }); } function initStyles() { var $styleContainer = $('#styles'); $('link[title]').each(function(i, link) { $styleContainer.append('<li>' + link.title + '</li>'); }); $('#styles li').click(function(e) { $('#styles li').removeClass('current'); $(this).addClass('current'); selectStyle($(this).text()); }); $('#styles li:first-child').click(); $styleContainer.perfectScrollbar(); } $(document).ready(function() { initCategories(); initStyles(); $window.resize(resizeLists); resizeLists(); }); }).call(this);
JavaScript
0
@@ -2446,24 +2446,8 @@ $( -document).ready( func
fa336b7a99d1ae7564985dd05d47e21e92f32f9a
Bring hide stickers icon to front when menu open.
src/components/views/rooms/Stickerpack.js
src/components/views/rooms/Stickerpack.js
/* Copyright 2015, 2016 OpenMarket Ltd Copyright 2017 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import { _t } from '../../../languageHandler'; import Widgets from '../../../utils/widgets'; import AppTile from '../elements/AppTile'; import ContextualMenu from '../../structures/ContextualMenu'; import MatrixClientPeg from '../../../MatrixClientPeg'; import Modal from '../../../Modal'; import sdk from '../../../index'; import SdkConfig from '../../../SdkConfig'; import ScalarAuthClient from '../../../ScalarAuthClient'; export default class Stickerpack extends React.Component { constructor(props) { super(props); this.onShowStickersClick = this.onShowStickersClick.bind(this); this.onHideStickersClick = this.onHideStickersClick.bind(this); this.onFinished = this.onFinished.bind(this); this._launchManageIntegrations = this._launchManageIntegrations.bind(this); this.defaultStickersContent = ( <div className='mx_StickersContentPlaceholder'> <p>You don't currently have any stickerpacks enabled</p> <p>Click <a href=''>here</a> to add some!</p> <img src='img/stickerpack-placeholder.png' alt='Add a stickerpack' /> </div> ); this.popoverWidth = 300; this.popoverHeight = 300; this.state = { stickersContent: this.defaultStickersContent, showStickers: false, }; } componentDidMount() { this.scalarClient = null; if (SdkConfig.get().integrations_ui_url && SdkConfig.get().integrations_rest_url) { this.scalarClient = new ScalarAuthClient(); this.scalarClient.connect().then(() => { this.forceUpdate(); }).catch((e) => { console.log("Failed to connect to integrations server"); // TODO -- Handle Scalar errors // this.setState({ // scalar_error: err, // }); }); } // Stickers // TODO - Add support for stickerpacks from multiple app stores. // Render content from multiple stickerpack sources, each within their own iframe, within the stickerpack UI element. const stickerpackWidget = Widgets.getStickerpackWidgets()[0]; console.warn('Stickerpack widget', stickerpackWidget); let stickersContent; // Load stickerpack content if (stickerpackWidget && stickerpackWidget.content && stickerpackWidget.content.url) { this.widgetId = stickerpackWidget.id; stickersContent = ( <div style={{ overflow: 'hidden', height: '300px', }} > <div id='stickersContent' className='mx_StickersContent' style={{ border: 'none', height: this.popoverHeight - 30, width: this.popoverWidth, }} > <AppTile id={stickerpackWidget.id} url={stickerpackWidget.content.url} name={stickerpackWidget.content.name} room={this.props.room} type={stickerpackWidget.content.type} fullWidth={true} userId={stickerpackWidget.sender || MatrixClientPeg.get().credentials.userId} creatorUserId={MatrixClientPeg.get().credentials.userId} waitForIframeLoad={true} show={true} showMenubar={false} /> </div> <div style={{ height: '20px', position: 'absolute', bottom: '5px', right: '19px', width: '263px', textAlign: 'right', padding: '5px', borderTop: '1px solid #999', }}> <span className='mx_Stickerpack_addLink' onClick={this._launchManageIntegrations} >Add sticker packs</span> </div> </div> ); } else { // Default content to show if stickerpack widget not added stickersContent = <p>Click here to add your first sitckerpack</p>; } this.setState({stickersContent}); } onShowStickersClick(e) { const GenericElementContextMenu = sdk.getComponent('context_menus.GenericElementContextMenu'); const buttonRect = e.target.getBoundingClientRect(); // The window X and Y offsets are to adjust position when zoomed in to page const x = buttonRect.right + window.pageXOffset - 37; const y = (buttonRect.top + (buttonRect.height / 2) + window.pageYOffset) - 19; // const self = this; this.stickersMenu = ContextualMenu.createMenu(GenericElementContextMenu, { chevronOffset: 10, chevronFace: 'bottom', left: x, top: y, menuWidth: this.popoverWidth, menuHeight: this.popoverHeight, element: this.state.stickersContent, onFinished: this.onFinished, }); this.setState({showStickers: true}); } onHideStickersClick(ev) { this.stickersMenu.close(); } onFinished() { this.setState({showStickers: false}); this.stickersMenu = null; } _launchManageIntegrations() { this.onFinished(); const IntegrationsManager = sdk.getComponent("views.settings.IntegrationsManager"); const src = (this.scalarClient !== null && this.scalarClient.hasCredentials()) ? this.scalarClient.getScalarInterfaceUrlForRoom( this.props.room.roomId, 'add_integ', // this.widgetId, ) : null; Modal.createTrackedDialog('Integrations Manager', '', IntegrationsManager, { src: src, }, "mx_IntegrationsManager"); } render() { const TintableSvg = sdk.getComponent("elements.TintableSvg"); let stickersButton; if (this.state.showStickers) { // Show hide-stickers button stickersButton = <div id='stickersButton' key="controls_hide_stickers" className="mx_MessageComposer_stickers" onClick={this.onHideStickersClick} ref='target' title={_t("Hide Stickers")}> <TintableSvg src="img/icons-hide-stickers.svg" width="35" height="35" /> </div>; } else { // Show show-stickers button stickersButton = <div id='stickersButton' key="constrols_show_stickers" className="mx_MessageComposer_stickers" onClick={this.onShowStickersClick} title={_t("Show Stickers")}> <TintableSvg src="img/icons-show-stickers.svg" width="35" height="35" /> </div>; } return stickersButton; } }
JavaScript
0
@@ -7361,32 +7361,64 @@ omposer_stickers + mx_MessageComposer_hideStickers %22%0A
a3aa09b09a1da3180ac37012ba39b39453c4c153
Revert "Fallback to other things when keyCode is not available"
src/Native/Keyboard.js
src/Native/Keyboard.js
Elm.Native.Keyboard = {}; Elm.Native.Keyboard.make = function(localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.Keyboard = localRuntime.Native.Keyboard || {}; if (localRuntime.Native.Keyboard.values) { return localRuntime.Native.Keyboard.values; } var NS = Elm.Native.Signal.make(localRuntime); function keyEvent(event) { return { alt: event.altKey, meta: event.metaKey, keyCode: event.keyCode || event.which || event.charCode || 0 }; } function keyStream(node, eventName, handler) { var stream = NS.input(eventName, { alt: false, meta: false, keyCode: 0 }); localRuntime.addListener([stream.id], node, eventName, function(e) { localRuntime.notify(stream.id, handler(e)); }); return stream; } var downs = keyStream(document, 'keydown', keyEvent); var ups = keyStream(document, 'keyup', keyEvent); var presses = keyStream(document, 'keypress', keyEvent); var blurs = keyStream(window, 'blur', function() { return null; }); return localRuntime.Native.Keyboard.values = { downs: downs, ups: ups, blurs: blurs, presses: presses }; };
JavaScript
0
@@ -450,46 +450,8 @@ Code - %7C%7C event.which %7C%7C event.charCode %7C%7C 0 %0A%09%09%7D
f5024cc03c050f14896950d1fa13b4e95b051f9c
update fileexporler 重构
myfileexporler/index.js
myfileexporler/index.js
//index.js /** * Module dependencies. */ var fs = require('fs'); fs.readdir(__dirname,function(err,files){ console.log(files); }); fs.readdir(process.cwd(), function(err,files){ console.log(''); if (!files.length) { return console.log('\033[31m No files to show!\033[39m\n'); }; console.log('Select which file or directory you want to see\n'); function file(i){ var filename = files[i]; fs.stat(__dirname + '/' + filename,function(err,stat){ if(stat.isDirectory()){ console.log(' '+i+' \033[36m' + filename+'/\033[39m'); }else{ console.log(' '+i+' \033[90m' + filename+'\033[39m'); } i++; if(i == files.length){ console.log(''); process.stdout.write(' '+i+' \033[33mEnter your choice ' + '\033[39m'); process.stdin.resume(); process.stdin.setEncoding('utf8'); }else{ file(i); } }); } file(0); });
JavaScript
0.000001
@@ -59,16 +59,64 @@ re('fs') +%0A,stdin = process.stdin%0A,stdout = process.stdout ;%0Afs.rea @@ -672,18 +672,12 @@ %09%09%09i -++;%0A%09%09%09i f( +++ i == @@ -692,16 +692,18 @@ ength)%7B%0A +/* %09%09%09%09cons @@ -857,16 +857,42 @@ 'utf8'); +*/%0A read(); %0A%0A%09%09%09%7Del @@ -922,16 +922,397 @@ %09%7D);%0A%09%7D%0A + function read()%7B%0A %09console.log('');%0A stdout.write('%5C033%5B33mEnter your choice ' + '%5C033%5B39m');%0A stdin.resume();%0A stdin.setEncoding('utf8');%0A stdin.on('data',option);%0A %7D%0A function option(data)%7B%0A %09if(!files%5BNumber(data)%5D)%7B%0A %09stdout.write('%09%5C033%5B31mEnter your choice:%09%5C33%5B39m');%0A %7Delse%7B%0A %09stdin.pause();%0A %7D%0A %7D%0A %09file(0)
4ae9e7178c567362cf9b5fce898e93048e4b72b4
Remove console.log
lib/modules/storage/utils/transform_to_class.js
lib/modules/storage/utils/transform_to_class.js
import _ from 'lodash'; import AstroClass from '../../../core/class.js'; import resolveValues from '../../fields/utils/resolve_values.js'; function transformToClass(className, options = {}) { // Set default options. _.defaults(options, { defaults: true }); options.clone = false; return function(rawDoc) { let Class = AstroClass.get(className); if (Class) { const typeField = Class.getTypeField(); if (typeField) { console.log(typeField, rawDoc[typeField]); const TypeClass = AstroClass.get(rawDoc[typeField]); if (TypeClass) { Class = TypeClass; } } // Resolve values using the "resolveValue" method if provided. const resolvedDoc = resolveValues({ Class, values: rawDoc }); const doc = new Class(resolvedDoc, options); doc._isNew = false; return doc; } return rawDoc; }; }; export default transformToClass;
JavaScript
0.000004
@@ -449,55 +449,8 @@ ) %7B%0A -%09%09%09%09console.log(typeField, rawDoc%5BtypeField%5D);%0A
f96d2c71661ec8eedbb19eef0166953a6c2f92fd
Load SwellRT even if callback was called
src/js/services/pear.js
src/js/services/pear.js
'use strict'; /** * @ngdoc function * @name Pear2Pear.service:Pear * @description * # Pear service * Provides controllers with a data model for pear to pear app * It serves as an abstraction between Pear data and backend (SwellRT) */ angular.module('Pear2Pear') .factory('pear', ['$rootScope', 'swellRT', '$q', function($rootScope, swellRT, $q) { var proxy = { model: {} }; var def = $q.defer(); var communities = { all: function() { return [ { id: '1', name: 'Medialab Prado' }, { id: '2', name: 'GRASIA' }, { id: '3', name: 'Nosaltres' } ]; }, find: function(id) { return { id: id, name: 'Medialab Prado', projects: [ { id: '1', title: 'Festilab' }, { id: '2', title: 'Jardineando' } ] }; }, create: function(callback) { return { id: '1', name: 'Medialab Prado', projects: [ { id: '1', title: 'Festilab' }, { id: '2', title: 'Jardineando' } ] }; }, destroy: function(id) { return id; } }; var projects = { all: function() { return proxy.model; }, find: function(id) { return proxy.model[id]; }, create: function(callback) { var p = { id: Math.random().toString(36).substr(2, 5), title: '', chat: [], pad: new swellRT.TextObject(), needs: [], promoter: users.current() }; proxy.model[p.id] = p; callback(p); }, destroy: function(id) { delete proxy.model[id]; } }; var users = { current: function() { return window.sessionStorage.getItem('userId'); }, setCurrent: function() { }, isCurrent: function(user) { return user === users.current(); } }; var addChatMessage = function(projectId, message) { proxy.model[projectId].chat.push({ text: message, // TODO change when ready standpoint: 'mine', who: users.current(), time: (new Date()).toJSON() }); }; window.onSwellRTReady = function (){ window.SwellRT.startSession( SwellRTConfig.server, SwellRTConfig.user, SwellRTConfig.pass, function() { window.SwellRT.openModel( SwellRTConfig.chatpadWaveId, function(model) { proxy.model = swellRT.proxy(model); def.resolve(proxy.model); }, function(error){ console.log(error); }); }); } return { projects: projects, users: users, addChatMessage: addChatMessage, onLoad: function(f){ def.promise.then(f); } }; }]);
JavaScript
0
@@ -2960,24 +2960,156 @@ );%0A %7D +,%0A function(error) %7B%0A console.log(error);%0A %7D);%0A %7D;%0A%0A if (window.SwellRT) %7B%0A window.onSwellRTReady( );%0A %7D%0A%0A
80a7df5b00042c1af09526f6c2591f8a1e973b05
Remove default value for data in the batch reduce
src/js/structs/Batch.js
src/js/structs/Batch.js
/** * An immutable batch is an ever growing batch with a reduce capability. * * This can be used to keep action transactions that can be applied through * a set of reducers to a data set in order to transform it. * * Why 'Batch'? Because it's not really a `Stack`, since you cannot `pop` * items from it. Also not a `Log`, because it can be confused with the * logging utilities. * * @example <caption>Using Batch</caption> * class Component extends React.Component() { * constructor() { * super(); * this.state = { * actionBatch: new Batch() * } * } * * handleAction() { * this.setState({ * actionBatch: this.state.actionBatch.add({ * action: 'set', * key: 'foo', * value: 'bar' * }) * }) * } * * render() { * let data = this.state.actionBatch.reduce( * applyActionsToDataCallback, * this.props.data * ); * * return <Visualize data={data} /> * } * } * * */ class Batch { constructor() { // This creates a context for the functions which have access to the batch // variable and also access to the instance. So `this` can be returned and // functions could be chained. const context = {instance:this, batch:[]}; this.add = this.add.bind(context); this.reduce = this.reduce.bind(context); } /** * Add an action to the batch, and return the new batch * * NOTE: This is currently mutating the underlying batch array, but * this will change in the future, so use this function assuming * it will return the new batch you should operate upon! * * @param {Action} item * @returns {Batch} Returns the instance for the batch for chaining. */ add(item) { this.batch.push(item); return this.instance; }; /** * Apply the given reducer function to the data provided. * * This interface is exactly the same as the native Array.reduce function. * * @param {function(state, item)} callback - The callback function to use * @param {any} data - The initial state of the reduce function * @returns {any} - The resulting state of the reduce function */ reduce(callback, data = {}) { return this.batch.reduce(callback, data); }; } module.exports = Batch;
JavaScript
0.000001
@@ -2230,13 +2230,8 @@ data - = %7B%7D ) %7B%0A
5aa4df86ef92e738113973a898938f24b6c5c612
Update to BEM modifier-class
src/cookies-eu-banner.js
src/cookies-eu-banner.js
; // jshint ignore:line (function (root, factory, undefined) { 'use strict'; if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { // root is window root.CookiesEuBanner = factory(); } }(window, function () { 'use strict'; var CookiesEuBanner, document = window.document; CookiesEuBanner = function (launchFunction, waitAccept, useLocalStorage, undefined) { if (!(this instanceof CookiesEuBanner)) { return new CookiesEuBanner(launchFunction); } this.cookieTimeout = 33696000000; // 13 months in milliseconds this.bots = /bot|crawler|spider|crawling/i; this.cookieName = 'hasConsent'; this.trackingCookiesNames = ['__utma', '__utmb', '__utmc', '__utmt', '__utmv', '__utmz', '_ga', '_gat', '_gid']; this.launchFunction = launchFunction; this.waitAccept = waitAccept || false; this.useLocalStorage = useLocalStorage || false; this.init(); }; CookiesEuBanner.prototype = { init: function () { // Detect if the visitor is a bot or not // Prevent for search engine take the cookie alert message as main content of the page var isBot = this.bots.test(navigator.userAgent); // Check if DoNotTrack is activated var dnt = navigator.doNotTrack || navigator.msDoNotTrack || window.doNotTrack; var isToTrack = (dnt !== null && dnt !== undefined) ? (dnt && dnt !== 'yes' && dnt !== 1 && dnt !== '1') : true; // Do nothing if it is a bot // If DoNotTrack is activated, do nothing too if (isBot || !isToTrack || this.hasConsent() === false) { this.removeBanner(0); return false; } // User has already consent to use cookies to tracking if (this.hasConsent() === true) { // Launch user custom function this.launchFunction(); return true; } // If it's not a bot, no DoNotTrack and not already accept, so show banner this.showBanner(); if (!this.waitAccept) { // Accept cookies by default for the next page this.setConsent(true); } }, /* * Show banner at the top of the page */ showBanner: function () { var _this = this, getElementById = document.getElementById.bind(document), banner = getElementById('cookies-eu-banner'), rejectButton = getElementById('cookies-eu-reject'), acceptButton = getElementById('cookies-eu-accept'), moreLink = getElementById('cookies-eu-more'), waitRemove = (banner.dataset.waitRemove === undefined) ? 0 : parseInt(banner.dataset.waitRemove), // Variables for minification optimization addClickListener = this.addClickListener, removeBanner = _this.removeBanner.bind(_this, waitRemove); banner.style.display = 'block'; if (moreLink) { addClickListener(moreLink, function () { _this.deleteCookie(_this.cookieName); }); } if (acceptButton) { addClickListener(acceptButton, function () { removeBanner(); _this.setConsent(true); _this.launchFunction(); }); } if (rejectButton) { addClickListener(rejectButton, function () { removeBanner(); _this.setConsent(false); // Delete existing tracking cookies _this.trackingCookiesNames.map(_this.deleteCookie); }); } }, /* * Set consent cookie or localStorage */ setConsent: function (consent) { if (this.useLocalStorage) { return localStorage.setItem(this.cookieName, consent); } this.setCookie(this.cookieName, consent); }, /* * Check if user already consent */ hasConsent: function () { var cookieName = this.cookieName; var isCookieSetTo = function (value) { return document.cookie.indexOf(cookieName + '=' + value) > -1 || localStorage.getItem(cookieName) === value; }; if (isCookieSetTo('true')) { return true; } else if (isCookieSetTo('false')) { return false; } return null; }, /* * Create/update cookie */ setCookie: function (name, value) { var date = new Date(); date.setTime(date.getTime() + this.cookieTimeout); document.cookie = name + '=' + value + ';expires=' + date.toGMTString() + ';path=/'; }, /* * Delete cookie by changing expire */ deleteCookie: function (name) { var hostname = document.location.hostname.replace(/^www\./, ''), commonSuffix = '; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/'; document.cookie = name + '=; domain=.' + hostname + commonSuffix; document.cookie = name + '=' + commonSuffix; }, addClickListener: function (DOMElement, callback) { if (DOMElement.attachEvent) { // For IE 8 and earlier versions return DOMElement.attachEvent('onclick', callback); } // For all major browsers, except IE 8 and earlier DOMElement.addEventListener('click', callback); }, /* * Delays removal of banner allowing developers * to specify their own transition effects */ removeBanner: function (wait) { var banner = document.getElementById('cookies-eu-banner'); banner.classList.add('before-remove'); setTimeout (function() { if (banner && banner.parentNode) { banner.parentNode.removeChild(banner); } }, wait); } }; return CookiesEuBanner; }));
JavaScript
0
@@ -5399,16 +5399,35 @@ st.add(' +cookies-eu-banner-- before-r
91d5cec520061c33ca2f967d2039cb4ccd2868bb
clean up
lib/commands/Command.js
lib/commands/Command.js
var Base = require('../core/Base'); var _super = Base.prototype; var fs = require('fs'); var child_process = require('child_process'); var npath = require('path'); module.exports = Base.extend({ 'lineDelimiter': '\n\n', 'lines': [], 'padding': ' ', 'logLines': function () { var self = this; self.lines.forEach(function (line) { console.log(self.padding + line); }); }, 'ensureAsimovProject': function () { var self = this; var deferred = self.deferred(); var path = npath.join(process.cwd(), 'main.js'); if (!self.filesystem.pathExists(path)) { self.logger.log(self.namespace, 'The "' + self.options.command + '" command can only be run in asimov.js projects'); var message = 'Couldn\'t find main.js in ' + process.cwd(); console.log('[' + self.namespace + '] ' + message); process.exit(1); } function log (data) { data = data.toString().replace('/\n/g', '').trim(); if (data.length < 10 || data.indexOf('npm') === 0) return; self.logger.log('install', data); } var modulePath = npath.join(process.cwd(), 'node_modules'); var moduleFolderExists = fs.existsSync(modulePath); if (!moduleFolderExists) { var child = child_process.spawn('npm', ['install']); child.on('exit', function () { deferred.resolve(path); }); child.stdout.on('data', log); child.stderr.on('data', log); } else { deferred.resolve(path); } return deferred.promise(); }, 'logAsimovHeader': function () { var self = this; self.logger.pending('cli', 'Loading asimov.js @ ' + self.options.pkg.version); } });
JavaScript
0.000001
@@ -1188,24 +1188,25 @@ odulePath);%0A +%0A if (!mod
24eecae9026c49bb0dbd86a6b5f209b38b80ce9d
Add blank lines before and after when appending env vars
generators/utils.js
generators/utils.js
import { template, last, isEmpty, dropRight } from 'lodash'; const path = require('path'); const archiver = require('archiver'); const shortid = require('shortid'); const fs = require('fs-extra'); const Promise = require('bluebird'); const cpy = require('cpy'); const copy = Promise.promisify(fs.copy); const readFile = Promise.promisify(fs.readFile); const writeFile = Promise.promisify(fs.writeFile); const appendFile = Promise.promisify(fs.appendFile); const remove = Promise.promisify(fs.remove); const readJson = Promise.promisify(fs.readJson); const writeJson = Promise.promisify(fs.writeJson); const stat = Promise.promisify(fs.stat); const mkdirs = Promise.promisify(fs.mkdirs); const npmDependencies = require('./npmDependencies.json'); export { cpy }; export { copy }; export { remove }; export { mkdirs }; export { readFile }; export { writeFile }; export { appendFile }; export { readJson }; export { writeJson }; /** * @private * @param subStr {string} - what to indent * @param indentLevel {number} - how many levels to indent * @returns {string} */ function indentCode(subStr, indentLevel) { let defaultIndentation = 2; let indent = ' '.repeat(indentLevel * defaultIndentation); let array = subStr.toString().split('\n').filter(Boolean); array.forEach((line, index) => { array[index] = indent + line; }); return array.join('\n'); } /** * Traverse files and remove placeholder comments * @param params */ export function walkAndRemoveComments(params) { const build = path.join(__base, 'build', params.uuid); return new Promise((resolve, reject) => { fs.walk(build) .on('data', (item) => { return stat(item.path).then((stats) => { if (stats.isFile()) { return removeCode(item.path, '//='); } }); }) .on('error', (err) => { reject(err); }) .on('end', () => { resolve(); }); }); } export async function exists(filepath) { try { await stat(filepath); } catch (err) { if (err.code === 'ENOENT') { return false; } } return true; } export function generateZip(req, res) { let archive = archiver('zip'); archive.on('error', function(err) { res.status(500).send(err.message); }); res.on('close', function() { console.log('closing...'); console.log('Archive wrote %d bytes', archive.pointer()); return res.status(200).send('OK').end(); }); res.attachment('megaboilerplate-express.zip'); archive.pipe(res); let files = [ __base + '/modules/express/app.js', __base + '/modules/express/package.json' ]; for (let i in files) { archive.append(fs.createReadStream(files[i]), { name: path.basename(files[i]) }); } archive.finalize(); } /** * Add NPM package to package.json. * @param pkgName * @param params * @param isDev */ export async function addNpmPackage(pkgName, params, isDev) { const packageJson = path.join(__base, 'build', params.uuid, 'package.json'); const packageObj = await readJson(packageJson); const pkgVersion = npmDependencies[pkgName]; if (isDev) { packageObj.devDependencies = packageObj.devDependencies || {}; packageObj.devDependencies[pkgName] = pkgVersion; } else { packageObj.dependencies[pkgName] = pkgVersion; } await writeJson(packageJson, packageObj, { spaces: 2 }); } /** * Add NPM script to package.json. */ export async function addNpmScript(name, value, params) { const packageJson = path.join(__base, 'build', params.uuid, 'package.json'); const packageObj = await readJson(packageJson); packageObj.scripts[name] = value; await writeJson(packageJson, packageObj, { spaces: 2 }); } /** * Cleanup build files. * @param params */ export async function cleanup(params) { await remove(path.join(__base, 'build', params.uuid)); } export async function prepare(params) { let gitignore = path.join(__base, 'modules', 'prepare', '.gitignore'); //params.uuid = shortid.generate(); // TODO: Remove params.uuid = 'testing' await remove(path.join(__base, 'build', params.uuid)); await mkdirs(path.join(__base, 'build', params.uuid)); await copy(gitignore, path.join(__base, 'build', params.uuid, '.gitignore')); console.info('Created', params.uuid); return params; } /** * @param srcFile {buffer} - where to remove * @param subStr {string} - what to remove * @returns {string} */ export async function removeCode(srcFile, subStr) { let srcData = await readFile(srcFile); let array = srcData.toString().split('\n'); array.forEach((line, index) => { if (line.includes(subStr)) { array[index] = null; } }); array = array.filter((value) => { return value !== null; }); srcData = array.join('\n'); await writeFile(srcFile, srcData); } /** * * @param srcFile {buffer} - where to replace * @param subStr {string} - what to replace * @param newSrcFile {string} - replace it with this * @param [opts] {object} - options * @returns {string} */ export async function replaceCode(srcFile, subStr, newSrcFile, opts) { opts = opts || {}; let srcData = await readFile(srcFile); let newSrcData = await readFile(newSrcFile); const array = srcData.toString().split('\n'); array.forEach((line, index) => { const re = new RegExp(subStr + '$|(\r\n|\r|\n)'); const isMatch = re.test(line); // Preserve whitespace if it detects //_ token if (line.indexOf('//_') > - 1) { array[index] = ''; } if (isMatch) { if (opts.indentLevel) { newSrcData = indentCode(newSrcData, opts.indentLevel); } if (isEmpty(last(newSrcData.toString().split('\n')))) { newSrcData = dropRight(newSrcData.toString().split('\n')).join('\n'); } if (opts.leadingBlankLine) { newSrcData = ['\n', newSrcData].join(''); } array[index] = newSrcData; } }); srcData = array.join('\n'); await writeFile(srcFile, srcData); } /** * lodash _.template() function * @param srcFile * @param data */ export async function templateReplace(srcFile, data) { const src = await readFile(srcFile); const compiled = template(src.toString()); const newSrc = compiled(data); await writeFile(srcFile, newSrc); } /** * Add env vars to .env * @param params * @param data */ export async function addEnv(params, data) { const env = path.join(__base, 'build', params.uuid, '.env'); const vars = []; for (const i in data) { if (data.hasOwnProperty(i)) { vars.push([i, data[i]].join('=')); } } await appendFile(env, vars.join('\n')); }
JavaScript
0.000003
@@ -6559,16 +6559,23 @@ ile(env, + '%5Cn' + vars.jo @@ -6582,13 +6582,20 @@ in('%5Cn') + + '%5Cn' );%0A%7D%0A
945cf2ea01137cb38619adbf3f278160013666ae
Change option 'maxresults' to 'limit'
lib/code.js
lib/code.js
var exec = require('child_process').exec; var _ = require("lodash"); var path = require("path"); var exclureDirs = require("./data/excludedirs"); var extensions = require("./data/extensions"); var escapeRegExp = function(str) { return str.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); }; var escapeShell = function(str) { return str.replace(/([\\"'`$\s\(\)<>])/g, '\\$1'); }; var grepEscapeRegExp = function(str) { return str.replace(/[[\]{}()*+?.,\\^$|#\s"']/g, '\\$&'); }; var parseOutput = function(output, options) { var contextLineRegex, formatted, lines, mainLineRegex, stats; mainLineRegex = /^:?([\s\S]+):(\d+):([\s\S]*)$/; contextLineRegex = /^([\s\S]+)\-(\d+)\-([\s\S]*)$/; lines = output.split('\n'); formatted = {}; stats = { numberOfMatches: 0, numberOfSearchedFiles: 0 }; formatted = lines.map(function(line) { return line.trimLeft(); }).filter(function(line) { return mainLineRegex.test(line) || contextLineRegex.test(line); }).map(function(line) { return line.match(mainLineRegex) || line.match(contextLineRegex); }).reduce(function(accu, matches) { var fileName, line, lineNumber, _ref; _ref = [matches[1], parseInt(matches[2], 10), matches[3]], fileName = _ref[0], lineNumber = _ref[1], line = _ref[2]; fileName = path.relative(options.root, fileName); if (!accu[fileName]) { accu[fileName] = []; } accu[fileName].push({ lineNumber: lineNumber, line: line, occurence: mainLineRegex.test(matches[0]) }); stats.numberOfMatches += 1; return accu; }, {}); stats.numberOfSearchedFiles = Object.keys(formatted).length; return { results: formatted, matches: stats.numberOfMatches, files: stats.numberOfSearchedFiles }; }; var search = function(options, cb) { var query, include, splitText, flags; options = _.defaults(options || {}, { query: "", root: "", caseSensitive: true, wholeWord: false, regExp: false, replace: false, maxresults: null }); if (!options.query || !options.root) return cb(new Error("Need 'query' and 'root'")); include = (process.platform != "darwin" ? "\\" : "") + "*{" + (extensions.join(',')) + "}"; if (!options.regExp) { splitText = options.query.split('\\n'); splitText = splitText.map(grepEscapeRegExp); options.query = splitText.join('\\n'); } options.query = options.query.replace(new RegExp("\\\'", 'g'), "'\\''"); options.query = options.query.replace(/-/g, '\\-'); flags = [ '-s', // Silent mode '-r', // Recursively search subdirectories listed. '-n', // Each output line is preceded by its relative line number in the file '-A 3', // Print num lines of trailing context after each match. '-B 3', // Print num lines of trailing context before each match. '-i', // Match case insensitively '-w', // Only match whole words '--color=never', // Disable color output to get plain text '--binary-files=without-match', // Do not search binary files ]; if (process.platform != "darwin") flags.push("-P"); if (options.caseSensitive) flags.splice(flags.indexOf('-i'), 1); if (!options.wholeWord) flags.splice(flags.indexOf('-w'), 1); if (options.maxresults) flags.push("-m " + parseInt(options.maxresults, 10)); query = "grep " + (flags.join(' ')) + " --exclude-dir=" + (exclureDirs.join(' --exclude-dir=')) + " --include=" + include + " '" + options.query + "' \"" + (escapeShell(options.root)) + "\""; exec(query, function (error, stdout, stderr) { if (error) return cb(error); cb(null, parseOutput(stdout, options)); }); }; module.exports = search;
JavaScript
0.999883
@@ -2162,26 +2162,21 @@ -maxresults +limit : null%0A @@ -3647,26 +3647,21 @@ options. -maxresults +limit ) flags. @@ -3694,18 +3694,13 @@ ons. -maxresults +limit , 10
8aa7a2b1b2f350d43769e5f9955a02bf8e122ea9
load all the fonts
demo/demo.js
demo/demo.js
DefineModule('main', function (require) { var CanvasRenderer = require('pxlr/gl/canvas'); //var font = require('pxlr/fonts/arcade-small'); var font = require('pxlr/fonts/elian'); function changeFont(font) { return function () { console.log(font); }; } document.getElementById('arcade').addEventListener('click', changeFont('arcade')); document.getElementById('arcade-small').addEventListener('click', changeFont('arcade-small')); document.getElementById('phoenix').addEventListener('click', changeFont('phoenix')); document.getElementById('elian').addEventListener('click', changeFont('elian')); var renderer = new CanvasRenderer({ width: 200, height: 150 }); renderer.setFillColor("#FFFFFF"); var frame = renderer.newRenderFrame(); frame.clear(); var offset = 0; //"-- Arcade Small --".split('').forEach(function (letter) { // var letterSprite = font[ letter ]; // // letterSprite.applyColor("#000000"); // letterSprite.renderToFrame(frame, offset, 0); // offset += letterSprite.width + 1; //}); offset = 0; "abcdefghijklmnopqrstuvwxyz".split('').forEach(function (letter) { var letterSprite = font[ letter ]; letterSprite.applyColor("#000000"); letterSprite.renderToFrame(frame, offset, 10); offset += letterSprite.width + 1; }); offset = 0; "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('').forEach(function (letter) { var letterSprite = font[ letter ]; letterSprite.applyColor("#000000"); letterSprite.renderToFrame(frame, offset, 20); offset += letterSprite.width + 1; }); offset = 0; //"0123456789.,!?<>-:$+%".split('').forEach(function (letter) { // var letterSprite = font[ letter ]; // // letterSprite.applyColor("#000000"); // letterSprite.renderToFrame(frame, offset, 30); // offset += letterSprite.width + 1; //}); offset = 0; "This is a sample sentence. So is this.".split('').forEach(function (letter) { var letterSprite = font[ letter ]; letterSprite.applyColor("#000000"); letterSprite.renderToFrame(frame, offset, 40); offset += letterSprite.width + 1; }); renderer.renderFrame(); });
JavaScript
0.000004
@@ -91,22 +91,21 @@ ');%0A +%0A -// var font = r @@ -92,34 +92,109 @@ );%0A%0A var font +s = + %7B%0A 'arcade': require('pxlr/fonts/arcade'),%0A 'arcade-small': require('pxlr/f @@ -216,52 +216,141 @@ ll') -; +, %0A -var font = require('pxlr/fonts/elian') + 'phoenix': require('pxlr/fonts/phoenix'),%0A 'elian': require('pxlr/fonts/elian')%0A %7D;%0A var activeFont = 'arcade' ;%0A%0A @@ -425,25 +425,25 @@ -console.log( +activeFont = font -) ;%0A
9810b19e139279066337077d4d23f23c61144adb
add assertion, https://github.com/phetsims/phet-io-test-sim/issues/13
js/PhetioCapsule.js
js/PhetioCapsule.js
// Copyright 2019-2020, University of Colorado Boulder /** * A PhET-iO class that encapsulates a PhetioObject that is not created during sim startup to provide PhET-iO API * validation, API communication (like to view in studio before creation), and to support PhET-iO state if applicable. * * Constructing a PhetioCapsule creates a container encapsulating a wrapped element that can be of any type. * * Clients should use myCapsule.getElement() instead of storing the element value itself. * * @author Michael Kauzmann (PhET Interactive Simulations) * @author Sam Reid (PhET Interactive Simulations) * @author Chris Klusendorf (PhET Interactive Simulations) */ import merge from '../../phet-core/js/merge.js'; import PhetioDynamicElementContainer from './PhetioDynamicElementContainer.js'; import Tandem from './Tandem.js'; import tandemNamespace from './tandemNamespace.js'; // constants const DEFAULT_CONTAINER_SUFFIX = 'Capsule'; class PhetioCapsule extends PhetioDynamicElementContainer { /** * @param {function(tandem, ...):PhetioObject} createElement - function that creates the encapsulated element * @param {Array.<*>|function.<[],Array.<*>>} defaultArguments - arguments passed to createElement during API baseline generation * @param {Object} [options] */ constructor( createElement, defaultArguments, options ) { options = merge( { tandem: Tandem.REQUIRED, // {string} The capsule's tandem name must have this suffix, and the base tandem name for its wrapped element // will consist of the capsule's tandem name with this suffix stripped off. containerSuffix: DEFAULT_CONTAINER_SUFFIX }, options ); super( createElement, defaultArguments, options ); // @public (read-only PhetioCapsuleIO) {PhetioObject} this.element = null; } /** * Dispose the underlying element. Called by the PhetioStateEngine so the capsule element can be recreated with the * correct state. * @param {boolean} [fromStateSetting] - Used for validation during state setting, see PhetioDynamicElementContainer.disposeElement() * @public (phet-io) * @override */ disposeElement( fromStateSetting ) { super.disposeElement( this.element, fromStateSetting ); this.element = null; } /** * Creates the element if it has not been created yet, and returns it. * @param {Array.<*>} [argsForCreateFunction] * @returns {Object} * @public */ getElement( ...argsForCreateFunction ) { if ( !this.element ) { this.create( argsForCreateFunction ); } return this.element; } /** * @public * @override * @param {object} [options] */ clear( options ) { options = merge( { // Used for validation during state setting. See PhetioDynamicElementContainer.disposeElement() for documentation fromStateSetting: false }, options ); if ( this.element ) { this.disposeElement( options.fromStateSetting ); } } /** * Primarily for internal use, clients should usually use getElement. * @param {Array.<*>} argsForCreateFunction * @param {boolean} [fromStateSetting] - used for validation during state setting, see PhetioDynamicElementContainer.disposeElement() for documentation * @returns {Object} * @public (phet-io) */ create( argsForCreateFunction, fromStateSetting ) { assert && assert( this.isPhetioInstrumented(), 'TODO: support uninstrumented PhetioCapsules? see https://github.com/phetsims/tandem/issues/184' ); assert && this.supportsDynamicState && _.hasIn( window, 'phet.joist.sim.' ) && phet.joist.sim.isSettingPhetioStateProperty.value && assert( fromStateSetting, 'dynamic elements should only be created by the state engine when setting state.' ); // create with default state and substructure, details will need to be set by setter methods. this.element = this.createDynamicElement( this.phetioDynamicElementName, argsForCreateFunction, this.phetioType.parameterTypes[ 0 ] ); this.notifyElementCreated( this.element ); return this.element; } } tandemNamespace.register( 'PhetioCapsule', PhetioCapsule ); export default PhetioCapsule;
JavaScript
0
@@ -2175,24 +2175,106 @@ Setting ) %7B%0A + assert && assert( this.element, 'cannot dispose if element is not defined' );%0A super.di
92a968d7ca2e59e875d4d4dacc01c86e0d9fc300
Add missing js update.
lib/codo.js
lib/codo.js
(function() { var Generator, Parser, findit, fs, util; fs = require('fs'); util = require('util'); findit = require('findit'); Parser = require('./parser'); Generator = require('./generator'); exports.run = function() { var arg, args, argv, bool, codoopts, config, configs, extra, filename, input, optimist, option, options, parser, _i, _j, _k, _l, _len, _len2, _len3, _len4, _ref, _ref2, _ref3; codoopts = { _: [] }; try { configs = fs.readFileSync('.codoopts', 'utf8'); _ref = configs.split('\n'); for (_i = 0, _len = _ref.length; _i < _len; _i++) { config = _ref[_i]; if (option = /^-{1,2}([\w-]+)\s+(['"])?(.*?)\2?$/.exec(config)) { codoopts[option[1]] = option[3]; } else if (bool = /^-{1,2}([\w-]+)\s*$/.exec(config)) { codoopts[bool[1]] = true; } else if (config !== '') { codoopts._.push(config); } } } catch (_error) {} optimist = require('optimist').usage('Usage: $0 [options] [source_files [- extra_files]]').options('r', { alias: 'readme', describe: 'The readme file used.', "default": codoopts.readme || codoopts.r || 'README.md' }).options('q', { alias: 'quiet', describe: 'Show no warnings.', boolean: true, "default": codoopts.quiet || false }).options('o', { alias: 'output-dir', describe: 'The output directory.', "default": codoopts['output-dir'] || codoopts.o || './doc' }).options('v', { alias: 'verbose', describe: 'Show parsing errors.', boolean: true, "default": codoopts.verbose || codoopts.v || false }).options('h', { alias: 'help', describe: 'Show the help.' }).options('private', { boolean: true, "default": codoopts.private || false, describe: 'Show private methods' })["default"]('title', codoopts.title || 'CoffeeScript API Documentation'); argv = optimist.argv; if (argv.h) { return console.log(optimist.help()); } else { options = { inputs: [], output: argv.o, extras: [], readme: argv.r, title: argv.title, quiet: argv.q, private: argv.private, verbose: argv.v }; extra = false; args = argv._.length !== 0 ? argv._ : codoopts._; for (_j = 0, _len2 = args.length; _j < _len2; _j++) { arg = args[_j]; if (arg === '-') { extra = true; } else { if (extra) { options.extras.push(arg); } else { options.inputs.push(arg); } } } if (options.inputs.length === 0) options.inputs.push('./src'); try { parser = new Parser(options); _ref2 = options.inputs; for (_k = 0, _len3 = _ref2.length; _k < _len3; _k++) { input = _ref2[_k]; _ref3 = findit.sync(input); for (_l = 0, _len4 = _ref3.length; _l < _len4; _l++) { filename = _ref3[_l]; if (filename.match(/\.coffee$/)) { try { parser.parseFile(filename); } catch (error) { console.log("Cannot parse file " + filename + ": " + error.message); } } } } new Generator(parser, options).generate(); if (!options.quiet) return parser.showResult(); } catch (error) { return console.log("Cannot generate documentation: " + error.message); } } }; }).call(this);
JavaScript
0
@@ -1132,20 +1132,19 @@ ile used -. ',%0A + %22d @@ -1274,17 +1274,16 @@ warnings -. ',%0A @@ -1425,17 +1425,16 @@ irectory -. ',%0A @@ -1575,17 +1575,16 @@ g errors -. ',%0A @@ -1699,16 +1699,16 @@ 'help',%0A + de @@ -1729,17 +1729,16 @@ the help -. '%0A %7D)
b5c3fa629f9ce258010d7fadc4582dc3d5a7122c
add propertyIds to state
src/containers/entitysetsearch/UserRow.js
src/containers/entitysetsearch/UserRow.js
import React, { PropTypes } from 'react'; import { Button } from 'react-bootstrap'; import { Table, Column, Cell } from 'fixed-data-table'; import PropertyTextCell from './PropertyTextCell'; import userProfileImg from '../../images/user-profile-icon.png'; import styles from './styles.module.css'; const TABLE_WIDTH = 1000; const ROW_HEIGHT = 50; const TABLE_OFFSET = 2; const PROPERTY_COLUMN_WIDTH = 200; const COLUMN_WIDTH = (TABLE_WIDTH - PROPERTY_COLUMN_WIDTH); const HEADERS = ['PROPERTY', 'DATA']; export default class UserRow extends React.Component { constructor(props) { super(props); this.state = { numRows: 1 } } componentDidMount() { const numRows = this.getPropertyIds().length; this.setState({numRows}); } renderTable = () => { if (!this.props.userPage) return null; const tableHeight = ((this.state.numRows + 1) * ROW_HEIGHT) + TABLE_OFFSET; return ( <Table rowsCount={this.state.numRows} rowHeight={ROW_HEIGHT} headerHeight={ROW_HEIGHT} width={TABLE_WIDTH} height={tableHeight}> {this.renderPropertyColumn()} {this.renderDataColumn()} </Table> ); } renderPropertyColumn() { const header = HEADERS[0]; const propertyTitles = this.getPropertyTitles(); return ( <Column key={0} header={header} cell={ <PropertyTextCell data={propertyTitles} /> } width={PROPERTY_COLUMN_WIDTH} /> ) } renderDataColumn() { const header = HEADERS[1]; const cellData = this.getCellData(); return ( <Column key={1} header={<Cell>{header}</Cell>} cell={ <PropertyTextCell data={cellData} /> } width={COLUMN_WIDTH} /> ); } getPropertyIds() { const { row, propertyTypes, firstName, lastName, dob } = this.props; const propertyIds = Object.keys(row).filter((id) => { if (dob && id === dob.id) return false; return (id !== firstName.id && id !== lastName.id); }); return propertyIds; } getPropertyTitles() { const { propertyTypes } = this.props; var propertyIds = this.getPropertyIds(); var headers = propertyIds.map((id) => { var property = propertyTypes.filter((propertyType) => { return propertyType.id === id; }); return property[0].title; }); return headers; } getCellData(){ const { row, propertyTypes, firstName, lastName, dob } = this.props; const propertyIds = this.getPropertyIds(); return propertyIds.map((id) => { var formatValue = this.props.formatValueFn([row][0][id]); return formatValue; }); } selectUser = () => { if (this.props.userPage) return; this.props.selectUserFn(this.props.row); } renderBackButton = () => { if (!this.props.userPage) return null; return ( <div> <Button onClick={this.props.backFn} bsStyle="primary" className={styles.backButton}>Back to results</Button> <br /> </div> ); } getFirstNameVal = () => { return this.props.formatValueFn(this.props.row[this.props.firstName.id]); } getLastNameVal = () => { return this.props.formatValueFn(this.props.row[this.props.lastName.id]); } renderDOB = () => { if (!this.props.dob) return null; const dobVal = this.props.row[this.props.dob.id]; if (!dobVal) return null; return <div className={styles.userProfileDetailItem}><b>Date of Birth:</b> {this.props.formatValueFn(dobVal)}</div>; } getClassName = () => { return (this.props.userPage) ? styles.userProfile : styles.userListItem; } renderUserProfile = () => { return ( <div className={this.getClassName()} onClick={this.selectUser}> <img src={userProfileImg} className={styles.userIcon} role="presentation" /> <div className={styles.userProfileDetails}> <div className={styles.userProfileDetailItem}><b>First Name:</b> {this.getFirstNameVal()}</div> <div className={styles.userProfileDetailItem}><b>Last Name:</b> {this.getLastNameVal()}</div> {this.renderDOB()} </div> </div> ); } getContainerClassName = () => { return (this.props.userPage) ? '' : styles.userListContainer; } render() { return ( <div className={this.getContainerClassName()}> {this.renderBackButton()} {this.renderUserProfile()} {this.renderTable()} </div> ); } static propTypes = { row: PropTypes.object.isRequired, propertyTypes: PropTypes.array.isRequired, firstName: PropTypes.object.isRequired, lastName: PropTypes.object.isRequired, dob: PropTypes.object, selectUserFn: PropTypes.func, backFn: PropTypes.func, userPage: PropTypes.bool, formatValueFn: PropTypes.func } }
JavaScript
0.000001
@@ -631,16 +631,39 @@ mRows: 1 +,%0A propertyIds: %5B%5D %0A %7D%0A @@ -700,22 +700,26 @@ const -numRow +propertyId s = this @@ -735,16 +735,84 @@ rtyIds() +;%0A this.setState(%7BpropertyIds%7D);%0A%0A const numRows = propertyIds .length; @@ -2292,36 +2292,39 @@ pertyIds = this. -getP +state.p ropertyIds();%0A @@ -2313,26 +2313,24 @@ .propertyIds -() ;%0A var he @@ -2651,36 +2651,39 @@ pertyIds = this. -getP +state.p ropertyIds();%0A%0A @@ -2676,18 +2676,16 @@ pertyIds -() ;%0A%0A r
f8a565f6861c5af79037f9b23c0c6cbf04089850
Fix non nullable plugin properties. Ref issue #288.
assets/js/app/plugins/plugin-helper-service.js
assets/js/app/plugins/plugin-helper-service.js
/** * This file contains all necessary Angular controller definitions for 'frontend.admin.login-history' module. * * Note that this file should only contain controllers and nothing else. */ (function() { 'use strict'; angular.module('frontend.plugins') .service('PluginHelperService', [ '_','$log','BackendConfig','Upload','PluginsService', function( _,$log,BackendConfig,Upload,PluginsService) { function assignExtraProperties(_pluginName, options,fields,prefix) { Object.keys(fields).forEach(function (item) { if(fields[item].schema) { assignExtraProperties(_pluginName, options,fields[item].schema.fields,item); }else{ var path = prefix ? prefix + "." + item : item; var value = fields[item].default; if ((fields[item].type === 'array' || fields[item].type === 'set') && (typeof value === 'object' || typeof value === 'string') && _pluginName !== 'statsd' ) { value = []; } fields[item].value = value fields[item].help = _.get(options,path) ? _.get(options,path).help : ''; } }); } function createConfigProperties(pluginName,fields,prefix,data) { Object.keys(fields).forEach(function (key) { if(fields[key].schema) { createConfigProperties(pluginName,fields[key].schema.fields,key,data); }else{ var path = prefix ? prefix + "." + key : key; // if (fields[key].value instanceof Array && pluginName !== 'statsd') { // // Transform to comma separated string // // data['config.' + path] = fields[key].value.join(","); // if(!data.config) data.config = {}; // if(fields[key].value) { // data.config[path] = fields[key].value.join(","); // } // } else { // // data['config.' + path] = fields[key].value; // if(!data.config) data.config = {}; // if(fields[key].value) { // data.config[path] = fields[key].value; // } // } if(!data.config) data.config = {}; if(fields[key].fields) { fields[key].fields.forEach(field => { if(!data.config[path]) data.config[path] = {}; const prop = Object.keys(field)[0]; data.config[path][Object.keys(field)[0]] = _.get(field, `${prop}.value`); }) }else{ if(fields[key].value !== "" && fields[key].value !== 'undefined' && fields[key].value !== undefined) { data.config[path] = fields[key].value; } } } }); } var handlers = { common : function(data,success,error) { PluginsService.add(data) .then(function(resp){ success(resp); }).catch(function(err){ error(err); }); }, ssl : function(data, success,error,event) { var files = []; files.push(data['config.cert']) files.push(data['config.key']) Upload.upload({ url: 'kong/plugins', arrayKey: '', data: { file: files, 'name' : data.name, 'config.only_https': data['config.only_https'], 'config.accept_http_if_already_terminated': data['config.accept_http_if_already_terminated'] } }).then(function (resp) { success(resp) }, function (err) { error(err) }, function (evt) { event(evt) }); } } return { addPlugin : function(data, success,error,event) { if(handlers[data.name]) { return handlers[data.name](data, success,error,event); }else{ return handlers['common'](data, success,error,event); } }, createConfigProperties : function(pluginName,fields,prefix) { var output = {} createConfigProperties(pluginName,fields,prefix,output) return output; }, assignExtraProperties : function(_pluginName, options,fields,prefix) { return assignExtraProperties(_pluginName, options,fields,prefix) }, /** * Customize data fields for specified plugins if required by Konga's logic * @param pluginName * @param fields */ customizeDataFieldsForPlugin : function(pluginName,fields) { switch (pluginName) { case 'ssl': fields.cert.type = 'file' fields.key.type = 'file' break; } }, /** * Mutate request data for specified plugins if required by Konga's logic * @param request_data * @param fields */ applyMonkeyPatches : function(request_data,fields) { if(request_data.name === 'response-ratelimiting' && fields.limits.custom_fields) { //console.log("fields.limits.custom_fields",fields.limits.custom_fields) Object.keys(fields.limits.custom_fields) .forEach(function(key){ Object.keys(fields.limits.custom_fields[key]) .forEach(function(cf_key){ request_data['config.limits.' + key + '.' + cf_key] = fields.limits.custom_fields[key][cf_key].value }); }); } } }; } ]) ; }());
JavaScript
0
@@ -3393,16 +3393,80 @@ !== %22%22%0A + && fields%5Bkey%5D.value !== null%0A
599ff84902edc48c18a43ffe2ac3462695fee704
remove console.log in watcher
app/src/core/watcher.js
app/src/core/watcher.js
// watch the graph for changes const nodes = (graphNodes, cy) => { console.log(graphNodes.same(cy.nodes())) // add the files location to the title bar const titleBar = document.getElementById('title-bar-id') if (graphNodes.same(cy.nodes()) === false) { // add the files location to the title bar titleBar.innerHTML += ` *` } else { titleBar.innerHTML = titleBar.innerHTML.replace(' *', ' ') } } const edges = (graphEdges, cy) => { console.log(graphEdges.same(cy.edges())) const titleBar = document.getElementById('title-bar-id') if ( graphEdges.same(cy.edges()) === false && titleBar.innerText !== `${titleBar.innerHTML} *` ) { // add the files location to the title bar titleBar.innerHTML += ` *` } else if (graphEdges.same(cy.edges()) === false) { titleBar.innerHTML = titleBar.innerHTML } else { titleBar.innerHTML = titleBar.innerHTML.replace(' *', ' ') } } module.exports = { nodes, edges }
JavaScript
0.000001
@@ -64,96 +64,8 @@ =%3E %7B -%0A console.log(graphNodes.same(cy.nodes()))%0A // add the files location to the title bar %0A%0A @@ -121,16 +121,17 @@ ar-id')%0A +%0A if (gr
96d647b4749adfd4576760e3e899c20f054ed1f1
fix for durations over an hour
src/utils/format-time.js
src/utils/format-time.js
export default function formatTime(current) { let h = Math.floor(current / 3600) let m = Math.floor(current / 60) let s = Math.floor(current % 60) if (s < 10) { s = '0' + s } if (h > 0) { return h + ':' + m + ':' + s } else { return m + ':' + s } }
JavaScript
0.001975
@@ -97,23 +97,38 @@ h.floor( +( current + - (h * 3600)) / 60)%0A
a98236c5e7f09068bd7dff8744ca11bc6b7ef2e2
Fix bug introduced from messed up merge.
lib/control/v1/index.js
lib/control/v1/index.js
'use strict'; const Handlers = require('../util').Handlers; const Err = require('../util').Err; const VerifyHeaders = require('../util').VerifyHeaders; exports.attach = function(app, storage) { app.get('/v1/health', require('./health')(storage)); app.get('/v1/token/default', require('./token')(storage)); // Backend endpoints app.get('/v1/secret/:token/:path(*)', require('./secret')(storage)); app.get('/v1/cubbyhole/:token/:path(*)', require('./cubbyhole')(storage)); app.get('/v1/credential/:token/:mount/:role', require('./credential')(storage)); app.post('/v1/transit/:token/decrypt', require('./transit')(storage)); app.use('/v1/transit', Handlers.allowed('POST')); app.use(Handlers.allowed('GET')); app.use(Err); };
JavaScript
0
@@ -189,16 +189,121 @@ rage) %7B%0A + app.use(VerifyHeaders(%5B'POST', 'PUT'%5D, %7B%0A 'Content-Type': 'application/json; charset=utf-8'%0A %7D));%0A%0A app.ge
4b9f97736fa4457c47b62adc39a08e4c0dc8c4d6
add expiration
models/user_model.js
models/user_model.js
var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); var jwt = require('jsonwebtoken'); var UserSchema = mongoose.Schema({ username: { type: String }, password: { type: String } }); UserSchema.pre('save', function(callback) { var user = this; // Break out if the password hasn't changed if (!user.isModified('password')) return callback(); // Password changed so we need to hash it bcrypt.genSalt(5, function(err, salt) { if (err) return callback(err); bcrypt.hash(user.password, salt, null, function(err, hash) { if (err) return callback(err); user.password = hash; callback(); }); }); }); UserSchema.methods.generateToken = function(secret) { var self = this; var token = jwt.sign({ issuer: self._id, expiresInMinutes: 1 }, secret); return token; }; UserSchema.methods.verifyPassword = function(password, cb) { bcrypt.compare(password, this.password, function(err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; module.exports = mongoose.model('User', UserSchema);
JavaScript
0.999644
@@ -793,13 +793,43 @@ ._id -, %0A - +%7D, secret, %7B algorithm: 'RS256', exp @@ -847,21 +847,10 @@ es: -1%0A %7D, secret +5%7D );%0A
525e8b5c492f32d7eefc110504452cd7240f06be
add console log when server starts
app/src/server/index.js
app/src/server/index.js
'use strict' require('./debug.js')() const path = require('path') const fs = require('fs') const express = require('express') const helmet = require('helmet') // TODO: article about all header this provides const morgan = require('morgan') const responseTime = require('response-time') const compression = require('compression') const nunjucks = require('nunjucks') const config = require('../config/config.js') const nunjucksFilters = require('./utils/nunjucks-filters.js') const paths = require('./paths.js') const routes = require('./routes.js') // app const app = express() // middlewares const logWriteStream = fs.createWriteStream( path.join(paths.log, new Date().toISOString().slice(0, 10)) + '.log', { flags: 'a' } ) app.use(helmet()) app.use(morgan('short', { stream: logWriteStream })) app.use(responseTime()) app.use(compression()) // template config app.set('views', paths.templates) const nunjucksEnv = nunjucks.configure(app.get('views'), { autoescape: true, express: app }) for (const filterName in nunjucksFilters) { // add custom filters nunjucksEnv.addFilter(filterName, nunjucksFilters[filterName]) } // static files app.use('/static', express.static(paths.static)) app.use('/static/articles', express.static(paths.articles)) // TODO: make only avaliable in debug app.use('/static/node_modules', express.static(paths.nodeModules)) // TODO: make only avaliable in debug // pages app.get('/', routes.index) app.get('/rss', routes.rss) app.get('/robots.txt', routes.robotsTxt) app.get('/humans.txt', routes.humansTxt) app.get('/debug', routes.debug) app.get('/debug/:article', routes.debugArticle) app.get('/:article', routes.article) // start server app.listen(config.port)
JavaScript
0.000002
@@ -1711,10 +1711,70 @@ fig.port +, () =%3E console.log('server started at port ' + config.port) )%0A
deae9746f296561e682f6d9a0dcf5c50a58c3dfc
Clean debug logs
components/CEButton.js
components/CEButton.js
import React from 'react'; import InteropHelper from 'components/InteropHelper'; import { Button } from 'react-bootstrap'; import svg from 'components/resources/ico/Compiler-Explorer.svg'; class CEButton extends React.Component { compilerCeId(opt) { if (opt.compiler.startsWith('clang')) return 'clang' + opt.compiler.substr(6).replace('.', '') + '0'; return 'g' + opt.compiler.substr(4).replace('.', ''); } optimCe(opt) { switch (opt.optim) { case 'G': return '-Og'; case 'F': return '-Ofast'; case 'S': return '-Os'; default: return '-O' + opt.optim; } } versionCe(opt) { switch (opt.cppVersion) { case '20': return '2a'; case '17': return '1z'; default: return opt.cppVersion; } } optionsCe(opt) { const cppVersion = '-std=c++' + this.versionCe(opt); return cppVersion + ' ' + this.optimCe(opt); } openCodeInCE(texts, options) { console.log("texts: " + texts); console.log("options: " + options); let sessions = [].concat(texts).map((t, i) => ({ "id": i, "language": "c++", "source": t, "compilers": [{ "id": this.compilerCeId([].concat(options)[i]), "options": this.optionsCe([].concat(options)[i]), "libs": [{ "name": "benchmark", "ver": "140" }] }] })); var clientstate = { "sessions": sessions }; var link = window.location.protocol + '//godbolt.org/clientstate/' + InteropHelper.b64UTFEncode(JSON.stringify(clientstate)); window.open(link, '_blank'); } render() { return <Button variant="outline-dark" onClick={() => this.openCodeInCE(this.props.texts, this.props.options)} > <img src={svg} style={{ height: "1.2em" }} alt="Open in Compiler Explorer" /> </Button>; } } export default CEButton;
JavaScript
0.000002
@@ -1143,92 +1143,8 @@ ) %7B%0A - console.log(%22texts: %22 + texts);%0A console.log(%22options: %22 + options);%0A
51aa5a7bd6b8774528fb79d54a3cbc60a6963da5
Correct getWorkDir() typo
lib/controllers/git-tab-header-controller.js
lib/controllers/git-tab-header-controller.js
import React from 'react'; import PropTypes from 'prop-types'; import {CompositeDisposable} from 'atom'; import {nullAuthor} from '../models/author'; import GitTabHeaderView from '../views/git-tab-header-view'; export default class GitTabHeaderController extends React.Component { static propTypes = { getCommitter: PropTypes.func.isRequired, // Workspace currentWorkDir: PropTypes.string, getCurrentWorkDirs: PropTypes.func.isRequired, changeWorkingDirectory: PropTypes.func.isRequired, contextLocked: PropTypes.bool.isRequired, setContextLock: PropTypes.func.isRequired, // Event Handlers onDidChangeWorkDirs: PropTypes.func.isRequired, onDidUpdateRepo: PropTypes.func.isRequired, } constructor(props) { super(props); this._isMounted = false; this.state = { currentWorkDirs: [], committer: nullAuthor, changingLock: null, changingWorkDir: null, }; this.disposable = new CompositeDisposable(); } static getDerivedStateFromProps(props) { return { currentWorkDirs: props.getCurrentWorkDirs(), }; } componentDidMount() { this._isMounted = true; this.disposable.add(this.props.onDidChangeWorkDirs(this.resetWorkDirs)); this.disposable.add(this.props.onDidUpdateRepo(this.updateCommitter)); this.updateCommitter(); } componentDidUpdate(prevProps) { if ( prevProps.onDidChangeWorkDirs !== this.props.onDidChangeWorkDirs || prevProps.onDidUpdateRepo !== this.props.onDidUpdateRepo ) { this.disposable.dispose(); this.disposable = new CompositeDisposable(); this.disposable.add(this.props.onDidChangeWorkDirs(this.resetWorkDirs)); this.disposable.add(this.props.onDidUpdateRepo(this.updateCommitter)); } if (prevProps.getCommitter !== this.props.getCommitter) { this.updateCommitter(); } } render() { return ( <GitTabHeaderView committer={this.state.committer} // Workspace workdir={this.getWorkDir()} workdirs={this.state.currentWorkDirs} contextLocked={this.getLocked()} changingWorkDir={this.state.changingWorkDir !== null} changingLock={this.state.changingLock !== null} // Event Handlers handleWorkDirSelect={this.handleWorkDirSelect} handleLockToggle={this.handleLockToggle} /> ); } handleLockToggle = async () => { if (this.state.changingLock !== null) { return; } const nextLock = !this.props.contextLocked; try { this.setState({changingLock: nextLock}); await this.props.setContextLock(this.state.changingWorkDir || this.props.currentWorkDir, nextLock); } finally { await new Promise(resolve => this.setState({changingLock: null}, resolve)); } } handleWorkDirSelect = async e => { if (this.state.changingWorkDir !== null) { return; } const nextWorkDir = e.target.value; try { this.setState({changingWorkDir: nextWorkDir}); await this.props.changeWorkingDirectory(nextWorkDir); } finally { await new Promise(resolve => this.setState({changingWork: null}, resolve)); } } resetWorkDirs = () => { this.setState(() => ({ currentWorkDirs: [], })); } updateCommitter = async () => { const committer = await this.props.getCommitter() || nullAuthor; if (this._isMounted) { this.setState({committer}); } } getWorkDir() { return this.state.changeWorkDir !== null ? this.state.changingWorkDir : this.props.currentWorkDir; } getLocked() { return this.state.changingLock !== null ? this.state.changingLock : this.props.contextLocked; } componentWillUnmount() { this._isMounted = false; this.disposable.dispose(); } }
JavaScript
0.998428
@@ -2638,58 +2638,18 @@ his. -state.changingWorkDir %7C%7C this.props.curren +ge tWorkDir , ne @@ -2644,16 +2644,18 @@ tWorkDir +() , nextLo @@ -3454,25 +3454,27 @@ .state.chang -e +ing WorkDir !==
19d9e38441c064ec780bbf7a86895ec6332783d4
update travis commands and reference
src/utils/get-scripts.js
src/utils/get-scripts.js
import fs from 'fs'; import path from 'path'; import yaml from 'js-yaml'; import lodash from 'lodash'; const scriptCache = {}; export function clearCache() { Object.keys(scriptCache).forEach((key) => { scriptCache[key] = undefined; }); } function getCacheOrFile(key, fn) { if (scriptCache[key]) { return scriptCache[key]; } const value = fn(); scriptCache[key] = value; return value; } const travisCommands = [ // Reference: http://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle 'before_install', 'install', 'before_script', 'script', 'after_success or after_failure', 'before_deploy', 'after_deploy', 'after_script', ]; export default function getScripts(filepath, content = null) { return getCacheOrFile(filepath, () => { const basename = path.basename(filepath); const fileContent = content !== null ? content : fs.readFileSync(filepath, 'utf-8'); if (basename === 'package.json') { return lodash.values(JSON.parse(fileContent).scripts || {}); } if (basename === '.travis.yml') { const metadata = yaml.safeLoad(content) || {}; return lodash(travisCommands) .map((cmd) => metadata[cmd] || []) .flatten() .value(); } return []; }); }
JavaScript
0
@@ -452,16 +452,17 @@ ce: http +s ://docs. @@ -484,42 +484,13 @@ ser/ -customizing-the-build/#The-Build-L +job-l ifec @@ -558,16 +558,34 @@ cript',%0A + 'before_cache',%0A 'after @@ -596,12 +596,14 @@ cess - or +',%0A ' afte @@ -625,32 +625,44 @@ before_deploy',%0A + 'deploy',%0A 'after_deploy'
2b7c972c01cdcb06328b5ddeb7042f4ad35f2dea
add config options for mongo just to give some flexiblity
config_template.js
config_template.js
'use strict'; module.exports = { discord: { token: "DISCORD_TOKEN", adminRole: "Modteam" }, modules: { db : { url: "mongodb://localhost:27017/des" }, destiny: { apikey: "BUNGIE_TOKEN", url: "https://www.bungie.net/Platform/Destiny", defaultType: 2, collection: "destiny.manifest" }, voc: { psnChannel: "psn" }, welcome: { } }, commandPrefix: "d!", appDir: "", language: "en" };
JavaScript
0
@@ -157,44 +157,339 @@ -url: %22mongodb://localhost:27017/des%22 +// Update url with actual mongo connection string. %0A url: %22mongodb://localhost:27017/des%22,%0A // all options are optional%0A options: %7B %0A uri_decode_auth: %22%22%0A db: %22%22,%0A server: %22%22,%0A replSet: %22%22,%0A promiseLibrary: %22%22%0A %7D %0A
c2da5d736447ba1ac554a253d7c20429817c08d3
Make LAN the default URL type (#2841)
src/ProjectSettings.js
src/ProjectSettings.js
/** * @flow */ import _ from 'lodash'; import JsonFile from '@expo/json-file'; import fs from 'fs'; import mkdirp from 'mkdirp'; import path from 'path'; let projectSettingsFile = 'settings.json'; let projectSettingsDefaults = { hostType: 'tunnel', lanType: 'ip', dev: true, minify: false, urlRandomness: null, }; let packagerInfoFile = 'packager-info.json'; function projectSettingsJsonFile(projectRoot: string, filename: string) { return new JsonFile(path.join(dotExpoProjectDirectory(projectRoot), filename)); } export async function readAsync(projectRoot: string) { let projectSettings; try { projectSettings = await projectSettingsJsonFile(projectRoot, projectSettingsFile).readAsync(); } catch (e) { projectSettings = await projectSettingsJsonFile(projectRoot, projectSettingsFile).writeAsync( projectSettingsDefaults ); } if (projectSettings.hostType === 'ngrok') { // 'ngrok' is deprecated projectSettings.hostType = 'tunnel'; } if (projectSettings.urlType) { // urlType is deprecated as a project setting delete projectSettings.urlType; } if ('strict' in projectSettings) { // strict mode is not supported at the moment delete projectSettings.strict; } // Set defaults for any missing fields _.defaults(projectSettings, projectSettingsDefaults); return projectSettings; } export async function setAsync(projectRoot: string, json: any) { try { return await projectSettingsJsonFile(projectRoot, projectSettingsFile).mergeAsync(json, { cantReadFileDefault: projectSettingsDefaults, }); } catch (e) { return await projectSettingsJsonFile(projectRoot, projectSettingsFile).writeAsync( _.defaults(json, projectSettingsDefaults) ); } } export async function readPackagerInfoAsync(projectRoot: string) { try { return await projectSettingsJsonFile(projectRoot, packagerInfoFile).readAsync({ cantReadFileDefault: {}, }); } catch (e) { return await projectSettingsJsonFile(projectRoot, packagerInfoFile).writeAsync({}); } } export async function setPackagerInfoAsync(projectRoot: string, json: any) { try { return await projectSettingsJsonFile(projectRoot, packagerInfoFile).mergeAsync(json, { cantReadFileDefault: {}, }); } catch (e) { return await projectSettingsJsonFile(projectRoot, packagerInfoFile).writeAsync(json); } } export function dotExpoProjectDirectory(projectRoot: string) { let dirPath = path.join(projectRoot, '.expo'); try { // move .exponent to .expo let oldDirPath = path.join(projectRoot, '.exponent'); if (fs.statSync(oldDirPath).isDirectory()) { fs.renameSync(oldDirPath, dirPath); } } catch (e) { // no old directory, continue } mkdirp.sync(dirPath); return dirPath; } export function dotExpoProjectDirectoryExists(projectRoot: string) { let dirPath = path.join(projectRoot, '.expo'); try { if (fs.statSync(dirPath).isDirectory()) { return true; } } catch (e) { // file doesn't exist } return false; } export async function getPackagerOptsAsync(projectRoot: string) { let projectSettings = await readAsync(projectRoot); return projectSettings; }
JavaScript
0.000088
@@ -239,22 +239,19 @@ tType: ' -tunnel +lan ',%0A lan
fc8633b94d540989671845d1e5d611f689559278
Update assets/js/modules/adsense/datastore/service.js
assets/js/modules/adsense/datastore/service.js
assets/js/modules/adsense/datastore/service.js
/** * modules/adsense data store: service. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Wordpress dependencies */ import { addQueryArgs } from '@wordpress/url'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { STORE_NAME } from './constants'; import { STORE_NAME as CORE_USER } from '../../../googlesitekit/datastore/user/constants'; import { STORE_NAME as CORE_SITE } from '../../../googlesitekit/datastore/site/constants'; import { parseDomain } from '../util/url'; const { createRegistrySelector } = Data; export const selectors = { /** * Gets a URL to the service. * * @since n.e.x.t * * @param {Object} state Data store's state. * @param {Object} [args] Object containing optional path and query args * @param {string} [args.path] A path to append to the base url. * @param {Object} [args.query] Object of query params to be added to the URL. * @return {(string|undefined)} The URL to the service, or `undefined` if not loaded. */ getServiceURL: createRegistrySelector( ( select ) => ( state, { path, query } = {} ) => { const userEmail = select( CORE_USER ).getEmail(); if ( userEmail === undefined ) { return undefined; } const baseURI = 'https://www.google.com/adsense/new'; const queryParams = query ? { ...query, authuser: userEmail } : { authuser: userEmail }; if ( path ) { const sanitizedPath = `/${ path.replace( /^\//, '' ) }`; return addQueryArgs( `${ baseURI }${ sanitizedPath }`, queryParams ); } return addQueryArgs( baseURI, queryParams ); } ), /** * Returns the URL for creating a new AdSense account. * * @since n.e.x.t * * @return {string} AdSense URL to create a new account. */ getCreateAccountURL: createRegistrySelector( ( select ) => () => { const query = { source: 'site-kit', utm_source: 'site-kit', utm_medium: 'wordpress_signup', }; const siteURL = select( CORE_SITE ).getReferenceSiteURL(); if ( undefined !== siteURL ) { query.url = siteURL; } return addQueryArgs( 'https://www.google.com/adsense/signup/new', query ); } ), /** * Returns the URL to an AdSense account's overview page. * * @since n.e.x.t * * @return {string} AdSense account overview URL. */ getAccountURL: createRegistrySelector( ( select ) => () => { const accountID = select( STORE_NAME ).getAccountID(); if ( accountID === undefined ) { return undefined; } return select( STORE_NAME ).getServiceURL( { path: `${ accountID }/home`, query: { source: 'site-kit' } } ); } ), /** * Returns the URL to an AdSense account's site overview page. * * @since n.e.x.t * * @return {string} AdSense account site overview URL. */ getAccountSiteURL: createRegistrySelector( ( select ) => () => { const accountID = select( STORE_NAME ).getAccountID(); const siteURL = select( CORE_SITE ).getReferenceSiteURL(); if ( accountID === undefined || siteURL === undefined ) { return undefined; } const query = { // TODO: Check which of these parameters are actually required. source: 'site-kit', url: parseDomain( siteURL ) || siteURL, }; return select( STORE_NAME ).getServiceURL( { path: `${ accountID }/sites/my-sites`, query } ); } ), /** * Returns the URL to the AdSense site list overview * * @since n.e.x.t * * @return {string} AdSense account site list overview URL. */ getAccountSitesURL: createRegistrySelector( ( select ) => ( ) => { const accountID = select( STORE_NAME ).getAccountID(); if ( accountID === undefined ) { return undefined; } const query = { // TODO: Check which of these parameters are actually required. source: 'site-kit', utm_source: 'site-kit', }; return select( STORE_NAME ).getServiceURL( { path: `${ accountID }/sites/my-sites`, query } ); } ), /** * Returns the URL to an AdSense account's site ads preview page. * * @since n.e.x.t * * @return {string} AdSense account site ads preview URL. */ getAccountSiteAdsPreviewURL: createRegistrySelector( ( select ) => () => { const accountID = select( STORE_NAME ).getAccountID(); const siteURL = select( CORE_SITE ).getReferenceSiteURL(); if ( accountID === undefined || siteURL === undefined ) { return undefined; } const query = { source: 'site-kit', url: parseDomain( siteURL ) || siteURL, }; return select( STORE_NAME ).getServiceURL( { path: `${ accountID }/myads/sites/preview`, query } ); } ), }; const store = { selectors, }; export default store;
JavaScript
0
@@ -1836,16 +1836,20 @@ ense/new +/u/0 ';%0A%09%09con
e1984cd51accec2fb3d5bf9340bba8245ce98a81
modify slider code to use statechange event
app/static/js/script.js
app/static/js/script.js
var VPR = VPR || {}; VPR.activeIndex = VPR.submissions.indexOf(VPR.activeSlide); var slider = $('.bxslider').bxSlider({ infiniteLoop: false, controls: false, startSlide: VPR.activeIndex - 1 }); $('#slider_next').click(function(event) { event.preventDefault(); slider.goToNextSlide(); ++VPR.activeIndex; VPR.getOnDeck(VPR.activeIndex); History.pushState(null, null, VPR.submissions[VPR.activeIndex]); return false; }); $('#slider_prev').click(function(event) { event.preventDefault(); slider.goToPrevSlide(); --VPR.activeIndex; VPR.getPrevSlide(VPR.activeIndex); History.pushState(null, null, VPR.submissions[VPR.activeIndex]); return false; }); VPR.slide = $('#' + VPR.activeSlide); VPR.onDeck = function(idx) { if (typeof VPR.submissions[idx + 2] !== undefined) { return $('#' + VPR.submissions[idx + 2]); } else { return false; } }; VPR.getOnDeck = function() { var idx = VPR.activeIndex; if (idx + 2 < VPR.submissions.length) { var onDeckID = VPR.submissions[idx + 2]; if (!VPR.onDeck(idx).find('h2').length) { $.get('/' + onDeckID, function(data) { var onDeckSlide = $(data).find('#' + onDeckID); VPR.onDeck(idx).replaceWith(onDeckSlide); }); } VPR.getPrevSlide(); } }; VPR.prevSlide = function(idx) { if (typeof VPR.submissions[idx - 1] !== undefined) { return $('#' + VPR.submissions[idx - 1]); } else { return false; } }; VPR.getPrevSlide = function() { var idx = VPR.activeIndex; if (idx > 1) { var prevSlideID = VPR.submissions[idx - 1]; if (!VPR.prevSlide(idx).find('h2').length) { // this own't work for index $.get('/' + prevSlideID, function(data) { var prevSlide = $(data).find('#' + prevSlideID); VPR.prevSlide(idx).replaceWith(prevSlide); }); } } }; $(document).ready(function () { VPR.getOnDeck(); });
JavaScript
0
@@ -32,16 +32,57 @@ eIndex = + typeof VPR.submissions !== 'undefined' ? VPR.sub @@ -114,16 +114,23 @@ veSlide) + : null ;%0A%0Avar s @@ -163,16 +163,18 @@ lider(%7B%0A + infini @@ -190,16 +190,18 @@ alse,%0A + + controls @@ -209,16 +209,18 @@ false,%0A + startS @@ -240,20 +240,16 @@ iveIndex - - 1 %0A%7D);%0A%0A$( @@ -324,73 +324,70 @@ -slider.goToNextSlide();%0A ++VPR.activeIndex;%0A VPR.getOnDeck( +if ( VPR.activeIndex %3C slider.getSlideCount() - 1 ) %7B%0A VPR. @@ -389,35 +389,40 @@ VPR.activeIndex -);%0A +++;%0A History.push @@ -466,32 +466,39 @@ .activeIndex%5D);%0A + %7D%0A%0A return false @@ -582,76 +582,45 @@ -slider.goToPrevSlide();%0A --VPR.activeIndex;%0A VPR.getPrevSlide( +if ( VPR.activeIndex %3E 0 ) %7B%0A VPR. @@ -630,19 +630,24 @@ iveIndex -);%0A +--;%0A Hist @@ -703,24 +703,31 @@ iveIndex%5D);%0A + %7D%0A%0A return f @@ -733,24 +733,174 @@ false;%0A%7D);%0A%0A +History.Adapter.bind(window, 'statechange', function () %7B%0A slider.goToSlide(VPR.activeIndex);%0A VPR.getNextSlide();%0A VPR.getPrevSlide();%0A%7D);%0A%0A VPR.slide = @@ -1111,444 +1111,8 @@ %7D;%0A%0A -VPR.getOnDeck = function() %7B%0A var idx = VPR.activeIndex;%0A if (idx + 2 %3C VPR.submissions.length) %7B%0A var onDeckID = VPR.submissions%5Bidx + 2%5D;%0A if (!VPR.onDeck(idx).find('h2').length) %7B%0A $.get('/' + onDeckID, function(data) %7B%0A var onDeckSlide = $(data).find('#' + onDeckID);%0A VPR.onDeck(idx).replaceWith(onDeckSlide);%0A %7D);%0A %7D%0A VPR.getPrevSlide();%0A %7D%0A%7D;%0A%0A VPR. @@ -1733,16 +1733,431 @@ %7D%0A%7D;%0A%0A +VPR.getNextSlide = function() %7B%0A var idx = VPR.activeIndex;%0A if (idx + 2 %3C VPR.submissions.length) %7B%0A var onDeckID = VPR.submissions%5Bidx + 2%5D;%0A if (!VPR.onDeck(idx).find('h2').length) %7B%0A $.get('/' + onDeckID, function(data) %7B%0A var onDeckSlide = $(data).find('#' + onDeckID);%0A VPR.onDeck(idx).replaceWith(onDeckSlide);%0A %7D);%0A %7D%0A %7D%0A%7D;%0A%0A %0A$(docum @@ -2196,14 +2196,41 @@ .get -OnDeck +NextSlide();%0A VPR.getPrevSlide ();%0A
790d326ea0095168eb3b96113bafb93c25649a51
fix var reference issue
src/core/subscription.js
src/core/subscription.js
import * as os from 'os'; import * as moment from 'moment'; import Tyr from '../tyr'; import Collection from './collection'; import Query from './query'; const Subscription = new Collection({ id: '_t3', name: 'tyrSubscription', client: false, fields: { _id: { is: 'mongoid' }, u: { link: 'user', label: 'User' }, c: { is: 'string', label: 'Collection' }, q: { is: 'string', label: 'Query', note: 'Stringified MongoDB query.' }, on: { is: 'date' }, // TODO: this is temporary, long-term would like to hook up tyranid to session table and use that to // determine user -> instance bindings i: { is: 'string', label: 'Instance' }, } }); /* interface LocalListener { [collectionId: string]: { changeHandlerDereg: () => void, queries: { [queryStr: string]: { queryObj: MongoDBQuery, instances: { [instanceId: string]: boolean }, users: { [userId: string]: boolean } } } } } */ let localListeners /*: LocalListener*/ = {}; async function parseSubscriptions(subscription) { //con sole.log('parseSubscriptions(), Tyr.instanceId=', Tyr.instanceId); const subs = subscription ? [ subscription ] : await Subscription.findAll({}); //con sole.log(Tyr.instanceId + ' *** parseSubscriptions, ' + subs.length + ' subs'); if (!subscription) { // if we're reparsing all subs, clear out existing data for (const colId in localListeners) { const listener = localListeners[colId]; listener && changeHandlerDereg && changeHandlerDereg(); } localListeners = {}; } for (const sub of subs) { const colId = sub.c, col = Tyr.byId[colId]; let listener = localListeners[colId]; if (!localListeners[colId]) { const changeHandlerDereg = col.on({ type: 'change', handler: async event => { //con sole.log(Tyr.instanceId + ' *** ' + col.def.name + ' change:');//, event); const { document, query, _documents } = event; for (const queryStr in listener.queries) { const queryDef = listener.queries[queryStr]; let refinedDocument = document, refinedQuery = query; async function fireEvent() { //con sole.log(Tyr.instanceId + ' *** matched'); //con sole.log(Tyr.instanceId + ' *** queryDef.instances', queryDef.instances); for (const instanceId in queryDef.instances) { const event = new Tyr.Event({ collection: Subscription, dataCollectionId: colId, query: refinedQuery, document: refinedDocument, type: 'subscriptionEvent', when: 'pre', instanceId: instanceId }); if (instanceId === Tyr.instanceId) { handleSubscriptionEvent(event); } else { await Tyr.Event.fire(event); } } } if (document) { if (!Query.matches(queryDef.queryObj, document)) continue; refinedQuery = undefined; await fireEvent(); } else if (_documents) { refinedQuery = undefined; for (const doc of _documents) { if (Query.matches(queryDef.queryObj, doc)) { refinedDocument = doc; await fireEvent(); } } } else /*if (query)*/ { refinedQuery = Query.intersection(queryDef.queryObj, query); if (!refinedQuery) continue; await fireEvent(); } } } }); listener = localListeners[colId] = { changeHandlerDereg, queries: {} }; } const queryStr = sub.q; let queryDef = listener.queries[queryStr]; if (!queryDef) { queryDef = listener.queries[queryStr] = { queryObj: col.fromClientQuery(JSON.parse(queryStr)), instances: {}, users: {} }; } queryDef.instances[sub.i] = true; queryDef.users[sub.u] = true; } } Subscription.on({ type: 'subscribe', async handler(event) { await parseSubscriptions(event.subscription); } }); Subscription.on({ type: 'unsubscribe', async handler(event) { // TODO: pass in user and only unsubscribe the user rather than reparsing? await parseSubscriptions(); } }); //let bootNeeded = 'Subscription needs to be booted'; Subscription.boot = async function(stage, pass) { if (stage === 'link' && Tyr.db) { //if (bootNeeded) { await parseSubscriptions(); //bootNeeded = undefined; //} return undefined; //bootNeeded; } }; Collection.prototype.subscribe = async function(query, user, cancel) { //con sole.log(Tyr.instanceId + ' *** subscribe:', query, user, cancel); const queryStr = JSON.stringify(query); if (!query) { if (cancel) { await Subscription.remove({ query: { u: user._id, c: this.id } }); await Tyr.Event.fire({ collection: Subscription, type: 'unsubscribe', when: 'pre', broadcast: true }); return; } else { throw new Error('missing query'); } } const subscription = await Subscription.findOne({ query: { u: user._id, c: this.id, q: queryStr } }); if (cancel) { if (subscription) { await subscription.$remove(); await Tyr.Event.fire({ collection: Subscription, type: 'unsubscribe', when: 'pre', broadcast: true }); } return; } if (!subscription || subscription.i !== Tyr.instanceId) { let s = subscription; if (s) { s.on = new Date(); s.i = Tyr.instanceId; } else { s = new Subscription({ u: user._id, c: this.id, q: queryStr, on: new Date(), i: Tyr.instanceId }); } await s.$save(); await Tyr.Event.fire({ collection: Subscription, type: 'subscribe', when: 'pre', broadcast: true, subscription: s }); } }; Subscription.unsubscribe = async function(userId) { const rslts = await Subscription.remove({ query: { u: userId } }); if (rslts.result.n) { await Tyr.Event.fire({ collection: Subscription, type: 'unsubscribe', when: 'pre', broadcast: true }); } }; async function handleSubscriptionEvent(event) { //con sole.log(Tyr.instanceId + ' *** handleSubscriptionEvent:');//, event); const col = event.dataCollection, listener = localListeners[col.id], mQuery = event.query, mDoc = event.document; if (listener) { const userIds = {}; for (const queryStr in listener.queries) { const queryDef = listener.queries[queryStr]; if (mQuery) { if (Query.intersection(queryDef.query, mQuery)) { for (const userId in queryDef.users) { userIds[userId] = true; } } } else { // if mDoc if (Query.matches(queryDef.query, mDoc)) { for (const userId in queryDef.users) { userIds[userId] = true; } } } } const documents = await event.documents; const sockets = Tyr.io.sockets.sockets; for (const socketId in sockets) { const socket = sockets[socketId]; if (userIds[socket.userId]) { socket.emit('subscriptionEvent', { colId: event.dataCollectionId, docs: documents.map(doc => doc.$toClient()) }); } } } } Subscription.on({ type: 'subscriptionEvent', handler: handleSubscriptionEvent }); export default Subscription;
JavaScript
0
@@ -1546,24 +1546,33 @@ listener && +listener. changeHandle @@ -1581,16 +1581,25 @@ ereg && +listener. changeHa
ae5cd5e49fda871713661c4b2ae21c06b005c44f
add code tag spec
spec/doc-renderer/custom-filters/code.spec.js
spec/doc-renderer/custom-filters/code.spec.js
var rewire = require('rewire'); var filter = rewire('../../../lib/doc-renderer/custom-filters/code'); describe("code custom filter", function() { var markedMock; beforeEach(function() { markedMock = jasmine.createSpy('marked').andReturn('<code>bar</code>'); filter.__set__('marked', markedMock); }); it("should have the name 'code'", function() { expect(filter.name).toEqual('code'); }); it("should transform the content using the provided marked function, wrapped in back-ticks", function() { expect(filter.process('foo')).toEqual('<code>bar</code>'); expect(markedMock).toHaveBeenCalledWith('`foo`'); }); });
JavaScript
0.000001
@@ -163,158 +163,8 @@ k;%0A%0A - beforeEach(function() %7B%0A markedMock = jasmine.createSpy('marked').andReturn('%3Ccode%3Ebar%3C/code%3E');%0A filter.__set__('marked', markedMock);%0A %7D);%0A it @@ -328,31 +328,30 @@ tion -, wrapped in back-ticks + into highlighted code %22, f @@ -394,93 +394,298 @@ s('f -oo')).toEqual('%3Ccode%3Ebar%3C/code%3E');%0A expect(markedMock).toHaveBeenCalledWith('%60foo%60 +unction foo() %7B %7D')).toEqual(%0A '%3Ccode class=%22prettyprint linenum%22%3E'+%0A '%3Cspan class=%22function%22%3E' +%0A '%3Cspan class=%22keyword%22%3Efunction%3C/span%3E '+%0A '%3Cspan class=%22title%22%3Efoo%3C/span%3E' +%0A '%3Cspan class=%22params%22%3E()%3C/span%3E %7B' +%0A '%3C/span%3E %7D' +%0A '%3C/code%3E ');%0A
182662eb2607a115586406d0edda88cb5072d27f
comment out mongo connection
devServer.js
devServer.js
var path = require('path'); var express = require('express'); var webpack = require('webpack'); var config = require('./webpack.config.dev'); var app = express(); var compiler = webpack(config); app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(require('webpack-hot-middleware')(compiler)); app.use(express.static('public')); app.use('/public', express.static('public')); app.use(express.static('public')) // DATABASE var mongoose = require('mongoose'); mongoose.connect('mongodb://<dbuser>:<dbpassword>@ds153845.mlab.com:53845/inspectionlog'); var Schema = mongoose.Schema; var inspectionSchema = new Schema({ address: { line1: String, line2: String, city: String, state: String, zip: String, }, clientStatus: String, recordsOnFile: { proposal: Boolean, engagementLetter: Boolean, invoice: Boolean }, dobAppNum: String, specialInspectionType: { tr1: Boolean, tr8: Boolean }, copiesOfInitialReports: { tr1: Boolean, tr8: Boolean }, dateOfInspection: Date, inspectorName: String, typeOfInspection: { progress: [Date], final: Date }, itemInspected: [String], inspectionReportOnFile: Boolean, inspectionResultsPass: Boolean, copiesOfFinalReports: { tr1: Boolean, tr8: Boolean }, jobSignOffDate: Date, comments: [String] }); var Inspection = mongoose.model('Inspection', inspectionSchema); // ROUTES app.get('*', function(req, res) { res.sendFile(path.join(__dirname, 'index.html')); }); app.listen(3000, function(err) { if (err) { console.log(err); return; } console.log('Listening at http://localhost:3000'); });
JavaScript
0
@@ -527,16 +527,19 @@ oose');%0A +// mongoose
b93b59119f6f1a189d54c946f258ac12ebd2e5e4
Fix #124 - include error details in mocha unit test results - use the 'tap' eror reporter instead of xunit because 'xunit' does not print the trace.
Nodejs/Product/Nodejs/TestFrameworks/mocha/mocha.js
Nodejs/Product/Nodejs/TestFrameworks/mocha/mocha.js
var fs = require('fs'); var find_tests = function (testFileList, discoverResultFile, projectFolder) { var Mocha = detectMocha(projectFolder); if (!Mocha) { return; } function getTestList(suite, testFile) { if (suite) { if (suite.tests && suite.tests.length !== 0) { suite.tests.forEach(function (t, i, testArray) { testList.push({ test: t.fullTitle(), suite: suite.fullTitle(), file: testFile, line: 0, column: 0 }); }); } if (suite.suites) { suite.suites.forEach(function (s, i, suiteArray) { getTestList(s, testFile); }); } } } var testList = []; testFileList.split(';').forEach(function (testFile) { var mocha = new Mocha(); try { mocha.ui('tdd'); mocha.addFile(testFile); mocha.loadFiles(); getTestList(mocha.suite, testFile); } catch (e) { //we would like continue discover other files, so swallow, log and continue; console.error('catch discover error:' + e); } }); var fd = fs.openSync(discoverResultFile, 'w'); fs.writeSync(fd, JSON.stringify(testList)); fs.closeSync(fd); }; module.exports.find_tests = find_tests; var run_tests = function (testName, testFile, workingFolder, projectFolder) { var Mocha = detectMocha(projectFolder); if (!Mocha) { return; } var mocha = new Mocha(); mocha.ui('tdd'); //set timeout to 10 minutes, because the default of 2 sec might be too short (TODO: make it configurable) mocha.suite.timeout(600000); if (testName) { mocha.grep(testName); } mocha.addFile(testFile); //Choose 'xunit' rather 'min'. The reason is when under piped/redirect, //mocha produces undisplayable text to stdout and stderr. Using xunit works fine mocha.reporter('xunit'); mocha.run(function (code) { process.exit(code); }); }; function detectMocha(projectFolder) { try { var Mocha = new require(projectFolder + '\\node_modules\\mocha'); return Mocha; } catch (ex) { console.log("NTVS_ERROR:Failed to find Mocha package. Mocha must be installed in the project locally. Mocha can be installed locally with the npm manager via solution explorer or with \".npm install mocha\" via the Node.js interactive window."); return null; } } module.exports.run_tests = run_tests;
JavaScript
0
@@ -1938,16 +1938,17 @@ // + Choose ' xuni @@ -1943,21 +1943,19 @@ Choose ' -xunit +tap ' rather @@ -2009,16 +2009,17 @@ ,%0A // + mocha pr @@ -2090,16 +2090,81 @@ s fine %0A + // And 'xunit' does not print the stack trace from the test.%0A moch @@ -2175,21 +2175,19 @@ porter(' -xunit +tap ');%0A
ab41e46437ee5938ddab78ba8ea862258b9e79ef
Default name '[unnamed]' if existing name is empty
lib/EntrySelector/EntrySelector.js
lib/EntrySelector/EntrySelector.js
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import Switch from 'react-router-dom/Switch'; import Route from 'react-router-dom/Route'; import Link from 'react-router-dom/Link'; import Icon from '../Icon'; import Paneset from '../Paneset'; import Pane from '../Pane'; import PaneMenu from '../PaneMenu'; import NavList from '../NavList'; import NavListSection from '../NavListSection'; class EntrySelector extends React.Component { static propTypes = { addButtonTitle: PropTypes.string, detailComponent: PropTypes.func.isRequired, parentMutator: PropTypes.object.isRequired, location: PropTypes.object.isRequired, allEntries: PropTypes.arrayOf( PropTypes.object, ).isRequired, entryCreator: PropTypes.func.isRequired, paneTitle: PropTypes.string, history: PropTypes.shape({ push: PropTypes.func.isRequired, }).isRequired, match: PropTypes.shape({ path: PropTypes.string.isRequired, }).isRequired, }; constructor(props) { super(props); this.state = { creatingEntry: false, }; this.activeLink = this.activeLink.bind(this); this.clearSelection = this.clearSelection.bind(this); this.linkPath = this.linkPath.bind(this); this.onClickAdd = this.onClickAdd.bind(this); } componentDidUpdate(prevProps) { // If a new item has been added to the list, push it to history to gain focus if (this.state.creatingEntry) { const entryDiffs = _.differenceBy(this.props.allEntries, prevProps.allEntries, 'id'); this.props.history.push(`${this.props.match.path}/${entryDiffs[0].id}`); // eslint-disable-next-line react/no-did-update-set-state this.setState({ creatingEntry: false, }); } } onClickAdd() { this.setState({ creatingEntry: true, }); this.props.entryCreator(); } clearSelection() { const { allEntries } = this.props; let id; if (allEntries.length > 0) { id = allEntries[0].id; } this.props.history.push(`${this.props.match.path}/${id}`); } linkPath(id) { return `${this.props.match.path}/${id}`; } activeLink(links) { return this.props.location.pathname || this.linkPath(links[0].key); } render() { const { addButtonTitle, allEntries, paneTitle, parentMutator } = this.props; const links = _.sortBy(allEntries, ['name']).map(e => ( <Link key={e.id} to={this.linkPath(e.id)}>{e.name}</Link> )); const ComponentToRender = this.props.detailComponent; const routes = allEntries.map(e => ( <Route key={e.id} path={this.linkPath(e.id)} render={() => ( <Pane paneTitle={e.name} defaultWidth="fill"> <ComponentToRender clearSelection={this.clearSelection} initialValues={e} loanPolicies={allEntries} parentMutator={parentMutator} /> </Pane> )} /> )); const LastMenu = ( <PaneMenu> <button title={addButtonTitle} onClick={this.onClickAdd}> <Icon icon="plus-sign" /> </button> </PaneMenu> ); return ( <Paneset nested defaultWidth="fill"> <Pane defaultWidth="25%" lastMenu={LastMenu} paneTitle={paneTitle}> <NavList> <NavListSection activeLink={this.activeLink(links)}> {links} </NavListSection> </NavList> </Pane> <Switch> {routes} </Switch> </Paneset> ); } } export default EntrySelector;
JavaScript
0.999286
@@ -2448,24 +2448,45 @@ (e.id)%7D%3E +xx %7Be.name -%7D + %7C%7C '%5Bunnamed%5D'%7D yy %3C/Link%3E%0A
5f2373314f039c5f48820b01bd01d64306f16c02
correct code for spinner
demo/views/misc/spinner-demo/spinner-demo.js
demo/views/misc/spinner-demo/spinner-demo.js
import React from 'react'; import { connect } from 'utils/flux'; import AppStore from './../../../stores/app'; import AppActions from './../../../actions/app'; import Example from './../../../components/example'; import Spinner from 'components/spinner'; import Row from 'components/row'; import RadioButton from 'components/radio-button'; class SpinnerDemo extends React.Component { /** * @method value */ value = (key) => { return this.state.appStore.getIn(['spinner', key]); } /** * @method action */ get action() { return AppActions.appValueUpdated.bind(this, 'spinner'); } /** * @method demo */ get demo() { return ( <div className='spinner-demo__spinner' > <Spinner as={ this.value('as') } size={ this.value('size') } /> </div> ); } /** * @method code */ get code() { let html = "import Spinner from 'carbon/lib/components/spinner';\n\n"; html += "<Spinner"; html += ` as={ ${this.value('as')} }` html += ` size={ ${this.value('size')} }` html += "/>\n\n"; return html; } /** * @method controls */ get controls() { return ( <div> <h2>Size</h2> <Row> <RadioButton onClick={ this.action.bind(this, 'size') } name='size' value='small' label='Small'/> <RadioButton onClick={ this.action.bind(this, 'size') } name='size' value='smed' label='Small-Medium' /> <RadioButton defaultChecked={ true } onClick={ this.action.bind(this, 'size') } name='size' value='lmed' label='Large-Medium'/> <RadioButton onClick={ this.action.bind(this, 'size') } name='size' value='large' label='Large' /> </Row> <h2>As</h2> <Row> <RadioButton defaultChecked={ true } onClick={ this.action.bind(this, 'as') } name='as' value='info' label='Info'/> <RadioButton onClick={ this.action.bind(this, 'as') } name='as' value='error' label='Error' /> <RadioButton onClick={ this.action.bind(this, 'as') } name='as' value='help' label='Help'/> </Row> <Row> <RadioButton onClick={ this.action.bind(this, 'as') } name='as' value='maintenance' label='Maintenance' /> <RadioButton onClick={ this.action.bind(this, 'as') } name='as' value='new' label='New' /> <RadioButton onClick={ this.action.bind(this, 'as') } name='as' value='success' label='Success' /> </Row> <Row> <RadioButton onClick={ this.action.bind(this, 'as') } name='as' value='warning' label='Warning' /> </Row> </div> ); } /** * @method render */ render() { return ( <Example title="Spinner" readme="components/spinner" demo={ this.demo } code={ this.code } controls={ this.controls } /> ); } } export default connect(SpinnerDemo, AppStore);
JavaScript
0.000181
@@ -972,18 +972,17 @@ += %60 as= -%7B +' $%7Bthis.v @@ -992,18 +992,17 @@ e('as')%7D - %7D +' %60%0A ht @@ -1014,18 +1014,17 @@ %60 size= -%7B +' $%7Bthis.v @@ -1036,18 +1036,17 @@ 'size')%7D - %7D +' %60%0A ht
1541bc0ee773c20594aab9a7b330d4f7559d31c7
Add the ga -> GA acronym into the base tag manager store.
assets/js/modules/tagmanager/datastore/base.js
assets/js/modules/tagmanager/datastore/base.js
/** * `modules/tagmanager` base data store * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import Modules from 'googlesitekit-modules'; import { STORE_NAME } from './constants'; import { submitChanges, validateCanSubmitChanges } from './settings'; let baseModuleStore = Modules.createModuleStore( 'tagmanager', { storeName: STORE_NAME, settingSlugs: [ 'accountID', 'ampContainerID', 'containerID', 'internalContainerID', 'internalAMPContainerID', 'useSnippet', 'ownerID', 'gaPropertyID', ], submitChanges, validateCanSubmitChanges, } ); // Rename generated pieces to adhere to our convention. baseModuleStore = ( ( { actions, selectors, ...store } ) => { // eslint-disable-next-line sitekit/acronym-case const { setAmpContainerID, ...restActions } = actions; // eslint-disable-next-line sitekit/acronym-case const { getAmpContainerID, ...restSelectors } = selectors; return { ...store, actions: { ...restActions, // eslint-disable-next-line sitekit/acronym-case setAMPContainerID: setAmpContainerID, }, selectors: { ...restSelectors, // eslint-disable-next-line sitekit/acronym-case getAMPContainerID: getAmpContainerID, }, }; } )( baseModuleStore ); export default baseModuleStore;
JavaScript
0.000001
@@ -1342,32 +1342,49 @@ tAmpContainerID, + setGaPropertyID, ...restActions @@ -1396,16 +1396,16 @@ ctions;%0A - %09// esli @@ -1473,16 +1473,33 @@ ainerID, + getGaPropertyID, ...rest @@ -1667,24 +1667,113 @@ ontainerID,%0A +%09%09%09// eslint-disable-next-line sitekit/acronym-case%0A%09%09%09setGAPropertyID: setGaPropertyID,%0A %09%09%7D,%0A%09%09selec @@ -1853,16 +1853,16 @@ ym-case%0A - %09%09%09getAM @@ -1890,24 +1890,113 @@ ontainerID,%0A +%09%09%09// eslint-disable-next-line sitekit/acronym-case%0A%09%09%09getGAPropertyID: getGaPropertyID,%0A %09%09%7D,%0A%09%7D;%0A%7D )
de965dbb184beba300503c8a9d42f41d8173879e
Fix picked color sometimes undefined
notSquare.js
notSquare.js
var squares = document.querySelectorAll(".square"); var colors = []; for (var i = squares.length - 1; i >= 0; i--) { colors.push(getRandomRGB()); } var pickedColor = colors[getRandomInt(0, colors.length + 1)]; var h1 = document.querySelector('h1'); var t = document.createTextNode(' ' + pickedColor); h1.appendChild(t); function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; } function getRandomRGB() { var red = getRandomInt(0, 256); var green = getRandomInt(0, 256); var blue = getRandomInt(0, 256); var rgb = "rgb(" + red + ", " + green + ", " + blue + ")"; return rgb; } var colorCounter = 0; squares.forEach(function(square) { square.style.backgroundColor = colors[colorCounter]; colorCounter++; square.addEventListener('click', function() { if (square.style.backgroundColor === pickedColor) { alert("You're right!!") } else { alert("WRONG!") square.style.backgroundColor = '#232323'; } }) });
JavaScript
0.000001
@@ -204,12 +204,8 @@ ngth - + 1 )%5D;%0A @@ -990,30 +990,8 @@ e %7B%0A - alert(%22WRONG!%22)%0A
72e8b0e9d1989b6506cfee32c9df00f34bbc26b9
sort city names
js/chart.js
js/chart.js
define(["d3", "lodash", "baseChart", "heatMap"], function(d3, _, BaseChart, HeatMap) { // base svg chart, which auto resizes to fit containing element var module = function($chartNode, customOptions, extendedEvents) { var sensorMap = null; var cities = null; var localEvents = []; var localOptions = {}; var dimensions = null; var width = null; var height = null; var svg = null; var baseChart = new BaseChart($chartNode, localOptions, localEvents); baseChart.visualize = visualize; baseChart.setOptions(customOptions); baseChart.on('chartResize', onResize); var margin = {top: 70, right: 20, bottom: 20, left: 20}; var cityScale = d3.scale.ordinal(); var color = d3.scale.linear().range(["white", "blue"]); var colorScale = d3.scale.category10(); var offset = 0; var cityOrder = { "San Francisco": 0, "Boston": 1, "Rio de Janeiro": 2, "Genève": 3, "ಬೆಂಗಳೂರು": 4, "Republik Singapura": 5, "上海市": 6 }; function initialize() { baseChart.initialize(); onResize(baseChart.getDimensions()); svg = baseChart.getContainer() .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); svg.append('text') .classed('type-title', true) .attr('text-anchor', 'middle') .attr('y', margin.top / -2) .attr('dy', '1em') .text('Air Quaility'); visualize(); } function setData(data) { sensorMap = SENSORS.map(function(sensor) { return { extent: d3.extent(data, function(d) {return d[sensor];}), name: sensor }; }).reduce(function(p, c) { p[c.name] = { extent: c.extent, color: d3.scale.linear() .range(["white", colorScale(c.name)]) .domain(c.extent) }; return p; }, {}); var cityMap = d3.nest() .key(function(d) { return d.city_name; }) .map(data); var cityNames = Object.keys(cityMap); cityScale.domain(cityNames); cities = cityNames.map(function(name) { var group = svg.append('g').classed(name, true); var city = { name: name, group: group, map: new HeatMap(group, function(d) {return d.id;}), data: cityMap[name] }; city.group.append('text').classed('city-title', true).text(city.name); city.map.color(function(d) { return color(d.value); }); return city; }).sort(function(a,b){ return cityOrder[a] - cityOrder[b]; }); visualize(); } var ROW_COUNT = 7; var COL_COUNT = 24; function setFrame(type, offset) { color = sensorMap[type].color; d3.select('.type-title').text(SENSOR_TITLE[type]); cities.forEach(function(city) { var rows = d3.range(ROW_COUNT).map(function(row) { var base = offset + row * COL_COUNT; return city.data.slice(base, base + COL_COUNT).map(function(d) { return { id: d.date, type: type, value: d[type] }; }); }); city.map.setData(rows); }); visualize(); } function onResize(_dimensions) { dimensions = _dimensions; width = dimensions.width - (margin.left + margin.right); height = dimensions.height - (margin.top + margin.bottom); cityScale.rangeBands([0, height], .2); visualize(); } function visualize() { if (!svg || !cities) return; svg .select('text.type-title') .attr('x', width / 2); cities.forEach(function(city) { city.group.attr('transform', 'translate(0, ' + cityScale(city.name) + ')'); city.map.visualize(width, cityScale.rangeBand()); }); } // exports var exports = { setData: setData, setFrame: setFrame }; initialize(CITIES); return $.extend(exports, baseChart); }; // end module return module; });
JavaScript
0.999861
@@ -894,17 +894,16 @@ %C3%A8ve%22: 3, - %0A%09 %22%E0%B2%AC%E0%B3%86%E0%B2%82 @@ -912,17 +912,16 @@ %E0%B3%82%E0%B2%B0%E0%B3%81%22: 4, - %0A%09 %22Rep @@ -1941,17 +1941,87 @@ cityMap) -; +.sort(function(a,b)%7B%0A return cityOrder%5Ba%5D - cityOrder%5Bb%5D;%0A %7D);%0A %0A cit @@ -2483,76 +2483,8 @@ ty;%0A - %7D).sort(function(a,b)%7B%0A %09return cityOrder%5Ba%5D - cityOrder%5Bb%5D;%0A
6192fcbb32065a56cb0e5b4b4afac8805d5c4629
add missing braces - fixed
lib/xlsx/xform/drawing/two-cell-anchor-xform.js
lib/xlsx/xform/drawing/two-cell-anchor-xform.js
/** * Copyright (c) 2016-2017 Guyon Roche * LICENCE: MIT - please refer to LICENCE file included with this module * or https://github.com/guyonroche/exceljs/blob/master/LICENSE */ 'use strict'; var utils = require('../../../utils/utils'); var colCache = require('../../../utils/col-cache'); var BaseXform = require('../base-xform'); var StaticXform = require('../static-xform'); var CellPositionXform = require('./cell-position-xform'); var PicXform = require('./pic-xform'); var TwoCellAnchorXform = module.exports = function() { this.map = { 'xdr:from': new CellPositionXform({tag: 'xdr:from'}), 'xdr:to': new CellPositionXform({tag: 'xdr:to'}), 'xdr:pic': new PicXform(), 'xdr:clientData': new StaticXform({tag: 'xdr:clientData'}), }; }; utils.inherits(TwoCellAnchorXform, BaseXform, { get tag() { return 'xdr:twoCellAnchor'; }, prepare: function(model, options) { this.map['xdr:pic'].prepare(model.picture, options); // convert model.range into tl, br if (typeof model.range === 'string') { var range = colCache.decode(model.range); // Note - zero based model.tl = { col: range.left - 1, row: range.top - 1 }; // zero based but also +1 to cover to bottom right of br cell model.br = { col: range.right, row: range.bottom }; } else { model.tl = model.range.tl; model.br = model.range.br; } }, render: function(xmlStream, model) { if(model.range.editAs) xmlStream.openNode(this.tag, {editAs: model.range.editAs}); else xmlStream.openNode(this.tag); model.tl.editAsOneCell = model.range.editAs == 'oneCell'; model.br.editAsOneCell = model.range.editAs == 'oneCell'; this.map['xdr:from'].render(xmlStream, model.tl); this.map['xdr:to'].render(xmlStream, model.br); this.map['xdr:pic'].render(xmlStream, model.picture); this.map['xdr:clientData'].render(xmlStream, {}); xmlStream.closeNode(); }, parseOpen: function(node) { if (this.parser) { this.parser.parseOpen(node); return true; } switch (node.name) { case this.tag: this.reset(); this.model = { editAs: node.attributes['editAs'] }; break; default: this.parser = this.map[node.name]; if (this.parser) { this.parser.parseOpen(node); } break; } return true; }, parseText: function(text) { if (this.parser) { this.parser.parseText(text); } }, parseClose: function(name) { if (this.parser) { if (!this.parser.parseClose(name)) { this.parser = undefined; } return true; } switch (name) { case this.tag: this.model = this.model || {}; this.model.tl = this.map['xdr:from'].model; this.model.br = this.map['xdr:to'].model; this.model.picture = this.map['xdr:pic'].model; return false; default: // could be some unrecognised tags return true; } }, reconcile: function(model, options) { var rel = options.rels[model.picture.rId]; var match = rel.Target.match(/.*\/media\/(.+[.][a-z]{3,4})/); if (match) { var name = match[1]; var mediaId = options.mediaIndex[name]; model.medium = options.media[mediaId]; } if (Number.isInteger(model.tl.row) && Number.isInteger(model.tl.col) && Number.isInteger(model.br.row) && Number.isInteger(model.br.col)) { model.range = colCache.encode(model.tl.row + 1, model.tl.col + 1, model.br.row, model.br.col); } else { model.range = { tl: model.tl, br: model.br, }; } if (model.editAs) { model.range.editAs = model.editAs; delete model.editAs; } delete model.tl; delete model.br; } });
JavaScript
0
@@ -1478,16 +1478,17 @@ %7B%0A if + (model.r @@ -1499,16 +1499,18 @@ .editAs) + %7B %0A x @@ -1571,21 +1571,25 @@ s%7D);%0A + %7D else + %7B %0A x @@ -1617,16 +1617,22 @@ s.tag);%0A + %7D%0A mode @@ -1665,32 +1665,33 @@ .range.editAs == += 'oneCell';%0A @@ -1736,16 +1736,17 @@ ditAs == += 'oneCel @@ -2243,18 +2243,15 @@ utes -%5B' +. editAs -'%5D %0A
120042fc5b4fdd83adf77aaf07f73ced60a5868b
Fix 'specified' typo in parseOptionsTest
test/parseOptionsTest.js
test/parseOptionsTest.js
import {expect} from 'chai'; import commander from 'commander'; import parseOptions from './../src/parseOptions'; function parse(argv) { return parseOptions(['node', 'script.js'].concat(argv)); } describe('Command Line Interface', () => { // Command line parser uses commander which has global state. // To be able to test different command-line combinations, // we'll need to reset the state between tests. beforeEach(() => { commander.outFile = undefined; commander.transform = undefined; }); it('when no transforms given, throws error', () => { expect(() => { parse([]); }).to.throw('No transforms specifed :('); }); it('when single transforms given, enables it', () => { const options = parse(['-t', 'class']); expect(options.transforms).to.deep.equal([ 'class', ]); }); it('when --transfrom=let,no-strict,commonjs given, enables only these transforms', () => { const options = parse(['--transform', 'let,no-strict,commonjs']); expect(options.transforms).to.deep.equal([ 'let', 'no-strict', 'commonjs', ]); }); it('when --transform=unknown given, raises error', () => { expect(() => { parse(['--transform', 'unknown']); }).to.throw('Unknown transform "unknown".'); }); it('by default reads STDIN and writes to STDOUT', () => { const options = parse(['-t', 'class']); expect(options.inFile).to.equal(undefined); expect(options.outFile).to.equal(undefined); expect(options.replace).to.equal(undefined); }); it('when existing <filename> given reads <filename> and writes to STDOUT', () => { const options = parse(['-t', 'class', 'lib/io.js']); expect(options.inFile).to.equal('lib/io.js'); expect(options.outFile).to.equal(undefined); expect(options.replace).to.equal(undefined); }); it('when not-existing <filename> given raises error', () => { expect(() => { parse(['-t', 'class', 'missing.js']); }).to.throw('File missing.js does not exist.'); }); it('when more than one <filename> given raises error', () => { expect(() => { parse(['-t', 'class', 'lib/io.js', 'lib/transformer.js']); }).to.throw('Only one input file allowed, but 2 given instead.'); }); it('when --out-file <filename> given writes <filename> and reads STDIN', () => { const options = parse(['-t', 'class', '--out-file', 'some/file.js']); expect(options.inFile).to.equal(undefined); expect(options.outFile).to.equal('some/file.js'); expect(options.replace).to.equal(undefined); }); it('when --replace <dirname> given transforms all files in glob pattern', () => { const options = parse(['-t', 'class', '--replace', '*.js']); expect(options.inFile).to.equal(undefined); expect(options.outFile).to.equal(undefined); expect(options.replace).to.equal('*.js'); }); it('when --replace used together with input file, raises error', () => { expect(() => { parse(['-t', 'class', '--replace', 'lib/', 'lib/io.js']); }).to.throw('The --replace and plain input file options cannot be used together.'); }); it('when --replace used together with outout file, raises error', () => { expect(() => { parse(['-t', 'class', '--replace', 'lib/', '-o', 'some/file.js']); }).to.throw('The --replace and --out-file options cannot be used together.'); }); it('when --replace used with existing dir name, turns it into glob pattern', () => { const options = parse(['-t', 'class', '--replace', 'lib/']); expect(options.inFile).to.equal(undefined); expect(options.outFile).to.equal(undefined); expect(options.replace).to.be.oneOf(['lib/**/*.js', 'lib\\**\\*.js']); }); });
JavaScript
0.022184
@@ -639,16 +639,17 @@ s specif +i ed :(');
d3b66daf1e8e87fdc6d990a314cd02eca94b2f68
Fix bug for non sentral users, causing JS to break.
public/scripts/models/user.js
public/scripts/models/user.js
/* * Copyright (c) $year, Den Norske Turistforening (DNT) * * https://github.com/Turistforeningen/turadmin */ define(function (require, exports, module) { "use strict"; // Dependencies var $ = require('jquery'), _ = require('underscore'), Backbone = require('backbone'), state = require('state'); // Module return Backbone.Model.extend({ idAttribute: '_id', type: 'user', defaults: {}, initialize: function (options) { // TODO: Major options = state.userData; options.grupper = state.userGroups; var additionalGroups = state.groupsData || []; // Check if user is member of all groups that the route is associated with // If not, add the missing groups to the user groups array // NOTE: The better (and more complicated) way to solve this would be to have two separate arrays, // but the current way be an acceptable solution, as the group will only be available in the // user groups array while the user is editing an object already associated with the group for (var i = 0; i < additionalGroups.length; i++) { var additionalGroup = additionalGroups[i]; var additionalGroupId = additionalGroup._id; if (!_.findWhere(options.grupper, {object_id: additionalGroupId})) { var group = { object_id: additionalGroup._id, navn: additionalGroup.navn }; if (!!additionalGroup.privat && !!additionalGroup.privat.sherpa2_id) { group.sherpa_id = additionalGroup.privat.sherpa2_id; } options.grupper.push(group); } } this.set('epost', options.epost); this.set('grupper', options.grupper); this.set('navn', options.navn); options = options || {}; var userType, id, navn; // Possible userType values: 'sherpa', 'mittnrk', 'gruppebruker' id = options._id; switch(options.provider) { case 'DNT Connect': // Special handling of DNT Connect users break; case 'Mitt NRK': // Special handling of Mitt NRK users break; case 'Innholdspartner': // Special handling of Innholdspartner users if (!!options.gruppe && !!options.gruppe._id) { this.set('gruppe', options.gruppe._id); } break; default: // No default } this.set('provider', options.provider); if (!this.get('navn') && (!!options.fornavn && !!options.etternavn)) { this.set('navn', options.fornavn + ' ' + options.etternavn); } var grupper = this.get('grupper'); var admin = !!_.findWhere(grupper, {navn: 'Den Norske Turistforening'}); this.set('admin', admin); // NOTE: Deprecating this, use property "er_admin" instead. this.set('er_admin', admin); var isDntGroupMember = this.isDntGroupMember({grupper: grupper}); this.set('er_dnt_gruppe_medlem', isDntGroupMember); this.set('_id', id); this.set('id', id); this.setDefaultGroup(); Raven.setUserContext({ name: this.get('navn'), id: this.get('id'), email: this.get('epost'), provider: this.get('provider'), is_admin: !!this.get('er_admin') }); }, isDntGroupMember: function (user) { var userGroups = user.grupper; return (!!userGroups && !!userGroups.length); }, getDefaultGroup: function () { return this.defaultGroup; }, setIsGroupUser: function () { var isGroupUser = (this.get('gruppe') === this.get('id')); this.set('er_gruppebruker', isGroupUser); }, setDefaultGroup: function () { var provider = this.get('provider'); switch(provider) { case 'DNT Connect': var userGroups = this.get('grupper'); if (userGroups.length > 0) { var sentralGroup = _.findWhere(userGroups, {type: 'sentral'}); var foreningGroup = _.findWhere(userGroups, {type: 'forening'}); var turlagGroup = _.findWhere(userGroups, {type: 'turlag'}); var turgruppeGroup = _.findWhere(userGroups, {type: 'turgruppe'}); this.set('gruppe', sentralGroup.object_id || foreningGroup.object_id || turlagGroup.object_id || turgruppeGroup.object_id); } break; case 'Innholdspartner': // Does not require any additional handling. Yet. break; default: // No default } } }); });
JavaScript
0
@@ -4896,34 +4896,34 @@ -this.set('gruppe', +var defaultGroup = sentral @@ -4923,34 +4923,24 @@ sentralGroup -.object_id %7C%7C forening @@ -4940,34 +4940,24 @@ oreningGroup -.object_id %7C%7C turlagGr @@ -4959,26 +4959,16 @@ lagGroup -.object_id %7C%7C turg @@ -4981,20 +4981,319 @@ roup -.object_id); +;%0A%0A if (defaultGroup) %7B%0A this.set('gruppe', defaultGroup.object_id);%0A%0A %7D else %7B%0A Raven.captureMessage('DNT Connect user did not belong to any groups.', %7Bextra: %7Buser: this.toJSON()%7D%7D);%0A %7D%0A %0A
3f4f08a4274e111e9cdfd7c697311a65a3292a52
Fix prototype resolution
polyfill.js
polyfill.js
'use strict'; var clear = require('es5-ext/array/#/clear') , eIndexOf = require('es5-ext/array/#/e-index-of') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , callable = require('es5-ext/object/valid-callable') , validValue = require('es5-ext/object/valid-value') , d = require('d') , ee = require('event-emitter') , Symbol = require('es6-symbol') , iterator = require('es6-iterator/valid-iterable') , forOf = require('es6-iterator/for-of') , Iterator = require('./lib/iterator') , isNative = require('./is-native-implemented') , call = Function.prototype.call , defineProperties = Object.defineProperties, getPrototypeOf = Object.getPrototypeOf , MapPoly; module.exports = MapPoly = function (/*iterable*/) { var iterable = arguments[0], keys, values, self; if (!(this instanceof MapPoly)) throw new TypeError('Constructor requires \'new\''); if (isNative && setPrototypeOf) self = setPrototypeOf(new Map(), getPrototypeOf(this)); else self = this; if (iterable != null) iterator(iterable); defineProperties(self, { __mapKeysData__: d('c', keys = []), __mapValuesData__: d('c', values = []) }); if (!iterable) return self; forOf(iterable, function (value) { var key = validValue(value)[0]; value = value[1]; if (eIndexOf.call(keys, key) !== -1) return; keys.push(key); values.push(value); }, self); return self; }; if (isNative) { if (setPrototypeOf) setPrototypeOf(MapPoly, Map); MapPoly.prototype = Object.create(Map.prototype, { constructor: d(MapPoly) }); } ee(defineProperties(MapPoly.prototype, { clear: d(function () { if (!this.__mapKeysData__.length) return; clear.call(this.__mapKeysData__); clear.call(this.__mapValuesData__); this.emit('_clear'); }), delete: d(function (key) { var index = eIndexOf.call(this.__mapKeysData__, key); if (index === -1) return false; this.__mapKeysData__.splice(index, 1); this.__mapValuesData__.splice(index, 1); this.emit('_delete', index, key); return true; }), entries: d(function () { return new Iterator(this, 'key+value'); }), forEach: d(function (cb/*, thisArg*/) { var thisArg = arguments[1], iterator, result; callable(cb); iterator = this.entries(); result = iterator._next(); while (result !== undefined) { call.call(cb, thisArg, this.__mapValuesData__[result], this.__mapKeysData__[result], this); result = iterator._next(); } }), get: d(function (key) { var index = eIndexOf.call(this.__mapKeysData__, key); if (index === -1) return; return this.__mapValuesData__[index]; }), has: d(function (key) { return (eIndexOf.call(this.__mapKeysData__, key) !== -1); }), keys: d(function () { return new Iterator(this, 'key'); }), set: d(function (key, value) { var index = eIndexOf.call(this.__mapKeysData__, key), emit; if (index === -1) { index = this.__mapKeysData__.push(key) - 1; emit = true; } this.__mapValuesData__[index] = value; if (emit) this.emit('_add', index, key); return this; }), size: d.gs(function () { return this.__mapKeysData__.length; }), values: d(function () { return new Iterator(this, 'value'); }), toString: d(function () { return '[object Map]'; }) })); Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () { return this.entries(); })); Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map'));
JavaScript
0.000002
@@ -1001,18 +1001,43 @@ totypeOf -) +&& (Map !== MapPoly)) %7B%0A%09%09 self = s @@ -1089,13 +1089,19 @@ );%0A%09 +%7D else +%7B%0A%09%09 self @@ -1109,16 +1109,19 @@ = this;%0A +%09%7D%0A %09if (ite
0adadb55dd355843459257f11a8e730832465a72
Fix for gdata extension
extensions/gdata/module/scripts/project/exporters.js
extensions/gdata/module/scripts/project/exporters.js
/* Copyright 2011, Google 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 name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function() { var handleUpload = function(options, exportAllRows, onDone, prompt) { var doUpload = function() { var name = window.prompt(prompt, theProject.metadata.name); if (name) { var dismiss = DialogSystem.showBusy($.i18n._('gdata-exporter')["uploading"]); $.post( "command/gdata/upload", { "project" : theProject.id, "engine" : exportAllRows ? '' : JSON.stringify(ui.browsingEngine.getJSON()), "name" : name, "format" : options.format, "options" : JSON.stringify(options) }, function(o) { dismiss(); if (o.url) { window.open(o.url, '_blank'); } else { alert($.i18n._('gdata-exporter')["upload-error"] + o.message) } onDone(); }, "json" ); } }; if (GdataExtension.isAuthorized()) { doUpload(); } else { GdataExtension.showAuthorizationDialog(doUpload); } }; CustomTabularExporterDialog.uploadTargets.push({ id: 'gdata/google-spreadsheet', label: $.i18n._('gdata-exporter')["new-spreadsheet"], handler: function(options, exportAllRows, onDone) { handleUpload(options, exportAllRows, onDone, $.i18n._('gdata-exporter')["enter-spreadsheet"]); } }); CustomTabularExporterDialog.uploadTargets.push({ id: 'gdata/fusion-table', label: $.i18n._('gdata-exporter')["new-fusion"], handler: function(options, exportAllRows, onDone) { handleUpload(options, exportAllRows, onDone, $.i18n._('gdata-exporter')["enter-fusion"]); } }); })();
JavaScript
0
@@ -1491,16 +1491,264 @@ .%0A%0A */%0A%0A +var dictionary = %22%22;%0A$.ajax(%7B%0A%09url : %22/command/gdata/load-language?%22,%0A%09type : %22POST%22,%0A%09async : false,%0A%09data : %7B%0A%09%09lng : lang%0A%09%7D,%0A%09success : function(data) %7B%0A%09%09dictionary = data;%0A%09%7D%0A%7D);%0A$.i18n.setDictionary(dictionary);%0A// End internationalization%0A%0A (functio
05ecddf8052d332f210437d5df663ca43a8093a4
better unique filter
lib/workers/repository/extract/file-match.js
lib/workers/repository/extract/file-match.js
const minimatch = require('minimatch'); module.exports = { getIncludedFiles, filterIgnoredFiles, getMatchingFiles, }; function getIncludedFiles(fileList, includePaths) { if (!(includePaths && includePaths.length)) { return fileList; } return fileList.filter(file => includePaths.some( includePath => file === includePath || minimatch(file, includePath) ) ); } function filterIgnoredFiles(fileList, ignorePaths) { if (!(ignorePaths && ignorePaths.length)) { return fileList; } return fileList.filter( file => !ignorePaths.some( ignorePath => file.includes(ignorePath) || minimatch(file, ignorePath) ) ); } function getMatchingFiles(fileList, manager, fileMatch) { let matchedFiles = []; for (const match of fileMatch) { logger.debug(`Using file match: ${match} for manager ${manager}`); matchedFiles = matchedFiles.concat( fileList.filter(file => file.match(new RegExp(match))) ); } // filter out duplicates matchedFiles = matchedFiles.filter( (item, pos) => matchedFiles.indexOf(item) === pos ); return matchedFiles; }
JavaScript
0.999625
@@ -1004,112 +1004,27 @@ s%0A -matchedFiles = matchedFiles.filter(%0A (item, pos) =%3E matchedFiles.indexOf(item) === pos%0A );%0A return +return %5B...new Set( matc @@ -1031,12 +1031,14 @@ hedFiles +)%5D ;%0A%7D%0A
65d59f2e4088b821024d7a4979d7907d62eefc17
Check for errors when creating a new post
src/js/views/omnibox.js
src/js/views/omnibox.js
console.log('views/omnibox.js') /** * Handle interactions with the Chrome omnibox */ window.OmniboxView = Backbone.View.extend({ initialize: function() { _.bindAll(this); }, // events: { }, /** * Gets called when the user hits enter in the omnibox */ onInputEntered: function(text) { if (text.indexOf('@@') === 0) { chrome.tabs.create({ url: 'https://alpha.app.net/' + text.substring(2) }); return; } if (text.indexOf('##') === 0) { chrome.tabs.create({ url: 'https://alpha.app.net/hashtags/' + text.substring(2) }); return; } if (text.indexOf('::') === 0) { text = text.substring(2); } var post = new Post(); // TODO: catch errors post.save({ text: text }, { headers: { 'Authorization': 'Bearer ' + accounts.at(0).get('access_token') }, success: post.success, error: post.error, }); }, /** * Display suggestions to the user when the omnibox text changes */ onInputChanged: function(text, suggest) { var suggestions = []; suggestions.push({ content: '::' + text, description: (256 - text.length) + ' characters remaning' }); if (text.indexOf(' ') > -1 || text.length === 0) { suggest(suggestions); return; } if (text.indexOf('#') === 0 || text.indexOf('@') === 0) { text = text.substring(1); } suggestions.push({ content: '@@' + text, description: 'View the @<match>' + text + "</match> profile on App.net" }); suggestions.push({ content: '##' + text, description: 'Search the #<match>' + text + "</match> hashtag on App.net" }); suggest(suggestions); } }); omniboxview = new OmniboxView();
JavaScript
0
@@ -728,16 +728,27 @@ rors%0A + var save = post.sa @@ -928,16 +928,94 @@ %7D);%0A + if (save == false) %7B%0A post.error('Post length was too long.');%0A %7D%0A %7D,%0A%0A%0A
f8b6620e5a1dbd227379088182f27781b0550cae
fix frame url calculation #31
js/contentscript.js
js/contentscript.js
var frameURL = window.location.href; var isTopFrame = (window.parent == window); // Receives messages from the inspected page frame and redirects them to the background, // building up the first step towards the communication between the backbone agent and the panel. window.addEventListener("message", function(event) { // Only accept messages from same frame if (event.source != window) return; var message = event.data; // Only accept our messages if (typeof message != 'object' || message === null || message.target != 'page') return; message.frameURL = frameURL; chrome.extension.sendMessage(message); }, false); // Receives messages from the background and redirects them to the inspected page. chrome.runtime.onMessage.addListener(function(message) { // Only accept messages for our frame if (message.frameURL != frameURL) return; window.postMessage(message, '*'); }); if (isTopFrame) { /* Code to be executed only if this is the top frame content script! */ // Sends a message to the background when the DOM of the inspected page is ready // (typically used by the panel to check if the backbone agent is on the page). window.addEventListener('DOMContentLoaded', function() { chrome.extension.sendMessage({ target: 'page', name: 'ready' }); }, false); }
JavaScript
0.000001
@@ -1,40 +1,177 @@ -var frameURL = window.location.href; +// as per chrome, frameURL is the original frame url without eventual hash string%0Avar frameURL = window.location.origin + window.location.pathname + window.location.search;%0A %0Avar
6dc8c35f69a016365b50e0c4854acfcdc9c1aba5
remove login information (sis id, etc) from user profile page
public/sfu/js/collab_space.js
public/sfu/js/collab_space.js
(function($) { var utils = { onPage: function(regex, fn) { if (location.pathname.match(regex)) fn(); }, hasAnyRole: function(/*roles, cb*/) { var roles = [].slice.call(arguments, 0); var cb = roles.pop(); for (var i = 0; i < arguments.length; i++) { if (ENV.current_user_roles.indexOf(arguments[i]) !== -1) { return cb(true); } } return cb(false); }, isUser: function(id, cb) { cb(ENV.current_user_id == id); }, onElementRendered: function(selector, cb, _attempts) { var el = $(selector); _attempts = ++_attempts || 1; if (el.length) return cb(el); if (_attempts == 60) return; setTimeout(function() { utils.onElementRendered(selector, cb, _attempts); }, 250); } } utils.onPage(/^\/courses\/\d+\/users$/, function() { // remove everything except Contributor and Moderator roles from enrollment options function removeUnusedRoles(index) { var $this = $(this); var val = $this.val(); if (!(val === '' || val === 'Contributor' || val === 'Moderator')) { $this.remove() } } utils.onElementRendered('#content>div', function() { $('select[name="enrollment_role"] option, #enrollment_type option').each(removeUnusedRoles); }); utils.onElementRendered('#addUsers', function() { $('#addUsers').on('click', function(ev) { $('#enrollment_type option').each(removeUnusedRoles); $('#privileges').remove(); }); }); // remove last activity column from roster table utils.onElementRendered('table.roster', function() { var $userTable = $('table.roster'); $userTable.find('thead th').get(-1-1).remove(); $userTable.find('tbody tr').each(function() { $(this).find('td').get(-1-1).remove(); }); }); }); })(jQuery);
JavaScript
0
@@ -2122,16 +2122,168 @@ %7D);%0A%0A + // remove SIS ID from user profile%0A utils.onPage(/%5E%5C/courses%5C/%5Cd+%5C/users%5C/%5Cd+$/, function() %7B%0A $('#login_information').remove();%0A %7D);%0A%0A %7D)(jQuer
516955ef133f52bcd5e93f831efe995abe4c6afc
add flux dependency to loader decorator
src/decorators/loader.js
src/decorators/loader.js
import React from 'react'; export default function(target) { target.prototype.__defineGetter__('loader', function() { return this.context.flux.loader; }); };
JavaScript
0
@@ -4,25 +4,25 @@ ort -React +flux from ' -react +./flux ';%0A%0A @@ -54,16 +54,31 @@ arget) %7B +%0A%09flux(target); %0A%0A%09targe
d48069597812ade4d0f9e8361fe2bf75395a99ac
Add measurements controller
src/MCM.KidsIdApp/www/scripts/app.js
src/MCM.KidsIdApp/www/scripts/app.js
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' var app = angular.module('mcmapp', ['ionic', 'ionic-datepicker']) app.factory('storageService', function ($window, $injector) { //Could also have used a provider for this instead of a factory, but then we can't use the $injector // for instantiating the storage service implementation which is annoying. if ($window.tinyHippos) { console.log("Detected Ripple emulator. Using InMemoryStorageService instead of FileStorageService."); return $injector.get('inMemoryStorageService'); } else { return $injector.get('fileStorageService'); } }); //app.controller('landingController', function ($scope, $state) { // $scope.showinstructionindex = function () { // $state.go('instructionindex'); // } // $scope.showchildprofilelist = function () { // $state.go('childprofilelist'); // } // $scope.showabout = function () { // $state.go('about'); // } // $scope.showsettings = function () { // $state.go('settings'); // } //}); //app.controller('forgotPasswordController', function ($scope, $state) { // // Setup scope for forgot password page //}); //app.controller('childprofilelistController', function ($scope, $state) { // // Setup scope for child profile list page //}); //app.controller('instructionindexController', function ($scope, $state) { // // Setup scope for instruction index page //}); //app.controller('settingsController', function ($scope, $state) { // // Setup scope for settings page //}); //app.controller('aboutController', function ($scope, $state) { // // Setup scope for about page //}); //app.controller('myChildrenController', function ($scope) { // //My children page //}); app.config(function ($stateProvider, $urlRouterProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider .state('login', { url: '/login', templateUrl: 'templates/login.html', controller: 'loginController' }) .state('forgotPassword', { url: '/forgotpassword', templateUrl: 'templates/forgotpassword.html', controller: 'forgotPasswordController' }) .state('landing', { url: '/landing', templateUrl: 'templates/landingpage.html', controller: 'landingController' }) .state('myChildren', { url: '/mychildren', templateUrl: 'templates/mychildren.html', controller: 'myChildrenController' }) .state('instructionIndex', { url: '/instructionindex', templateUrl: 'templates/instructionindex.html', controller: 'instructionIndexController' }) .state('childProfileList', { url: '/childprofilelist', templateUrl: 'templates/childprofilelist.html', controller: 'childProfileListController' }) .state('childProfileItem', { url: '/childprofileitem/:childId', templateUrl: 'templates/childprofileitem.html', controller: 'childProfileItemController' }) .state('settings', { url: '/settings', templateUrl: 'templates/settingspage.html', controller: 'settingsController' }) .state('about', { url: '/about', templateUrl: 'templates/aboutpage.html', controller: 'aboutController' }) .state('basicDetails', { url: '/basicDetails/:childId', templateUrl: 'templates/basicdetails.html', controller: 'basicDetailsController' }) .state('photos', { url: '/photos/:childId', templateUrl: 'templates/photos.html', controller: 'photosController' }) // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/login'); }); app.run(function($ionicPlatform) { $ionicPlatform.ready(function () { if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) { if (window.tinyHippos) { //Ripple emulator shows an error on every screen you navigate to but setting the keyboard plugin to null seems to be a hack-ish way //to stop getting errors after the very first one. window.cordova.plugins.Keyboard = null; } // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (cordova.plugins.Keyboard.hideKeyboardAccessoryBar) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } // Don't remove this line unless you know what you are doing. It stops the viewport // from snapping when text inputs are focused. Ionic handles this internally for // a much nicer keyboard experience. cordova.plugins.Keyboard.disableScroll(true); } if(window.StatusBar) { StatusBar.styleDefault(); } }); })
JavaScript
0.000001
@@ -588,32 +588,51 @@ indow.tinyHippos + %7C%7C !window.cordova ) %7B%0A cons @@ -4024,24 +4024,200 @@ ller'%0A %7D) +%0A %0A .state('measurements', %7B%0A url: 'measurements/:childId',%0A templateUrl: 'templates/measurements.html',%0A controller: 'measurementsController'%0A %7D) %0A%0A // if
01b4ff499ffc9f26565149bddd135ceea5a59837
allow plugins to drag onto page
RcmAdmin/public/js/admin/ajax-plugin-edit-helper.js
RcmAdmin/public/js/admin/ajax-plugin-edit-helper.js
/** * <AjaxPluginEditHelper|ajax-plugin-edit-helper> * Provides shared ajax editing functionality * * @constructor */ var AjaxPluginEditHelper = function (instanceId, container, pluginHandler) { /** * Always refers to this object unlike the 'this' JS variable; */ var me = this; var pluginBaseUrl = '/api/admin/instance-configs/' //+ pluginHandler.getName() //+ '/' + pluginHandler.getId(); me.ajaxGetInstanceConfigs = function (callback) { container.hide();//Hide while loading to prevent weirdness $.getJSON( pluginBaseUrl, function (result) { container.show(); //result.instanceConfig, result.defaultInstanceConfig callback(result.instanceConfig, result.defaultInstanceConfig); // MIGHT REMOVE!!!!!! pluginHandler.updateView(); } ); }; /** * An input group is an array of text inputs, useful for html selects. * This function builds an array of input groups. * @param groupDataKeyNames * @param data * @param defaultData * @return {Object} */ me.buildInputGroups = function (groupDataKeyNames, data, defaultData) { var inputGroups = {}; $.each(groupDataKeyNames, function () { inputGroups[this] = me.buildInputGroup( data[this], defaultData[this] ); }); return inputGroups; }; /** * An input group is an array of text inputs, useful for html selects. * This function transfers the data from html text boxes to the data array * @param inputGroups * @param data * @return {*} */ me.captureInputGroups = function (inputGroups, data) { $.each(inputGroups, function (inputGroupName, inputGroup) { data = me.captureInputGroup(inputGroupName, inputGroup, data); }); return data; }; /** * An input group is an array of text inputs, useful for html selects. * This function builds a single input group * @param currentTranslations * @param defaultTranslations * @return {Object} */ me.buildInputGroup = function (currentTranslations, defaultTranslations) { var inputs = {}; $.each(defaultTranslations, function (key, value) { inputs[key] = $.dialogIn('text', value, currentTranslations[key]); }); return inputs }; /** * An input group is an array of text inputs, useful for html selects. * This function transfers the data from html text boxes to the data array * @param inputGroupName * @param inputGroup * @param data * @return {*} */ me.captureInputGroup = function (inputGroupName, inputGroup, instanceConfig) { $.each(instanceConfig[inputGroupName], function (key) { if (inputGroup[key]) { instanceConfig[inputGroupName][key] = inputGroup[key].val() } }); return instanceConfig; }; me.buildEmailInputGroup = function (emailGroupData) { return { fromEmail: $.dialogIn('text', 'From Email', emailGroupData['fromEmail']), fromName: $.dialogIn('text', 'From Name', emailGroupData['fromName']), subject: $.dialogIn('text', 'Subject', emailGroupData['subject']), body: $.dialogIn('richEdit', 'Body', emailGroupData['body']) }; }; this.attachPropertiesDialog = function (showMainPropertiesCallback) { //Double clicking will show properties dialog container.delegate('div', 'dblclick', function (event) { event.stopPropagation(); showMainPropertiesCallback(); }); //Add right click menu $.contextMenu({ selector: rcm.getPluginContainerSelector(instanceId), //Here are the right click menu options items: { edit: { name: 'Edit Properties', icon: 'edit', callback: function () { showMainPropertiesCallback(); } } } }); } }; /* </AjaxPluginEditHelper|ajax-plugin-edit-helper> */
JavaScript
0
@@ -360,18 +360,16 @@ -// + plugin @@ -394,18 +394,16 @@ -// + '/'%0A
a39bf0fe36e46594bca2f98ea8418c840b4b5233
Update RegistrationSuccessView template for BMUN 63.
huxley/www/static/js/huxley/components/RegistrationSuccessView.js
huxley/www/static/js/huxley/components/RegistrationSuccessView.js
/** * Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved. * Use of this source code is governed by a BSD License (see LICENSE). * * @jsx React.DOM */ 'use strict'; var React = require('react'); var NavLink = require('./NavLink'); var OuterView = require('./OuterView'); var RegistrationSuccessView = React.createClass({ render: function() { return ( <OuterView> <div class="letter"> <h1>Thank You</h1> <p> Thank you for registering for BMUN 62! Country assignments will be made available soon in your Huxley account. A summary of fees is listed below: </p> <h3>School Registration Fee</h3> <ul> <li>$40 (if registered by November 1, 2013)</li> <li>$50 (if registered after November 1, 2013)</li> </ul> <h3>Delegate Registration Fee</h3> <ul> <li>$40 per delegate (by February 10, 2014)</li> <li>$50 per delegate (by February 24, 2014)</li> <li>$55 per delegate (after February 24, 2014)</li> </ul> <h3>Payment Instructions</h3> <p> <strong> We ask that you compile delegate fees into ONE check </strong> &nbsp;&#8212; please do not have your students mail individual checks. </p> <p> Please mail all checks out to: </p> <div class="address"> <p><strong>Berkeley Model United Nations</strong> <br /> P.O. Box #4306 <br /> Berkeley, CA 94704-0306 </p> </div> <p> If you have any questions or concerns, please feel free to contact me at <a href="mailto:[email protected]">[email protected]</a>. We look forward to seeing you in March! </p> <p>Sincerely,</p> <p class="sender"> <strong>Shrey Goel</strong> <br /> <span class="subtext"> Under-Secretary General of External Relations <br /> Berkeley Model United Nations, 62nd Session </span> </p> </div> <hr /> <NavLink direction="right" href="/login"> Proceed to Login </NavLink> </OuterView> ); } }); module.exports = RegistrationSuccessView;
JavaScript
0
@@ -520,17 +520,17 @@ r BMUN 6 -2 +3 ! Countr @@ -748,372 +748,111 @@ li%3E$ -40 (if registered by November 1, 2013)%3C/li%3E%0A %3Cli%3E$50 (if registered after November 1, 2013)%3C/li%3E%0A %3C/ul%3E%0A %3Ch3%3EDelegate Registration Fee%3C/h3%3E%0A %3Cul%3E%0A %3Cli%3E$40 per delegate (by February 10, 2014)%3C/li%3E%0A %3Cli%3E$50 per delegate (by February 24, 2014)%3C/li%3E%0A %3Cli%3E$55 per delegate (after February 24, 2014) +50%3C/li%3E%0A %3C/ul%3E%0A %3Ch3%3EDelegate Registration Fee%3C/h3%3E%0A %3Cul%3E%0A %3Cli%3E$50 %3C/li @@ -1761,18 +1761,19 @@ ong%3E -Shrey Goel +Hee Soo Kim %3C/st @@ -1959,17 +1959,17 @@ tions, 6 -2 +3 nd Sessi
42eb19bb91713c330d1e68e00d12b5d26f15df6f
reset list for each manager
lib/workers/repository/process/deprecated.js
lib/workers/repository/process/deprecated.js
module.exports = { raiseDeprecationWarnings, }; async function raiseDeprecationWarnings(config, packageFiles) { if (!config.repoIsOnboarded) { return; } if ( config.suppressNotifications && config.suppressNotifications.includes('deprecationWarningIssues') ) { return; } const deprecatedPackages = {}; for (const [manager, files] of Object.entries(packageFiles)) { for (const packageFile of files) { for (const dep of packageFile.deps) { const { deprecationMessage } = dep; if (deprecationMessage) { deprecatedPackages[dep.depName] = deprecatedPackages[dep.depName] || { deprecationMessage, depPackageFiles: [], }; deprecatedPackages[dep.depName].depPackageFiles.push( packageFile.packageFile ); } } } logger.debug({ deprecatedPackages }); for (const [depName, val] of Object.entries(deprecatedPackages)) { const { deprecationMessage, depPackageFiles } = val; logger.info( { depName, deprecationMessage, packageFiles: depPackageFiles, }, 'npm dependency is deprecated' ); const issueTitle = `Dependency deprecation warning: ${depName} (${manager})`; let issueBody = deprecationMessage; issueBody += `\n\nPlease take the actions necessary to rename or substitute this deprecated package and commit to your base branch. If you wish to ignore this deprecation warning and continue using \`${depName}\` as-is, please add it to your [ignoreDeps](https://renovatebot.com/docs/configuration-options/#ignoredeps) array in Renovate config before closing this issue, otherwise another issue will be recreated the next time Renovate runs.`; issueBody += `\n\nAffected package file(s): ${depPackageFiles .map(f => '`' + f + '`') .join(', ')}`; issueBody += '\n\n Would you like to disable Renovate\'s deprecation warning issues? Add the following to your config:\n\n```\n"suppressNotifications": ["deprecationWarningIssues"]\n```\n\n'; // istanbul ignore if if (config.dryRun) { logger.info('DRY-RUN: Ensure deprecation warning issue for ' + depName); } else { await platform.ensureIssue(issueTitle, issueBody); } } } }
JavaScript
0.000005
@@ -296,41 +296,8 @@ %7D%0A - const deprecatedPackages = %7B%7D;%0A fo @@ -353,24 +353,59 @@ geFiles)) %7B%0A + const deprecatedPackages = %7B%7D;%0A for (con
88df6bf5b53867f3b3cf0094cfa7b70147455c51
Update canvas.js
javascript/canvas.js
javascript/canvas.js
// Get Canvas var canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d"), width = 512, height = 480; canvas.tabIndex = 1; canvas.width = width; canvas.height = height; // Background Image var bgReady = false; var bgImage = new Image(); bgImage.onload = function () { bgReady = true; }; bgImage.src = "http://placekitten.com/512/480"; // Hero Image var heroReady = false; var heroImage = new Image(); heroImage.onload = function () { heroReady = true; }; heroImage.src = "http://placekitten.com/32/32"; // Kitty Image var kittyReady = false; var kittyImage = new Image(); kittyImage.onload = function () { kittyReady = true; }; kittyImage.src = "http://placekitten.com/30/32"; // Game objects var hero = { speed: 256, x: 0, y: 0 }; var kitty = { x: 0, y: 0 }; var kittyCaught = 0; // Handle keyboard controls var keysDown = {}; addEventListener("keydown", function (e) { keysDown[e.keyCode] = true; e.preventDefault(); }, false); addEventListener("keyup", function (e) { delete keysDown[e.keyCode]; }, false); var reset = function () { hero.x = (canvas.width / 2) - 16; hero.y = (canvas.height / 2) - 16; kitty.x = 32 + (Math.random() * (canvas.width - 64)); kitty.y = 32 + (Math.random() * (canvas.height - 64)); }; // Update game objects var update = function (modifier) { if (38 in keysDown) { hero.y -= hero.speed * modifier; } if (40 in keysDown) { hero.y += hero.speed * modifier; } if (37 in keysDown) { hero.x -= hero.speed * modifier; } if (39 in keysDown) { hero.x += hero.speed * modifier; } // Stop from going off the page if (hero.x >= canvas.width - 32) { hero.x = canvas.width - 32; } else if (hero.x <= 0) { hero.x = 0; } if (hero.y >= canvas.height - 32) { hero.y = canvas.height - 32; } else if (hero.y <= 0) { hero.y = 0; } // Collision if (hero.x <= (kitty.x + 32) && kitty.x <= (hero.x + 32) && hero.y <= (kitty.y + 32) && kitty.y <= (hero.y + 32)) { ++kittyCaught; nowSwitch = thenSwitch; reset(); } }; // Render var render = function () { if (bgReady) { ctx.drawImage(bgImage, 0, 0); } if (heroReady) { ctx.drawImage(heroImage, hero.x, hero.y); } if (kittyReady) { ctx.drawImage(kittyImage, kitty.x, kitty.y); } ctx.fillStyle = "#EEE"; ctx.font = "24px Ubuntu"; ctx.textAlign = "left"; ctx.textBaseline = "top"; ctx.fillText("Kitties caught : " + kittyCaught, 32, 32); ctx.fillText("Lives : " + lives, 365, 32); ctx.fillText("Timer : " + parseInt(countDown / 100), 32, 64); }; var gameOver = function () { document.write("Game Over. Kitties only have nine lives."); }; var main = function () { now = Date.now(); var delta = now - then; var nowSwitch = Date.now(); countDown = nowSwitch - thenSwitch; update(delta / 1000); if (countDown >= 1300) { lives--; if (lives == 0) { gameOver(); } thenSwitch = nowSwitch; reset(); } render(); then = now; requestAnimationFrame(main); }; var w = window; requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame; // Initalized Variables var then, thenSwitch, nowSwitch; var countDown; var lives; var start = function() { then = thenSwitch = nowSwitch = Date.now(); reset(); countDown = 0; lives = 9; //hero.x = (canvas.width / 2) - 16; //hero.y = (canvas.height / 2) - 16; main(); } start();
JavaScript
0.000001
@@ -3416,16 +3416,37 @@ es = 9;%0A + kittiesCaught = 0;%0A //hero
66499ea7c646f71c9043860ca868ec363a062ebf
Exit if no features found
AGStoSHP.js
AGStoSHP.js
// @Author: Joshua Tanner // @Date: 12/8/2014 (created) // @Description: Easy way to create shapefiles (and geojson, geoservices json) // from ArcGIS Server services // @services.txt format :: serviceLayerURL|layerName // @githubURL : https://github.com/tannerjt/AGStoShapefile // Node Modules var ogr2ogr = require('ogr2ogr'); var q = require('q'); var request = q.nfbind(require('request')); var fs = require('fs'); var queryString = require('query-string'); // ./mixin.js // merge user query params with default var mixin = require('./mixin'); var serviceFile = process.argv[2] || 'services.txt'; var outDir = process.argv[3] || './output/'; if(outDir[outDir.length - 1] !== '/') { outDir += '/'; } // Make request to each service fs.readFile(serviceFile, function (err, data) { if (err) { console.log(err); throw err; } data.toString().split('\n').forEach(function (service) { var service = service.split('|'); //get total number of records | assume 1000 max each request if(service[0].split('').length == 0) return; var baseUrl = getBaseUrl(service[0].trim()) + '/query'; request({ url : baseUrl + "/?where=1=1&returnIdsOnly=true&f=json", method : 'GET', json : true }, function (err, response, body) { var err = err || body.error; if(err) { console.log(err); throw err; } requestService(service[0].trim(), service[1].trim(), body.objectIds); }); }) }); // Resquest JSON from AGS function requestService(serviceUrl, serviceName, objectIds) { var requests = []; for(var i = 0; i < Math.ceil(objectIds.length / 100); i++) { var ids = []; if ( ((i + 1) * 100) < objectIds.length ) { ids = objectIds.slice(i * 100, (i + 1) * 100); } else { ids = objectIds.slice(i * 100, objectIds.length); } // we need these query params var reqQS = { objectIds : ids.join(','), geometryType : 'esriGeometryEnvelope', returnGeometry : true, returnIdsOnly : false, outFields : '*', outSR : '4326', f : 'json' }; // user provided query params var userQS = getUrlVars(serviceUrl); // mix one obj with another var qs = mixin(userQS, reqQS); var qs = queryString.stringify(qs); var url = decodeURIComponent(getBaseUrl(serviceUrl) + '/query/?' + qs); var r = request({ url : url, method : 'GET', json : true }); requests.push(r); }; q.allSettled(requests).then(function (results) { for(var i = 0; i < results.length; i++) { if(i == 0) { allFeatures = results[i].value[0].body; } else { allFeatures.features = allFeatures.features.concat(results[i].value[0].body.features); } } console.log('creating', serviceName, 'json'); var json = allFeatures; fs.writeFile(outDir + serviceName + '.json', JSON.stringify(json), function (err) { if(err) throw err; // Create Geojson console.log('creating', serviceName, 'geojson'); var ogr = ogr2ogr(outDir + serviceName + '.json') .skipfailures(); ogr.exec(function (er, data) { if (er) console.log(er); fs.writeFile(outDir + serviceName + '.geojson', JSON.stringify(data), function (err) { // Create Shapefile once geojson written if (er) console.log(er); console.log('creating', serviceName, 'shapefile'); var shapefile = ogr2ogr(outDir + serviceName + '.geojson') .format('ESRI Shapefile') .skipfailures(); shapefile.stream().pipe(fs.createWriteStream(outDir + serviceName + '.zip')); }); }); }); }).catch(function (err) { console.log(err); throw err; }); } //http://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url function getUrlVars(url) { var vars = {}, hash; var hashes = url.slice(url.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars[hash[0].toString()] = hash[1]; } return vars; } // get base url for query function getBaseUrl(url) { // remove any query params var url = url.split("?")[0]; if((/\/$/ig).test(url)) { url = url.substring(0, url.length - 1); } return url; }
JavaScript
0.000001
@@ -2516,16 +2516,54 @@ else %7B%0A +%09%09%09%09if(!allFeatures.features) return;%0A %09%09%09%09allF
21cf1a7e7e556fcd6d6064a2244003858c600d2c
Improve error message for indexing null/undefined.
src/values/EmptyValue.js
src/values/EmptyValue.js
'use strict'; const Value = require('../Value'); const BridgeValue = require('./BridgeValue'); const CompletionRecord = require('../CompletionRecord'); class EmptyValue extends Value { constructor() { super(null); } get truthy() { return false; } *not() { return Value.fromNative(true); } *doubleEquals(other) { if ( other instanceof EmptyValue ) return Value.true; else if ( other instanceof BridgeValue ) return this.fromNative(this.toNative() == other.toNative()); else return Value.false; } *observableProperties() { return; } *instanceOf() { return Value.false; } } module.exports = EmptyValue;
JavaScript
0
@@ -592,16 +592,302 @@ se;%0A%09%7D%0A%0A +%09/**%0A%09 * @param %7BString%7D name%0A%09 * @param %7BRealm%7D realm%0A%09 * @returns %7BCompletionRecord%7D Indexing empty values is a type error.%0A%09 */%0A%09*get(name, realm) %7B%0A%09%09let err = 'Cannot read property %5C'' + name + '%5C' of ' + this.specTypeName;%0A%09%09return CompletionRecord.makeTypeError(realm, err);%0A%09%7D%0A%0A %7D%0A%0Amodul
f95ec3421b949bd54bdd84f51fc65ed03662f286
Clean up tab select/close
notable/static/js/views/noteTab.js
notable/static/js/views/noteTab.js
/** * @fileoverview Describes a bootstrap tab */ define([ 'text!templates/noteDetail.html', 'text!templates/tab.html', 'backbone', 'underscore', 'lib/jquery.hotkeys', 'codemirror', 'lib/codemirror/mode/rst/rst' ], function(noteDetailTemplate, tabTemplate) { return Backbone.View.extend({ initialize: function() { this._editor = null; this._tab = null; }, render: function(collection) { var note = this.model.toJSON(), tabs = this.options.tabs, tabContent = this.options.tabContent; // No tabs are active tabs.find('.active').removeClass('active'); // Add new tab content tabContent.append(_.template(noteDetailTemplate, { note: note })); // Use codemirror for the content this.el = $(tabContent).find('.editor').last().parent(); this.$el = $(this.el); this._editor = CodeMirror(_.first(this.$el.find('.editor')), { mode: 'rst', value: note.content, extraKeys: { 'Ctrl-S': _.bind(this.save, this) } }); this.$('input').bind('keydown', 'ctrl+s', _.bind(this.save, this)); // Somehow this seems to result in the right tab saving, but // seemms like a defect waiting to happen. $(document).bind('keydown', 'ctrl+s', _.bind(this.save, this)); this.$('.delete').on('click', _.bind(this.onDelete, this)); this.$('.save').on('click', _.bind(this.save, this)); this.$('.save-close').on('click', { callback: _.bind(this.close, this) }, _.bind(this.save, this)); // Add a new tab tabs.append(_.template(tabTemplate, { note: note })); // Set event handlers, and show the tab this._tab = this.getTab(); this._tab.on('shown', _.bind(this.shown, this)) .tab('show') .find('button').on('click', _.bind(this.close, this)); this.$('.subject input').on('keyup', _.bind(this.onSubjectChange, this)); return this; }, onDelete: function() { // TODO: Wrap this in a confirmation modal this.model.destroy(); this.close(); return false; }, onSubjectChange: function() { this._tab.find('span').text(this.$('.subject input').val()); }, show: function() { this._tab.tab('show'); }, shown: function() { if (this.model.get('subject')) { this._editor.focus(); } else { this.$('.subject input').focus(); } }, saved: function() { $('.saved').fadeIn().delay(4000).fadeOut(); }, save: function(event) { if (!this.$el.is(":visible")) { return; } this.model.save({ content: this._editor.getValue(), password: this.$el.find('.password input').val(), subject: this.$el.find('.subject input').val(), tags: this.$el.find('.tags input').val() }, { success: _.bind(function() { this.saved(); if (event.data && event.data.callback) { event.data.callback(); } }, this) }); return false; }, getTab: function() { return this.options.tabs.find(this.selector()); }, selector: function() { return 'a[href=#'+ this.model.get('uid') +']'; }, close: function() { // Show the previous tab and then remove this one this.options.tabs.find(this.selector()) .parent() .prev() .find('a') .tab('show') .parent() .next() .remove(); // Remove the tab content (after the ^ animation is finished) (ick) setTimeout(_.bind(function() { $('#' + this.model.get('uid')).detach().remove(); }, this), 300); // Let parents deal with me this.trigger('destroy'); } }); });
JavaScript
0
@@ -3339,36 +3339,26 @@ the -previous tab -and +to the -n remove + left of thi @@ -3364,24 +3364,42 @@ is one%0A + var tabToDelete = this.option @@ -3430,51 +3430,43 @@ r()) +; %0A - .parent()%0A .prev()%0A +tabToDelete.parent().prev() .fin @@ -3471,25 +3471,16 @@ ind('a') -%0A .tab('sh @@ -3487,61 +3487,10 @@ ow') -%0A .parent()%0A .next()%0A .remove() ; +%0A %0A @@ -3499,13 +3499,13 @@ // -Remov +Delet e th @@ -3514,174 +3514,125 @@ tab -content (after the %5E animation is finished) (ick)%0A setTimeout(_.bind(function() %7B%0A $('#' + this.model.get('uid')).detach().remove();%0A %7D, this), 300); +and the tab content%0A tabToDelete.parent().detach().remove();%0A $(tabToDelete.attr('href')).detach().remove() %0A%0A
8972b766977723d7e31211ba182977cf19a7fa53
allow for chaining
ohmahgerd.js
ohmahgerd.js
var colors = require("colors"); var fs = require("fs"); var cheerio = require('cheerio'); var readline = require('readline'); var rl = readline.createInterface(process.stdin, process.stdout); var tags = []; var commands = []; var file = null; var html = null; //** //MAIN LOGIC //** if(process.argv.length > 2){ //first, get tags and commands process.argv.forEach(function(val, index, array){ if(index >= 2){ if(val[0] === "-"){ tags.push(val); } else{ commands.push(val); } } }); // //COMMANDS // if(commands[0] === "open"){ open(commands[1]); rl.setPrompt('OMG> '); rl.prompt(); rl.on('line', function(line){ var input = line.trim(); // if(input === "exit"){ rl.close(); process.exit(0); } else{ } // rl.prompt(); }).on('close', function() { process.exit(0); }); } else if(commands[0] === "use"){ use(commands[1]); if(commands[2] === "add"){ //by default, add to body if((typeof commands[4]) === (typeof undefined)){ $("body").append(commands[3]); //like: node ohmahgerd.js use index.html add "<h1>hi</h1>" } else{ $(commands[3]).append(commands[4]); } } //TODO: /* addClass removeClass remove after before */ } else{ console.log(colors.red.bold.underline('This command does not exist')); } if(file !== null){ fs.writeFileSync(file, $.html()); } // //TAGS // //TODO: implement tags /* --help : help -o : output file after command */ } else{ //no arguments passed console.log(colors.red.bold.underline('You didn\'t pass any arguments!')); console.log('Try \'ohmahgerd --help\'') } //** //HELPER FUNCTIONS //** function open(path){ if(fs.existsSync(path)) { file = path; html = fs.readFileSync(path, "utf8"); $ = cheerio.load(html); } else{ console.log(colors.red.bold.underline('The file ' + path + ' does not exist')); } } function use(path){ if(fs.existsSync(path)) { file = path; html = fs.readFileSync(path, "utf8"); $ = cheerio.load(html); } else{ console.log(colors.red.bold.underline('The file ' + path + ' does not exist')); } }
JavaScript
0.000001
@@ -255,16 +255,209 @@ null;%0A%0A +//**%0A//COMMANDS%0A//**%0A%0Avar func = %7B%7D;%0A%0Afunc.add = function(dest, to_add)%7B //like: ohmahgerd use index.html add %22.p%22 %22%3Ci%3Ehi%3C/i%3E%22%0A console.log(dest + %22%7C%22 + to_add);%0A $(dest).append(to_add);%0A%7D;%0A%0A //**%0A//M @@ -922,27 +922,16 @@ trim();%0A - //%0A @@ -1029,41 +1029,18 @@ se%7B%0A - %0A %7D%0A%0A%0A // +%0A %7D %0A%0A @@ -1193,255 +1193,216 @@ %5D);%0A +%0A -if(commands%5B2%5D === %22add%22)%7B%0A //by default, add to body%0A if((typeof commands%5B4%5D) === (typeof undefined))%7B%0A $(%22body%22).append(commands%5B3%5D); //like: node ohmahgerd.js use index.html add %22%3Ch1%3Ehi%3C/h1%3E%22%0A %7D%0A else%7B +var i = 2;%0A while(i %3C (commands.length - 1))%7B%0A var command_name = commands%5Bi%5D;%0A var num_args = func%5Bcommand_name%5D.length;%0A var args = commands.slice(i + 1, i + 2 + num_args);%0A %0A @@ -1410,55 +1410,72 @@ - $( +func%5B command -s%5B3%5D).append(commands%5B4%5D);%0A %7D +_name%5D.apply(this, args);%0A i+=(num_args + 1); %0A @@ -1503,16 +1503,26 @@ /*%0A + add%0A ad @@ -1854,16 +1854,36 @@ d%0A */%0A%0A + process.exit(0);%0A%0A %7D%0Aelse%7B%0A
4058875a6310836fde7d494942eda9f9aa300d30
Split find into find and findAll
discovery.js
discovery.js
var request = require("request"); /* * DiscoveryClient constructor. * Creates a new uninitialized DiscoveryClient. */ function DiscoveryClient(host, options) { this.host = host; this.state = {announcements: {}}; this.errorHandlers = [this._backoff.bind(this)]; this.watchers = [this._update.bind(this), this._unbackoff.bind(this)]; this.announcements = []; this.backoff = 1; this.logger = (options && options.logger) || require("ot-logger"); } /* Increase the watch backoff interval */ DiscoveryClient.prototype._backoff = function () { this.backoff = Math.min(this.backoff * 2, 10240); } /* Reset the watch backoff interval */ DiscoveryClient.prototype._unbackoff = function() { this.backoff = 1; } DiscoveryClient.prototype._randomServer = function() { return this.servers[Math.floor(Math.random()*this.servers.length)]; } /* Consume a WatchResult from the discovery server and update internal state */ DiscoveryClient.prototype._update = function (update) { var disco = this; if (update.fullUpdate) { Object.keys(disco.state.announcements).forEach(function (id) { delete disco.state.announcements[id]; }); } disco.state.index = update.index; update.deletes.forEach(function (id) { delete disco.state.announcements[id]; }); update.updates.forEach(function (announcement) { disco.state.announcements[announcement.announcementId] = announcement; }); } /* Connect to the Discovery servers given the endpoint of any one of them */ DiscoveryClient.prototype.connect = function (onComplete) { var disco = this; request({ url: "http://" + this.host + "/watch", json: true }, function (error, response, update) { if (error) { onComplete(error); } if (response.statusCode != 200) { onComplete(new Error("Unable to initiate discovery: " + update), undefined, undefined); } if (!update.fullUpdate) { onComplete(new Error("Expecting a full update: " + update), undefined, undefined); } disco._update(update); disco.servers = []; Object.keys(disco.state.announcements).forEach(function (id) { var announcement = disco.state.announcements[id]; if (announcement.serviceType == "discovery") { disco.servers.push(announcement.serviceUri); } }); disco._schedule(); setInterval(disco._announce.bind(disco), 10000); onComplete(undefined, disco.host, disco.servers); }); }; /* Register a callback on every discovery update */ DiscoveryClient.prototype.onUpdate = function (watcher) { this.watchers.push(watcher); } /* Register a callback on every error */ DiscoveryClient.prototype.onError = function (handler) { this.errorHandlers.push(handler); } /* Internal scheduling method. Schedule the next poll in the event loop */ DiscoveryClient.prototype._schedule = function() { var c = this.poll.bind(this); if (this.backoff <= 1) { setImmediate(c); } else { setTimeout(c, this.backoff).unref(); } } /* Long-poll the discovery server for changes */ DiscoveryClient.prototype.poll = function () { var disco = this; var server = this._randomServer(); var url = server + "/watch?since=" + (this.state.index + 1); request({ url: url, json: true }, function (error, response, body) { if (error) { disco.errorHandlers.forEach(function (h) { h(error); }); disco._schedule(); return; } if (response.statusCode == 204) { disco._schedule(); return; } if (response.statusCode != 200) { var error = new Error("Bad status code " + response.statusCode + " from watch: " + response); disco.errorHandlers.forEach(function (h) { h(error); }); disco._schedule(); return; } disco.watchers.forEach(function (w) { w(body); }); disco._schedule(); }); }; /* Lookup a service by service type! * Accepts one of: * serviceType as string * serviceType:feature as string * predicate function over announcement object */ DiscoveryClient.prototype.find = function (predicate) { var disco = this; var candidates = []; if (typeof(predicate) != "function") { var serviceType = predicate; predicate = function(announcement) { return a.serviceType == serviceType || a.serviceType + ":" + a.feature == serviceType; }; } Object.keys(disco.state.announcements).forEach(function (id) { var a = disco.state.announcements[id]; if (predicate(a)) { candidates.push(a.serviceUri); } }); if (candidates.length == 0) { return undefined; } return candidates[Math.floor(Math.random()*candidates.length)]; } DiscoveryClient.prototype._announce = function() { var disco = this; function cb(error, announcement) { if (error) { disco.errorHandlers.forEach(function (h) { h(error); }); } } this.announcements.forEach(function (a) { disco._singleAnnounce(a, cb); }); } DiscoveryClient.prototype._singleAnnounce = function (announcement, cb) { var server = this._randomServer(); request({ url: server + "/announcement", method: "POST", json: true, body: announcement }, function (error, response, body) { if (error) { cb(error); return; } if (response.statusCode != 201) { cb(new Error("During announce, bad status code " + response.statusCode + ": " + body)); return; } cb(undefined, body); }); } /* Announce ourselves to the registry */ DiscoveryClient.prototype.announce = function (announcement, cb) { var disco = this; this._singleAnnounce(announcement, function(error, a) { if (error) { cb(error); return; } disco.logger.log("Announced as " + a); disco.announcements.push(a); cb(undefined, a); }); } /* Remove a previous announcement. The passed object *must* be the * lease as returned by the 'announce' callback. */ DiscoveryClient.prototype.unannounce = function (announcement, callback) { var disco = this; var server = disco._randomServer(); var url = server + "/announcement/" + announcement.announcementId; disco.announcements.splice(disco.announcements.indexOf(announcement), 1); request({ url: url, method: "DELETE" }, function (error, response, body) { if (error) { disco.logger.error(error); } else { disco.logger.log("Unannounce DELETE '" + url + "' returned " + response.statusCode + ": " + body); } if (callback) { callback(); } }); } module.exports = DiscoveryClient;
JavaScript
0.001656
@@ -3996,16 +3996,19 @@ ype.find +All = funct @@ -4469,16 +4469,141 @@ %7D%0A %7D); +%0A%0A return candidates;%0A%7D%0A%0ADiscoveryClient.prototype.find = function (predicate) %7B%0A var candidates = this.findAll(predicate); %0A if (c
17c5547c97d7c70ed5e4978359169893a8a11685
Add splash-elements to tests.
test/polymer-app-test.js
test/polymer-app-test.js
const path = require('path'); const helpers = require('yeoman-test'); const assert = require('yeoman-assert'); describe('yo kk578:polymer-app MyPolymerAppProject', () => { before(() => { const dummies = [ path.join(__dirname, '../generators/node-server'), path.join(__dirname, '../generators/node'), [helpers.createDummyGenerator(), 'kk578:app'] ]; return helpers.run(path.join(__dirname, '../generators/polymer-app')) .withGenerators(dummies) .inDir(path.join(__dirname, './tmp/polymer-app')) .withArguments('MyPolymerAppProject') .withPrompts({ name: 'The Tester', email: '[email protected]', gitRemoteUrl: '[email protected]:KK578/MyPolymerAppProject.git' }) .toPromise(); }); /////////////////////////////////////////////////////////////////////////////////////////////// it('should not copy files from development', () => { assert.noFile(['build/', 'node_modules/']); }); describe('Bower', () => { it('should generate bower.json with MyPolymerAppProject', () => { assert.file('bower.json'); assert.jsonFileContent('bower.json', { name: 'MyPolymerAppProject', authors: [ { name: 'The Tester', email: '[email protected]' } ], repository: { type: 'git', url: '[email protected]:KK578/MyPolymerAppProject.git' } }); }); it('should have basic polymer dependencies', () => { assert.fileContent('bower.json', /"polymer": "Polymer\/polymer.*"/); assert.fileContent('bower.json', /"paper-elements": "PolymerElements\/paper-elements.*"/); assert.fileContent('bower.json', /"lodash"/); }); it('should have basic polymer devDependencies', () => { assert.fileContent('bower.json', /"polymer": "Polymer\/polymer.*"/); assert.fileContent('bower.json', /"iron-component-page": "PolymerElements\/iron-component-page.*"/); }); it('should generate a .bowerrc', () => { assert.file('.bowerrc'); }); }); describe('npm', () => { it('should generate extra devDependencies to package.json', () => { assert.fileContent('package.json', /"grunt-babel"/); assert.fileContent('package.json', /"grunt-bower-task"/); assert.fileContent('package.json', /"grunt-minify-polymer"/); assert.fileContent('package.json', /"grunt-sass"/); assert.fileContent('package.json', /"grunt-vulcanize"/); }); }); describe('Server', () => { it('should generate browser-sync plugins', () => { assert.file([ 'server/configs/browser-sync/plugins/scroll.js', 'server/configs/browser-sync/handlers/polymer-style-inject.js' ]); }); it('should generate additional server routes', () => { assert.file([ 'server/routes/bower.js', 'server/routes/components.js', 'server/routes/staging.js', 'server/routes/wct.js' ]); }); }); describe('Grunt', () => { it('should generate additional grunt configs for polymer-app', () => { assert.file([ 'grunt/babel.js', 'grunt/bower.js', 'grunt/minifyPolymer.js', 'grunt/minifyPolymerCSS.js', 'grunt/sass.js', 'grunt/vulcanize.js' ]); }); it('should add new tasks for Bower', () => { assert.fileContent('grunt/aliases.js', /build:bower/); assert.fileContent('grunt/bower.js', /development/); assert.fileContent('grunt/bower.js', /production/); assert.fileContent('grunt/minifyPolymer.js', /bower/); assert.fileContent('grunt/minifyPolymerCSS.js', /bower/); assert.fileContent('grunt/uglify.js', /bower/); assert.fileContent('grunt/watch.js', /bower/); }); it('should add new tasks for views', () => { assert.fileContent('grunt/aliases.js', /build:views/); assert.fileContent('grunt/eslint.js', /views/); assert.fileContent('grunt/minifyPolymer.js', /views/); assert.fileContent('grunt/sass.js', /sass-partials/); assert.fileContent('grunt/sass.js', /views/); assert.fileContent('grunt/uglify.js', /views/); assert.fileContent('grunt/watch.js', /views/); }); it('should add new tasks for custom components', () => { assert.fileContent('grunt/aliases.js', /build:components/); assert.fileContent('grunt/eslint.js', /components/); assert.fileContent('grunt/minifyPolymer.js', /components/); assert.fileContent('grunt/sass.js', /components/); assert.fileContent('grunt/uglify.js', /components/); assert.fileContent('grunt/watch.js', /components/); }); it('should add new tasks for production build'); }); describe('Public', () => { it('should generate basic views', () => { assert.file([ 'public/404.html', 'public/bower.html', 'public/elements.html', 'public/index.html' ]); }); it('should generate SASS partials', () => { assert.file([ 'public/stylesheets/partials/_layouts.scss', 'public/stylesheets/partials/_mixins.scss' ]); }); it('should generate SASS stylesheets for views', () => { assert.file([ 'public/stylesheets/404.scss', 'public/stylesheets/bower.scss', 'public/stylesheets/index.scss', 'public/stylesheets/theme.scss' ]); }); it('should generate front end scripts', () => { assert.file([ 'es6-support.js', 'es6-support.dev.js', 'load.js' ]); }); it('should generate custom components'); it('should generate WCT suite'); }); });
JavaScript
0
@@ -4543,32 +4543,67 @@ elements.html',%0A +%09%09%09%09'public/splash-elements.html',%0A %09%09%09%09'public/inde
7b24ae1fd9131598b61e2df1a7c9732489742aa2
Rename methods: getXXX => idToXXX
lib/database/storage.js
lib/database/storage.js
// -*- indent-tabs-mode: nil; js2-basic-offset: 2 -*- var fs = require('fs'); var path = require('path'); var mkdirp = require('mkdirp'); var rmRSync = require('../rm').rmRSync; var crypto = require('crypto'); function FileStorage(args) { this.initialize(args); } FileStorage.prototype = { initialize: function(args) { this.name = args.name; this.basePath = args.basePath || '/tmp'; }, get directoryPath() { if (!this._directoryPath) { this._directoryPath = paht.join(this.basePath, this.name); } return this._directoryPath; }, // because document id can be too long, we should use a short hash // string instead of full id. getFileName: function(id) { var shasum = crypto.createHash('sha1'); shasum.update(id); return shasum.digest('hex'); }, getFilePath: function(id) { var filename = this.getFileName(id); return path.join(this.directoryPath, filename); }, saveSync: function(document) { if (!this.directoryExistsSync()) mkdirp.sync(this.databaseDirectory); var filePath = this.getFilePath(document.id); if (path.existsSync(filePath)) fs.unlinkSync(filePath); var contents = JSON.stringify(document); var file = fs.openSync(filePath, 'w', 0644); fs.writeSync(file, contents); fs.closeSync(file); }, readSync: function(id) { if (!this.directoryExistsSync()) return null; var filePath = this.getFilePath(document.id); if (path.existsSync(filePath)) return null; var contents = fs.readFileSync(filePath, 'UTF-8'); return JSON.parse(contents); }, deleteSync: function(id) { if (!this.directoryExistsSync()) return; var filePath = this.getFilePath(document.id); if (path.existsSync(filePath)) fs.unlinkSync(filePath); }, clearSync: function() { if (this.directoryExistsSync()) rmRSync(this.directoryPath); }, directoryExistsSync: function() { return path.existsSync(this.directoryPath); } }; exports.FileStorage = FileStorage; function MemoryStorage() { this._storage = {}; } MemoryStorage.prototype = { saveSync: function(document) { this._storage[document.id] = document; }, readSync: function(id) { return this._storage[id] || null; }, deleteSync: function(id) { delete this._storage[id]; }, clearSync: function() { this._storage = {}; } }; exports.MemoryStorage = MemoryStorage;
JavaScript
0.000723
@@ -664,19 +664,20 @@ l id.%0A -get +idTo FileName @@ -801,19 +801,20 @@ %7D,%0A%0A -get +idTo FilePath @@ -850,27 +850,28 @@ name = this. -get +idTo FileName(id) @@ -1060,35 +1060,36 @@ filePath = this. -get +idTo FilePath(documen @@ -1420,35 +1420,36 @@ filePath = this. -get +idTo FilePath(documen @@ -1709,19 +1709,20 @@ = this. -get +idTo FilePath
9547877d501f2b6bb34c7fcdb1af2c172da6f512
fix function source padding
src/Component/VarDumper/src/Cloner/VarCloner.js
src/Component/VarDumper/src/Cloner/VarCloner.js
const Caster = Jymfony.Component.VarDumper.Caster.Caster; const AbstractCloner = Jymfony.Component.VarDumper.Cloner.AbstractCloner; const Stub = Jymfony.Component.VarDumper.Cloner.Stub; // Global object ids. const objectIds = new WeakMap(); let currentObjectId = 1; /** * @memberOf Jymfony.Component.VarDumper.Cloner */ class VarCloner extends AbstractCloner { _doClone(variable) { const objectRefs = new Map(); let len = 1; let pos = 0; const queue = [ [ variable ] ]; let currentDepth = 0; let currentDepthFinalIndex = 0; const minDepth = this._minDepth; const maxString = this._maxString; const maxItems = this._maxItems; let minimumDepthReached = 0 === minDepth; let a = null; let stub = null; for (let i = 0; i < len; ++i) { if (i > currentDepthFinalIndex) { ++currentDepth; currentDepthFinalIndex = len - 1; if (currentDepth >= minDepth) { minimumDepthReached = true; } } const vals = queue[i]; for (const [ k, v ] of __jymfony.getEntries(vals)) { switch (true) { case undefined === v: case null === v: case isBoolean(v): case isNumber(v): continue; case isString(v): { if ('' === v) { continue; } let cut; if (0 <= maxString && v[1 + (maxString >> 2)] !== undefined && 0 < (cut = v.length - maxString)) { stub = new Stub(); stub.type = Stub.TYPE_STRING; stub.class_ = undefined; stub.attr.cut = cut; stub.value = v.substr(0, maxString); } else { continue; } a = null; } break; case isSymbol(v): stub = new Stub(); stub.type = Stub.TYPE_SYMBOL; stub.class_ = undefined; stub.value = v; a = null; break; case isArray(v): if (0 === v.length) { continue; } stub = new Stub(); stub.type = Stub.TYPE_ARRAY; stub.class_ = v.length; a = [ ...v ]; break; case isFunction(v) && ! v.__self__: { let class_ = Object.prototype.toString.call(v); const matches = class_.match(/^\[object (\w+)\]/); const kind = matches ? matches[1] : 'Function'; const value = { [Caster.PREFIX_VIRTUAL + 'name']: Object.prototype.hasOwnProperty.call(v, 'name') ? __jymfony.trim(v.name) : '<unknown function>', [Caster.PREFIX_VIRTUAL + 'function']: v.toString(), }; try { const r = new ReflectionClass(v); class_ = __jymfony.trim(r.name || r.getConstructor().name); value[Caster.PREFIX_VIRTUAL + 'name'] = __jymfony.trim(r.name || r.getConstructor().name || '<unknown function>'); } catch (e) { // Do nothing. } stub = new Stub(); stub.type = Stub.TYPE_OBJECT; stub.class_ = kind; stub.value = v; a = value; } break; case isFunction(v) && !! v.__self__: case isObject(v): { let h = objectIds.get(v); if (undefined === h) { objectIds.set(v, h = currentObjectId++); stub = new Stub(); stub.type = Stub.TYPE_OBJECT; stub.class_ = isObjectLiteral(v) ? 'Object' : ReflectionClass.getClassName(v); stub.value = v; stub.handle = h; a = this._castObject(stub, 0 < i); if (v !== stub.value) { if (Stub.TYPE_OBJECT !== stub.type || undefined === stub.value) { break; } objectIds.set(stub.value, h = currentObjectId++); stub.handle = h; } stub.value = undefined; if (0 <= maxItems && maxItems <= pos && minimumDepthReached) { stub.attr.cut = __jymfony.keys(a).length; a = null; } } if (! objectRefs.has(h)) { objectRefs.set(h, stub); } else { stub = objectRefs.get(h); ++stub.refCount; a = null; } } break; } if (null !== a && 0 < __jymfony.keys(a).length) { if (! minimumDepthReached || 0 > maxItems) { queue[len] = a; stub.attr.position = len++; } else if (pos < maxItems) { if (maxItems < (pos += __jymfony.keys(a).length)) { a = __jymfony.keys(a) .slice(0, maxItems - pos) .reduce((res, k) => (res[k] = a[k], res), {}); if (0 <= ~~stub.attr.cut) { stub.attr.cut += pos - maxItems; } } queue[len] = a; stub.attr.position = len++; } else if (0 <= stub.attr.cut) { stub.attr.cut += __jymfony.keys(a).length; stub.attr.position = 0; } } if (Stub.TYPE_ARRAY === stub.type && stub.attr.cut) { stub = [ stub.attr.cut, stub.attr.position ]; } vals[k] = stub; } queue[i] = vals; } return queue; } } module.exports = VarCloner;
JavaScript
0
@@ -3083,16 +3083,584 @@ tion';%0A%0A + const functionBody = v.toString().split('%5Cn');%0A const firstLine = functionBody.shift();%0A let pad = Infinity;%0A for (let i = 0; i %3C functionBody.length; ++i) %7B%0A const m = functionBody%5Bi%5D.match(/%5E(%5Cs+)/);%0A if (null === m) %7B%0A pad = 0;%0A break;%0A %7D%0A%0A pad = Math.min(m%5B1%5D.length, pad);%0A %7D%0A%0A @@ -3691,16 +3691,16 @@ lue = %7B%0A - @@ -3916,27 +3916,84 @@ tion'%5D: -v.toString( +%5BfirstLine, ...functionBody.map(line =%3E line.substr(pad))%5D.join('%5Cn' ),%0A
abe2fd9a2c675d7965191f9368c7e44ada90133f
Set the caption even if there are no buttons
dist/gala.js
dist/gala.js
var gala = (function() { var LEFT_BTN = '<span class="fa fa-fw fa-backward gala-nav"></span>'; var RIGHT_BTN = '<span class="fa fa-fw fa-forward gala-nav"></span>'; var FIGURE = '<figure class="gala-figure"></figure>'; var CAPTION = '<figcaption></figcaption>'; var addButtons = function($gala, $images) { var height = $gala.height() + 'px'; $images.css('left', 0); // First transition is ignored w/o this $gala.before(LEFT_BTN).prev().css('line-height', height).click(getOnClickLeft($gala, $images)); $gala.after(RIGHT_BTN).next().css('line-height', height).click(getOnClickRight($gala, $images)); updateButtonState($gala, 0, $images.length); updateCaptionText($gala, $images, 0); }; var addCaption = function($gala, $images) { $gala.wrap(FIGURE).after(CAPTION); }; var create = function(gala) { var $gala = $(gala); var $images = $gala.children('img'); addCaption($gala, $images); if ($images.length > 1) { addButtons($gala, $images); } }; var getOnClickLeft = function($gala, $images) { return function() { var width = $gala.width(); var offset = parseInt($images.css('left'), 10); var totalImages = $images.length; if (offset % width != 0 || totalImages <= 1 || offset <= -(width * (totalImages-1))) { return; } $images.css('left', (offset-width)+'px'); var currentImage = 1-offset/width; updateButtonState($gala, currentImage, totalImages); updateCaptionText($gala, $images, currentImage); }; }; var getOnClickRight = function($gala, $images) { return function() { var width = $gala.width(); var offset = parseInt($images.css('left'), 10); var totalImages = $images.length; if (offset % width != 0 || totalImages <= 1 || offset >= 0) { return; } $images.css('left', (offset+width)+'px'); var currentImage = -offset/width-1; updateButtonState($gala, currentImage, totalImages); updateCaptionText($gala, $images, currentImage); }; }; var updateButtonState = function($gala, currentImage, totalImages) { if (currentImage <= 0) { $gala.next().addClass('gala-disabled'); } else { $gala.next().removeClass('gala-disabled'); } if (currentImage >= totalImages-1) { $gala.prev().addClass('gala-disabled'); } else { $gala.prev().removeClass('gala-disabled'); } }; var updateCaptionText = function($gala, $images, currentImage) { var $caption = $gala.siblings('figcaption'); $caption.fadeOut(200, function() { $caption.text($images[currentImage].getAttribute('alt')).fadeIn(200); }); }; return { initialize: function() { $('.gala').each(function(index, gala) { create(gala); }); } } })(); $(document).ready(gala.initialize);
JavaScript
0.000014
@@ -674,50 +674,8 @@ h);%0A - updateCaptionText($gala, $images, 0);%0A %7D; @@ -761,16 +761,58 @@ PTION);%0A + updateCaptionText($gala, $images, 0);%0A %7D;%0A%0A
10af8659596fdb70f197489ec23a2dc34427e238
Update colorizer.js to check for ANSICON and have colors on Windows
modules/colorizer.js
modules/colorizer.js
/*! * Casper is a navigation utility for PhantomJS. * * Documentation: http://casperjs.org/ * Repository: http://github.com/n1k0/casperjs * * Copyright (c) 2011-2012 Nicolas Perriault * * Part of source code is Copyright Joyent, Inc. and other Node contributors. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*global exports, console, patchRequire, require:true*/ var require = patchRequire(require); var fs = require('fs'); var utils = require('utils'); var env = require('system').env; exports.create = function create(type) { "use strict"; if (!type) { return; } if (!(type in exports)) { throw new Error(utils.format('Unsupported colorizer type "%s"', type)); } return new exports[type](); }; /** * This is a port of lime colorizer. * http://trac.symfony-project.org/browser/tools/lime/trunk/lib/lime.php * * (c) Fabien Potencier, Symfony project, MIT license */ var Colorizer = function Colorizer() { "use strict"; var options = { bold: 1, underscore: 4, blink: 5, reverse: 7, conceal: 8 }; var foreground = { black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37 }; var background = { black: 40, red: 41, green: 42, yellow: 43, blue: 44, magenta: 45, cyan: 46, white: 47 }; var styles = { 'ERROR': { bg: 'red', fg: 'white', bold: true }, 'INFO': { fg: 'green', bold: true }, 'TRACE': { fg: 'green', bold: true }, 'PARAMETER': { fg: 'cyan' }, 'COMMENT': { fg: 'yellow' }, 'WARNING': { fg: 'red', bold: true }, 'GREEN_BAR': { fg: 'white', bg: 'green', bold: true }, 'RED_BAR': { fg: 'white', bg: 'red', bold: true }, 'INFO_BAR': { bg: 'cyan', fg: 'white', bold: true }, 'WARN_BAR': { bg: 'yellow', fg: 'white', bold: true }, 'SKIP': { fg: 'magenta', bold: true }, 'SKIP_BAR': { bg: 'magenta', fg: 'white', bold: true } }; /** * Adds a style to provided text. * * @param String text * @param String styleName * @return String */ this.colorize = function colorize(text, styleName, pad) { if (fs.isWindows() || !env['ANSICON'] || !(styleName in styles)) { return text; } return this.format(text, styles[styleName], pad); }; /** * Formats a text using a style declaration object. * * @param String text * @param Object style * @return String */ this.format = function format(text, style, pad) { if (fs.isWindows() || !env['ANSICON'] || !utils.isObject(style)) { return text; } var codes = []; if (style.fg && foreground[style.fg]) { codes.push(foreground[style.fg]); } if (style.bg && background[style.bg]) { codes.push(background[style.bg]); } for (var option in options) { if (style[option] === true) { codes.push(options[option]); } } // pad if (typeof pad === "number" && text.length < pad) { text += new Array(pad - text.length + 1).join(' '); } return "\u001b[" + codes.join(';') + 'm' + text + "\u001b[0m"; }; }; exports.Colorizer = Colorizer; /** * Dummy colorizer. Does basically nothing. * */ var Dummy = function Dummy() { "use strict"; this.colorize = function colorize(text, styleName, pad) { return text; }; this.format = function format(text, style, pad){ return text; }; }; exports.Dummy = Dummy;
JavaScript
0
@@ -3215,32 +3215,33 @@ d) %7B%0A if +( (fs.isWindows() @@ -3232,34 +3232,34 @@ (fs.isWindows() -%7C%7C +&& !env%5B'ANSICON'%5D @@ -3254,24 +3254,25 @@ v%5B'ANSICON'%5D +) %7C%7C !(styleN @@ -3613,16 +3613,17 @@ if +( (fs.isWi @@ -3630,18 +3630,18 @@ ndows() -%7C%7C +&& !env%5B'A @@ -3648,16 +3648,17 @@ NSICON'%5D +) %7C%7C !uti
bf005e6fd93293cb26a994a5e51c5c6135f62a97
Remove content layout padding adjustments.
src/ContentBlocks/ContentLayoutEngine/styles.js
src/ContentBlocks/ContentLayoutEngine/styles.js
import React from 'react'; import styled, { css } from 'styled-components'; import GrommetBox from 'grommet/components/Box'; import GrommetSection from 'grommet/components/Section'; const responsiveBoxStyles = (props) => { if (props.hideForResponsive) { return css` @media screen and (max-width: 1056px) { display: none !important; } `; } return css` @media screen and (max-width: 1056px) { padding-right: 0px; padding-bottom: 24px; max-width: 100%; flex-basis: auto; width: 100%; } `; }; // eslint-disable-next-line no-unused-vars export const Box = styled(({ hideForResponsive, ...rest }) => <GrommetBox {...rest} />)` padding: 0; margin: 0; padding-right: 24px; padding-bottom: 48px; ${props => responsiveBoxStyles(props)} `; export const Section = styled(GrommetSection)` & > div:empty { padding: 0; margin: 0; } &:first-child > div:first-child { margin-top: 0; padding-top: 0; } ul { margin-bottom: 24px; padding-bottom: 0; li:last-child { p:last-child { margin-bottom: 0; } } } &:last-child > div:last-child, div > div, { margin-bottom: 0; padding-bottom: 0; p:last-child, div:last-child:not(.grommetux-tile), h2:last-child, h3:last-child, h4:last-child, h5:last-child, ul:last-child { margin-bottom: 0; padding-bottom: 0; li:last-child { p:last-child { margin-bottom: 0; } } } } `;
JavaScript
0
@@ -694,82 +694,8 @@ %3E)%60%0A - padding: 0;%0A margin: 0;%0A padding-right: 24px;%0A padding-bottom: 48px;%0A $%7B @@ -838,635 +838,8 @@ %0A %7D -%0A%0A &:first-child %3E div:first-child %7B%0A margin-top: 0;%0A padding-top: 0;%0A %7D%0A%0A ul %7B%0A margin-bottom: 24px;%0A padding-bottom: 0;%0A%0A li:last-child %7B%0A p:last-child %7B%0A margin-bottom: 0;%0A %7D%0A %7D%0A %7D%0A%0A &:last-child %3E div:last-child,%0A div %3E div, %7B%0A margin-bottom: 0;%0A padding-bottom: 0;%0A %0A p:last-child,%0A div:last-child:not(.grommetux-tile),%0A h2:last-child,%0A h3:last-child,%0A h4:last-child,%0A h5:last-child,%0A ul:last-child %7B%0A margin-bottom: 0;%0A padding-bottom: 0;%0A%0A li:last-child %7B%0A p:last-child %7B%0A margin-bottom: 0;%0A %7D%0A %7D%0A %7D%0A %7D %0A%60;%0A
b633caaf97e555526fc53192fd7ddb4935196456
change var to let/const
src/edit/getEXIFdata.js
src/edit/getEXIFdata.js
/* eslint-disable no-unused-vars */ L.EXIF = function getEXIFdata(img) { if (Object.keys(EXIF.getAllTags(img)).length !== 0) { console.log(EXIF.getAllTags(img)); var GPS = EXIF.getAllTags(img); var altitude; /* If the lat/lng is available. */ if ( typeof GPS.GPSLatitude !== 'undefined' && typeof GPS.GPSLongitude !== 'undefined' ) { // sadly, encoded in [degrees,minutes,seconds] // primitive value = GPS.GPSLatitude[x].numerator var lat = GPS.GPSLatitude[0] + GPS.GPSLatitude[1] / 60 + GPS.GPSLatitude[2] / 3600; var lng = GPS.GPSLongitude[0] + GPS.GPSLongitude[1] / 60 + GPS.GPSLongitude[2] / 3600; if (GPS.GPSLatitudeRef !== 'N') { lat = lat * -1; } if (GPS.GPSLongitudeRef === 'W') { lng = lng * -1; } } // Attempt to use GPS compass heading; will require // some trig to calc corner points, which you can find below: var angle = 0; // "T" refers to "True north", so -90. if (GPS.GPSImgDirectionRef === 'T') { angle = (Math.PI / 180) * (GPS.GPSImgDirection.numerator / GPS.GPSImgDirection.denominator - 90); // "M" refers to "Magnetic north" } else if (GPS.GPSImgDirectionRef === 'M') { angle = (Math.PI / 180) * (GPS.GPSImgDirection.numerator / GPS.GPSImgDirection.denominator - 90); } else { console.log('No compass data found'); } console.log('Orientation:', GPS.Orientation); /* If there is orientation data -- i.e. landscape/portrait etc */ if (GPS.Orientation === 6) { // CCW angle += (Math.PI / 180) * -90; } else if (GPS.Orientation === 8) { // CW angle += (Math.PI / 180) * 90; } else if (GPS.Orientation === 3) { // 180 angle += (Math.PI / 180) * 180; } /* If there is altitude data */ if ( typeof GPS.GPSAltitude !== 'undefined' && typeof GPS.GPSAltitudeRef !== 'undefined' ) { // Attempt to use GPS altitude: // (may eventually need to find EXIF field of view for correction) if ( typeof GPS.GPSAltitude !== 'undefined' && typeof GPS.GPSAltitudeRef !== 'undefined' ) { altitude = GPS.GPSAltitude.numerator / GPS.GPSAltitude.denominator + GPS.GPSAltitudeRef; } else { altitude = 0; // none } } } else { alert('EXIF initialized. Press again to view data in console.'); } };
JavaScript
0.000001
@@ -165,19 +165,21 @@ ));%0A -var +const GPS = E @@ -203,19 +203,19 @@ g);%0A -var +let altitud @@ -483,19 +483,19 @@ r%0A -var +let lat =%0A @@ -597,19 +597,19 @@ ;%0A -var +let lng =%0A @@ -988,19 +988,19 @@ w:%0A%0A -var +let angle =
3544c5cbd6abf4ed6bbc7f429f1af7773e26ae32
bump version to 1.1.2
dist/gitu.js
dist/gitu.js
#!/usr/bin/env node "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _child_process = require("child_process"); var _colors = require("colors"); var _colors2 = _interopRequireDefault(_colors); var _figlet = require("figlet"); var _figlet2 = _interopRequireDefault(_figlet); var _assert = require("assert"); var _assert2 = _interopRequireDefault(_assert); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var CMD = function () { function CMD(path, args) { _classCallCheck(this, CMD); this.path = path; this.args = args; } _createClass(CMD, [{ key: "execute", value: function execute(cb) { var childProcess = (0, _child_process.spawn)(this.path, this.args, { cwd: process.cwd(), stdio: 'inherit' }); childProcess.on('exit', function (code) { if (code !== 0) { console.log(_colors2.default.red('git-upload failed.')); process.exit(1); } cb(); }); } }]); return CMD; }(); new CMD('git', ['add', '.']).execute(function () { new CMD('git', ['commit', '-m', process.argv.slice(2).join(' ')]).execute(function () { new CMD('git', ['push']).execute(function () { console.log(_colors2.default.green('done!')); (0, _figlet2.default)('200 OK!', function (err, text) { _assert2.default.ifError(err); console.log(text); }); }); }); }); //# sourceMappingURL=gitu.js.map
JavaScript
0
@@ -2300,37 +2300,4 @@ %0A%7D); -%0A//# sourceMappingURL=gitu.js.map
d65537a676ca69ce94ca0b9861e6401269762dc7
Use message type redirection on both stderr & stdout
lib/delve-server-mgr.js
lib/delve-server-mgr.js
'use babel'; /** Delve Server Manager @description Manages the Delve server process **/ const ChildProc = require('child_process'); const EventEmitter = require('events'); const Path = require('path'); import Config from './config.js'; const delveCommands = { debug: 'debug', test: 'test' }; /** @class @extends EventEmitter @name DelveServerMgr @desc Manages the Delve server process and lifecycle of the session @emits 'startServer' on delve server start, gives host & port of server @emits 'error' on delve server error or unexpected disconnect **/ export default class DelveServerMgr extends EventEmitter { constructor() { super(); this.delveProc = null; this._pid = null; this.hasSessionStarted = false; } startDebugSession(packagePath, flags) { this.spawnProcess(delveCommands.debug, packagePath, flags); } startTestingSession(packagePath, flags) { this.spawnProcess(delveCommands.test, packagePath, flags); } endSession() { this.hasSessionStarted = false; if (this.delveProc) this.delveProc.kill(); this._pid = null; this.delveProc = null; } /** @private @name #spawnProcess @desc creates a new delve process with the given command and registers our event handlers with it @param { String } command @param { String } cwd => will affect what package is being run against @param { String|String[] } buildFlags :optional **/ spawnProcess(command, cwd, buildFlags) { let { serverHost, serverPort, logServerMessages } = Config; console.debug('Config obj is ', Config); let args = [command, '--headless', `--listen=${serverHost}:${serverPort}`]; if (buildFlags) if (Array.isArray(buildFlags)) args.push(`--build-flags=${buildFlags.join(' ')}`); else args.push(`--build-flags="${buildFlags}"`); if (logServerMessages) args.push('--log'); this.delveProc = ChildProc.spawn('dlv', args, { cwd: Path.resolve(cwd) }); this._pid = this.delveProc.pid; this.isRemote = false; this.delveProc.on('data', data => { if (!this.hasSessionStarted) { this.hasSessionStarted = true; return this.emit('serverStart', serverHost, serverPort); } console.debug('Received Delve data: ', data); }); this.delveProc.on('error', err => this.emit('error', err)); // Delve will output *all* of it's messages on stdout (even for error) // however log info messages will start with a timestamp => yyyy/mm/dd // so redirect if we find 4 numbers at the start (a year) this.delveProc.stdout.on('data', d => { let msg = d.toString(); if (msg.trimLeft().search(/^[0-9]{4}.*$/) < 0) return this.emit('error', d.toString()); this.emit('delveMessage', d); }); this.delveProc.on('disconnect', () => { // make sure we think we have a session before declaring an error if (this.hasSessionStarted) this.emit('error', new Error('Delve server disconnected')); }); this.delveProc.on('close', exitCode => this.emit( 'fatal', new Error(`Delve exited with code ${exitCode}`) ) ); if (logServerMessages) { let logMsg = d => console.debug('Delve: ', d.toString()); this.on('delveMessage', logMsg); this.delveProc.on('message', msg => console.debug('Delve: ', msg)); } } }
JavaScript
0.000001
@@ -1562,53 +1562,8 @@ ig;%0A - console.debug('Config obj is ', Config);%0A @@ -2547,40 +2547,38 @@ -this.delveProc.stdout.on('data', +let detectMsgTypeAndRedirect = d = @@ -2747,32 +2747,160 @@ sage', d);%0A %7D +;%0A%0A this.delveProc.stdout.on('data', detectMsgTypeAndRedirect);%0A this.delveProc.stderr.on('data', detectMsgTypeAndRedirect );%0A%0A this.del
7556df72659e549554bf5695e883e855d944019c
Make sure to return the current version of entity from tree.intersects
modules/core/tree.js
modules/core/tree.js
import rbush from 'rbush'; import { coreDifference } from './difference'; export function coreTree(head) { var rtree = rbush(); var bboxes = {}; var tree = {}; function entityBBox(entity) { var bbox = entity.extent(head).bbox(); bbox.id = entity.id; bboxes[entity.id] = bbox; return bbox; } function updateParents(entity, insertions, memo) { head.parentWays(entity).forEach(function(way) { if (bboxes[way.id]) { rtree.remove(bboxes[way.id]); insertions[way.id] = way; } updateParents(way, insertions, memo); }); head.parentRelations(entity).forEach(function(relation) { if (memo[entity.id]) return; memo[entity.id] = true; if (bboxes[relation.id]) { rtree.remove(bboxes[relation.id]); insertions[relation.id] = relation; } updateParents(relation, insertions, memo); }); } tree.rebase = function(entities, force) { var insertions = {}; for (var i = 0; i < entities.length; i++) { var entity = entities[i]; if (!entity.visible) continue; if (head.entities.hasOwnProperty(entity.id) || bboxes[entity.id]) { if (!force) { continue; } else if (bboxes[entity.id]) { rtree.remove(bboxes[entity.id]); } } insertions[entity.id] = entity; updateParents(entity, insertions, {}); } rtree.load(Object.values(insertions).map(entityBBox)); return tree; }; tree.intersects = function(extent, graph) { if (graph !== head) { var diff = coreDifference(head, graph); var changed = diff.didChange; if (changed.addition || changed.deletion || changed.geometry) { var insertions = {}; head = graph; if (changed.deletion) { diff.deleted().forEach(function(entity) { rtree.remove(bboxes[entity.id]); delete bboxes[entity.id]; }); } if (changed.geometry) { diff.modified().forEach(function(entity) { rtree.remove(bboxes[entity.id]); insertions[entity.id] = entity; updateParents(entity, insertions, {}); }); } if (changed.addition) { diff.created().forEach(function(entity) { insertions[entity.id] = entity; }); } rtree.load(Object.values(insertions).map(entityBBox)); } } return rtree.search(extent.bbox()) .map(function(bbox) { return head.entity(bbox.id); }); }; return tree; }
JavaScript
0
@@ -2983,20 +2983,21 @@ return -head +graph .entity(
0a1272a0904efe2a9df48da57e1f8ce9f46d97e2
Update irpf90 to new styles
src/languages/irpf90.js
src/languages/irpf90.js
/* Language: IRPF90 Author: Anthony Scemama <[email protected]> Description: IRPF90 is an open-source Fortran code generator : http://irpf90.ups-tlse.fr Category: scientific */ function(hljs) { var PARAMS = { className: 'params', begin: '\\(', end: '\\)' }; var F_KEYWORDS = { constant: '.False. .True.', type: 'integer real character complex logical dimension allocatable|10 parameter ' + 'external implicit|10 none double precision assign intent optional pointer ' + 'target in out common equivalence data', keyword: 'kind do while private call intrinsic where elsewhere ' + 'type endtype endmodule endselect endinterface end enddo endif if forall endforall only contains default return stop then ' + 'public subroutine|10 function program .and. .or. .not. .le. .eq. .ge. .gt. .lt. ' + 'goto save else use module select case ' + 'access blank direct exist file fmt form formatted iostat name named nextrec number opened rec recl sequential status unformatted unit ' + 'continue format pause cycle exit ' + 'c_null_char c_alert c_backspace c_form_feed flush wait decimal round iomsg ' + 'synchronous nopass non_overridable pass protected volatile abstract extends import ' + 'non_intrinsic value deferred generic final enumerator class associate bind enum ' + 'c_int c_short c_long c_long_long c_signed_char c_size_t c_int8_t c_int16_t c_int32_t c_int64_t c_int_least8_t c_int_least16_t ' + 'c_int_least32_t c_int_least64_t c_int_fast8_t c_int_fast16_t c_int_fast32_t c_int_fast64_t c_intmax_t C_intptr_t c_float c_double ' + 'c_long_double c_float_complex c_double_complex c_long_double_complex c_bool c_char c_null_ptr c_null_funptr ' + 'c_new_line c_carriage_return c_horizontal_tab c_vertical_tab iso_c_binding c_loc c_funloc c_associated c_f_pointer ' + 'c_ptr c_funptr iso_fortran_env character_storage_size error_unit file_storage_size input_unit iostat_end iostat_eor ' + 'numeric_storage_size output_unit c_f_procpointer ieee_arithmetic ieee_support_underflow_control ' + 'ieee_get_underflow_mode ieee_set_underflow_mode newunit contiguous recursive ' + 'pad position action delim readwrite eor advance nml interface procedure namelist include sequence elemental pure ' + // IRPF90 special keywords 'begin_provider &begin_provider end_provider begin_shell end_shell begin_template end_template subst assert touch ' + 'soft_touch provide no_dep free irp_if irp_else irp_endif irp_write irp_read', built_in: 'alog alog10 amax0 amax1 amin0 amin1 amod cabs ccos cexp clog csin csqrt dabs dacos dasin datan datan2 dcos dcosh ddim dexp dint ' + 'dlog dlog10 dmax1 dmin1 dmod dnint dsign dsin dsinh dsqrt dtan dtanh float iabs idim idint idnint ifix isign max0 max1 min0 min1 sngl ' + 'algama cdabs cdcos cdexp cdlog cdsin cdsqrt cqabs cqcos cqexp cqlog cqsin cqsqrt dcmplx dconjg derf derfc dfloat dgamma dimag dlgama ' + 'iqint qabs qacos qasin qatan qatan2 qcmplx qconjg qcos qcosh qdim qerf qerfc qexp qgamma qimag qlgama qlog qlog10 qmax1 qmin1 qmod ' + 'qnint qsign qsin qsinh qsqrt qtan qtanh abs acos aimag aint anint asin atan atan2 char cmplx conjg cos cosh exp ichar index int log ' + 'log10 max min nint sign sin sinh sqrt tan tanh print write dim lge lgt lle llt mod nullify allocate deallocate ' + 'adjustl adjustr all allocated any associated bit_size btest ceiling count cshift date_and_time digits dot_product ' + 'eoshift epsilon exponent floor fraction huge iand ibclr ibits ibset ieor ior ishft ishftc lbound len_trim matmul ' + 'maxexponent maxloc maxval merge minexponent minloc minval modulo mvbits nearest pack present product ' + 'radix random_number random_seed range repeat reshape rrspacing scale scan selected_int_kind selected_real_kind ' + 'set_exponent shape size spacing spread sum system_clock tiny transpose trim ubound unpack verify achar iachar transfer ' + 'dble entry dprod cpu_time command_argument_count get_command get_command_argument get_environment_variable is_iostat_end ' + 'ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode ' + 'is_iostat_eor move_alloc new_line selected_char_kind same_type_as extends_type_of' + 'acosh asinh atanh bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn erf erfc erfc_scaled gamma log_gamma hypot norm2 ' + 'atomic_define atomic_ref execute_command_line leadz trailz storage_size merge_bits ' + 'bge bgt ble blt dshiftl dshiftr findloc iall iany iparity image_index lcobound ucobound maskl maskr ' + 'num_images parity popcnt poppar shifta shiftl shiftr this_image ' + // IRPF90 special built_ins 'IRP_ALIGN irp_here' }; return { case_insensitive: true, keywords: F_KEYWORDS, contains: [ hljs.inherit(hljs.APOS_STRING_MODE, {className: 'string', relevance: 0}), hljs.inherit(hljs.QUOTE_STRING_MODE, {className: 'string', relevance: 0}), { className: 'function', beginKeywords: 'subroutine function program', illegal: '[${=\\n]', contains: [hljs.UNDERSCORE_TITLE_MODE, PARAMS] }, hljs.COMMENT('!', '$', {relevance: 0}), hljs.COMMENT('begin_doc', 'end_doc', {relevance: 10}), { className: 'number', begin: '(?=\\b|\\+|\\-|\\.)(?=\\.\\d|\\d)(?:\\d+)?(?:\\.?\\d*)(?:[de][+-]?\\d+)?\\b\\.?', relevance: 0 } ] }; }
JavaScript
0
@@ -303,16 +303,15 @@ -constant +literal : '.
74bca2ab7da4ba8f24092b3414b4603caa5de251
Remove qualifier
lib/node_modules/@stdlib/math/base/special/gamma1pm1/test/test.js
lib/node_modules/@stdlib/math/base/special/gamma1pm1/test/test.js
'use strict'; // MODULES // var tape = require( 'tape' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var gamma = require( '@stdlib/math/base/special/gamma' ); var abs = require( '@stdlib/math/base/special/abs' ); var incrspace = require( '@stdlib/math/utils/incrspace' ); var EPS = require( '@stdlib/math/constants/float64-eps' ); var gamma1pm1 = require( './../lib' ); // FIXTURES // var smallPositive = require( './fixtures/cpp/small_positive.json' ); var smalleNegative = require( './fixtures/cpp/small_negative.json' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.equal( typeof gamma1pm1, 'function', 'main export is a function' ); t.end(); }); tape( 'the function simply computes `gamma(x+1) - 1` for most `x` (negative)', function test( t ) { var expected; var val; var x; var y; var i; x = incrspace( -170.5, -0.5, 0.5 ); for ( i = 0; i < x.length; i++ ) { // Add 0.1, as the gamma function is not defined for negative integers: val = x[ i ] + 0.1; y = gamma1pm1( val ); expected = gamma( val+1.0 ) - 1.0; t.equal( y, expected, 'returns expected value' ); } t.end(); }); tape( 'the function simply computes `gamma(x+1) - 1` for most `x` (positive)', function test( t ) { var expected; var val; var x; var y; var i; x = incrspace( 2.0, 170.5, 0.5 ); for ( i = 0; i < x.length; i++ ) { val = x[ i ]; y = gamma1pm1( val ); expected = gamma( val+1.0 ) - 1.0; t.equal( y, expected, 'returns expected value' ); } t.end(); }); tape( 'the function accurately computes `gamma(x+1) - 1` for small negative numbers', function test( t ) { var expected; var delta; var tol; var x; var v; var i; x = smalleNegative.x; expected = smalleNegative.expected; for ( i = 0; i < x.length; i++ ) { v = gamma1pm1( x[ i ] ); delta = abs( v - expected[ i ] ); tol = 2.0 * EPS * abs( expected[ i ] ); t.ok( delta <= tol, 'within tolerance. x: ' + x[ i ] + '. Value: ' + v + '. Expected: ' + expected[ i ] + '. Tolerance: ' + tol + '.' ); } t.end(); }); tape( 'the function accurately computes `gamma(x+1) - 1` for small positive numbers', function test( t ) { var expected; var delta; var tol; var x; var v; var i; x = smallPositive.x; expected = smallPositive.expected; for ( i = 0; i < x.length; i++ ) { v = gamma1pm1( x[ i ] ); delta = abs( v - expected[ i ] ); tol = 2.0 * EPS * abs( expected[ i ] ); t.ok( delta <= tol, 'within tolerance. x: ' + x[ i ] + '. Value: ' + v + '. Expected: ' + expected[ i ] + '. Tolerance: ' + tol + '.' ); } t.end(); }); tape( 'the function returns `NaN` if provided `NaN`', function test( t ) { var val = gamma1pm1( NaN ); t.equal( isnan( val ), true, 'equals NaN' ); t.end(); });
JavaScript
0.000006
@@ -733,39 +733,32 @@ ( 'the function -simply computes %60gamma( @@ -1187,15 +1187,8 @@ ion -simply comp
9ad22fdcb1378eb275c57130479563eed9af6e67
fix optional mesh indices
gl/GLVertexArray.js
gl/GLVertexArray.js
export default class GLVertexArray { constructor({ gl = undefined, mesh = undefined, program = undefined } = {}) { this.gl = gl; const extension = gl.getExtension("OES_vertex_array_object"); if(extension) { this.gl.createVertexArray = extension.createVertexArrayOES.bind(extension); this.gl.bindVertexArray = extension.bindVertexArrayOES.bind(extension); } this._vertexArray = this.gl.createVertexArray(); if(mesh || program) { this.add({ mesh, program }); } } add({ mesh = undefined, program = undefined } = {}) { this.bind(); program.attributes.set(mesh.attributes); mesh.indices.buffer.bind(); this.unbind(); } bind() { this.gl.bindVertexArray(this._vertexArray); } unbind() { this.gl.bindVertexArray(null); } }
JavaScript
0
@@ -677,16 +677,41 @@ butes);%0A + if(mesh.indices) %7B%0A mesh @@ -730,24 +730,30 @@ fer.bind();%0A + %7D%0A this.unb
bc684cf7bedd6e9c50a377fa3bd61e901a446efb
Modify UI
components/event-detail.js
components/event-detail.js
var React = require('react-native'); var Collapsible = require('react-native-collapsible'); var Accordion = require('react-native-collapsible/Accordion') var styles = require('../stylesheets/layout'); var Header = require('./header'); var Swiper = require('react-native-swiper'); var { View, ListView, Text, Image, TouchableHighlight } = React; var EventDetail = React.createClass({ getInitialState: function() { return { scenarios: [], dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), loaded: false, }; }, componentDidMount: function() { this.fetchData(); }, fetchData: function() { var event_id = this.props.bet_event.id; var Event_URL = 'http:/localhost:3000/events/' + event_id + '/scenarios'; fetch(Event_URL) .then((response) => response.json()) .then((responseData) => { this.setState({ scenarios: responseData, dataSource: this.state.dataSource.cloneWithRows(responseData), loaded: true, }); console.log(responseData); }) .done(); }, goBack() { this.props.navigator.pop(); }, goToScenario: function(scenario) { this.props.navigator.push({ component: ScenarioDetail, passProps: { scenario: scenario, } }); }, renderScenarios: function(scenario) { return ( <TouchableHighlight onPress={this.goToScenario.bind(this, scenario)}> <View> <View style={styles.container}> <Text style={styles.bodyText}>{scenario.question}</Text> </View> <View style={styles.separator} /> </View> </TouchableHighlight> ) }, postWager: function(scenario) { var scenarioId = scenario.id; var eventId = this.props.bet_event.id; var scenarioURL = 'http:/localhost:3000/wagers'; fetch(scenarioURL, { method: "POST", body: JSON.stringify({ "amount": 1000, "scenario_id": scenarioId }) }); }, renderDropdown: function(scenario) { return ( <Swiper onMomentumScrollEnd={() => console.log(this.postWager(scenario))}> <View> <Text style={{color: 'black', fontWeight: 'bold', fontSize: 20}}>How much do you want to bet?</Text> </View> <View> <Text style={{color: 'black', fontWeight: 'bold', fontSize: 20}}>Thanks for betting. Good luck!</Text> </View> </Swiper> ) }, renderHeader: function(scenario) { var yv = scenario.yes_votes, nv = scenario.no_votes, wd = scenario.wager_difference; return ( <View> <View style={styles.container}> <Text style={styles.bodyText}>{scenario.question}</Text> <Text style={{color: 'green', fontWeight: 'bold', fontSize: 20}}>Yes: {yv}</Text> <Text style={{color: 'red', fontWeight: 'bold', fontSize: 20}}>No: {nv} </Text> <Text style={{color: 'blue', fontWeight: 'bold', fontSize: 20}}>Wager Difference: {wd}</Text> <Text>___________________________________________________</Text> </View> <View style={styles.separator} /> </View> ) }, render() { return ( <Image style={styles.imageBackground} source={{uri: 'http://i.imgur.com/YZWUKAq.jpg'}}> <Header/> <View style={styles.container}> <View style={{color: '#FFFFFF'}}> <Accordion sections={this.state.scenarios} renderHeader={this.renderHeader} renderContent={this.renderDropdown} /> </View> </View> </Image> ); } }); module.exports = EventDetail;
JavaScript
0.000001
@@ -2220,36 +2220,25 @@ 0%7D%7D%3E -How much do you want to bet? +Bet 5000 Satoshi! %3C/Te @@ -2945,18 +2945,18 @@ ntSize: -20 +18 %7D%7D%3EWager @@ -2960,22 +2960,16 @@ ger Diff -erence : %7Bwd%7D%3C/
de153f49d1aff4652d1c23da8da84f98c4ad6e40
rebuild of pure.js
dist/pure.js
dist/pure.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * @file pure * @desc Prevents the component from updating unless a prop has changed. * Uses shallow equal to test for changes. * @author Roman Zanettin <[email protected]> * @date 2017-02-15 */ var _compose = require('./compose'); var _compose2 = _interopRequireDefault(_compose); var _shouldUpdate = require('./shouldUpdate'); var _shouldUpdate2 = _interopRequireDefault(_shouldUpdate); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var withUpdatePolicy = (0, _shouldUpdate2.default)(function (props, nextProps) { // handle invalid props if (!props || !nextProps || (typeof props === 'undefined' ? 'undefined' : _typeof(props)) !== 'object' || (typeof nextProps === 'undefined' ? 'undefined' : _typeof(nextProps)) !== 'object') { return true; } var keys = Object.keys(props); for (var i = 0; i < keys; i += 1) { if (props[keys[i]] !== nextProps[keys[i]]) { return true; // just update if we find a shallow diff } } return false; }); /** * @param {Function} component * @returns {Function} */ exports.default = function (Component) { return (0, _compose2.default)(withUpdatePolicy)(Component); };
JavaScript
0.000002
@@ -2882,16 +2882,23 @@ i %3C keys +.length ; i += 1
f936f4fbcba941885a9a03546d1bb3c9d793c922
Change this.name and priority
backend/servers/mcservd/initializers/apikey.js
backend/servers/mcservd/initializers/apikey.js
const {Initializer, api} = require('actionhero'); module.exports = class APIKeyInitializer extends Initializer { constructor() { super(); this.name = 'zapikey'; this.startPriority = 50; } initialize() { // ************************************************************************************************* // require('../lib/apikey-cache') in initialize so that rethinkdb initializer has run before the require // statement, otherwise rethinkdb in r is not defined. // ************************************************************************************************* const apikeyCache = require('../lib/apikey-cache'); const middleware = { name: this.name, global: true, preProcessor: async (data) => { if (data.actionTemplate.do_not_authenticate) { return; } if (!data.params.apikey) { throw new Error('Not authorized'); } let user = await apikeyCache.find(data.params.apikey); if (! user) { throw new Error('Not authorized'); } data.user = user; } }; api.actions.addMiddleware(middleware) } };
JavaScript
0.00358
@@ -165,17 +165,16 @@ name = ' -z apikey'; @@ -207,9 +207,11 @@ y = -5 +100 0;%0A
3216a860a3c90489d2d06bc2cb0c1c1b54d208e7
Fix indentation in zephir.js
src/languages/zephir.js
src/languages/zephir.js
/* Language: Zephir Author: Oleg Efimov <[email protected]> */ function(hljs) { var STRING = { className: 'string', contains: [hljs.BACKSLASH_ESCAPE], variants: [ { begin: 'b"', end: '"' }, { begin: 'b\'', end: '\'' }, hljs.inherit(hljs.APOS_STRING_MODE, {illegal: null}), hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}) ] }; var NUMBER = {variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE]}; return { aliases: ['zep'], case_insensitive: true, keywords: 'and include_once list abstract global private echo interface as static endswitch ' + 'array null if endwhile or const for endforeach self var let while isset public ' + 'protected exit foreach throw elseif include __FILE__ empty require_once do xor ' + 'return parent clone use __CLASS__ __LINE__ else break print eval new ' + 'catch __METHOD__ case exception default die require __FUNCTION__ ' + 'enddeclare final try switch continue endfor endif declare unset true false ' + 'trait goto instanceof insteadof __DIR__ __NAMESPACE__ ' + 'yield finally int uint long ulong char uchar double float bool boolean string' + 'likely unlikely', contains: [ hljs.C_LINE_COMMENT_MODE, hljs.HASH_COMMENT_MODE, hljs.COMMENT( '/\\*', '\\*/', { contains: [ { className: 'doctag', begin: '@[A-Za-z]+' } ] } ), hljs.COMMENT( '__halt_compiler.+?;', false, { endsWithParent: true, keywords: '__halt_compiler', lexemes: hljs.UNDERSCORE_IDENT_RE } ), { className: 'string', begin: '<<<[\'"]?\\w+[\'"]?$', end: '^\\w+;', contains: [hljs.BACKSLASH_ESCAPE] }, { // swallow composed identifiers to avoid parsing them as keywords begin: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/ }, { className: 'function', beginKeywords: 'function', end: /[;{]/, excludeEnd: true, illegal: '\\$|\\[|%', contains: [ hljs.UNDERSCORE_TITLE_MODE, { className: 'params', begin: '\\(', end: '\\)', contains: [ 'self', hljs.C_BLOCK_COMMENT_MODE, STRING, NUMBER ] } ] }, { className: 'class', beginKeywords: 'class interface', end: '{', excludeEnd: true, illegal: /[:\(\$"]/, contains: [ {beginKeywords: 'extends implements'}, hljs.UNDERSCORE_TITLE_MODE ] }, { beginKeywords: 'namespace', end: ';', illegal: /[\.']/, contains: [hljs.UNDERSCORE_TITLE_MODE] }, { beginKeywords: 'use', end: ';', contains: [hljs.UNDERSCORE_TITLE_MODE] }, { begin: '=>' // No markup, just a relevance booster }, STRING, NUMBER ] }; }
JavaScript
0.000778
@@ -555,16 +555,18 @@ ds:%0A + 'and inc @@ -647,16 +647,18 @@ ' +%0A + 'array n @@ -737,16 +737,18 @@ ' +%0A + + 'protect @@ -827,16 +827,18 @@ ' +%0A + 'return @@ -907,16 +907,18 @@ ' +%0A + + 'catch _ @@ -975,24 +975,26 @@ CTION__ ' +%0A + 'enddecl @@ -1061,24 +1061,26 @@ e false ' +%0A + 'trait g @@ -1134,16 +1134,18 @@ ' +%0A + 'yield f @@ -1214,24 +1214,26 @@ n string' +%0A + 'likely
464adc7047997a03d990d11f4d59249184dd81cf
Remove unnecessary timeout from tests
test/shared/functions.js
test/shared/functions.js
import webdriver from 'selenium-webdriver'; export function check(done, func) { try { func(); } catch (ex) { done(ex); } } export function doBefore(done, action, load = './build/extension', port = 9515, browser = 'chrome') { this.driver = new webdriver.Builder() .usingServer(`http://localhost:${port}`) .withCapabilities({ chromeOptions: { args: [ `load-extension=${load}` ] } }) .forBrowser(browser) .build(); action().then(() => done()); } export function doAfter(done, timeout = 20000) { this.timeout(timeout); this.driver.quit().then(done); }
JavaScript
0.000002
@@ -529,53 +529,11 @@ done -, timeout = 20000) %7B%0A this.timeout(timeout); +) %7B %0A t
a3f93390ea4435c4735ca46d459a79d81b69b16b
set "autoBlur: true" by default
src/dropdown/Dropdown.js
src/dropdown/Dropdown.js
import React from 'react'; import { props, t, skinnable } from '../utils'; import Select from 'react-select'; import find from 'lodash/find'; import omit from 'lodash/omit'; import cx from 'classnames'; import { warn } from '../utils/log'; const isEmptyArray = x => t.Array.is(x) && x.length === 0; export const Props = { value: t.maybe(t.union([t.Number, t.String, t.Object, t.list(t.Object)])), valueLink: t.maybe(t.struct({ value: t.maybe(t.union([t.Number, t.String, t.Object, t.list(t.Object)])), requestChange: t.Function })), onChange: t.maybe(t.Function), options: t.list(t.Object), size: t.enums.of(['medium', 'small']), disabled: t.maybe(t.Boolean), searchable: t.maybe(t.Boolean), clearable: t.maybe(t.Boolean), backspaceRemoves: t.maybe(t.Boolean), multi: t.maybe(t.Boolean), flat: t.maybe(t.Boolean), id: t.maybe(t.String), className: t.maybe(t.String), style: t.maybe(t.Object) }; /** A dropdown field * @param value - selected value * @param valueLink - defines actions to be taken when a particular value is selected * @param onChange - called when value is changed * @param options - available options * @param size - medium | small * @param disabled - true if disabled * @param searchable - true if it should be possible to search the desired value by writing into the dropdown * @param clearable - true if it should be possible to reset the selected value * @param backspaceRemoves - whether pressing backspace removes the last item when there is no input value * @param multi - true if it should be possible to select multiple values * @param flat - whether it should have a flat style */ @skinnable() @props(Props, { strict: false }) export default class Dropdown extends React.Component { static defaultProps = { delimiter: ',', size: 'medium', disabled: false, searchable: false, clearable: false, multi: false, flat: false } componentDidMount() { this.logWarnings(); } logWarnings = () => { if (this.props.children) { warn('You\'re passing children. Not expected behaviour'); } }; getValue = () => ( this.props.valueLink ? this.props.valueLink.value : this.props.value ); valueToOption = (value, options) => { if (t.String.is(value) || t.Number.is(value)) { const { multi, delimiter } = this.props; if (multi) { const values = String(value).split(delimiter); return values.map(v => find(options, { value: v })); } return find(options, { value }); } return value; }; getOnChange = () => this.props.valueLink ? this.props.valueLink.requestChange : this.props.onChange; getCustomClassNames() { const { size, flat, clearable } = this.props; return cx({ 'is-medium': size === 'medium', 'is-small': size === 'small', 'is-flat': flat, 'is-clearable': clearable }); } _onChange = _value => { const onChange = this.getOnChange(); const value = isEmptyArray(_value) ? null : _value; return onChange(value); } getLocals() { const { _onChange, props: { className, options, backspaceRemoves, clearable, ...props } } = this; return { ...omit(props, 'valueLink'), options, clearable, backspaceRemoves: t.Nil.is(backspaceRemoves) ? clearable : backspaceRemoves, resetValue: null, className: cx('dropdown', className, this.getCustomClassNames()), value: this.valueToOption(this.getValue(), options), onChange: _onChange }; } template(locals) { return <Select {...locals} />; } }
JavaScript
0.000546
@@ -841,16 +841,48 @@ olean),%0A + autoBlur: t.maybe(t.Boolean),%0A id: t. @@ -1683,16 +1683,104 @@ t style%0A + * @param autoBlur - whether it should blur automatically when the user selects a value%0A */%0A@ski @@ -2043,16 +2043,36 @@ t: false +,%0A autoBlur: true %0A %7D%0A%0A
c8212cef2a64b51bd8fcb4371e494948708a8fa8
add more form candy
magnific_popup/blocks/magnific_popup/auto.js
magnific_popup/blocks/magnific_popup/auto.js
hideAllTheDivs = function() { $('#single-options, #singleImage, #galleryImages, #select1').hide(); }; handleSelection = function() { hideAllTheDivs(); switch ($(this).val()) { case 'single': $('#singleImage').show("slow"); $('#single-options').show("slow"); break; case 'popup': $('#galleryImages').show("slow"); break; case 'zoom': $('#singleImage').show("slow"); break; case 'vidMap': $('#vidMap').show("slow"); } }; function ccmValidateBlockForm() { if ($('#magnific_type').val() == 'select1') { ccm_addError(ccm_t('selection-required')); } if ($('#magnific_type').val() == 'single' && $("#ccm-b-image-fm-value").val() == 0) { ccm_addError(ccm_t('image-required')); } if ($('#magnific_type').val() == 'single' && $('#singleOption').val() == 'select-2') { ccm_addError(ccm_t('single-option-required')); } if ($('#magnific_type').val() == 'popup' && $('#fsID').val() == '') { ccm_addError(ccm_t('gallery-required')); } if ($('#magnific_type').val() == 'zoom' && $("#ccm-b-image-fm-value").val() == 0) { ccm_addError(ccm_t('image-required')); } if ($('#magnific_type').val() == 'vidMap' && $('#videoOptions').val() == 'select-3') { ccm_addError(ccm_t('video-map-selection-required')); } if ($('#magnific_type').val() == 'vidMap' && $('#vidMapURL').val() == '') { ccm_addError(ccm_t('url-requried')); } if ($('#magnific_type').val() == 'vidMap' && $('#vidMapLinkText').val() == '') { ccm_addError(ccm_t('link-text-required')); } return false; }
JavaScript
0
@@ -75,23 +75,41 @@ mages, # -select1 +youtubeThumb, #vimeoThumb ').hide( @@ -468,13 +468,160 @@ );%0A%09 -%7D%0A%7D;%0A +%09%09break;%0A%09%09case 'youtubeThumb':%0A%09%09%09$('#youtubeThumb').show(%22slow%22);%0A%09%09case 'vimeoThumb':%0A%09%09%09$('#vimeoThumb').show(%22slow%22);%0A%09%7D%0A%7D;%0A%0A%0A%0A// input validation %0Afun
7f88436332bd78bac2dfc57eb509d846cde922d6
Remove unused code
lib/extract/extractTransform.js
lib/extract/extractTransform.js
import Matrix2D from '../Matrix2D'; import _ from 'lodash'; let pooledMatrix = new Matrix2D(); function transformToMatrix(props, transform) { pooledMatrix.reset(); appendTransform(props); if (transform) { appendTransform(transform); } return pooledMatrix.toArray(); } class TransformParser { constructor() { const floating = '(\\-?[\\d\\.e]+)'; const commaSpace = '\\,?\\s*'; this.regex = { split: /[\s*()|,]/, matrix: new RegExp( '^matrix\\(' + floating + commaSpace + floating + commaSpace + floating + commaSpace + floating + commaSpace + floating + commaSpace + floating + '\\)$') }; } parse(transform) { if (transform) { const retval = {}; let transLst = _.filter( transform.split(this.regex.split), (ele) => { return ele !== ''; } ); for (let i = 0; i < transLst.length; i++) { let trans = transLst[i]; switch (trans) { case 'matrix': if (i + 7 <= transLst.length) { retval.matrix = _.map((transLst.slice(i + 1,i + 7)), parseFloat); } break; case 'translate': retval.translateX = transLst[i + 1]; retval.translateY = (transLst.length === 3) ? transLst[i + 2] : 0; break; case 'scale': retval.scaleX = transLst[i + 1]; retval.scaleY = (transLst.length === 3) ? transLst[i + 2] : retval.scaleX; break; case 'rotate': retval.rotation = transLst[i + 1]; break; case 'skewX': retval.skewX = transLst[i + 1]; break; case 'skewY': retval.skewY = transLst[i + 1]; break; default: break; } } return retval; } } } export const tp = new TransformParser(); function appendTransform(transform) { if (transform) { if (typeof transform === 'string') { const transformParsed = tp.parse(transform); if (transformParsed.matrix) { pooledMatrix.append(...transformParsed.matrix); } else { let trans = props2transform(transformParsed); if (typeof trans !== 'string') { transform = trans; } } } if (typeof transform !== 'string') { pooledMatrix .appendTransform( transform.x + transform.originX, transform.y + transform.originY, transform.scaleX, transform.scaleY, transform.rotation, transform.skewX, transform.skewY, transform.originX, transform.originY ); } } } function universal2axis(universal, axisX, axisY, defaultValue) { let coords = []; let x; let y; if (_.isString(universal)) { coords = universal.split(/\s*,\s*/); if (coords.length === 2) { x = +coords[0]; y = +coords[1]; } else if (coords.length === 1) { x = y = +coords[0]; } } else if (_.isNumber(universal)) { x = y = universal; } axisX = +axisX; if (!isNaN(axisX)) { x = axisX; } axisY = +axisY; if (!isNaN(axisY)) { y = axisY; } return [x || defaultValue || 0, y || defaultValue || 0]; } export function props2transform(props) { if (props && (typeof props === 'string')) { return props; } let [originX, originY] = universal2axis(props.origin, props.originX, props.originY); let [scaleX, scaleY] = universal2axis(props.scale, props.scaleX, props.scaleY, 1); let [skewX, skewY] = universal2axis(props.skew, props.skewX, props.skewY); let [translateX, translateY] = universal2axis( props.translate, _.isNil(props.translateX) ? (props.x || 0) : props.translateX, _.isNil(props.translateY) ? (props.y || 0) : props.translateY ); return { rotation: +props.rotation || 0, scaleX: scaleX, scaleY: scaleY, originX: originX, originY: originY, skewX: skewX, skewY: skewY, x: translateX, y: translateY }; } export default function (props) { return transformToMatrix(props2transform(props), props.transform ? props2transform(props.transform) : null); }
JavaScript
0.000006
@@ -298,485 +298,64 @@ %7D%0A%0Ac -lass TransformParser %7B%0A constructor() %7B%0A const floating = '(%5C%5C-?%5B%5C%5Cd%5C%5C.e%5D+)';%0A const commaSpace = '%5C%5C,?%5C%5Cs*';%0A%0A this.regex = %7B%0A split: /%5B%5Cs*()%7C,%5D/,%0A matrix: new RegExp(%0A '%5Ematrix%5C%5C(' +%0A floating + commaSpace +%0A floating + commaSpace +%0A floating + commaSpace +%0A floating + commaSpace +%0A floating + commaSpace +%0A floating + '%5C%5C)$')%0A %7D;%0A %7D +onst SPLIT_REGEX = /%5B%5Cs*()%7C,%5D/;%0A%0Aclass TransformParser %7B %0A%0A @@ -502,24 +502,19 @@ lit( -this.regex.split +SPLIT_REGEX ),%0A
4a08536a2bd93a9b15a5d956423dbeaafc7e3a9b
Update overlay.js
overlay.js
overlay.js
"use strict"; var state = require("reflex/state") var reductions = require("reducers/reductions") var patch = require("diffpatcher/patch") var diff = require("diffpatcher/diff") var keys = Object.keys function overlay(mapping) { /** Function takes overlay `mapping` that is `id` mapped to a function value responsible for computing a value for that id. Each function will be used to perform a reductions over a stream of state updates. In return they supposed to compute value for the given `id`. In return this function returns a function which given a stream of state changes will return equivalent stream of changes but with a computed properties added. This allows adding computed fields to a state model so that units and components could use them as regular state attributes. Also note that resulting stream will only contain changes to the computed properties if they actually changed. ## Example var foo = overlay({ count: function(previous, current) { var items = current.items var ids = Object.keys(items) var completed = ids.map(function(id) { return items[id] }).filter(function(item) { return item.completed }).length return { all: items.count, completed: completed, pending: count - completed } } }) **/ // Cache keys of the mapping in an array to avoid call overhead on each // update. var ids = keys(mapping) function compute(input) { /** Function takes `input` of state updates and returns equivalent stream but with computed properties added which were defined in curried `mapping` **/ var previous = state() var overlay = state() return reductions(input, function(_, delta) { // Compute current state without changes to computed properties // by applying `delta` to a previous state with computed properties. var current = patch(previous, delta) // Compute new overlay by running each attribute computation. var computed = ids.reduce(function(delta, id) { // Attribute computations are invoked with a previous computed // state & current state without computed properties. Complete state // is most likely what is needed to calculate a new value. Although // if in some cases `delta` is a better option, it still can be // calculated by `diff`-ing provided values that will return `delta` // by using an optimized code path. delta[id] = mapping[id](previous, current) return delta }, {}) // Computed delta with computed properties by applying delta // between `overlay` (previously computed properties) and `computed` // (currently computed properties) to the state change delta. This // way only changed computed properties will be added which will avoid // further reactions down the data flow. delta = patch(delta, diff(overlay, computed)) // Update previous computed state by patching previous state // with delta that contains computed properties. previous = patch(previous, delta) // Also update overlay value with a current version of computed values. overlay = computed // Finally return delta with changed computed properties added to it // so that reactors down the flow will react on updates with computed // properties. return delta }) } } module.exports = overlay
JavaScript
0.000001
@@ -92,16 +92,94 @@ ctions%22) +%0Avar channel = require(%22reducers/channel%22)%0Avar pipe = require(%22reducers/pipe%22) %0A%0Avar pa @@ -1876,22 +1876,61 @@ e()%0A -return +var stream = channel()%0A%0A var transformed = reducti @@ -3628,19 +3628,87 @@ %0A %7D)%0A - %7D +%0A pipe(transformed, stream)%0A%0A return stream%0A %7D%0A%0A return compute %0A%7D%0A%0Amodu
e9dcb9393cfddb5c051214bfaffeb61e1c4e70a3
use regular expression mutation effect to determine draw variants from low to high impact
js/drawMutations.js
js/drawMutations.js
var _ = require('./underscore_ext'); var {contrastColor, lightgreyHEX} = require('./color_helper'); var {impact} = require('./models/mutationVector'); var labelFont = 12; var labelMargin = 1; // left & right margin var radius = 4; var minVariantHeight = pixPerRow => Math.max(pixPerRow, 2); // minimum draw height of 2 var toYPx = (zoom, v) => { var {height, count, index} = zoom, svHeight = height / count; return {svHeight, y: (v.y - index) * svHeight + (svHeight / 2)}; }; var toYPxSubRow = (zoom, v) => { var {rowCount, subrow} = v, {height, count} = zoom, svHeight = height / (count * rowCount); return {svHeight, y: toYPx(zoom, v).y + svHeight * ((1 - rowCount) / 2 + subrow)}; }; var splitRows = (count, height) => height / count > labelFont; function push(arr, v) { arr.push(v); return arr; } // XXX note this draws outside the zoom area. It could be optimized // by considering zoom count and index. function drawBackground(vg, width, height, pixPerRow, hasValue) { var [stripes] = _.reduce( _.groupByConsec(hasValue, _.identity), ([acc, sum], g) => [g[0] ? acc : push(acc, [sum, g.length]), sum + g.length], [[], 0]); vg.smoothing(false); vg.box(0, 0, width, height, 'white'); // white background var rects = stripes.map(([offset, len]) => [ 0, (offset * pixPerRow), width, pixPerRow * len ]); vg.drawRectangles(rects, {fillStyle: 'grey'}); var nullLabels = stripes.filter(([, len]) => len * pixPerRow > labelFont); nullLabels.forEach(([offset, len]) => { vg.textCenteredPushRight(0, pixPerRow * offset, width, pixPerRow * len, 'black', labelFont, "null"); }); } function drawImpactNodes(vg, width, zoom, smallVariants) { // --------- separate variants to SV(with feet "[" , "]" or size >50bp) vs others (small) --------- var {height, count} = zoom, vHeight = minVariantHeight(height / count), minWidth = 2; // double that is the minimum width we draw // --------- small variants drawing start here --------- var varByImp = _.groupByConsec(smallVariants, v => v.color); varByImp = _.sortBy(varByImp, list => impact[list[0].data.effect]); // draw variants from low to high impact varByImp.forEach(vars => { var points = vars.map(v => { var {y} = toYPx(zoom, v), padding = _.max([minWidth - Math.abs(v.xEnd - v.xStart), 0]); return [v.xStart - padding, y, v.xEnd + padding, y]; }); vg.drawPoly(points, {strokeStyle: vars[0].color, lineWidth: vHeight}); // small variants label if (height / count > labelFont) { let h = height / count, minTxtWidth = vg.textWidth(labelFont, 'WWWW'); vars.forEach(function(v) { var {xStart, xEnd, data} = v, {y} = toYPx(zoom, v), label = data.aminoAcid || data.alt, textWidth = vg.textWidth(labelFont, label); if ((xEnd - xStart) >= minTxtWidth / 5 * label.length) { vg.textCenteredPushRight( xStart + labelMargin, y - h / 2, xEnd - xStart - labelMargin, h, contrastColor(vars[0].color), labelFont, label); } else { vg.textCenteredPushRight( xStart, y - h / 2, textWidth, h, lightgreyHEX, labelFont, label); } }); } }); } function drawSVNodes(vg, width, zoom, svVariants) { var {count, height} = zoom, toY = splitRows(count, height) ? toYPxSubRow : toYPx, varByIdMap = svVariants.map(v => { var {data: {alt, altGene}} = v, {svHeight, y} = toY(zoom, v); return { ...v, y, h: minVariantHeight(svHeight), alt, altGene }; }); //SV variants draw color background according to joining chromosome varByIdMap.forEach(variant => { var {xStart, xEnd, y, color, h} = variant, points = [[xStart, y, xEnd, y]]; vg.drawPoly(points, {strokeStyle: color, lineWidth: h}); }); varByIdMap.forEach(variant => { var {xStart, xEnd, y, h} = variant, endMark = xEnd < width - 1 ? [[xEnd, y, xEnd + 1, y]] : [], startMark = xStart > 0 ? [[xStart, y, xStart + 1, y]] : [], points = [...startMark, ...endMark]; vg.drawPoly(points, {strokeStyle: 'black', lineWidth: h}); }); //feet variants show text label when there is only one variant for this sample, otherwise, text might overlap if (height / count > labelFont) { let margin = 2 * labelMargin, //more labelMargin due to drawing of breakpoint minTxtWidth = vg.textWidth(labelFont, 'WWWW'); varByIdMap.forEach(variant => { var {xStart, xEnd, y, alt, altGene, h} = variant; if ( (h > labelFont) && ((xEnd - xStart) - margin >= minTxtWidth)) { vg.clip(xStart + margin, y - h / 2, xEnd - xStart - 2 * margin, h, () => vg.textCenteredPushRight( xStart + margin, y - h / 2, xEnd - xStart - margin, h, 'black', labelFont, altGene ? altGene + " " + alt : alt) ); } }); }; } var drawWithBackground = _.curry((draw, vg, props) => { let {width, zoom, nodes} = props, {count, height, index} = zoom; if (!nodes) { vg.box(0, 0, width, height, "gray"); return; } let {samples, index: {bySample: samplesInDS}} = props, last = index + count, toDraw = nodes.filter(v => v.y >= index && v.y < last), pixPerRow = height / count, hasValue = samples.slice(index, index + count).map(s => samplesInDS[s]); vg.labels(() => { drawBackground(vg, width, height, pixPerRow, hasValue); draw(vg, width, zoom, toDraw); }); }); var drawMutations = drawWithBackground(drawImpactNodes); var drawSV = drawWithBackground(drawSVNodes); module.exports = {drawMutations, drawSV, splitRows, radius, minVariantHeight, toYPx, toYPxSubRow, labelFont};
JavaScript
0
@@ -105,16 +105,30 @@ %7Bimpact +, getSNVEffect %7D = requ @@ -2094,16 +2094,37 @@ impact%5B +getSNVEffect(impact, list%5B0%5D. @@ -2134,16 +2134,17 @@ a.effect +) %5D); // d
5b01dfee79a4863165827e1353e136e50ca1f993
Update EventDispatcher documentation
lib/event/EventDispatcher.js
lib/event/EventDispatcher.js
'use strict'; const events = Symbol('events'); const Listeners = require('./Listeners'); /** * Stores event listeners and provides the capability to notify them of events. */ class EventDispatcher { /** * Creates an instance of EventDispatcher. */ constructor() { this[events] = new Map(); } /** * Registers a listener for the provided event. * * @param {string} event - the event to add the listener to * @param {function} listener - the listener to register * @return {EventDispatcher} the instance */ addListener(event, listener) { if (this[events].has(event)) { this[events].get(event).push(listener); } else { this[events].set(event, new Listeners(listener)); } return this; } /** * Remove the provided event listener. If the listener is not present for the provided event, * the method has no operation. * * @param {string} event - the event to remove the listener from * @param {function} listener - the listener to remove */ removeListener(event, listener) { if (this[events].has(event)) { this[events].get(event).remove(listener); } } /** * Removes any listeners for the provided event classifier. * * @param {string} event - the event to remove listeners for */ removeListeners(event) { this[events].set(event, new Listeners()); } /** * Gets a copy of the listeners for the provided event classifier. * * @param {string} event - the event to copy listeners from * @returns {Listeners} the listeners copy or null if no listeners are present */ getListeners(event) { const listeners = this[events].get(event); if (listeners) { return listeners.copy(); } return null; } /** * Dispatches the provided event, optionally accepting an object to pass to listeners. * * @param {string} event - the event to dispatch * @param {*} [object] - optional object to pass to listeners */ dispatch(event, object) { if (this[events].has(event)) { // ensure only the currently present listeners receive notification this[events].get(event).copy().notify(object); } } } module.exports = EventDispatcher;
JavaScript
0
@@ -211,30 +211,26 @@ * -Creates an instance of +Instantiates a new Eve @@ -324,16 +324,23 @@ isters a +n event listene @@ -340,39 +340,16 @@ listener - for the provided event .%0A *%0A @@ -393,27 +393,18 @@ to -add the listen -er to + for %0A @@ -495,20 +495,40 @@ er%7D -the instance +self, allowing for chained calls %0A @@ -822,50 +822,22 @@ sent - for the provided event,%0A * the +, this method has @@ -836,24 +836,20 @@ hod -ha +doe s no - operation +thing .%0A @@ -1136,32 +1136,39 @@ s any listeners +stored for the provided @@ -1169,35 +1169,24 @@ ovided event - classifier .%0A *%0A * @@ -1342,11 +1342,15 @@ * -Get +Provide s a @@ -1371,36 +1371,31 @@ steners for -the provided +a given event class @@ -1449,30 +1449,18 @@ ent -to copy listeners from +classifier %0A
88529c254e132352aecde93bc28578a7c40eba1c
Change hard coded concept to semi-dynamic concept
js/form-controls.js
js/form-controls.js
var FormController = (function () { var _addEventHandlers = function () { $("#process-data").click(processData); }; var parseData = function() { var parseResultMessage = $("#data-parse-result-message"); var rulesContainer = $("#rules-div"); rulesContainer.hide(); parseResultMessage.empty(); $("#data-parse-error-list").remove(); $("#rules-list").remove(); var csv = $("#data-input").val(); var data = Papa.parse(csv); parseResultMessage.toggleClass("text-danger", data.errors.length > 0); parseResultMessage.toggleClass("text-success", !data.errors.length); if (!data.errors.length) { rulesContainer.show(); return data; } rulesContainer.hide(); parseResultMessage.text("Data Input Errors"); var errorList = $("<ul/>", { "id": "data-parse-error-list" }); data.errors.forEach(function(error) { console.error(error); var row = $("<span/>", { "text": error.row, "class": "badge" }) var errorMessage = error.code + ": " + error.message; var errorItem = $("<li />", { "text": errorMessage }); errorItem.prepend(row); errorList.append(errorItem); }) $("#data-parse-result").append(errorList); return false; }; var displayRules = function(rules) { var ruleList = $("<ol/>", { "id": "rules-list" }); rules.forEach(function(rule) { console.log(rule); var ruleText = ""; rule.conditions.forEach(function(condition) { ruleText += "(" + condition.attribute + ", " + condition.value + ") && "; }); ruleText = ruleText.substring(0, ruleText.length - 3); ruleText += "-> "; ruleText += "(" + rule.decision.name + ", " + rule.decision.value + ")" var ruleItem = $("<li/>", { "text": ruleText }); ruleList.append(ruleItem); $("#rules-div").append(ruleList); }); }; var processData = function() { var csv = parseData(); if (!csv) { return; } var data = csv.data; LEM2.dataset = data; var concept = new Set([1,2,4,5]); var ruleset = LEM2.executeProcedure(concept); displayRules(ruleset.rules); }; return { addEventHandlers: _addEventHandlers }; })(); $(document).ready(FormController.addEventHandlers);
JavaScript
0.997338
@@ -2084,24 +2084,43 @@ = csv.data; +%0A%0A // Initialize %0A LEM2.da @@ -2141,42 +2141,65 @@ -var concept = new Set(%5B1,2,4,5%5D +LEM2.newAttributeValueBlocks();%0A LEM2.newConcepts( );%0A +%0A @@ -2238,15 +2238,24 @@ ure( +LEM2. concept +s%5B0%5D );%0A
6912bdc9804291ad75113c331d1701ad50ed5228
Add credentials method.
lib/fhir.js
lib/fhir.js
"use strict"; var https, http, url, request, FHIR; https = require("https"); http = require("http"); url = require("url"); request = function (options, body, callback) { var responseHandler, req; if (callback === undefined && typeof(body) === "function") { callback = body; body = undefined; } responseHandler = function (res) { var body; body = ""; res.on("data", function (chunk) { body += chunk; }); res.on("end", function () { var path; if ([200, 204].indexOf(res.statusCode) !== -1) { callback(null, body); } else if (res.statusCode === 201) { path = res.headers.location.split("/"); callback(null, { type: path[1], id: path[2], vid: path[4] }); } else { callback({ statusCode: res.statusCode, message: body }); } }); }; // Setting withCredentials to false is required until // https://github.com/substack/http-browserify/pull/47 is fixed. options.withCredentials = false; if (options.protocol === "https:") { req = https.request(options, responseHandler); } else { req = http.request(options, responseHandler); } if (body !== undefined) { req.write(body); } req.end(); }; FHIR = function (url) { if (typeof url === "string") { this.url = url; } else if (url !== null && typeof url === "object" && url.hasOwnProperty("url") === true) { this.url = url.url; } else { throw new Error("Please provide a URL parameter."); } // Remove trailing "/" from URL. if (this.url.indexOf("/", this.url.length - 1) !== -1) { this.url = this.url.substring(0, this.url.length - 1); } }; FHIR.prototype.read = function (type, id, callback) { var options; options = url.parse(this.url + "/" + type + "/" + id); options.method = "GET"; request(options, callback); }; FHIR.prototype.vread = function (type, id, vid, callback) { var options; options = url.parse(this.url + "/" + type + "/" + id + "/_history/" + vid); options.method = "GET"; request(options, callback); }; FHIR.prototype.update = function (type, id, body, callback) { var options; options = url.parse(this.url + "/" + type + "/" + id); options.method = "PUT"; options.headers = { "Content-Type": "application/json" }; request(options, JSON.stringify(body), callback); }; FHIR.prototype.delete = function (type, id, callback) { var options; options = url.parse(this.url + "/" + type + "/" + id); options.method = "DELETE"; request(options, callback); }; FHIR.prototype.create = function (type, body, callback) { var options; options = url.parse(this.url + "/" + type); options.method = "POST"; options.headers = { "Content-Type": "application/json" }; request(options, JSON.stringify(body), callback); }; FHIR.prototype.search = function (type, params, callback) { var options; if (callback === undefined && typeof(params) === "function") { callback = params; params = type; type = null; } if (type !== null) { options = url.parse(this.url + "/" + type); } else { options = url.parse(this.url + "/"); } Object.keys(params).forEach(function (param, idx) { if (idx === 0) { options.path = options.path + "?"; } else { options.path = options.path + "&"; } options.path = options.path + param + "=" + params[param]; }); options.method = "GET"; request(options, callback); }; FHIR.prototype.history = function (type, id, callback) { var options; if (callback === undefined && id === undefined && typeof(type) === "function") { callback = type; id = null; type = null; } else if (callback === undefined && typeof(id) === "function") { callback = id; id = null; } if (type !== null && id !== null) { options = url.parse(this.url + "/" + type + "/" + id + "/_history"); } else if (type !== null && id === null) { options = url.parse(this.url + "/" + type + "/_history"); } else { options = url.parse(this.url + "/_history"); } options.method = "GET"; request(options, callback); }; module.exports = FHIR;
JavaScript
0
@@ -1937,16 +1937,171 @@ ;%0A %7D%0A + // Prepare credentials.%0A this.auth = null;%0A%7D;%0A%0AFHIR.prototype.credentials = function (username, password) %7B%0A this.auth = username + %22:%22 + password;%0A %7D;%0A%0AFHIR @@ -2246,32 +2246,86 @@ method = %22GET%22;%0A + if (this.auth !== null) options.auth = this.auth;%0A request(opti @@ -2521,32 +2521,86 @@ method = %22GET%22;%0A + if (this.auth !== null) options.auth = this.auth;%0A request(opti @@ -2851,32 +2851,86 @@ on/json%22%0A %7D;%0A + if (this.auth !== null) options.auth = this.auth;%0A request(opti @@ -3134,16 +3134,70 @@ ELETE%22;%0A + if (this.auth !== null) options.auth = this.auth;%0A requ @@ -3446,24 +3446,78 @@ son%22%0A %7D;%0A + if (this.auth !== null) options.auth = this.auth;%0A request( @@ -4221,32 +4221,86 @@ method = %22GET%22;%0A + if (this.auth !== null) options.auth = this.auth;%0A request(opti @@ -4959,24 +4959,24 @@ ry%22);%0A %7D%0A - options. @@ -4987,24 +4987,78 @@ od = %22GET%22;%0A + if (this.auth !== null) options.auth = this.auth;%0A request(
5f9cb63bab0eebafb6dfee110b2f9d1e92d4dc86
add preflight to SignalflowClient (#49)
lib/client/signalflow/signalflow_client.js
lib/client/signalflow/signalflow_client.js
'use strict'; // Copyright (C) 2016 SignalFx, Inc. All rights reserved. var RequestManager = require('./request_manager'); function SignalflowClient(apiToken, options) { var rm = new RequestManager(options); rm.authenticate(apiToken); function disconnect() { rm.disconnect(); } function signalflowRequest(opts, requestType) { var metaDataMap = {}; var msgBuffer = []; var callback = null; function resolveMessage(msg) { // we're duck typing error messages here, but it should be okay. if (msg.hasOwnProperty('error') && !msg.type) { errorMessageCallback(msg); } else { callback(null, msg); } } function errorMessageCallback(msg) { callback(msg, null); } function msgCallback(msg) { if (msg.type === 'metadata') { metaDataMap[msg.tsId] = msg; } if (!callback) { msgBuffer.push(msg); } else { resolveMessage(msg); } } var callbacks = { onMessage: msgCallback, onError: errorMessageCallback }; var requestId = rm.execute(opts, callbacks, null, requestType); return { close: function () { return rm.stop(requestId); }, get_known_tsids: function () { return Object.keys(metaDataMap); }, get_metadata: function (tsid) { if (!tsid || !metaDataMap[tsid]) { return null; } return metaDataMap[tsid]; }, stream: function (fn, errorFn) { if (typeof fn !== 'function') { return false; } callback = fn; msgBuffer.forEach(resolveMessage); msgBuffer = []; return true; } }; } return { disconnect: disconnect, execute: function (opts) { return signalflowRequest(opts, 'execute'); }, explain: function (opts) { return signalflowRequest(opts, 'explain'); } }; } module.exports = SignalflowClient;
JavaScript
0
@@ -1908,24 +1908,115 @@ 'explain');%0A + %7D,%0A preflight: function (opts) %7B%0A return signalflowRequest(opts, 'preflight');%0A %7D%0A %7D;%0A%7D
d7dd7b793fb7cea1d20ed14c95ea46b13f6524ed
Move jest manual mocking to top of file
src/__tests__/index.js
src/__tests__/index.js
const TwitterMedia = require('../'); const path = require('path'); const fs = require('fs'); jest.mock('../api-client'); const image = fs.readFileSync(path.join(__dirname, '..', '..', 'assets', 'image.jpg')); const video = fs.readFileSync(path.join(__dirname, '..', '..', 'assets', 'video.mp4')); describe('Promise API', () => { it('Image upload', () => { const twitter = new TwitterMedia(); return expect(twitter.uploadMedia('image', image)).resolves.toMatchSnapshot(); }); it('Image-set upload', () => { const twitter = new TwitterMedia(); return expect(twitter.uploadImageSet([image, image, image])).resolves.toMatchSnapshot(); }); it('Video upload', () => { const twitter = new TwitterMedia(); return expect(twitter.uploadMedia('video', video)).resolves.toMatchSnapshot(); }); }); describe('Callback API', () => { it('Image upload', () => { const twitter = new TwitterMedia(); expect.assertions(1); twitter.uploadMedia('image', image, (error, mediaID, body) => { expect(body).toMatchSnapshot(); }); }); it('Image-set upload', () => { const twitter = new TwitterMedia(); expect.assertions(1); twitter.uploadImageSet([image, image, image], (error, body) => { expect(body).toMatchSnapshot(); }); }); it('Video upload', () => { const twitter = new TwitterMedia(); expect.assertions(1); twitter.uploadMedia('video', video, (error, mediaID, body) => { expect(body).toMatchSnapshot(); }); }); });
JavaScript
0
@@ -1,12 +1,41 @@ +jest.mock('../api-client');%0A%0A const Twitte @@ -120,37 +120,8 @@ );%0A%0A -jest.mock('../api-client');%0A%0A cons
50218ffe523db8f0d461f0d0845767649e272d45
add underscore version to dep req
package.js
package.js
Package.describe({ name: 'mike:mocha', summary: "Run mocha tests in the browser", version: "0.4.8", debugOnly: true, git: "https://github.com/mad-eye/meteor-mocha-web" }); Npm.depends({ mocha: "1.17.1", chai: "1.9.0", mkdirp: "0.5.0" }); //TODO break this out into a separate package and depend weakly //Require npm assertion library if it doesn't exist.. //Npm.depends({chai: "1.9.0"}); Package.on_use(function (api, where) { api.use("underscore", ["server", "client"]); api.use(['velocity:[email protected]'], "server"); api.use(['velocity:[email protected]'], "client"); api.use(['[email protected]'], "client"); api.use(['velocity:[email protected]'], ["client", "server"]); api.use("velocity:[email protected]"); api.add_files(["reporter.js", "server.js"], "server"); api.add_files(["client.html", "mocha.js", "reporter.js", "client.js", "chai.js"], "client"); api.add_files(["sample-tests/client.js","sample-tests/server.js"], "server", {isAsset: true}); api.export("MochaWeb", ["client", "server"]); api.export("MeteorCollectionTestReporter", ["client", "server"]); });
JavaScript
0
@@ -460,16 +460,22 @@ derscore [email protected] %22, %5B%22ser
7942483cac9a5bd6d6f6bfe0e948ba294ff7de96
attach babel-plugin-syntax-dynamic-import (#461)
src/lib/babel-config.js
src/lib/babel-config.js
export default (env, options={}) => { const isProd = env && env.production; return { babelrc: false, presets: [ [require.resolve('babel-preset-env'), { loose: true, uglify: true, modules: options.modules || false, targets: { browsers: options.browsers }, exclude: [ 'transform-regenerator', 'transform-es2015-typeof-symbol' ] }] ], plugins: [ require.resolve('babel-plugin-transform-object-assign'), require.resolve('babel-plugin-transform-class-properties'), require.resolve('babel-plugin-transform-export-extensions'), require.resolve('babel-plugin-transform-object-rest-spread'), require.resolve('babel-plugin-transform-decorators-legacy'), require.resolve('babel-plugin-transform-react-constant-elements'), isProd && require.resolve('babel-plugin-transform-react-remove-prop-types'), [require.resolve('babel-plugin-transform-react-jsx'), { pragma: 'h' }], [require.resolve('babel-plugin-jsx-pragmatic'), { module: 'preact', export: 'h', import: 'h' }] ].filter(Boolean) }; };
JavaScript
0
@@ -396,16 +396,74 @@ gins: %5B%0A +%09%09%09require.resolve('babel-plugin-syntax-dynamic-import'),%0A %09%09%09requi
5857c5dc1b9c71e45096543b274cbb859c8ed9c3
Update version number
dist/van11y-accessible-hide-show-aria.min.js
dist/van11y-accessible-hide-show-aria.min.js
/** * van11y-accessible-hide-show-aria - ES2015 accessible hide-show system (collapsible regions), using ARIA (compatible IE9+ when transpiled) * @version v1.0.4 * @link https://van11y.net/accessible-hide-show/ * @license MIT : https://github.com/nico3333fr/van11y-accessible-hide-show-aria/blob/master/LICENSE */ "use strict";function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e){var t="js-expandmore",n="js-expandmore-button",r="expandmore__button",i="label_expand_",a="data-hideshow-prefix-class",o="expand_",c="expandmore__to_expand",s="data-controls",d="aria-expanded",u="data-labelledby",l="data-hidden",f="is-opened",p="js-first_load",b="1500",m=function(t){return e.getElementById(t)},y=function(e,t){e.classList?e.classList.add(t):e.className+=" "+t},v=function(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(^|\\b)"+t.split(" ").join("|")+"(\\b|$)","gi")," ")},E=function(e,t){return e.classList?e.classList.contains(t):new RegExp("(^| )"+t+"( |$)","gi").test(e.className)},_=function(e,t){Object.keys(t).forEach(function(n){e.setAttribute(n,t[n])})},g=function(e,t){if(e.fireEvent)e.fireEvent("on"+t);else{var n=document.createEvent("Events");n.initEvent(t,!0,!1),e.dispatchEvent(n)}},L=function(){return[].slice.call(e.querySelectorAll("."+t))},x=function A(){L().forEach(function(t,m){var g,L,x=m+1,A=t.hasAttribute(a)===!0?t.getAttribute(a)+"-":"",k=t.nextElementSibling,h=t.innerHTML,P=e.createElement("BUTTON");t.innerHTML="",y(P,A+r),y(P,n),_(P,(g={},_defineProperty(g,s,o+x),_defineProperty(g,d,"false"),_defineProperty(g,"id",i+x),_defineProperty(g,"type","button"),g)),P.innerHTML=h,t.appendChild(P),_(k,(L={},_defineProperty(L,u,i+x),_defineProperty(L,l,"true"),_defineProperty(L,"id",o+x),L)),y(k,A+c),E(k,p)===!0&&setTimeout(function(){v(k,p)},b),E(k,f)===!0&&(y(P,f),P.setAttribute(d,"true"),v(k,f),k.removeAttribute(l))}),["click","keydown"].forEach(function(r){e.body.addEventListener(r,function(e){if(E(e.target,n)===!0&&"click"===r){var i=e.target,a=m(i.getAttribute(s)),o=i.getAttribute(d);"false"===o?(i.setAttribute(d,!0),y(i,f),a.removeAttribute(l)):(i.setAttribute(d,!1),v(i,f),a.setAttribute(l,!0))}if(E(e.target,t)===!0){var c=e.target,u=c.querySelector("."+n);if(c!=u){if("click"===r)return g(u,"click"),!1;if("keydown"===r&&(13===e.keyCode||32===e.keyCode))return g(u,"click"),!1}}},!0)}),document.removeEventListener("DOMContentLoaded",A)};document.addEventListener("DOMContentLoaded",x)}(document);
JavaScript
0.000002
@@ -159,9 +159,9 @@ 1.0. -4 +5 %0A * @@ -2565,8 +2565,9 @@ cument); +%0A
5fe699d60703a309e5792bc07900d26352f56e99
Update default value
lib/assets/javascripts/builder/components/modals/add-widgets/layer-selector-view.js
lib/assets/javascripts/builder/components/modals/add-widgets/layer-selector-view.js
var _ = require('underscore'); var Backbone = require('backbone'); var CoreView = require('backbone/core-view'); var analyses = require('builder/data/analyses'); require('builder/components/form-components/index'); var CustomListItemView = require('builder/components/form-components/editors/select/select-layer-list-item-view'); var itemListTemplate = require('builder/components/form-components/editors/select/select-layer-item.tpl'); var selectedItemTemplate = require('builder/components/form-components/editors/select/select-layer-list-item.tpl'); /** * View for selecting the layer through which to load the column data. */ module.exports = CoreView.extend({ className: 'CDB-SelectorLayer', events: { 'click': '_onClick', 'change': '_onChange' }, initialize: function (opts) { this._stateModel = new Backbone.Model({ highlighted: false }); this._initBinds(); }, render: function () { this._unbindEvents(); this._initViews(); this._bindEvents(); return this; }, _initBinds: function () { this.listenTo(this._stateModel, 'change:highlighted', this._toggleHover); }, _initViews: function () { var self = this; var options = this._buildOptions(); this._selectView = new Backbone.Form.editors.Select({ className: 'Widget-select u-flex u-alignCenter', key: 'name', schema: { options: options }, model: self.model, showSearch: false, template: require('./select.tpl'), selectedItemTemplate: selectedItemTemplate, customListItemView: CustomListItemView, itemListTemplate: itemListTemplate, mouseOverAction: this._onMouseOver.bind(this), mouseOutAction: this._onMouseOut.bind(this) }); this._selectView.setValue(this.model.get('layer_index') || 0); this.$el.html(this._selectView.render().el); }, _onMouseOver: function () { this._stateModel.set('highlighted', true); }, _onMouseOut: function () { this._stateModel.set('highlighted', false); }, _toggleHover: function () { var $widget = this.$el.closest('.js-WidgetList-item'); $widget.toggleClass('is-hover', this._stateModel.get('highlighted')); }, _buildOptions: function () { return _.map(this.model.get('tuples'), function (item, index) { var layerDefModel = item.layerDefinitionModel; var nodeDefModel = item.analysisDefinitionNodeModel; var layerName = nodeDefModel.isSourceType() ? layerDefModel.getTableName() : layerDefModel.getName(); return { val: index, layerName: layerName, nodeTitle: analyses.short_title(nodeDefModel), layer_id: nodeDefModel.id, color: layerDefModel.getColor(), isSourceType: nodeDefModel.isSourceType() }; }).reverse(); }, _bindEvents: function () { if (this._selectView) { this._selectView.on('change', this._onChange, this); } }, _unbindEvents: function () { if (this._selectView) { this._selectView.off('change', this._onChange, this); } }, _onClick: function (event) { event.stopPropagation(); }, _onChange: function () { this.model.set('layer_index', this._selectView.getValue()); }, clean: function () { this._selectView.remove(); CoreView.prototype.clean.apply(this); } });
JavaScript
0.000001
@@ -1812,16 +1812,42 @@ dex') %7C%7C + (options%5B0%5D %7C%7C %7B%7D).val %7C%7C 0);%0A