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
f403d9d594da53b162892e387f4bc2e4b4a2c1cc
Update map.js
web/map.js
web/map.js
var zoomOut = 4; var zoomIn = 1; var tilePath = '../day/'; function CustomMapType() { } CustomMapType.prototype.tileSize = new google.maps.Size(512,512); CustomMapType.prototype.maxZoom = zoomOut+zoomIn; CustomMapType.prototype.getTile = function(coord, zoom, ownerDocument) { var div = ownerDocument.createElement('DIV'); var baseURL = tilePath + 'z' + (zoomOut-zoom) + '/'; baseURL += coord.x + ',' + coord.y + '.png'; div.style.width = this.tileSize.width + 'px'; div.style.height = this.tileSize.height + 'px'; div.style.backgroundColor = '#1B2D33'; div.style.backgroundImage = 'url(' + baseURL + ')'; return div; }; CustomMapType.prototype.name = "Custom"; CustomMapType.prototype.alt = "Tile Coordinate Map Type"; var map; var CustomMapType = new CustomMapType(); function initialize() { var mapOptions = { minZoom: 0, maxZoom: zoomIn+zoomOut, isPng: true, mapTypeControl: false, streetViewControl: false, /* stupid Google thinks the world is a sphere. */ center: new google.maps.LatLng(85,-180), zoom: zoomOut, mapTypeControlOptions: { mapTypeIds: ['custom', google.maps.MapTypeId.ROADMAP], style: google.maps.MapTypeControlStyle.DROPDOWN_MENU } }; map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); map.mapTypes.set('custom',CustomMapType); map.setMapTypeId('custom'); }
JavaScript
0.000001
@@ -64,14 +64,13 @@ = ' -../day +tiles /';%0A
14d6ef7dde6d5437491ce2f70e88780e4659e214
Fix documentation for GridLayout to add a return type
modules/ve/ui/layouts/ve.ui.GridLayout.js
modules/ve/ui/layouts/ve.ui.GridLayout.js
/*! * VisualEditor UserInterface GridLayout class. * * @copyright 2011-2013 VisualEditor Team and others; see AUTHORS.txt * @license The MIT License (MIT); see LICENSE.txt */ /** * Grid layout. * * @class * @extends ve.ui.Layout * * @constructor * @param {ve.ui.PanelLayout[]} panels Panels in the grid * @param {Object} [config] Config options * @cfg {number[]} [widths] Widths of columns as ratios * @cfg {number[]} [heights] Heights of columns as ratios */ ve.ui.GridLayout = function VeUiGridLayout( panels, config ) { var i, len, widths; // Config initialization config = config || {}; // Parent constructor ve.ui.Layout.call( this, config ); // Properties this.panels = []; this.widths = []; this.heights = []; // Initialization this.$.addClass( 've-ui-gridLayout' ); for ( i = 0, len = panels.length; i < len; i++ ) { this.panels.push( panels[i] ); this.$.append( panels[i].$ ); } if ( config.widths || config.heights ) { this.layout( config.widths || [1], config.heights || [1] ); } else { // Arrange in columns by default widths = []; for ( i = 0, len = this.panels.length; i < len; i++ ) { widths[i] = 1; } this.layout( widths, [1] ); } }; /* Inheritance */ ve.inheritClass( ve.ui.GridLayout, ve.ui.Layout ); /* Events */ /** * @event layout */ /** * @event update */ /* Static Properties */ ve.ui.GridLayout.static.tagName = 'div'; /* Methods */ /** * Set grid dimensions. * * @method * @param {number[]} widths Widths of columns as ratios * @param {number[]} heights Heights of rows as ratios * @emits layout * @throws {Error} If grid is not large enough to fit all panels */ ve.ui.GridLayout.prototype.layout = function ( widths, heights ) { var x, y, xd = 0, yd = 0, cols = widths.length, rows = heights.length; // Verify grid is big enough to fit panels if ( cols * rows < this.panels.length ) { throw new Error( 'Grid is not large enough to fit ' + this.panels.length + 'panels' ); } // Sum up denominators for ( x = 0; x < cols; x++ ) { xd += widths[x]; } for ( y = 0; y < rows; y++ ) { yd += heights[y]; } // Store factors this.widths = []; this.heights = []; for ( x = 0; x < cols; x++ ) { this.widths[x] = widths[x] / xd; } for ( y = 0; y < rows; y++ ) { this.heights[y] = heights[y] / yd; } // Synchronize view this.update(); this.emit( 'layout' ); }; /** * Update panel positions and sizes. * * @method * @emits update */ ve.ui.GridLayout.prototype.update = function () { var x, y, panel, i = 0, left = 0, top = 0, width = 0, height = 0, cols = this.widths.length, rows = this.heights.length; for ( y = 0; y < rows; y++ ) { for ( x = 0; x < cols; x++ ) { panel = this.panels[i]; width = this.widths[x]; height = this.heights[y]; panel.$.css( { 'width': Math.round( width * 100 ) + '%', 'height': Math.round( height * 100 ) + '%', 'left': Math.round( left * 100 ) + '%', 'top': Math.round( top * 100 ) + '%' } ); i++; left += width; } top += height; left = 0; } this.emit( 'update' ); }; /** * Get a panel at a given position. * * The x and y position is affected by the current grid layout. * * @method * @param {number} x Horizontal position * @param {number} y Vertical position */ ve.ui.GridLayout.prototype.getPanel = function ( x, y ) { return this.panels[( x * this.widths.length ) + y]; };
JavaScript
0.000001
@@ -3290,16 +3290,79 @@ osition%0A + * @returns %7Bve.ui.PanelLayout%7D The panel at the given postion%0A */%0Ave.u
a653f01e43f29a24104181ed3c99fe2129c65894
use .cmd versions for Windows
scripts/postinstall.es6
scripts/postinstall.es6
import fs from 'fs-plus' import path from 'path' import childProcess from 'child_process' async function spawn(cmd, args, opts = {}) { return new Promise((resolve, reject) => { const options = Object.assign({stdio: 'inherit'}, opts); const proc = childProcess.spawn(cmd, args, options) proc.on("error", reject) proc.on("exit", resolve) }) } function unlinkIfExistsSync(p) { try { if (fs.lstatSync(p)) { fs.removeSync(p); } } catch (err) { return } } function copyErrorLoggerExtensions(privateDir) { const from = path.join(privateDir, 'src') const to = path.resolve(path.join('packages', 'client-app', 'src')) unlinkIfExistsSync(path.join(to, 'error-logger-extensions')); fs.copySync(from, to); } async function installPrivateResources() { console.log("\n---> Linking private plugins") const privateDir = path.resolve(path.join('packages', 'client-private-plugins')) if (!fs.existsSync(privateDir)) { console.log("\n---> No client app to link. Moving on") return; } copyErrorLoggerExtensions(privateDir) // link private plugins for (const plugin of fs.readdirSync(path.join(privateDir, 'packages'))) { const from = path.resolve(path.join(privateDir, 'packages', plugin)); const to = path.resolve(path.join('packages', 'client-app', 'internal_packages', plugin)); unlinkIfExistsSync(to); fs.symlinkSync(from, to, 'dir'); } // link client-sync const clientSyncDir = path.resolve(path.join('packages', 'client-sync')); const destination = path.resolve(path.join('packages', 'client-app', 'internal_packages', 'client-sync')); unlinkIfExistsSync(destination); fs.symlinkSync(clientSyncDir, destination, 'dir'); } async function lernaBootstrap() { console.log("\n---> Installing packages"); let lernaCmd = "lerna" if (process.platform === "win32") { lernaCmd = "lerna.cmd" } await spawn(path.join('node_modules', '.bin', lernaCmd), ["bootstrap"]) } const npmEnvs = { system: process.env, apm: Object.assign({}, process.env, { NPM_CONFIG_TARGET: '0.10.40', }), electron: Object.assign({}, process.env, { NPM_CONFIG_TARGET: '1.4.15', NPM_CONFIG_ARCH: process.arch, NPM_CONFIG_TARGET_ARCH: process.arch, NPM_CONFIG_DISTURL: 'https://atom.io/download/electron', NPM_CONFIG_RUNTIME: 'electron', NPM_CONFIG_BUILD_FROM_SOURCE: true, }), }; async function npm(cmd, options) { const {cwd, env} = Object.assign({cwd: '.', env: 'system'}, options); await spawn("npm", [cmd], { cwd: path.resolve(__dirname, '..', cwd), env: npmEnvs[env], }) } async function electronRebuild() { if (!fs.existsSync(path.join("packages", "client-app", "apm"))) { console.log("\n---> No client app to rebuild. Moving on") return; } await npm('install', { cwd: path.join('packages', 'client-app', 'apm'), env: 'apm', }) await npm('rebuild', { cwd: path.join('packages', 'client-app'), env: 'electron', }) } const getJasmineDir = (packageName) => path.resolve( path.join('packages', packageName, 'spec', 'jasmine') ) const getJasmineConfigPath = (packageName) => path.resolve( path.join(getJasmineDir(packageName), 'config.json') ) function linkJasmineConfigs() { console.log("\n---> Linking Jasmine configs"); const linkToPackages = ['cloud-api', 'cloud-core', 'cloud-workers'] const from = getJasmineConfigPath('isomorphic-core') for (const packageName of linkToPackages) { const dir = getJasmineDir(packageName) if (!fs.existsSync(dir)) { fs.mkdirSync(dir) } const to = getJasmineConfigPath(packageName) unlinkIfExistsSync(to) fs.symlinkSync(from, to, 'file') } } function linkIsomorphicCoreSpecs() { console.log("\n---> Linking isomorphic-core specs to client-app specs") const from = path.resolve(path.join('packages', 'isomorphic-core', 'spec')) const to = path.resolve(path.join('packages', 'client-app', 'spec', 'isomorphic-core')) unlinkIfExistsSync(to) fs.symlinkSync(from, to, 'dir') } async function main() { try { await installPrivateResources() await lernaBootstrap(); // Given that `lerna bootstrap` does not install optional dependencies, we // need to manually run `npm install` inside `client-app` so // `node-mac-notifier` get's correctly installed and included in the build // See https://github.com/lerna/lerna/issues/121 console.log("\n---> Reinstalling client-app dependencies to include optional dependencies"); await npm('install', {cwd: 'packages/client-app'}) await electronRebuild(); linkJasmineConfigs(); linkIsomorphicCoreSpecs(); } catch (err) { console.error(err); process.exit(1); } } main()
JavaScript
0
@@ -2485,16 +2485,96 @@ tions);%0A + let npmCmd = %22npm%22%0A if (process.platform === %22win32%22) %7B npmCmd = %22npm.cmd%22 %7D%0A await @@ -2579,21 +2579,22 @@ t spawn( -%22 npm -%22 +Cmd , %5Bcmd%5D,
6e0f6fc662b7b8b71d106fc0ed05fd6c5e07ad33
Change title/edition on a published item does not change the url
src/main/web/florence/js/functions/_checkRenameUri.js
src/main/web/florence/js/functions/_checkRenameUri.js
function checkRenameUri(collectionId, data, renameUri, onSave) { if (renameUri) { swal({ title: "Warning", text: "You have changed the title or edition and this could change the uri. Are you sure you want to proceed?", type: "warning", showCancelButton: true, confirmButtonText: "Change url", cancelButtonText: "Cancel", closeOnConfirm: true }, function (result) { if (result === true) { // Does it have edition? if (data.description.edition) { //Special case dataset editions. They have edition but not title if (data.description.title) { var titleNoSpace = data.description.title.replace(/[^A-Z0-9]+/ig, "").toLowerCase(); } var editionNoSpace = data.description.edition.replace(/[^A-Z0-9]+/ig, "").toLowerCase(); var tmpNewUri = data.uri.split("/"); if (data.type === 'dataset') { tmpNewUri.splice([tmpNewUri.length - 1], 1, editionNoSpace); } else { tmpNewUri.splice([tmpNewUri.length - 2], 2, titleNoSpace, editionNoSpace); } var newUri = tmpNewUri.join("/"); //is it a compendium? Rename children array if (data.type === 'compendium_landing_page') { if (data.chapters) { data.chapters = renameCompendiumChildren(data.chapters, titleNoSpace, editionNoSpace); } if (data.datasets) { data.datasets = renameCompendiumChildren(data.datasets, titleNoSpace, editionNoSpace); } } moveContent(collectionId, data.uri, newUri, onSuccess = function () { Florence.globalVars.pagePath = newUri; onSave(collectionId, newUri, JSON.stringify(data)); } ); console.log(newUri); // is it an adHoc? } else if (data.type === 'static_adhoc') { var titleNoSpace = data.description.title.replace(/[^A-Z0-9]+/ig, "").toLowerCase(); var referenceNoSpace = data.description.reference.replace(/[^A-Z0-9]+/ig, "").toLowerCase(); var tmpNewUri = data.uri.split("/"); tmpNewUri.splice([tmpNewUri.length - 1], 1, referenceNoSpace + titleNoSpace); var newUri = tmpNewUri.join("/"); moveContent(collectionId, data.uri, newUri, onSuccess = function () { Florence.globalVars.pagePath = newUri; onSave(collectionId, newUri, JSON.stringify(data)); } ); console.log(newUri); } else { var titleNoSpace = data.description.title.replace(/[^A-Z0-9]+/ig, "").toLowerCase(); var tmpNewUri = data.uri.split("/"); //Articles with no edition. Add date as edition if (data.type === 'article' || data.type === 'article_download') { var editionDate = $.datepicker.formatDate('yy-mm-dd', new Date()); tmpNewUri.splice([tmpNewUri.length - 2], 2, titleNoSpace, editionDate); } else { tmpNewUri.splice([tmpNewUri.length - 1], 1, titleNoSpace); } var newUri = tmpNewUri.join("/"); //if it is a dataset rename children array if (data.type === 'dataset_landing_page') { if (data.datasets) { data.datasets = renameDatasetChildren(data.datasets, titleNoSpace); } } moveContent(collectionId, data.uri, newUri, onSuccess = function () { Florence.globalVars.pagePath = newUri; onSave(collectionId, newUri, JSON.stringify(data)); } ); console.log(newUri); } } else { refreshPreview(data.uri); loadPageDataIntoEditor(data.uri, collectionId); } }); } else { onSave(collectionId, data.uri, JSON.stringify(data)); } }
JavaScript
0
@@ -1793,32 +1793,33 @@ );%0A %7D +, %0A );%0A @@ -1817,39 +1817,126 @@ -);%0A console.log(newUri + onError = function () %7B%0A onSave(collectionId, data.uri, JSON.stringify(data));%0A %7D%0A );%0A @@ -2607,32 +2607,33 @@ );%0A %7D +, %0A );%0A @@ -2631,39 +2631,126 @@ -);%0A console.log(newUri + onError = function () %7B%0A onSave(collectionId, data.uri, JSON.stringify(data));%0A %7D%0A );%0A @@ -3815,32 +3815,33 @@ );%0A %7D +, %0A );%0A @@ -3839,39 +3839,126 @@ -);%0A console.log(newUri + onError = function () %7B%0A onSave(collectionId, data.uri, JSON.stringify(data));%0A %7D%0A );%0A
9bb85a8c73b81ae831e024750b96db99c0e76028
clean up
src/electron/electron.js
src/electron/electron.js
'use strict'; const { app, BrowserWindow } = require('electron'); // electron-connect is used only in dev mode, node_modules are not // shipped in the electron package so importing electron-connect // will throw an error when using "npm run package" let client; if (process.env.NODE_ENV === 'development') { client = require('electron-connect').client; } let win = null; const DEVELOPMENT = process.env.NODE_ENV === 'development'; app.on('ready', function () { // Initialize the window win = new BrowserWindow({ width: 1200, height: 900, autoHideMenuBar: true, frame: true }); if (DEVELOPMENT) { // Specify entry point win.loadURL('http://localhost:3000'); // devtools win.webContents.openDevTools(); // in dev mode the electron window is created with electron-connect // see /config/webpack.dev.js for further details client.create(win); } else { win.loadURL(`file://${__dirname}/index.html`) } // Remove window once app is closed win.on('closed', function () { win = null; }); }); app.on('activate', () => { if (win === null && !DEVELOPMENT) { createWindow() } }) app.on('window-all-closed', function () { if (process.platform != 'darwin') { app.quit(); } });
JavaScript
0.999723
@@ -1127,16 +1127,17 @@ )%0A %7D%0A%7D) +; %0A%0Aapp.on @@ -1197,16 +1197,17 @@ tform != += 'darwin
e87399b6ccec4edba7ef98d64bc40be56f281a65
fix domain
js/plot.js
js/plot.js
var BAR_WIDTH = 10; var MIN_HEIGHT = 5; var data = null; var plotted = false; var getters = { 'duration': function(d) { return d.duration; }, 'cpu_time': function(d) { return d.cpu_times.system + d.cpu_times.user; }, 'memory': function(d) { return d.ext_memory_info.rss; }, 'io': function(d) { return d.io_counters.read_count; } }; function plotGraph(data) { var f = $("#file"); // remove old chart and make new one $("#chart").remove(); $("#chart-div").append('<svg id="chart"></svg>'); var chart = d3.select("#chart"); var chartWidth = $("#chart-div").width(); var chartHeight = $(window).height() - $("#chart").position().top - 20; var key = $("#key")[0].value; var sort = $("#sort")[0].checked; var getterFunc = getters[key]; // plot it data = data.filter(function(elem) { return getterFunc(elem) !== null && getterFunc(elem) !== undefined; }); tip = d3.tip().html(function(d) { return "<div class='d3-tip'>" + "<pre>" + JSON.stringify(d, null, '\t') + "</pre>" + "</div>"; }); chart.call(tip); if (sort) { data.sort(function(a, b) { var x = getterFunc(a); var y = getterFunc(b); return d3.descending(x, y); }); } var computeHeight = d3.scale.linear() .domain([MIN_HEIGHT, d3.max(data, getterFunc)]) .range([MIN_HEIGHT, chartHeight]); chart.attr("width", data.length * BAR_WIDTH) .attr("height", chartHeight); chart.selectAll("rect") .data(data) .enter().append("rect") .attr("x", function(d, i) { return i * BAR_WIDTH; }) .attr("y", function(d, i) { return chartHeight - computeHeight(getterFunc(d)); }) .attr("height", function(d, i) { return computeHeight(getterFunc(d)); }) .attr("width", BAR_WIDTH) .on('mouseover', function(d) { tip.show(d); // center it horizontally var tipWidth = $('.d3-tip').width(); $('.d3-tip').css('left', $(window).width() / 2 - tipWidth / 2 + 'px'); }) .on('mouseout', tip.hide); plotted = true; } function handleFile(ev) { var files = ev.target.files; var file = files[0]; var reader = new FileReader(); reader.onloadend = function() { data = JSON.parse(reader.result); plotGraph(data); }; reader.readAsText(file); } var replot = function() { if (plotted) { plotGraph(data); } }; window.onresize = replot; $('#file').on('change', handleFile); $('#key').on('change', replot); $('#sort').on('change', replot); // plot a default graph d3.json("resources.json", function(d) { data = d; plotGraph(data); });
JavaScript
0.000006
@@ -719,17 +719,17 @@ ).top - -2 +3 0;%0A%0A @@ -1402,26 +1402,17 @@ domain(%5B -MIN_HEIGHT +0 , d3.max
f395596a24a381ea9bd7d05f18f75b76a2fcffec
Fix webhook command unauth attempt
src/commands/webhook.js
src/commands/webhook.js
const MenuUtils = require('../structs/MenuUtils.js') const FeedSelector = require('../structs/FeedSelector.js') const Translator = require('../structs/Translator.js') const Profile = require('../structs/db/Profile.js') const Feed = require('../structs/db/Feed.js') const Supporter = require('../structs/db/Supporter.js') const log = require('../util/logger.js') async function feedSelectorFn (m, data) { const { feed, translate } = data const webhook = feed.webhook const text = `${webhook ? translate('commands.webhook.existingFound', { name: webhook.name }) : ''}${translate('commands.webhook.prompt')}` return { ...data, existingWebhook: webhook, next: { text: text, embed: null } } } async function collectWebhookFn (m, data) { const { hooks, translate } = data const webhookName = m.content if (webhookName === '{remove}') { return { ...data, webhookName } } const nameRegex = /--name="(((?!(--name|--avatar)).)*)"/ const avatarRegex = /--avatar="(((?!(--name|--avatar)).)*)"/ const hookName = m.content.replace(nameRegex, '').replace(avatarRegex, '').trim() const hook = hooks.find(h => h.name === hookName) if (!hook) { throw new MenuUtils.MenuOptionError(translate('commands.webhook.notFound', { name: hookName })) } let customNameSrch = m.content.match(nameRegex) let customAvatarSrch = m.content.match(avatarRegex) if (customNameSrch) { customNameSrch = customNameSrch[1] if (customNameSrch.length > 32 || customNameSrch.length < 2) { throw new MenuUtils.MenuOptionError(translate('commands.webhook.tooLong')) } } if (customAvatarSrch) { customAvatarSrch = customAvatarSrch[1] } return { ...data, webhook: hook, customAvatarSrch, customNameSrch } } module.exports = async (bot, message, command) => { try { const [ profile, validServer ] = await Promise.all([ Profile.get(message.guild.id), Supporter.hasValidGuild(message.guild.id) ]) const guildLocale = profile ? profile.locale : undefined const translate = Translator.createLocaleTranslator(guildLocale) if (!validServer) { log.command.info(`Unauthorized attempt to access webhooks`, message.guild, message.author) return await message.channel.send(`Only servers with patron backing have access to webhooks.`) } if (!message.guild.me.permissionsIn(message.channel).has('MANAGE_WEBHOOKS')) { return await message.channel.send(translate('commands.webhook.noPermission')) } const hooks = await message.channel.fetchWebhooks() const feeds = await Feed.getManyBy('guild', message.guild.id) const feedSelector = new FeedSelector(message, feedSelectorFn, { command: command }, feeds) const collectWebhook = new MenuUtils.Menu(message, collectWebhookFn) const data = await new MenuUtils.MenuSeries(message, [feedSelector, collectWebhook], { hooks, locale: guildLocale, translate }).start() if (!data) { return } const { feed, existingWebhook, webhookName, webhook, customAvatarSrch, customNameSrch } = data if (webhookName === '{remove}') { if (typeof existingWebhook !== 'object') { await message.channel.send(translate('commands.webhook.noneAssigned')) } else { feed.webhook = undefined await feed.save() await message.channel.send(translate('commands.webhook.removeSuccess', { link: feed.url })) } return } feed.webhook = { id: webhook.id } if (customNameSrch) { feed.webhook.name = customNameSrch } if (customAvatarSrch) { feed.webhook.avatar = customAvatarSrch } log.command.info(`Webhook ID ${webhook.id} (${webhook.name}) connecting to feed ${feed.url}`, message.guild, message.channel) const connected = translate('commands.webhook.connected', { botUser: bot.user, link: feed.url }) await feed.save() webhook.send(connected, { username: customNameSrch, avatarURL: customAvatarSrch }) .catch(err => { if (err.message.includes('avatar_url')) { return webhook.send(connected, { username: customNameSrch }).catch(err => log.comamnd.warning(`rsswebhook 2`, message.guild, err)) // This may be a placeholder } }) } catch (err) { log.command.warning(`rsswebhook`, message.guild, err) if (err.code !== 50013) message.channel.send(err.message).catch(err => log.command.warning('rsswebhook 1', message.guild, err)) } }
JavaScript
0.008375
@@ -2102,16 +2102,37 @@ if ( +Supporter.enabled && !validSe
ec5f9cea6f65c7d4d40b712d035e814fb302c062
fix travis
scripts/test.e2e.ios.js
scripts/test.e2e.ios.js
const _ = require('lodash'); const exec = require('shell-utils').exec; const release = _.includes(process.argv, '--release'); run(); function run() { try { startRecording(); const conf = release ? `release` : `debug`; exec.execSync(`detox build --configuration ios.sim.${conf}`); exec.execAsync(`sleep 30`).then(() => { exec.execAsync(`open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app`); }); exec.execSync(`detox test --configuration ios.sim.${conf} ${process.env.CI ? '--cleanup' : ''}`); } finally { stopRecording(); } } function startRecording() { const screenId = exec.execSyncRead(`ffmpeg -f avfoundation -list_devices true -i "" 2>&1 | grep "Capture screen 0" | sed -e "s/.*\\[//" -e "s/\\].*//"`); exec.execAsync(`ffmpeg -f avfoundation -i "${screenId}:none" out.avi`); } function stopRecording() { exec.execSync(`killall ffmpeg || true`); const json = require('./../package.json'); json.name = 'fix-travis-rnn'; json.version = `0.0.${Date.now()}`; require('fs').writeFileSync('./package.json', JSON.stringify(json, null, 2), { encoding: 'utf-8' }); exec.execSync(`npm run release`); }
JavaScript
0.000002
@@ -158,30 +158,8 @@ y %7B%0A - startRecording();%0A @@ -202,16 +202,16 @@ debug%60;%0A + exec @@ -298,9 +298,9 @@ eep -3 +1 0%60). @@ -420,17 +420,37 @@ %7D);%0A -%0A + startRecording(); %0A exe
ee28c70b5de6ca723bd91e6e24b9f19f6a1c26c5
Update gulpfile.js
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var browserSync = require('browser-sync'); var postcss = require('gulp-postcss'); var atImport = require('postcss-import'); var customProps = require('postcss-custom-properties'); var calc = require('postcss-calc'); var autoprefixer = require('autoprefixer'); var cssnano = require('cssnano'); var stylelint = require('stylelint'); var reporter = require('postcss-reporter'); gulp.task('css', function () { var processors = [ atImport(), customProps(), calc(), autoprefixer({browsers: ['last 2 version']}), cssnano(), stylelint({ "rules": { "string-quotes": [2, "double"], "block-no-empty": 2, "color-hex-case": [2, "lower"], "selector-no-id": 2 } }), reporter({ clearMessages: true }) ]; return gulp.src('./src/css/*.css') .pipe(postcss(processors)) .pipe(gulp.dest('./dest/css')); }); gulp.task('serve', function () { browserSync.init({ server: 'dest/', open: false }); gulp.watch('src/css/**/*.css', ['css']); gulp.watch('dest/**/*.html').on('change', browserSync.reload); }); gulp.task('default', ['serve']);
JavaScript
0.000001
@@ -2,16 +2,25 @@ ar gulp + = requir @@ -46,16 +46,18 @@ serSync + = requir @@ -87,16 +87,22 @@ postcss + = requir @@ -133,16 +133,21 @@ tImport + = requir @@ -183,16 +183,18 @@ omProps + = requir @@ -234,16 +234,25 @@ ar calc + = requir @@ -287,16 +287,17 @@ refixer + = requir @@ -327,16 +327,22 @@ cssnano + = requir @@ -369,16 +369,20 @@ ylelint + = requir @@ -410,16 +410,21 @@ eporter + = requir
98ae95c46b7c3bb70eb4c0f859466576bf42ea64
Clean up read-generator a little
examples/create-generator.js
examples/create-generator.js
// Inject the dependencies to fsDb to work using node.js var platform = require('./node'); // And create a db instance var db = require('../lib/fs-db.js')(platform)("test.git", true); // And wrap in a repo API var repo = require('../lib/repo.js')(db); var run = require('gen-run'); var parallel = require('../lib/parallel.js'); // Mock data for generating some history var author = "Tim Caswell <tim@creationix.com>"; var committer = "JS-Git <js-git@creationix.com>"; var commits = { "Initial Commit\n": { "README.md": "# This is a test Repo\n\nIt's generated entirely by JavaScript\n" }, "Add package.json and blank module\n": { "README.md": "# This is a test Repo\n\nIt's generated entirely by JavaScript\n", "package.json": '{\n "name": "awesome-lib",\n "version": "3.1.3",\n "main": "awesome.js"\n}\n', "awesome.js": 'module.exports = function () {\n throw new Error("TODO: Implement Awesome");\n};\n' }, "Implement awesome and bump version to 3.1.4\n": { "README.md": "# This is a test Repo\n\nIt's generated entirely by JavaScript\n", "package.json": '{\n "name": "awesome-lib",\n "version": "3.1.4",\n "main": "awesome.js"\n}\n', "awesome.js": 'module.exports = function () {\n return 42;\n};\n' } }; run(function *() { yield repo.init(); console.log("Git database Initialized"); var parent; yield* each(commits, function* (message, files) { // Start building a tree object. var tree = {}; yield* each(files, function* (name, contents) { tree[name] = { mode: 0100644, hash: yield repo.saveBlob(contents) }; }); var now = gitDate(new Date); var commit = { tree: yield repo.saveTree(tree), parent: parent, author: author + " " + now, committer: committer + " " + now, message: message }; if (!parent) delete commit.parent; parent = yield repo.saveCommit(commit); yield repo.updateHead(parent); }); console.log("Done"); }); // Format a js data object into the data format expected in git commits. function gitDate(date) { var timezone = date.getTimezoneOffset() / 60; var seconds = Math.floor(date.getTime() / 1000); return seconds + " " + (timezone > 0 ? "-0" : "0") + timezone + "00"; } // Mini control-flow library function* each(object, fn) { var keys = Object.keys(object); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; yield* fn(key, object[key]); } }
JavaScript
0.000001
@@ -250,85 +250,8 @@ );%0A%0A -var run = require('gen-run');%0Avar parallel = require('../lib/parallel.js');%0A%0A // M @@ -1176,18 +1176,33 @@ %7D%0A%7D;%0A%0Ar -un +equire('gen-run') (functio
5881c7f0a29b902f1caa8e1148cc95e48bd72298
Make build specs depend on build
gulpfile.js
gulpfile.js
var browserify = require('gulp-browserify'); var clean = require('gulp-clean'); var concat = require('gulp-concat'); var exec = require('child_process').exec; var sh = require('execSync'); var fs = require('fs'); var gulp = require('gulp'); var gutil = require('gulp-util'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var libs = [ 'array', 'object', 'string', 'utilities', ]; var distLibs = libs.map(function(component) { return 'dist/' + component + '.js'; }); function mkTmpDir() { if (!fs.existsSync('tmp')) fs.mkdirSync('tmp'); } gulp.task('copy-spec-runner', function() { mkTmpDir(); return gulp.src('spec/runner.html') .pipe(gulp.dest('tmp')); }); gulp.task('copy-mocha-files', function() { mkTmpDir(); return gulp.src([ 'node_modules/mocha/mocha.js', 'node_modules/mocha/mocha.css', 'node_modules/chai/chai.js' ]).pipe(gulp.dest('tmp')); }); gulp.task('compile-spec-files', function() { mkTmpDir(); gulp.src(distLibs) .pipe(gulp.dest('tmp')); gulp.src('node_modules/underscore/underscore.js') .pipe(gulp.dest('tmp')); gulp.src('node_modules/chai-fuzzy/index.js') .pipe(rename('chai-fuzzy.js')) .pipe(gulp.dest('tmp')); return gulp.src('spec/*_spec.js') .pipe(gulp.dest('tmp')); }); gulp.task('compile-components', ['compile-libs'], function() { return gulp.src('lib/**/*.js') .pipe(rename(function(path) { path.basename = path.basename.replace(/^_/, ''); })) .pipe(gulp.dest('dist')); }); gulp.task('compile-libs', ['clean'], function() { return libs.forEach(function(lib) { return gulp.src('lib/' + lib + '/*.js') .pipe(concat(lib + '.js')) .pipe(gulp.dest('dist')); }); }); gulp.task('build', ['compile-components'], function() { return gulp.src('dist/**/*.js') .pipe(uglify()) .pipe(rename(function(path) { path.basename = path.basename += '.min'; })) .pipe(gulp.dest('dist')); }); gulp.task('clean', function() { return gulp.src(['dist/**/*', 'tmp']) .pipe(clean()); }); gulp.task('build-specs', ['copy-spec-runner', 'copy-mocha-files', 'compile-spec-files']); gulp.task('spec', ['build', 'build-specs'], function() { var mochaResult = sh.exec('mocha spec'); console.log(mochaResult.stdout); var testemResult = sh.exec('testem ci'); console.log(testemResult.stdout); gulp.src('tmp') .pipe(clean()); return (testemResult.code && mochaResult.code) ? 1 : 0; });
JavaScript
0
@@ -2079,16 +2079,25 @@ pecs', %5B +'build', 'copy-sp @@ -2172,25 +2172,16 @@ spec', %5B -'build', 'build-s
a572bcee01f6a6732debf90bface2503d2b03084
Remove nextTick
lib/index.js
lib/index.js
/** * Module dependencies. */ var Identify = require('segmentio-facade').Identify; var integration = require('segmentio-integration'); var isostring = require('isostring'); var hash = require('string-hash'); var mapper = require('./mapper'); var time = require('unix-time'); var extend = require('extend'); var dot = require('obj-case'); var Batch = require('batch'); var tick = process.nextTick; var is = require('is'); /** * Expose `Intercom` */ var Intercom = module.exports = integration('Intercom') .endpoint('https://api-segment.intercom.io') .ensure('settings.apiKey') .ensure('settings.appId') .ensure('message.userId') .channels(['server']) .retries(2); /** * Identify a user in intercom * * @param {Identify} identify * @param {Function} fn * @api public */ Intercom.prototype.identify = function(identify, fn){ var key = [this.settings.appId, identify.userId()].join(':'); var self = this; this.lock(key, function(){ return self .post('/users') .set(headers(identify, self.settings)) .type('json') .accept('json') .send(mapper.identify(identify)) .end(self.handle(function(err, res){ self.unlock(key, function(){ fn(err, res); }); })); }); }; /** * Group in two steps - company and then user * * @param {Group} group * @param {Function} fn * @api public */ Intercom.prototype.group = function(group, fn){ var json = group.json(); var traits = json.traits || {}; var self = this; return this .post('/companies') .set(headers(group, this.settings)) .type('json') .accept('json') .send(mapper.group(group)) .end(this.handle(function(err){ if (err) return fn(err); json.userId = group.userId(); traits.id = group.groupId(); json.traits = { companies: [traits] }; var identify = new Identify(json); self.identify(identify, fn); }) ); }; /** * Track the user's action * * @param {Track} track * @param {Function} fn * @api public */ Intercom.prototype.track = function(track, fn){ return this .post('/events') .set(headers(track, this.settings)) .type('json') .accept('json') .send(mapper.track(track)) .end(this.handle(fn)); }; /** * Format all the traits which are dates for intercoms format * * @param {Object} traits * @return {Object} * @api private */ Intercom.prototype.formatTraits = function(traits){ var output = {}; Object.keys(traits).forEach(function(key){ var val = traits[key]; if (isostring(val) || is.date(val)) { val = time(val); key = dateKey(key); } output[key] = val; }); return output; }; /** * Set up a key with the dates for intercom * * http://docs.intercom.io/#CustomDataDates * * @param {String} key * @return {String} * @api private */ function dateKey (key) { if (endswith(key, '_at')) return key; if (endswith(key, ' at')) return key.substr(0, key.length - 3) + '_at'; return key + '_at'; } /** * Test whether a string ends with the suffix * * @param {String} str * @param {String} suffix * @return {String} * @api private */ function endswith (str, suffix) { str = str.toLowerCase(); return str.substr(str.length - suffix.length) === suffix; } /** * Add headers * * @param {Facade} message * @return {Object} * @api private */ function headers (message, settings) { var buf = new Buffer(settings.appId + ':' + settings.apiKey); var auth = 'Basic ' + buf.toString('base64'); return { Authorization: auth, 'User-Agent': 'Segment.io/1.0.0' }; }
JavaScript
0
@@ -380,24 +380,20 @@ k = -process.nextTick +setImmediate ;%0Ava @@ -1840,17 +1840,16 @@ its%5D %7D;%0A -%0A
d359663a0a16d5e687519434d54106a757601383
Fix unmute
bot/commandlist.js
bot/commandlist.js
/** * contains a list of commands. you can link and unlink any command you like */ module.exports = { "ping": "ping", "hello": "hello", "lock": "lock", "stats": "stats", "add": "add", "remove": "remove", "unlock": "unlock", "info": "info", "hash": "hash", "bf2": "bf2", "alphakey": "alphakey", "bf2142": "bf2142", "link": "link", "refresh": "refresh", "yo": "yo", "cookie": "cookie", "request": "request", "status": "status", "quote": "quote", "q":"quote", // "emojify": "emojify", "emoji": "emoji", "e":"emoji", "http": "http", "8ball": "8ball", "slowmov": "slowmov", "whoisplaying": "whoisplaying", "say": "say", "delete": "delete", "exec": "exec", "query": "query", "cmute": "cmute", "cunmute": "cunmute", "cm":"cmute", "cum":"cunmute", "m":"mute", "um":"umute", "mute": "mute", "fun": "fun", "unmute": "unmute", "mute": "mute", "unmute": "unmute", "dj": "dj", "hi": "hello", "access_log": "access_log", "al":"al" //"game": "game" }
JavaScript
0.001118
@@ -901,16 +901,17 @@ %22um%22:%22u +n mute%22,%0A
b8bf0d535d34069f2194459f5c83d219d5d1e949
Add period with status Not yet started only if grid is empty
src/main/webapp/public/requisitions/period.factory.js
src/main/webapp/public/requisitions/period.factory.js
(function() { 'use strict'; angular.module('openlmis.requisitions').factory('PeriodFactory', periodFactory); periodFactory.$inject = ['$resource', 'RequisitionURL', 'RequisitionService', 'messageService', '$q', 'DateUtils', 'Status']; function periodFactory($resource, RequisitionURL, RequisitionService, messageService, $q, DateUtils, Status) { var resource = $resource(RequisitionURL('/api/requisitions/periodsForInitiate'), {}, { get: { method: 'GET', isArray: true, transformResponse: transformResponse } }); var service = { get: get }; return service; function get(programId, facilityId, emergency) { var deferred = $q.defer(); resource.get({programId: programId, facilityId: facilityId, emergency: emergency}, function(data) { getPeriodGridLineItems(data, programId, facilityId, emergency).then(function(items) { deferred.resolve(items); }).catch(function() { deferred.reject(); }); }, function() { deferred.reject(); }); return deferred.promise; } function getPeriodGridLineItems(periods, programId, facilityId, emergency) { var periodGridLineItems = [], deferred = $q.defer(); if (emergency == true) { getPreviousPeriodLineItems(programId, facilityId, emergency).then(search); } else { search(periodGridLineItems); } return deferred.promise; function search(lineItems) { RequisitionService.search(programId, facilityId).then(function(data) { periods.forEach(function (period, idx) { var foundRequisition = null; data.forEach(function (requisition) { if (requisition.processingPeriod.id == period.id) { foundRequisition = requisition; } }); if (emergency == false || (emergency == true && foundRequisition != null && foundRequisition.status != Status.INITIATED && foundRequisition.status != Status.SUBMITTED)) { lineItems.push(createPeriodGridItem(period, foundRequisition, idx)); } if (emergency == true && foundRequisition == null) { lineItems.push(createPeriodGridItem(period, null, idx)); } }); deferred.resolve(lineItems); }); } } function getPreviousPeriodLineItems(programId, facilityId, emergency) { var statuses = [Status.INITIATED, Status.SUBMITTED], deferred = $q.defer(); RequisitionService.search(programId, facilityId, statuses, emergency).then(function(data) { var lineItems = []; data.forEach(function(rnr) { lineItems.push(createPeriodGridItem(rnr.processingPeriod, rnr, 0)); }); deferred.resolve(lineItems); }, function() { deferred.reject(); }); return deferred.promise; } function createPeriodGridItem(period, requisition, idx) { return { name: period.name, startDate: period.startDate, endDate: period.endDate, rnrStatus: (requisition ? requisition.status : (idx === 0 ? messageService.get("msg.rnr.not.started") : messageService.get("msg.rnr.previous.pending"))), activeForRnr: (idx === 0 ? true : false), rnrId: (requisition ? requisition.id : null) }; } function transformResponse(data, headers, status) { if (status === 200) { var periods = angular.fromJson(data); periods.forEach(function(period) { period.startDate = DateUtils.toDate(period.startDate); period.endDate = DateUtils.toDate(period.endDate); }) return periods; } return data; } } })();
JavaScript
0
@@ -2333,147 +2333,30 @@ l && -%0A foundRequisition.status != Status.INITIATED &&%0A foundRequisition.status != Status.SUBMITTED + lineItems.length == 0 )) %7B
a901a59502f854f1deb18470384951188c4fab8b
Update rect.js
js/rect.js
js/rect.js
function Rect(initX) { this.x = initX; this.y = 288 - 32; this.velocity = 0; this.veleftright = 0; this.tail = this.x + 32; }; Rect.prototype.draw = function(context) { //context.beginPath(); context.strokeRect(this.x, this.y, 32, 32); //context.stroke(); //context.closePath(); }; Rect.prototype.update = function() { if (this.x < -32) { this.x = Game.entites[16].tail; } else if (this.x > 512) { this.x = -32; } if(player.input.left == true){ this.veleftright = 5; if(player.input.jump == true){ this.veleftright += 5; } }else if(player.input.right == true){ this.veleftright = -5; if(player.input.jump == true){ this.veleftright -= 5; } }else{ this.veleftright = 0; } this.y += this.velocity; this.x += this.veleftright; };
JavaScript
0
@@ -334,16 +334,18 @@ n() %7B%0A +/* if (this @@ -443,24 +443,26 @@ x = -32;%0A %7D +*/ %0A %0A if(pla
076a8d7f0590bfd1ffffa7797d178807d2c5fa92
fix validation
src/managers/master/fp-duration-estimation-manager.js
src/managers/master/fp-duration-estimation-manager.js
"use strict"; var ObjectId = require("mongodb").ObjectId; require("mongodb-toolkit"); var DLModels = require("dl-models"); var map = DLModels.map; var ProcessType = DLModels.master.ProcessType; var FinishingPrintingDurationEstimation = DLModels.master.FinishingPrintingDurationEstimation; var ProcessTypeManager = require('../master/process-type-manager'); var BaseManager = require("module-toolkit").BaseManager; var i18n = require("dl-i18n"); var generateCode = require("../../utils/code-generator"); module.exports = class DurationEstimationManager extends BaseManager { constructor(db, user) { super(db, user); this.collection = this.db.use(map.master.collection.FinishingPrintingDurationEstimation); this.processTypeManager = new ProcessTypeManager(db, user); } _getQuery(paging) { var _default = { _deleted: false }, pagingFilter = paging.filter || {}, keywordFilter = {}, query = {}; if (paging.keyword) { var regex = new RegExp(paging.keyword, "i"); var nameFilter = { "processType.name": { "$regex": regex } }; var areaFilter = { "areas.name": { "$regex": regex } } keywordFilter["$or"] = [nameFilter, areaFilter]; } query["$and"] = [_default, keywordFilter, pagingFilter]; return query; } _validate(process) { var errors = {}; var valid = process; var getEstimationPromise = this.collection.singleOrDefault({ _id: { '$ne': new ObjectId(valid._id) }, processTypeId: valid.processTypeId, _deleted: false }); var getProcessPromise = ObjectId.isValid(valid.processTypeId) ? this.processTypeManager.getSingleByIdOrDefault(new ObjectId(valid.processTypeId)) : Promise.resolve(null); // 2. begin: Validation. return Promise.all([getProcessPromise, getEstimationPromise]) .then(results => { var _process = results[0]; var _oldData = results[1]; if (!valid.processTypeId) errors["processTypeId"] = i18n.__("FPDurationEstimation.processTypeId.isRequired:%s is required", i18n.__("FPDurationEstimation.processTypeId._:Process Type"));//"code Jenis proses tidak boleh kosong"; else if (!_process) { errors["processTypeId"] = i18n.__("FPDurationEstimation.processTypeId.isRequired:%s is not exists", i18n.__("FPDurationEstimation.processTypeId._:Process Type")); } if (_oldData) { errors["processTypeId"] = i18n.__("FPDurationEstimation.processTypeId.isExists:%s is already exists", i18n.__("FPDurationEstimation.processTypeId._:Process Type")); } if (!valid.areas || valid.areas.length === 0) { errors["areas"] = i18n.__("FPDurationEstimation.areas.isRequired:%s is required", i18n.__("FPDurationEstimation.areas._:Areas")); } else { var areaErrors = []; var valueArr = valid.areas.map(function (area) { return area.name.toString() }); var areasDuplicateErrors = new Array(valueArr.length); valueArr.some(function (item, idx) { var _areaError = {}; if (valueArr.indexOf(item) != idx) { _areaError["name"] = i18n.__("FPDurationEstimation.areas.name.isDuplicate:%s is duplicate", i18n.__("FPDurationEstimation.areas.name._:Name")); } if (Object.getOwnPropertyNames(_areaError).length > 0) { areasDuplicateErrors[valueArr.indexOf(item)] = _areaError; areasDuplicateErrors[idx] = _areaError; } else { areasDuplicateErrors[idx] = _areaError; } }); for (var area of valid.areas) { var areaError = {}; var listAreaName = ["PPIC", "PREPARING", "PRE TREATMENT", "DYEING", "PRINTING", "FINISHING", "QC"]; var index = listAreaName.find(name => name.trim().toLocaleLowerCase() === area.name.trim().toLocaleLowerCase()) var _index = valid.areas.indexOf(area); if (area.name == "" || !area.name) { areaError["name"] = i18n.__("FPDurationEstimation.areas.name.isRequired:%s is required", i18n.__("FPDurationEstimation.areas.name._:Name")); } else if (index === -1) { areaError["name"] = i18n.__("FPDurationEstimation.areas.name.isNoExists:%s is no exists", i18n.__("FPDurationEstimation.areas.name._:Name")); } else if (Object.getOwnPropertyNames(areasDuplicateErrors[_index]).length > 0) { Object.assign(areaError, areasDuplicateErrors[_index]); } if (area.duration <= 0 || !area.duration) { areaError["duration"] = i18n.__("FPDurationEstimation.areas.duration.isRequired:%s is required", i18n.__("FPDurationEstimation.areas.duration._:Duration")); } else { area.duration = Number(area.duration) } areaErrors.push(areaError); } for (var areaError of areaErrors) { if (Object.getOwnPropertyNames(areaError).length > 0) { errors.areas = areaErrors; break; } } } if (Object.getOwnPropertyNames(errors).length > 0) { var ValidationError = require("module-toolkit").ValidationError; return Promise.reject(new ValidationError("data does not pass validation", errors)); } valid = new FinishingPrintingDurationEstimation(valid); valid.stamp(this.user.username, "manager"); return Promise.resolve(valid); }); } _beforeInsert(data) { data.code = generateCode(); data._createdDate = new Date(); return Promise.resolve(data); } _createIndexes() { var dateIndex = { name: `ix_${map.master.collection.FinishingPrintingDurationEstimation}__updatedDate`, key: { _updatedDate: -1 } }; var processTypeIdIndex = { name: `ix_${map.master.collection.FinishingPrintingDurationEstimation}_processTypeId`, key: { processTypeId: 1 }, unique: true }; return this.collection.createIndexes([dateIndex, processTypeIdIndex]); } }
JavaScript
0.000005
@@ -2733,32 +2733,21 @@ %7D -%0A + else if (_ol
3490691040a67f842129da85162e6de6920aa0d0
remove test name
modern-tribe-issue-summary.js
modern-tribe-issue-summary.js
// ==UserScript== // @name Central issue summary test // @namespace http://central.tri.be/ // @version 0.2.2 // @description Generate a ticket summary from visible tickets // @author Matthew Batchelder & Nick Pelton // @include /https?:\/\/central.tri.be\/projects\/[^\/]+\/issues\/?/ // @grant none // ==/UserScript== ( function( $ ) { var my = {}; my.$summary_container = $( '<div class="tribe-status-summary"/>' ); my.$titleBar = $( '#content .title-bar' ); // Bubble template my.TLP = ''; my.TLP += '<div class="tribe-status {class_name}" style="border:1px solid #eee;border-radius:5px;box-shadow:0 0 3px 0px rgba( 0, 0, 0, 0.1 );display:inline-block;margin:.25rem;text-align:center;">'; my.TLP += '<div class="tribe-status-count" style="font-size: 1.5rem;padding: .5rem;">{count}</div>'; my.TLP += '<div class="tribe-status-label" style="font-size:.7rem;padding:0 .5rem .5rem"><span style="background:{bg_color};border-radius:5px;padding: 5px;color:{txt_color};">{label}</span></div>'; my.TLP += '</div>'; // Render bubble and insert into DOM my.addBubble = function( count, label, class_name, bg_color, txt_color ){ var options = { count: count || 0, label: label || "empty", class_name: class_name || "", bg_color: bg_color || "", txt_color: txt_color || "" }; var template = my.TLP; template = template.replace(/{count}/g, options.count); template = template.replace(/{label}/g, options.label); template = template.replace(/{class_name}/g, options.class_name); template = template.replace(/{bg_color}/g, options.bg_color); template = template.replace(/{txt_color}/g, options.txt_color); my.$summary_container.append( template ); }; my.statuses = [ { code: 'status-2', name: 'Proposed', color: '#fffff6' }, { code: 'status-3', name: 'New', color: '#ffffe2' }, { code: 'status-4', name: 'In Progress', color: '#bfd4f2' }, { code: 'status-7', name: 'Pending Code Review', color: '#bfe5bf' }, { code: 'status-9', name: 'Pending Merge', color: '#009800', text: '#fff' }, { code: 'status-6', name: 'Pending Manager', color: '#76dbdf' }, { code: 'status-12', name: 'Pending Customer', color: '#e2c688' }, { code: 'status-25', name: 'On Hold', color: '#dbc7e3' }, { code: 'status-13', name: 'Pending Final Signoff', color: '#ccbfa2' }, { code: 'status-5', name: 'Pending QA', color: '#fad8c7' }, { code: 'status-10', name: 'Pending Smoketest', color: '#e9b398' }, { code: 'status-26', name: 'Complete', color: '#91be9c', text: '#fff' }, { code: 'status-11', name: 'Pending Release', color: '#7e987b', text: '#fff' }, { code: 'status-27', name: 'Declined', color: '#969696', text: '#fff' } ]; my.init = function() { this.$issues = $('#issue-list'); var issue_count = this.$issues.find( 'tr.issue' ).length; if ( ! issue_count ) { return; } // Ticket Count var $summary = $( '<div class="tribe-summary-text">Issue count: ' + issue_count + '</div>' ); my.$summary_container.append( $summary ); // Ticket Summary for ( var i in my.statuses ) { var $rows = this.$issues.find( 'tr.' + my.statuses[ i ].code ); if ( ! $rows.length ) { continue; } var text_color = ''; if ( 'undefined' !== my.statuses[ i ].text ) { text_color = 'color:' + my.statuses[ i ].text + ';'; } console.log( '.' + my.statuses[ i ].code, $rows.length ); my.addBubble( $rows.length, my.statuses[ i ].name, my.statuses[ i ].code, my.statuses[ i ].color, text_color ); } // Estimate summary var that = this; that.$rows = this.$issues.find( '.estimated_hours' ); if ( that.$rows.length ) { that.estimates = 0; $.each(this.$rows, function(index, $object){ val = ( parseFloat( $($object).html() ) || 0 ); that.estimates += val; }); that.hours = 0; that.$rows = this.$issues.find( '.spent_hours' ); $.each(this.$rows, function(index, $object){ val = ( parseFloat( $($object).html() ) || 0 ); that.hours += val; }); that.diff = that.estimates - that.hours; that.diff_text = "Under"; if(that.diff < 0){ that.diff_text = "Over"; } my.addBubble( Math.round( that.estimates * 100 ) / 100, "Hrs Est." ); my.addBubble( Math.round( that.hours * 100 ) / 100, "Hrs Spent" ); my.addBubble( Math.round( that.diff * 100 ) / 100, "Hrs " + that.diff_text ); } // Add to DOM my.$summary_container.find('.tribe-status:first' ).css( { 'margin-left': '0' } ); my.$titleBar.append( my.$summary_container ); }; $( function() { my.init(); } ); } )( jQuery );
JavaScript
0.999779
@@ -53,13 +53,8 @@ mary - test %0A//
68e01175c3e3d06adbc31476b9b6cb3789759710
Fix default cron configuration
lib/index.js
lib/index.js
var createJob = require('./createJob'); module.exports = function (sails) { return { defaults: {}, initialize: function (cb) { var config = sails.config.cron; var tasks = Object.keys(config); tasks.forEach(function (time) { return createJob({ cronTime: time, onTick: config[time] instanceof Function ? config[time] : config[time].onTick, onComplete: config[time].onComplete, timezone: config[time].timezone }); }); cb(); } }; };
JavaScript
0.000001
@@ -96,16 +96,24 @@ aults: %7B +cron: %7B%7D %7D,%0A%0A
ccbddfe20f2cff074dab92efde726911aea55d08
Remove unneeded action types
app/scripts/actionTypes.js
app/scripts/actionTypes.js
import keyMirror from 'keymirror' export default keyMirror({ API_FAILURE: null, API_REQUEST: null, API_SUCCESS: null, AUTH_LOGIN_FAILURE: null, AUTH_LOGIN_REQUEST: null, AUTH_LOGIN_SUCCESS: null, AUTH_LOGOUT: null, AUTH_REGISTER_FAILURE: null, AUTH_REGISTER_REQUEST: null, AUTH_REGISTER_SUCCESS: null, AUTH_RESET_PASSWORD_FAILURE: null, AUTH_RESET_PASSWORD_REQUEST: null, AUTH_RESET_PASSWORD_SUCCESS: null, AUTH_TICKET_FAILURE: null, AUTH_TICKET_REQUEST: null, AUTH_TICKET_SUCCESS: null, AUTH_TOKEN_EXPIRED_OR_INVALID: null, CHANGE_PROFILE_FAILURE: null, CHANGE_PROFILE_REQUEST: null, CHANGE_PROFILE_SUCCESS: null, DRAWER_COLLAPSE_ALL: null, DRAWER_TOGGLE_NAVIGATION: null, DRAWER_TOGGLE_SIDEBAR: null, FLASH_ADD_MESSAGE: null, FLASH_REMOVE_ALL_MESSAGES: null, FLASH_REMOVE_MESSAGE: null, INBOX_NEW_CONVERSATION_FAILURE: null, INBOX_NEW_CONVERSATION_INITIALIZE: null, INBOX_NEW_CONVERSATION_REQUEST: null, INBOX_NEW_CONVERSATION_SUCCESS: null, INBOX_NEW_MESSAGE_FAILURE: null, INBOX_NEW_MESSAGE_INITIALIZE: null, INBOX_NEW_MESSAGE_REQUEST: null, INBOX_NEW_MESSAGE_SUCCESS: null, INFINITE_LIST_FAILURE: null, INFINITE_LIST_INITIALIZE: null, INFINITE_LIST_REQUEST: null, INFINITE_LIST_SUCCESS: null, META_FAILURE: null, META_REQUEST: null, META_SUCCESS: null, PAGE_FAILURE: null, PAGE_REQUEST: null, PAGE_SUCCESS: null, PAGINATED_LIST_FAILURE: null, PAGINATED_LIST_REMOVE_ITEM: null, PAGINATED_LIST_REQUEST: null, PAGINATED_LIST_SUCCESS: null, RANDOM_MEETING_FAILURE: null, RANDOM_MEETING_REQUEST: null, RANDOM_MEETING_SUCCESS: null, REDIRECT: null, REPLACE: null, RESOURCE_CREATE_FAILURE: null, RESOURCE_CREATE_REQUEST: null, RESOURCE_CREATE_SUCCESS: null, RESOURCE_DELETE_FAILURE: null, RESOURCE_DELETE_REQUEST: null, RESOURCE_DELETE_SUCCESS: null, RESOURCE_FAILURE: null, RESOURCE_REQUEST: null, RESOURCE_SUCCESS: null, RESOURCE_UPDATE_FAILURE: null, RESOURCE_UPDATE_REQUEST: null, RESOURCE_UPDATE_SUCCESS: null, SLOTS_FAILURE: null, SLOTS_REQUEST: null, SLOTS_SUCCESS: null, STREAM_START: null, STREAM_STOP: null, UPLOAD_IMAGE_CLEAR: null, UPLOAD_IMAGE_FAILURE: null, UPLOAD_IMAGE_REMOVE_IMAGE: null, UPLOAD_IMAGE_REQUEST: null, UPLOAD_IMAGE_SET_IMAGES: null, UPLOAD_IMAGE_SUCCESS: null, USER_STATUS_FAILURE: null, USER_STATUS_REQUEST: null, USER_STATUS_SUCCESS: null, })
JavaScript
0.000001
@@ -2125,52 +2125,8 @@ l,%0A%0A - STREAM_START: null,%0A STREAM_STOP: null,%0A%0A UP
8afb8ec8cc5bbaa332ae91c43c76b48b41a79753
set correct default value when property becomes visible
addon/components/property-options/component.js
addon/components/property-options/component.js
import Ember from 'ember'; export default Ember.Component.extend({ tagName: '', showProperty: true, init() { this._super(...arguments); let property = this.get('property.property'); let document = this.get('document'); if (!property.isDependentProperty) { return; } this.setProperties({ isDependentProperty: true, dependsOnProperties: property.dependsOnProperties }); property.dependsOnProperties.forEach((dependsOn) => { this.callback = Ember.run.bind(this, this._onUpdatedMasterProperty); document.values.addObserver(dependsOn.property.documentPath, this.callback); }); document.values.addObserver('didLoad', this.callback); this._onUpdatedMasterProperty(); }, propertyOptions: Ember.computed('showProperty', function() { let showProperty = this.get('showProperty'); return { showProperty }; }), willDestroyElement() { this._super(...arguments); let property = this.get('property.property'); let document = this.get('document'); if (!property.isDependentProperty) { return; } property.dependsOnProperties.forEach((dependsOn) => { document.values.removeObserver(dependsOn.property.documentPath); }); document.values.removeObserver('didLoad', this.callback); }, _onUpdatedMasterProperty() { let property = this.get('property.property'); let document = this.get('document'); let dependencyCount = property.dependsOnProperties.length; let showProperty = property.dependsOnProperties.filter((dependsOn) => { let currentValue = document.get(dependsOn.property.documentPath); return dependsOn.values.indexOf(currentValue) > -1; }).length === dependencyCount; this.setProperties({ showProperty }); if (!showProperty) { document.set(property.documentPath, null); } } });
JavaScript
0.000001
@@ -1788,17 +1788,16 @@ if ( -! showProp @@ -1814,48 +1814,612 @@ -document.set(property.documentPath, null +this._setDefaultValue();%0A %7D else %7B%0A document.set(property.documentPath, null);%0A %7D%0A %7D,%0A%0A _setDefaultValue() %7B%0A let document = this.get('document');%0A let property = this.get('property.property');%0A let defaultValue = this.get('property.default');%0A let value;%0A%0A if (!Ember.isNone(document.get(property.documentPath))) %7B%0A return;%0A %7D%0A%0A if (Ember.isNone(defaultValue)) %7B%0A value = %7B 'array': %5B%5D, 'string': '', 'object': %7B%7D %7D%5Bproperty.type%5D;%0A %7D else %7B%0A value = defaultValue;%0A %7D%0A%0A if (!Ember.isNone(value)) %7B%0A document.set(property.documentPath, value );%0A
6469ee7f04e88bb1eb57a743e91939bda946ba3a
Fix links
Source/Mixin/Request.js
Source/Mixin/Request.js
/* --- script: Request.js description: Make various requests to back end license: Public domain (http://unlicense.org). requires: - LSD.Mixin - Core/Request - Ext/Request.Form - Ext/Request.Auto - Ext/document.createFragment provides: - LSD.Mixin.Request ... */ LSD.Mixin.Request = new Class({ behaviour: '[action], [src], [href]', options: { request: { method: 'get' }, states: { working: { enabler: 'busy', disabler: 'idle' } }, actions: { request: { enable: function() { if (this.attributes.autosend) this.send(); }, disable: function() { } } }, events: { getCommandAction: function() { if (!this.isRequestURLLocal()) return 'send'; }, getTargetAction: function() { if (this.getCommandAction() == 'send') return 'update'; } } }, send: function() { var options = Object.merge({}, this.options.request, {data: this.getRequestData(), url: this.getRequestURL(), method: this.getRequestMethod()}); for (var i = 0, j = arguments.length, arg, opts; i < j; i++) { var arg = arguments[i]; if (!arg) continue; if (typeof arg == 'object' && !arg.event) { if (("url" in arg) || ("method" in arg) || ("data" in arg)) Object.merge(options, arg) else options.data = Object.merge(options.data || {}, arg); } else if (arg.call) var callback = arg; } var request = this.getRequest(options); if (callback) request.addEvent('complete:once', callback); return request.send(options); }, getRequest: function(options) { var type = this.getRequestType(); if (!this.request || this.request.type != type) { if (!this.request) this.addEvent('request', { request: 'onRequest', complete: 'onRequestComplete', success: 'onRequestSuccess', failure: 'onRequestFailure' }); this.request = this[type == 'xhr' ? 'getXHRRequest' : 'getFormRequest'](options); if (!this.request.type) { this.request.type = type; this.fireEvent('register', ['request', this.request, type]); } } return this.request; }, onRequestSuccess: function() { if (this.chainPhase == -1 && this.getCommandAction() == 'send') this.callOptionalChain.apply(this, arguments); }, onRequest: function() { this.busy(); }, onRequestComplete: function() { this.idle(); }, getRequestData: Macro.defaults(function() { return null; }), getXHRRequest: function(options) { return new Request.Auto(options); }, getFormRequest: function(options) { return new Request.Form(options); }, getRequestType: function() { return this.attributes.transport || this.options.request.type; }, getRequestMethod: function() { return this.attributes.method || this.options.request.method; }, getRequestURL: function() { return this.attributes.href || this.attributes.src || this.attributes.action; }, isRequestURLLocal: function(base, host) { if (!host) host = location.host; if (!base) base = location.pathname; var url = this.getRequestURL(); return (url.charAt(0) == "#") || url.match(new RegExp('(?:' + host + ')?' + base + '/?#')); } });
JavaScript
0
@@ -709,24 +709,40 @@ events: %7B%0A + self: %7B%0A getCom @@ -758,32 +758,34 @@ n: function() %7B%0A + if (!thi @@ -832,18 +832,16 @@ + + %7D,%0A +%0A - %0A @@ -864,32 +864,34 @@ n: function() %7B%0A + if (this @@ -938,16 +938,26 @@ pdate';%0A + %7D%0A %7D%0A
8462af6d1c55cd3a5476a41c201346082568b61a
Enable source maps for browserify
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var jshint = require('gulp-jshint'); var less = require('gulp-less'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var path = require('path'); var rename = require('gulp-rename'); var react = require('gulp-react'); var flowtype = require('gulp-flowtype'); var source = require('vinyl-source-stream'); var jsxcs = require('gulp-jsxcs'); var gutil = require('gulp-util'); var jest = require('gulp-jest'); var browserify = require('browserify'); var reactify = require('reactify'); var es6defaultParams = require('es6-default-params'); // Lint Task gulp.task('prelint', function() { return gulp.src('js/**/*.js') .pipe(jsxcs().on('error', function(err) { console.log(err.toString()); })) .pipe(jshint.reporter('default')); }); // Lint Task gulp.task('postlint', function() { return gulp.src('build/**/*.js') .pipe(jshint({ esnext: true })) .pipe(jshint.reporter('default')); }); gulp.task('typecheck', function() { return gulp.src('js/**/*.js') .pipe(flowtype({ declarations: './flowtypes', background: false, // Watch/Server mode all: false, // Check all files regardless lib: '', // Library directory module: '', // Module mode stripRoot: false, // Relative vs Absolute paths weak: false, // Force weak check showAllErrors: false, // Show more than 50 errors killFlow: false, })) .pipe(jshint.reporter('default')); }); // Compile Our LESS gulp.task('less', function() { return gulp.src('./style/**/*.less') .pipe(less({ paths: [ path.join(__dirname, 'style') ] })) .pipe(gulp.dest('./build/css')); }); gulp.task('react', function() { return browserify('./js/main.js') .transform({ 'strip-types': true, es6: true}, reactify) .transform(es6defaultParams) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest('./build')); /* .pipe(react({ harmony: true, // Skip Flow type annotations! stripTypes: true })) */ }); // Concatenate & Minify JS gulp.task('releasify', function() { return gulp.src('build/**/*.js') .pipe(concat('all.js')) .pipe(gulp.dest('dist')) .pipe(rename('all.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')); }); // Test gulp.task('test', function() { return gulp.src('__tests__').pipe(jest({ //testDirectoryName: "__test__", testPathIgnorePatterns: [ "perseus", "bower_compoennts", "node_modules", "spec/support" ], moduleFileExtensions: [ "js", "json", "react" ] })); }); // Watch Files For Changes gulp.task('watch', function() { gulp.watch('js/**/*.js', ['prelint', 'typecheck', 'react']); gulp.watch('build/**/*.js', ['postlint']); gulp.watch('style/**/*.less', ['less']); }); // Default Task // Not including Flow typechecking by default because it takes so painfully long. // Maybe because of my code layout or otheriwse, needto figure it out before enabling by default. gulp.task('default', ['prelint', 'typecheck', 'react', 'less', 'postlint', 'watch']);
JavaScript
0.000031
@@ -1927,24 +1927,61 @@ /js/main.js' +, %7B%0A debug: true%0A %7D )%0A .t
384923fdf6054333c91590b584745661ad8bc30d
Fix spelling and add more help information.
lib/index.js
lib/index.js
var fs = require('fs'), util = require('util'), colors = require('colors'); var applyIf = function (object, config) { var property; if (object) { for (property in config) { if (object[property] === undefined) { object[property] = config[property]; } } } return object; } var processHierarchy = function(objects) { var dict = {}; objects.forEach(function(object) { dict[object._name || 'development'] = object; }); objects.forEach(function(object) { if (object._extend) { [].concat(object._extend).forEach(function(_extend) { if (dict[_extend]) { applyIf(object, dict[_extend]); } }) } }); return dict; } var applyEnv = function(object) { var appliedEnv = {}; for (property in object) { if (property === 'NODE_ENV') { continue; } process.env[property] = object[property]; appliedEnv[property] = object[property]; } return appliedEnv; } var populateEnv = function(objectsDict) { var env = process.env.NODE_ENV || 'development'; var objectToPopulateEnv = objectsDict[env]; if (objectToPopulateEnv == undefined) { return console.log('NODE_ENV', env, 'not found in .econf.json') } return applyEnv(objectToPopulateEnv); } module.exports = function(econfFile) { econfFile = econfFile || process.cwd() + '/.econf.js'; try { objects = require(econfFile); if (!util.isArray(objects)) { objects = [objects]; } objects = processHierarchy(objects); return populateEnv(objects); } catch(err) { console.log(err); } } module.exports.showEconfContent = function(cb) { var path = process.cwd() + '/.econf.js'; fs.stat(path, function(err) { if (err) { return console.log('File .econf.js not found'.red); } var objects = require(path); objects = processHierarchy(objects); for(property in objects) { var object = objects[property]; var _extend = ''; if (object._extend) { _extend = [].concat(object._extend); _extend = _extend.join(', '); _extend = '{' + _extend + '}'; } console.log(''); console.log(property.green, _extend.yellow); delete object._name; delete object._extend; console.log(' ', JSON.stringify(object, null, ' ').replace(/\n/g, '\n ').grey); } if (cb) { cb(); } }) } module.exports.createEconfFile = function() { var file = fs.readFileSync(__dirname + '/../.econf.js'); fs.writeFileSync(process.cwd() + '/.econf.js', file); module.exports.showEconfContent(function() { console.log(''); console.log('###########################################'.yellow); console.log('### Fo not forget to install econf lib ###'.yellow); console.log('### ###'.yellow); console.log('###'.yellow, 'npm install econf --save ', '###'.yellow); console.log('### ###'.yellow); console.log('### Do not forget to include econf lib ###'.yellow); console.log('### into your project at the first line ###'.yellow); console.log('### ###'.yellow); console.log('###'.yellow, 'require("econf")() ', '###'.yellow); console.log('### ###'.yellow); console.log('###########################################'.yellow); }); }
JavaScript
0
@@ -1652,23 +1652,16 @@ r) %7B%0A%09%09%09 -return console. @@ -1697,16 +1697,96 @@ '.red);%0A +%09%09%09console.log('To create .econf.js execute:'.yellow, 'econf init');%0A%09%09%09return;%0A %09%09%7D%0A%0A%09%09v @@ -2633,17 +2633,17 @@ og('### -F +D o not fo
7b6ca9cbf1be8c8cd340208e835997c170df3808
add up
J8-0.0.1.js
J8-0.0.1.js
/** * Created by lja on 2015/11/20. */ var type = (function () { 'use strict'; var class2type = {}, toString = class2type.toString; ('Boolean Number String Function Array Date RegExp Object Error').split(' ').forEach(function (name) { class2type['[object ' + name + ']'] = name.toLowerCase(); }); function isWindow(obj) { return obj !== null && obj.window && obj === obj.window; } function isFunction(obj) { return class2type[toString.call(obj)] === 'function'; } function isDocument(obj) { return obj && obj.nodeType === obj.DOCUMENT_NODE; } function isObject(obj) { return class2type[toString.call(obj)] === 'object'; } function isArray(obj) { return class2type[toString.call(obj)] === 'array'; } function isPlainObject(obj) { return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) === Object.prototype; } return { isWindow: isWindow, isFunction: isFunction, isDocument: isDocument, isObject: isObject, isPlainObject: isPlainObject, isArray: isArray }; })(); var Jackey8 = (function (type) { 'use strict'; var J8, emptyArray = [], jackey8 = {}, table = document.createElement('table'), tableRow = document.createElement('tr'), containers = { 'tr': document.createElement('tbody'), 'tbody': table, 'thead': table, 'tfoot': table, 'td': tableRow, 'th': tableRow, '*': document.createElement('div') }, // special attributes that should be get/set via method calls methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'], simpleSelectorRE = /^[\w-]*$/,//字母 数字 或者下划线,不包括空格 tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,//tag reg readyRE = /complete|loaded|interactive/, htmlFragmentRE = /^\s*<(\w+|!)[^>]*>/;//html片段 function filterNullArray(array) { return emptyArray.filter.call(array, function (item) { return item !== null; }); } //decorate the __proto__ and selector //todo: __proto__ not supported on IE jackey8.decorateDom = function (dom, selector) { dom = dom || []; dom.__proto__ = J8.fn;//jshint ignore:line dom.selector = selector; return dom; }; jackey8.createNodeByHtmlFragment = function (html, name, properties) { var dom, nodes, container; if (simpleSelectorRE.test(html)) { dom = J8(document.createElement(RegExp.$1)); } if (!dom) { if (html.replace) { html = html.replace(tagExpanderRE, '<$1></$2>'); } if (name === void 0) { name = htmlFragmentRE.test(html) && RegExp.$1; } if (!(name in containers)) { name = '*'; } container = containers[name]; container.innerHTML = '' + html;//add html fragment to dom, make it node dom = J8.each(emptyArray.slice.call(container.childNodes), function () { container.removeChild(this); }); } if (type.isPlainObject(properties)) { nodes = J8(dom); J8.each(properties, function (key, value) { if (methodAttributes.indexOf(key) > -1) { nodes[key](value); } else { nodes.attr(key, value); } }); } }; /** * find selector in context * by id class and 复杂类型:ul li * @param context * @param selector */ jackey8.queryDom = function (context, selector) { var found = [], maybeId = selector[0] === '#', maybeClass = selector[0] === '.', name = maybeId || maybeClass ? selector.slice(1) : selector, isSample = simpleSelectorRE.test(name); if (!type.isDocument(context)) { return found; } if (!isSample) { found = emptyArray.slice.call(context.querySelectorAll(selector)); } else { if (maybeId) { found = context.getElementById(name); if (found) { return [found]; } return []; } if (maybeClass) { found = context.getElementsByClassName(name); } else { found = context.getElementsByTagName(name); } } return emptyArray.slice.call(found); }; //selector: empty string function object array and the instance of Jackey8 jackey8.init = function (selector, context) { var dom; //if nothing given, return an empty collection if (!selector) { return jackey8.decorateDom(); } if (typeof selector === 'string') { selector = selector.trim(); //如果它是一个html片段,则创建一个节点 //提示:在chrome21和Firefox15下面, // 如果不是<开头, 会抛错 if (selector[0] === '<' && htmlFragmentRE.test(selector)) { //todo: dom = jackey8.createNodeByHtmlFragment(selector, RegExp.$1, context); selector = null; } //如果有parent,则先找到parent,然后使用find去找到selector else if (context !== void 0) { J8(context).find(selector); } else { // 正常的选取 // 1 id 2 class 3 复杂选取 // 作用域为document,因为如果存在context,则执行$(conetxt).find(selector) dom = jackey8.queryDom(document, selector); } } else if (type.isFunction(selector)) { J8(document).ready(selector); } else if (selector instanceof jackey8.decorateDom) { return selector; } else if (type.isArray(selector)) { dom = filterNullArray(selector); } else if (type.isObject(selector)) { dom = [selector]; selector = null; } else { dom = []; } return jackey8.decorateDom(dom, selector); }; J8 = function (selector, context) { return jackey8.init(selector, context); }; J8.each = function (elements, callback) { var i, key; if (type.isArray(elements)) { for (i = 0; i < elements.length; i++) { if (callback.call(elements[i], i, elements[i]) === false) { return elements; } } } else { for (key in elements) { if (callback.call(elements[key], key, elements[key]) === false) { return elements; } } } return elements; } J8.fn = { forEach: emptyArray.forEach, reduce: emptyArray.reduce, push: emptyArray.push, sort: emptyArray.sort, indexOf: emptyArray.indexOf, concat: emptyArray.concat, ready: function (callback) { if (readyRE.test(document.readyState) && document.body) { callback(J8); } else { //todo: need to test DOMContentLoaded in each browsers document.addEventListener('DOMContentLoaded', function () { callback(J8); }, false); return this; } } }; return J8; })(type); window.Jackey8 = Jackey8; if (window.J8 === void 0) { window.J8 = Jackey8; }
JavaScript
0.000048
@@ -7601,18 +7601,16 @@ %0A %7D;%0A -%0A%0A %0A
acf657e2e0ab463231f25c06cb2778c056ad34eb
Fix bug in CompoundPath#draw(ctx, draw) which was causing an error when a compound path didn't have any children.
src/path/CompoundPath.js
src/path/CompoundPath.js
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ /** * @name CompoundPath * * @class A compound path contains two or more paths, holes are drawn * where the paths overlap. All the paths in a compound path take on the * style of the backmost path and can be accessed through its * {@link Item#children} list. * * @extends PathItem */ var CompoundPath = this.CompoundPath = PathItem.extend(/** @lends CompoundPath# */{ /** * Creates a new compound path item and places it in the active layer. * * @param {Path[]} [paths] the paths to place within the compound path. * * @example {@paperscript} * // Create a circle shaped path with a hole in it: * var circle = new Path.Circle(new Point(50, 50), 30); * var innerCircle = new Path.Circle(new Point(50, 50), 10); * var compoundPath = new CompoundPath([circle, innerCircle]); * compoundPath.fillColor = 'red'; * * // Move the inner circle 5pt to the right: * compoundPath.children[1].position.x += 5; */ initialize: function(paths) { this.base(); // Allow CompoundPath to have children and named children. this._children = []; this._namedChildren = {}; // Do not reassign to paths, since arguments would get modified, which // we potentially use as array, depending on what is passed. var items = !paths || !Array.isArray(paths) || typeof paths[0] !== 'object' ? arguments : paths; for (var i = 0, l = items.length; i < l; i++) { var path = items[i]; // All paths except for the top one (last one in list) are set to // clockwise orientation when creating a compound path, so that they // appear as holes, but only if their orientation was not already // specified before (= _clockwise is defined). // TODO: Should this be handled in appendTop / Bottom instead? if (path._clockwise === undefined) path.setClockwise(i < l - 1); this.addChild(path); } }, /** * If this is a compound path with only one path inside, * the path is moved outside and the compound path is erased. * Otherwise, the compound path is returned unmodified. * * @return {CompoundPath|Path} the simplified compound path */ simplify: function() { if (this._children.length == 1) { var child = this._children[0]; child.insertAbove(this); this.remove(); return child; } return this; }, smooth: function() { for (var i = 0, l = this._children.length; i < l; i++) this._children[i].smooth(); }, draw: function(ctx, param) { var firstChild = this._children[0]; ctx.beginPath(); param.compound = true; for (var i = 0, l = this._children.length; i < l; i++) Item.draw(this._children[i], ctx, param); firstChild._setStyles(ctx); var fillColor = firstChild.getFillColor(), strokeColor = firstChild.getStrokeColor(); if (fillColor) { ctx.fillStyle = fillColor.getCanvasStyle(ctx); ctx.fill(); } if (strokeColor) { ctx.strokeStyle = strokeColor.getCanvasStyle(ctx); ctx.stroke(); } param.compound = false; } }, new function() { // Injection scope for PostScript-like drawing functions /** * Helper method that returns the current path and checks if a moveTo() * command is required first. */ function getCurrentPath(that) { if (!that._children.length) throw new Error('Use a moveTo() command first'); return that._children[that._children.length - 1]; } var fields = { // Note: Documentation for these methods is found in PathItem, as they // are considered abstract methods of PathItem and need to be defined in // all implementing classes. moveTo: function(point) { var path = new Path(); this.addChild(path); path.moveTo.apply(path, arguments); }, moveBy: function(point) { this.moveTo(getCurrentPath(this).getLastSegment()._point.add( Point.read(arguments))); }, closePath: function() { getCurrentPath(this).setClosed(true); } }; // Redirect all other drawing commands to the current path Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo', 'arcTo', 'lineBy', 'curveBy', 'arcBy'], function(key) { fields[key] = function() { var path = getCurrentPath(this); path[key].apply(path, arguments); }; }); return fields; });
JavaScript
0
@@ -2838,16 +2838,146 @@ aram) %7B%0A +%09%09var l = this._children.length;%0A%09%09// Return early if the compound path doesn't have any children:%0A%09%09if (l == 0) %7B%0A%09%09%09return;%0A%09%09%7D%0A %09%09var fi @@ -3006,16 +3006,16 @@ ren%5B0%5D;%0A - %09%09ctx.be @@ -3050,16 +3050,16 @@ = true;%0A + %09%09for (v @@ -3070,35 +3070,8 @@ = 0 -, l = this._children.length ; i
0f034677f647b8fad1b21bdbde259a51f2a5b9bc
Fix comma
widgets.js
widgets.js
sagecell.require(["notebook/js/widgets/widget"], function(WidgetManager){ var WebCameraView = IPython.DOMWidgetView.extend({ render: function(){ // based on https://developer.mozilla.org/en-US/docs/WebRTC/taking_webcam_photos var video = $('<video>')[0]; var canvas = $('<canvas>')[0]; var startbutton = $('<button>Take Pic</button>')[0]; var width = 320; var height = 0; var that = this; setTimeout(function() {that.$el.append(video).append(startbutton).append(canvas);}, 200); $(canvas).hide(); var streaming = false; navigator.getMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); navigator.getMedia({video: true, audio: false}, function(stream) { if (navigator.mozGetUserMedia) { video.mozSrcObject = stream; } else { var vendorURL = window.URL || window.webkitURL; video.src = vendorURL.createObjectURL(stream); } video.play(); }, function(err) { console.log("An error occured! " + err); } ); video.addEventListener('canplay', function(ev){ if (!streaming) { height = video.videoHeight / (video.videoWidth/width); video.setAttribute('width', width); video.setAttribute('height', height); canvas.setAttribute('width', width); canvas.setAttribute('height', height); streaming = true; } }, false); function takepicture() { canvas.width = width; canvas.height = height; video.pause(); $(video).fadeTo(1,0).delay(100).fadeTo(1,100); setTimeout(function() {video.play()}, 3000); canvas.getContext('2d').drawImage(video, 0, 0, width, height); that.model.set('imageurl',canvas.toDataURL('image/png')); that.touch(); } startbutton.addEventListener('click', function(ev){ takepicture(); ev.preventDefault(); }, false); }, }); WidgetManager.register_widget_view('WebCameraView', WebCameraView); var LinkView = IPython.WidgetView.extend({ render: function(){ _.each(this.model.get('widgets'), function(element, index, list) { var model = element[0], attr = element[1]; model.on('change:'+attr, function() {this.update_value(element)}, this); }, this); this.update_value(this.model.get('widgets')[0]); // TODO: register for any destruction handlers this.update_bindings([], this.model.get('widgets')) this.model.on('change:widgets', function(model, value, options) { this.update_bindings(model.previous('widgets'), value); }, this) }, update_bindings: function(oldlist, newlist) { var that = this this.do_diff(oldlist, newlist function(elt) {elt[0].off('change:'+elt[1], null, that);}, function(elt) {elt[0].on('change:'+elt[1], function(model, value, options) { that.update_value(elt, value) }, that);}) }, update_value: function(elt, value) { if (this.updating) {return;} var model = elt[0]; var attr = elt[1]; this.updating = true; _.each(_.without(this.model.get('widgets'), elt), function(element, index, list) { element[0].set(element[1], value); element[0].save_changes(); }, this); this.updating = false; }, }); IPython.WidgetManager.register_widget_view('LinkView', LinkView); }); // http://sagecell.sagemath.org/?z=eJylU21r2zAQ_h7IfxAZxTIYO-1aBqMqjA7GIGVjG-xDyAfZvlrKLMlI56b-9zs7Muk2OvYiDNKd7p7n7jm5D-CtNCCSvQzONt71mCwXy8ULhablq-tQed0hC74SiULswuui8PJwkTcaVV_mlTPFWSi6AZUH2IciYF-DxZMn34fk5ro4At2szvpImRJJ62TN_xW3G5KnYM8UTLilewSbG4kqP8igtG3Q2RzqvlDOQDF1_oTpucqJ41Tv_8BS4emo8d9JrLvhoOsGMBRGBgRfRPM3Av-i759C_qTtcqFN5zwy1AaWi85riyzZEDp1nec5PZnxJg8tQMcvpoyKUr0UX6G8nU588gblDvx4NdnIBHtvZANf4BF7D1yPRu-1WI2CN0BSoh8o6nOnwMO76OCeuPsgLimIRgBey5aCNtKU4PEuenjlWudFclAaIcmYkZ3AidcMrtxDNdLfQVB8JhLzYQw-goj5QIkVxX8EHzpK1Q8QO-tc0KidFdt1dj5-u4zduwdxuc5YpXRbe6C7t9qPWc7KdqMbhbG49eP9tDJ2gnmZXWXnBEIygyXnINb5VbqjAkIFFkY1xp2fwOd-MvbGlJp-lB8pXk1rQlguKKEmKT3BfIrHOBJRZWxmmHaq31n0rg3igy813kaLR3dL8xdVmsbBzsizvdH2G49vSmy3R5KMJXHIbUI9bvHk0Mlul041fgdN15U4&lang=sage /* from IPython.html.widgets import Widget, DOMWidget from IPython.html import widgets from IPython.utils.traitlets import Unicode, Bytes, Instance, Tuple, Any html("<script src='http://boxen.math.washington.edu/home/jason/pythreejs/pythreejs.js'></script>") load('http://boxen.math.washington.edu/home/jason/pythreejs/pythreejs.py') html("<script src='https://raw2.github.com/%s/ipywidgets/master/widgets.js'></script>"%username) load('https://rawgithub.com/%s/ipywidgets/master/widgets.py'%username) import time time.sleep(1) a = widgets.FloatSliderWidget(value=30) b = widgets.FloatSliderWidget() c = widgets.FloatSliderWidget() show(a) show(b) show(c) print a.value, b.max ll=Link(widgets=[[a,'value'], [b,'max']]) show(ll) def p(name, new): c.value = new+1 b.on_trait_change(p, 'max') */
JavaScript
0.999998
@@ -3456,16 +3456,17 @@ newlist +, %0A
e27449790ec167a2e610a02abadc9a8d1beb5392
add a missing space after the [beta] label
source/views/settings/sections/odds-and-ends.js
source/views/settings/sections/odds-and-ends.js
// @flow import React from 'react' import {View} from 'react-native' import {getVersion} from 'react-native-device-info' import {Cell, Section} from 'react-native-tableview-simple' import {version, allaboutolaf} from '../../../../package.json' import type {TopLevelViewPropsType} from '../../types' import {setFeedbackStatus} from '../../../flux/parts/settings' import {connect} from 'react-redux' import {CellToggle} from '../../components/cell-toggle' import {PushButtonCell} from '../components/push-button' import {trackedOpenUrl} from '../../components/open-url' class OddsAndEndsSection extends React.Component { props: TopLevelViewPropsType & { onChangeFeedbackToggle: (feedbackDisabled: boolean) => any, feedbackDisabled: boolean, } onPressButton = (id: string, title: string) => { this.props.navigator.push({ id: id, title: title, index: this.props.route.index + 1, }) } onCreditsButton = () => this.onPressButton('CreditsView', 'Credits') onPrivacyButton = () => this.onPressButton('PrivacyView', 'Privacy Policy') onLegalButton = () => this.onPressButton('LegalView', 'Legal') onSnapshotsButton = () => this.onPressButton('SnapshotsView', 'Snapshot Time') onSourceButton = () => trackedOpenUrl({ url: 'https://github.com/StoDevX/AAO-React-Native', id: 'ContributingView', }) render() { // allows us to show [dev], [beta], or nothing for release builds const versionMoniker = process.env.NODE_ENV === 'development' ? '[dev] ' : allaboutolaf.source ? `[${allaboutolaf.source}]` : '' // native (codepush) // eg, 2.1.2 (2.1.2+2957) const versionString = getVersion() === version ? getVersion() : `${getVersion()} (${version})` return ( <View> <Section header="MISCELLANY"> <PushButtonCell title="Credits" onPress={this.onCreditsButton} /> <PushButtonCell title="Privacy Policy" onPress={this.onPrivacyButton} /> <PushButtonCell title="Legal" onPress={this.onLegalButton} /> <PushButtonCell title="Contributing" onPress={this.onSourceButton} /> </Section> <Section header="ODDS &amp; ENDS"> <Cell cellStyle="RightDetail" title="Version" detail={`${versionMoniker}${versionString}`} /> <CellToggle label="Share Analytics" // These are both inverted because the toggle makes more sense as // optout/optin, but the code works better as optin/optout. value={!this.props.feedbackDisabled} onChange={val => this.props.onChangeFeedbackToggle(!val)} /> </Section> {process.env.NODE_ENV === 'development' ? <Section header="UTILITIES"> <PushButtonCell title="Snapshots" onPress={this.onSnapshotsButton} /> </Section> : null} </View> ) } } function mapStateToProps(state) { return { feedbackDisabled: state.settings.feedbackDisabled, } } function mapDispatchToProps(dispatch) { return { onChangeFeedbackToggle: s => dispatch(setFeedbackStatus(s)), } } export default connect(mapStateToProps, mapDispatchToProps)(OddsAndEndsSection)
JavaScript
0.998936
@@ -1576,16 +1576,17 @@ source%7D%5D + %60 : ''%0A%0A
a806f485caa6be7c6d940aa4b8dc7e0f152084dc
update DropdownSelect examples
examples/containers/app/modules/fields/DropdownSelectExamples.js
examples/containers/app/modules/fields/DropdownSelectExamples.js
import React, {Component} from 'react'; import DropdownSelect from 'src/DropdownSelect'; import Widget from 'src/Widget'; import WidgetHeader from 'src/WidgetHeader'; import Theme from 'src/Theme'; import PropTypeDescTable from '../PropTypeDescTable'; import DropdownSelectDoc from 'assets/propTypes/DropdownSelect.json'; import 'sass/containers/app/modules/fields/DropdownSelectExamples.scss'; export default class DropdownSelectExamples extends Component { constructor(props) { super(props); this.data = ['test0', 'test1', { text: 'test2', value: 2, desc: 'Here is test2.', onTouchTap() { console.log('test2 selected!'); } }, 'test3', 'test4', 'test5', { text: 'test6', value: 6, desc: 'Here is test6.', onTouchTap() { console.log('test6 selected!'); } }, 'test7', 'test8', 'test9']; this.groupedData = [{ name: 'socialNetwork', children: [{ iconCls: 'fa fa-facebook', text: 'Facebook', desc: 'Here is a Facebook Desc.' }, { iconCls: 'fa fa-twitter', text: 'Twitter', desc: 'Here is a Twitter Desc.' }, { iconCls: 'fa fa-google-plus', text: 'Google+', desc: 'Here is a Google+ Desc.' }] }, { name: 'device', children: [{ iconCls: 'fa fa-android', text: 'Android', desc: 'Here is a Android Desc.' }, { iconCls: 'fa fa-apple', text: 'Apple', desc: 'Here is a Apple Desc.' }, { iconCls: 'fa fa-windows', text: 'Windows', desc: 'Here is a Windows Desc.' }] }]; this.onChange = this::this.onChange; } onChange(value) { console.log(value); } render() { return ( <div className="example drop-down-select-examples"> <h2 className="example-title">Dropdown Select</h2> <p> <span>Dropdown Select</span> use to store operating elements. Click on the contact and a drop-down menu will appear. You can select from the list and execute the appropriate command. </p> <h2 className="example-title">Examples</h2> <Widget> <WidgetHeader className="example-header" title="Basic"/> <div className="widget-content"> <div className="example-content"> <div className="examples-wrapper"> <p><code>Dropdown Select</code> simple example.</p> <div className="field-group"> <DropdownSelect data={this.data} onChange={this.onChange}/> </div> </div> </div> </div> </Widget> <Widget> <WidgetHeader className="example-header" title="Self defined theme"/> <div className="widget-content"> <div className="example-content"> <div className="examples-wrapper"> <p>Set the <code>autoClose</code> property to false,the select list will not close when choose one item.</p> <div className="field-group"> <DropdownSelect theme={Theme.PRIMARY} data={this.data} onChange={this.onChange}/> </div> </div> </div> </div> </Widget> <Widget> <WidgetHeader className="example-header" title="With Filter"/> <div className="widget-content"> <div className="example-content"> <div className="examples-wrapper"> <div className="field-group"> <p>Set the <code>filter</code> property to true,the DropdownSelect will have user search input.</p> <DropdownSelect data={this.data} useFilter={true} useSelectAll={true} mode={DropdownSelect.Mode.CHECKBOX} autoClose={false} onChange={this.onChange}/> </div> </div> </div> </div> </Widget> <Widget> <WidgetHeader className="example-header" title="With multi"/> <div className="widget-content"> <div className="example-content"> <div className="examples-wrapper"> <div className="field-group"> <p> Set the <code>mod</code> property to <code>DropdownSelect.Mode.CHECKBOX</code>, the DropdownSelect can be Multiselect. </p> <DropdownSelect data={this.data} autoClose={false} mode={DropdownSelect.Mode.CHECKBOX} onChange={this.onChange}/> </div> </div> </div> </div> </Widget> <Widget> <WidgetHeader className="example-header" title="With isGrouped"/> <div className="widget-content"> <div className="example-content"> <div className="examples-wrapper"> <div className="field-group"> <p>Set the <code>isGrouped</code> property to true,the DropdownSelect will have group. </p> <DropdownSelect style={{width: 240}} popupStyle={{maxHeight: 300}} data={this.groupedData} autoClose={false} multi={true} isGrouped={true} rightIconCls="fa fa-caret-down" onChange={this.onChange}/> </div> </div> </div> </div> </Widget> <h2 className="example-title">Properties</h2> <PropTypeDescTable data={DropdownSelectDoc}/> </div> ); } };
JavaScript
0
@@ -1100,32 +1100,67 @@ a fa-facebook',%0A + value: 'Facebook',%0A @@ -1169,32 +1169,32 @@ xt: 'Facebook',%0A - @@ -1277,32 +1277,66 @@ fa fa-twitter',%0A + value: 'Twitter',%0A @@ -1459,24 +1459,58 @@ ogle-plus',%0A + value: 'Google+',%0A @@ -1693,32 +1693,66 @@ fa fa-android',%0A + value: 'Android',%0A @@ -1869,24 +1869,56 @@ fa-apple',%0A + value: 'Apple',%0A @@ -1991,32 +1991,32 @@ %7D, %7B%0A - @@ -2033,32 +2033,66 @@ fa fa-windows',%0A + value: 'Windows',%0A
a8d50835b910118301f7835dcdf9435223315d8b
Move to sign with Developer ID key :apple:
build/Gruntfile.js
build/Gruntfile.js
var path = require('path'); module.exports = function(grunt) { // Load the plugins... grunt.loadNpmTasks('grunt-electron'); // Load all platform specific tasks: switch (process.platform) { case 'win32': grunt.loadNpmTasks('grunt-electron-installer'); break; case 'darwin': grunt.loadNpmTasks('grunt-appdmg'); break; default: grunt.loadNpmTasks('grunt-electron-installer-debian'); grunt.loadNpmTasks('grunt-electron-installer-redhat'); break; } // Load the tasks in '/tasks' grunt.loadTasks('tasks'); // Set all subsequent paths to the relative to the root of the repo grunt.file.setBase(path.resolve('..')); var appInfo = grunt.file.readJSON('package.json'); var version = appInfo.version; var electronVer = appInfo.electronVersion; // Electron build version var numericVersion = appInfo.version.split('-')[0]; var buildIgnore = [ 'build/dist', 'build/node_modules', 'build/tasks', 'build/package.json', 'build/Gruntfile.js', 'node_modules/electron-prebuilt', 'node_modules/grunt*' ].join('|'); // Project configuration. grunt.initConfig({ name: appInfo.name, pkg: appInfo, electron: { macbuild: { options: { name: appInfo.name, dir: './', out: 'build/dist', icon: 'resources/darwin/app.icns', version: electronVer, platform: 'darwin', arch: 'x64', ignore: buildIgnore, 'app-version': version, overwrite: true, prune: true, 'osx-sign': { identity: '3rd Party Mac Developer Application: StoreBound LLC (AEJ8NZZ3TC)' }, 'app-bundle-id': 'pancakepainter-main', 'helper-bundle-id': 'pancakepainter-helper' } }, winbuild: { options: { name: appInfo.name, dir: './', out: 'build/dist', icon: 'resources/win32/app.ico', version: electronVer, platform: 'win32', arch: 'x64,ia32', ignore: buildIgnore, 'app-version': version, overwrite: true, prune: true, 'version-string': { CompanyName: 'PancakeBot Inc.', LegalCopyright: appInfo.copyright, FileDescription: appInfo.name, OriginalFilename: appInfo.name + '.exe', FileVersion: electronVer, ProductVersion: version, ProductName: appInfo.name, InternalName: appInfo.name } } }, linbuild: { options: { name: appInfo.name, dir: './', out: 'build/dist', icon: 'resources/app.png', ignore: buildIgnore, version: appInfo.electronVersion, platform: 'linux', arch: 'x64', 'app-version': appInfo.version, overwrite: true, prune: true } }, }, appdmg: { options: { basepath: 'build/dist/' + appInfo.name + '-darwin-x64', title: 'Install ' + appInfo.releaseInfo.appName, icon: '../../../resources/darwin/app.icns', background: '../../../resources/darwin/dmg_back.png', 'icon-size': 80, contents: [ {x: 448, y: 344, type: 'link', path: '/Applications'}, {x: 192, y: 344, type: 'file', path: appInfo.releaseInfo.appName +'.app'} ] }, target: { dest: 'build/dist/' + appInfo.releaseInfo.appName + '_Mac_v' + appInfo.version + '.dmg' } }, 'create-windows-installer': { 64: { iconUrl: appInfo.iconURL, appDirectory: 'build/dist/PancakePainter-win32-x64', outputDirectory: 'build/dist/winstall64/', loadingGif: 'resources/win32/install_anim.gif', version: numericVersion, authors: 'PancakeBot Inc.' }, 32: { iconUrl: appInfo.iconURL, appDirectory: 'build/dist/PancakePainter-win32-ia32', outputDirectory: 'build/dist/winstall32/', loadingGif: 'resources/win32/install_anim.gif', version: numericVersion, authors: 'PancakeBot Inc.' } }, 'electron-installer-debian': { options: { name: appInfo.name, productName: appInfo.releaseInfo.appName, description: appInfo.description, productDescription: appInfo.releaseInfo.description, genericName: 'Robot Controller', section: 'graphics', priority: 'optional', version: numericVersion, revision: appInfo.version.split('-')[1], categories: appInfo.releaseInfo.categories, lintianOverrides: [ 'changelog-file-missing-in-native-package', 'executable-not-elf-or-script', 'extra-license-file' ] }, linux64: { options: { icon: 'resources/app.png', arch: 'amd64' }, src: 'build/dist/' + appInfo.name + '-linux-x64', dest: 'build/dist/' } }, 'electron-installer-redhat': { options: { name: appInfo.name, productName: appInfo.releaseInfo.appName, description: appInfo.description, productDescription: appInfo.releaseInfo.description, genericName: 'Robot Controller', categories: appInfo.releaseInfo.categories, version: numericVersion, revision: appInfo.version.split('-')[1], }, linux64: { options: { arch: 'x86_64', icon: 'resources/app.png', }, src: 'build/dist/' + appInfo.name + '-linux-x64', dest: 'build/dist/' } }, }); // Default task(s). grunt.registerTask('default', ['build']); };
JavaScript
0
@@ -1629,22 +1629,8 @@ y: ' -3rd Party Mac Deve @@ -1635,16 +1635,19 @@ veloper +ID Applicat
d678c718ca9993cfb82d9d088b739afcd746a17a
Add custom to restify-bunyan-logger
lib/index.js
lib/index.js
'use strict'; var restify = require('restify'); var autoload = require('auto-load'); var session = require('client-sessions'); var async = require('async'); var http = require('http'); var https = require('https'); var lru = require('lru-cache'); var yaqs = require('yaqs'); var Logger = require("bunyan"); var restifyBunyanLogger = require('restify-bunyan-logger'); var Token = require('./models/token.js'); var TempToken = require('./models/temp-token.js'); var util = require('./util.js'); var usersQueue = require('./queues/users-queue.js'); // Create bunyan logger module.exports.log = new Logger.createLogger({ name: process.env.APP_NAME || 'provider', }); /** * Simple wrapper around the token model. * Only one token should match. * * retrieveData({accessToken: ...}) => data for this access token * retrieveData({'data.grant': ...}) => data with this value of grant. */ module.exports.retrieveData = function(hash, cb) { Token.findOne(hash, function(err, token) { if(!token) { return cb(new Error("no data matches")); } cb(err, token.data); }); }; /** * Create a new provider server. * This server will use `config.task_generator` as its main function, to turn a file into metadata. * * @param {Object} config Configuration hash. * Mandatory: * task_generator, to retrieve a list of tasks (a task is "a document to upload"). * task_handler, the uploading function. * Optional: * concurrency, max number of simultaneous calls to your task_handler function (default is 1) */ module.exports.createServer = function createServer(connectFunctions, workersFile, updateFile, config) { ['appId', 'appSecret', 'providerUrl'].forEach(function(name) { if(!config[name]) { console.warn('Error: Missing config.' + name + ' not found'); process.exit(1); } }); util.logError.config = config; if(config.opbeat && config.opbeat.secretToken) { var opbeat = require('opbeat'); util.logError.opbeat = opbeat(config.opbeat); } // Connect mongo util.connectMongo(config.mongoUrl); // Load endpoints generators var handlers = autoload(__dirname + "/handlers"); var middlewares = autoload(__dirname + "/middlewares"); http.globalAgent.maxSockets = config.maxSockets || 30; https.globalAgent.maxSockets = http.globalAgent.maxSockets; // Create server var server = restify.createServer({ log: module.exports.log }); server.on('after', restifyBunyanLogger()); server.use(restify.requestLogger()); server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(session({ cookieName: 'ANYFETCH_SESSION', secret: config.appSecret })); config.redisUrl = config.redisUrl || process.env.REDIS_URL || "redis://localhost"; if(module.exports.yaqsClient) { server.yaqsClient = module.exports.yaqsClient; } else { server.yaqsClient = yaqs({ prefix: config.appName || config.providerUrl, redis: config.redisUrl }); module.exports.yaqsClient = server.yaqsClient; } server.usersQueue = server.yaqsClient.createQueue('anyfetch-provider-users', { concurrency: config.usersConcurrency || 1, defaultTimeout: -1 }); server.childs = {}; function sigtermYaqs() { async.waterfall([ function killProcesses(cb) { async.each(Object.keys(server.childs), function(anyfetchToken, cb) { server.childs[anyfetchToken].kill(cb); }, cb); }, function stopAllQueues(cb) { server.yaqsClient.stopAllQueues(cb); }, function registerUsers(cb) { async.each(Object.keys(server.childs), function(anyfetchToken, cb) { server.usersQueue.createJob({ anyfetchToken: anyfetchToken, anyfetchApiUrl: server.childs[anyfetchToken].anyfetchApiUrl }).save(cb); }, cb); } ], function(err) { module.exports.log.info('YAQS has stopped.'); util.logError(err); process.exit(0); }); } process.once('SIGTERM', sigtermYaqs); // One element have a length of '1', so we can stock 50 elements server.tokenCache = lru({ max: 50, length: function() { return 1; }, maxAge: 60 * 60 * 1000 }); server.usersQueue .on('error', util.logError) .setWorker(usersQueue(server, config, workersFile, updateFile)) .start(); // Load routes and generate endpoints using closures server.get('/', handlers.index.get); server.get('/init/connect', handlers.init.connect.getGenerator(connectFunctions.redirectToService, config)); server.get('/init/callback', handlers.init.callback.getGenerator(connectFunctions.retrieveTokens, config)); server.post('/update', middlewares.token, handlers.update.postGenerator(server.yaqsClient, server.usersQueue, config)); server.post('/update/:identifier', middlewares.token, handlers.update.postGenerator(server.yaqsClient, server.usersQueue, config)); server.get('/status', handlers.status.get); server.post('/token', handlers.token.index.post); server.del('/token', middlewares.token, handlers.token.index.del); server.del('/token/reset', middlewares.token, handlers.token.reset.del); server.on('uncaughtException', function(req, res, route, err) { util.logError(err, req); if(!res._headerSent) { res.send(new restify.InternalServerError(err, err.message || 'unexpected error')); return true; } return false; }); module.exports.currentServer = server; // Expose the server return server; }; module.exports.debug = { cleanTokens: function(cb) { util.connectMongo(); async.parallel([ function(cb) { Token.remove({}, cb); }, function(cb) { TempToken.remove({}, cb); } ], cb); }, createToken: function(hash, cb) { util.connectMongo(); var token = new Token(hash); token.save(cb); }, createTempToken: function(hash, cb) { util.connectMongo(); var tempToken = new TempToken(hash); tempToken.save(cb); } }; module.exports.CancelError = require('./cancel-error.js'); module.exports.util = util;
JavaScript
0
@@ -2459,24 +2459,166 @@ unyanLogger( +%7B%0A custom: function(req, res, route, err, log) %7B%0A log.req.user = req.token ? req.token.accountName : null;%0A return log;%0A %7D%0A %7D ));%0A%0A serve
3afb0bb4d4ad0fef414239090a5cd72c4a42cf87
enforce Node.js version
Jakefile.js
Jakefile.js
/*global desc, task, jake, fail, complete */ (function() { "use strict"; desc("Build and test"); task("default", ["lint", "test"]); desc("Lint everything"); task("lint", [], function() { var lint = require("./build/lint/lint_runner.js"); var files = new jake.FileList(); files.include("**/*.js"); files.include("src/*/*.js"); // Why do I need this and he doesn't? files.exclude("node_modules"); var options = nodeLintOptions(); var passed = lint.validateFileList(files.toArray(), options, {}); if (!passed) fail("Lint failed"); }); desc("Test everything"); task("test", [], function() { var reporter = require("nodeunit").reporters["default"]; reporter.run(['src/server/_server_test.js'], null, function(failures) { if (failures) fail("Tests failed"); complete(); } ); }, { async: true } ); desc("Integrate"); task("integrate", ["default"], function() { console.log("1. Make sure 'git status' is clean."); console.log("2. Build on the integration box."); console.log(" a. Walk over to integration box."); console.log(" b. 'git pull'"); console.log(" c. 'jake'"); console.log(" d. 'If jake fails, stop! Try again after fixing the issue'"); console.log("3. 'git checkout integration'"); console.log("4. 'git merge master --no-ff --log"); console.log("5. 'git checkout master'"); }); function nodeLintOptions() { return { bitwise:true, curly:false, eqeqeq:true, forin:true, immed:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, regexp:true, undef:true, strict:true, trailing:true, node:true }; } }());
JavaScript
0.000048
@@ -135,24 +135,25 @@ %22test%22%5D);%0A%0A +%0A desc(%22Li @@ -183,24 +183,30 @@ sk(%22lint%22, %5B +%22node%22 %5D, function( @@ -675,16 +675,22 @@ test%22, %5B +%22node%22 %5D, funct @@ -1556,24 +1556,24 @@ master'%22);%0A - %7D);%0A%0A @@ -1565,24 +1565,737 @@ );%0A %7D);%0A%0A +// desc(%22Ensure correct version of Node is present%22);%0A task(%22node%22, %5B%5D, function() %7B%0A var desiredNodeVersion = %22v0.8.4%5Cn%22; // Note appended newline%0A var command = %22node --version%22;%0A console.log(%22%3E %22 + command);%0A%0A var out = %22%22;%0A var process = jake.createExec(command, %7B printStdout:true, printStderr: true %7D );%0A process.on(%22stdout%22, function(chunk) %7B%0A out += chunk;%0A %7D);%0A process.on(%22cmdEnd%22, function() %7B%0A if (out !== desiredNodeVersion) fail(%22Incorrect node version. Expected %22 + desiredNodeVersion);%0A console.log(%22Stdout: %22 + out);%0A complete();%0A %7D);%0A process.run();%0A %7D, %7B async: true %7D);%0A%0A function
b6f7c4401ef7c30b415415771ca81f2704f46e06
Remove unnecessary eslint disable
src/components/common/errorMessage/ErrorMessage.js
src/components/common/errorMessage/ErrorMessage.js
/* eslint-disable react/no-array-index-key */ import React from 'react'; import { PropTypes as Types } from 'prop-types'; import { FormattedMessage } from 'react-intl'; import './ErrorMessage.scss'; const noop = () => null; const ErrorMessage = ({ errors, onCancel, overlayed }) => { const content = ( <div className="card text-center p-4 tv-modal__content"> <div className="p-4"> <div> <p> <b> <FormattedMessage id="error.messages.intro" /> </b> </p> {errors.errors && errors.errors.map((error, index) => ( <p key={index}> <FormattedMessage id={error.code} /> {error.message} </p> ))} </div> {onCancel !== noop ? ( <button type="button" className="btn btn-secondary mt-4" onClick={onCancel}> <FormattedMessage id="error.message.close" /> </button> ) : ( '' )} </div> </div> ); if (overlayed) { return ( <div className="tv-modal"> <div className="container"> <div className="row mt-4 pt-4 justify-content-center">{content}</div> </div> </div> ); } return <div className="row mt-4 pt-4 justify-content-center">{content}</div>; }; ErrorMessage.defaultProps = { errors: { errors: [] }, onCancel: noop, overlayed: false, }; ErrorMessage.propTypes = { errors: Types.shape({ errors: Types.arrayOf(Types.shape({})), }), onCancel: Types.func, overlayed: Types.bool, }; export function getGlobalErrorCode(errors) { const globalErrorCode = (((errors || {}).errors || []).find((error) => !error.path) || {}).code; const firstLocalErrorCode = (((errors || {}).errors || [])[0] || {}).code; return globalErrorCode || firstLocalErrorCode; } export default ErrorMessage;
JavaScript
0.000004
@@ -1,51 +1,4 @@ -/* eslint-disable react/no-array-index-key */%0A%0A impo
264500ae7c7fea37a52155e0e276a99470d957ac
fix bug on blurring <Editor /> (#952)
lib/Editor/Editor.js
lib/Editor/Editor.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import className from 'classnames'; import ReactQuill from 'react-quill'; import merge from 'lodash/merge'; // eslint-disable-next-line import/no-webpack-loader-syntax import '!style-loader!css-loader!react-quill/dist/quill.snow.css'; import formField from '../FormField'; import css from './Editor.css'; import omitProps from '../../util/omitProps'; import sharedInputStylesHelper from '../sharedStyles/sharedInputStylesHelper'; import formStyles from '../sharedStyles/form.css'; import Label from '../Label'; class Editor extends Component { static propTypes = { className: PropTypes.string, defaultValue: PropTypes.string, dirty: PropTypes.bool, disableEditorTab: PropTypes.bool, editorClassName: PropTypes.string, editorRef: PropTypes.oneOfType([ PropTypes.func, PropTypes.object ]), error: PropTypes.node, formats: PropTypes.arrayOf(PropTypes.string), id: PropTypes.string, label: PropTypes.node, modules: PropTypes.object, onBlur: PropTypes.func, onChange: PropTypes.func, onFocus: PropTypes.func, onKeyDown: PropTypes.func, onKeyPress: PropTypes.func, onKeyUp: PropTypes.func, placeholder: PropTypes.string, preserveWhitespace: PropTypes.bool, readOnly: PropTypes.bool, required: PropTypes.bool, style: PropTypes.object, tabIndex: PropTypes.number, valid: PropTypes.bool, validationEnabled: PropTypes.bool, validStylesEnabled: PropTypes.bool, value: PropTypes.string, warning: PropTypes.node, }; static defaultProps = { validationEnabled: true, validStylesEnabled: false, required: false, readOnly: false, disableEditorTab: true, modules: {}, }; getRootStyle() { return className( formStyles.inputGroup, this.props.className, ); } getEditorStyle() { return className( sharedInputStylesHelper(this.props), css.editor, this.props.editorClassName, ); } handleTab = () => true; getModules() { if (this.props.disableEditorTab) { const tabBinding = { keyboard: { bindings: { tab: { key: 9, handler: () => true, } } } }; const modulesWithTabBindings = merge({}, this.props.modules, tabBinding); return modulesWithTabBindings; } return this.props.modules; } render() { const { error, editorRef, label, readOnly, required, warning, formats, ...restProps } = this.props; const component = ( <ReactQuill className={this.getEditorStyle()} modules={this.getModules()} formats={formats} ref={editorRef} readOnly={readOnly} theme="snow" {...omitProps(restProps, [ 'validationEnabled', 'validStylesEnabled', 'modules', ])} /> ); const warningElement = warning ? <div className={formStyles.feedbackWarning}>{warning}</div> : null; const errorElement = error ? <div className={formStyles.feedbackError}>{error}</div> : null; const labelElement = label ? <Label htmlFor={this.props.id} required={required} readOnly={readOnly} > {label} </Label> : null; return ( <div className={this.getRootStyle()}> {labelElement} {component} <div role="alert"> {warningElement} {errorElement} </div> </div> ); } } export default formField( Editor, ({ meta }) => ({ dirty: meta.dirty, error: (meta.touched && meta.error ? meta.error : ''), valid: meta.valid, warning: (meta.touched && meta.warning ? meta.warning : ''), }) );
JavaScript
0
@@ -1795,309 +1795,47 @@ %0A%0A -getRootStyle() %7B%0A return className(%0A formStyles.inputGroup,%0A this.props.className,%0A );%0A %7D%0A%0A getEditorStyle() %7B%0A return className(%0A sharedInputStylesHelper(this.props),%0A css.editor,%0A this.props.editorClassName,%0A );%0A %7D%0A%0A handleTab = () =%3E true;%0A%0A getModules() %7B +constructor(props) %7B%0A super(props);%0A %0A @@ -1839,21 +1839,16 @@ if ( -this. props.di @@ -2065,36 +2065,20 @@ -const +this. modules -WithTabBindings = m @@ -2123,82 +2123,321 @@ g);%0A -%0A return modulesWithTabBindings;%0A %7D%0A%0A return this.props.modules + %7D else %7B%0A this.modules = props.modules;%0A %7D%0A %7D%0A%0A getRootStyle() %7B%0A return className(%0A formStyles.inputGroup,%0A this.props.className,%0A );%0A %7D%0A%0A getEditorStyle() %7B%0A return className(%0A sharedInputStylesHelper(this.props),%0A css.editor,%0A this.props.editorClassName,%0A ) ;%0A @@ -2719,20 +2719,15 @@ his. -getM +m odules -() %7D%0A
4f7d036fe902962c53ea6a5aeb2ee3ed8ef214aa
Fix issue with invalid this context for graceful restart functions
bin/index.js
bin/index.js
var fs = require('fs'), path = require('path'), inherit = require('inherit'), fsExtra = require('fs-extra'), bseAdmin = require('bse-admin'), Tripwire = require('memory-tripwire'), logger = require('bem-site-logger').createLogger(module), SnapshotMaster = require('../lib/master/index'), DataBuilder = inherit(SnapshotMaster, { _bseConfig: undefined, MAX_CALLS_FOR_NEW_EXECUTE_ITERATION: 20, MAX_LAUNCH_COUNT: 5, callsForNewExecuteIteration: 0, launchCount: 0, loadConfig: function (callback) { var _this = this; this._logger.info('Load configuration file for bse-admin tool'); fs.readFile('./config/_bse.json', { encoding: 'utf-8' }, function (error, config) { if (error) { _this.logger.error('Can\'t read configuration file for bse-admin tool'); throw error; } _this._bseConfig = JSON.parse(config); callback && callback(); }); }, buildTarget: function () { return bseAdmin.syncNodes(this._bseConfig); }, execute: function () { /** * 1-я функция запланированного перезапуска сервиса. * Происходит после завершения MAX_LAUNCH_COUNT сборки. * Нужна для предотвращения случайного перезапуска сервиса в случае достижения лимита потребляемой памяти */ function gracefulRestart1() { if (this.launchCount === this.MAX_LAUNCH_COUNT) { logger.warn('Planned restart of service on reaching maximum launch count limit'); process.exit(1); } else { this.launchCount++; } } /** * 2-я функция запланированного перезапуска сервиса. * Нужна для предотвращения "заклинивания" сборки. В случае когда сборка зависает * и не заканчивается успешно или с ошибокой, попытки повторной сборки будут вызываться * до тех пор пока их количество не превысит MAX_CALLS_FOR_NEW_EXECUTE_ITERATION * после чего процесс будет перезапущен */ function gracefulRestart2() { if (this.callsForNewExecuteIteration === this.MAX_CALLS_FOR_NEW_EXECUTE_ITERATION) { logger.warn('Planned restart of service on reaching maximum calls for new iteration limit'); process.exit(1); } else { this.callsForNewExecuteIteration++; } } if (this['isActive']()) { this._logger.warn('Another execute process is being performed now'); gracefulRestart2(); return; } this['setActive'](); return this.__base() .then(function () { this.callsForNewExecuteIteration = 0; this['setIdle'](); gracefulRestart1(); }, this) .fail(function () { this.callsForNewExecuteIteration = 0; this['setIdle'](); gracefulRestart1(); }, this); } }), tripWireConfig = fsExtra.readJSONFileSync('./config/_tripwire.json'), appConfig = fsExtra.readJSONFileSync('./config/_config.json'), tripwire = new Tripwire(tripWireConfig), builder = new DataBuilder(appConfig); tripwire.start(); tripwire.on('bomb', function () { logger.warn('||| --- MEMORY LIMIT EXCEED. PROCESS WILL BE RESTARTED --- ||| '); }); builder.loadConfig(function () { builder.start(); });
JavaScript
0.000002
@@ -21,36 +21,8 @@ '),%0A - path = require('path'),%0A @@ -47,24 +47,24 @@ 'inherit'),%0A + fsExtra @@ -1177,17 +1177,16 @@ on () %7B%0A -%0A @@ -2803,17 +2803,27 @@ Restart2 -( +.apply(this );%0A @@ -3082,33 +3082,43 @@ gracefulRestart1 -( +.apply(this );%0A @@ -3298,17 +3298,27 @@ Restart1 -( +.apply(this );%0A
172e5eae5ebe261fa6fada39e8d211fa3a413663
Disable links prefetch
data/prefs.js
data/prefs.js
// Disable onload popups pref("dom.disable_open_during_load", true); // Disable usless security warnings pref("security.warn_entering_secure", false); pref("security.warn_entering_secure.show_once", true); pref("security.warn_leaving_secure", false); pref("security.warn_leaving_secure.show_once", false); pref("security.warn_submit_insecure", false); pref("security.warn_submit_insecure.show_once", false); pref("security.warn_viewing_mixed", true); pref("security.warn_viewing_mixed.show_once", false); pref("security.warn_entering_weak", true); pref("security.warn_entering_weak.show_once", false); // Set some style properties to not follow our dark gtk theme pref("ui.-moz-field", "#FFFFFF"); pref("ui.-moz-fieldtext", "#000000"); pref("ui.buttonface", "#D3D3DD"); pref("ui.buttontext", "#000000"); // Fonts pref("font.size.unit", "pt"); pref("font.default.ar", "sans-serif"); pref("font.size.variable.ar", 12); pref("font.size.fixed.ar", 9); pref("font.default.el", "serif"); pref("font.size.variable.el", 12); pref("font.size.fixed.el", 9); pref("font.default.he", "sans-serif"); pref("font.size.variable.he", 12); pref("font.size.fixed.he", 9); pref("font.default.ja", "sans-serif"); pref("font.size.variable.ja", 12); pref("font.size.fixed.ja", 12); pref("font.default.ko", "sans-serif"); pref("font.size.variable.ko", 12); pref("font.size.fixed.ko", 12); pref("font.default.th", "serif"); pref("font.size.variable.th", 12); pref("font.size.fixed.th", 9); pref("font.default.tr", "serif"); pref("font.size.variable.tr", 12); pref("font.size.fixed.tr", 9); pref("font.default.x-baltic", "serif"); pref("font.size.variable.x-baltic", 12); pref("font.size.fixed.x-baltic", 9); pref("font.default.x-central-euro", "serif"); pref("font.size.variable.x-central-euro", 12); pref("font.size.fixed.x-central-euro", 9); pref("font.default.x-cyrillic", "serif"); pref("font.size.variable.x-cyrillic", 12); pref("font.size.fixed.x-cyrillic", 9); pref("font.default.x-unicode", "serif"); pref("font.size.variable.x-unicode", 12); pref("font.size.fixed.x-unicode", 9); pref("font.default.x-western", "serif"); pref("font.size.variable.x-western", 12); pref("font.size.fixed.x-western", 9); pref("font.default.zh-CN", "sans-serif"); pref("font.size.variable.zh-CN", 12); pref("font.size.fixed.zh-CN", 12); pref("font.default.zh-TW", "sans-serif"); pref("font.size.variable.zh-TW", 12); pref("font.size.fixed.zh-TW", 12); pref("font.default.zh-HK", "sans-serif"); pref("font.size.variable.zh-HK", 12); pref("font.size.fixed.zh-HK", 12); // Enable error pages (xulrunner is missing this pref) pref("browser.xul.error_pages.enabled", true);
JavaScript
0
@@ -1,16 +1,86 @@ +// Disable links prefetch%0Auser_pref(%22network.prefetch-next%22, false);%0A%0A // Disable onloa
06709391d49045249356f16fdcb8da32420fee6d
Test size report
rules/no-only-tests.js
rules/no-only-tests.js
/** * @fileoverview Rule to flag use of .only in tests, preventing focused tests being committed accidentally * @author Levi Buzolic */ 'use strict'; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ const BLOCK_DEFAULTS = ['describe', 'it', 'context', 'test', 'tape', 'fixture', 'serial']; const FOCUS_DEFAULTS = ['only']; module.exports = { meta: { docs: { description: 'disallow .only blocks in tests', category: 'Possible Errors', recommended: true, url: 'https://github.com/levibuzolic/eslint-plugin-no-only-tests', }, fixable: true, schema: [ { type: 'object', properties: { block: { type: 'array', items: { type: 'string', }, uniqueItems: true, }, focus: { type: 'array', items: { type: 'string', }, uniqueItems: true, }, fix: { type: 'boolean', }, }, additionalProperties: false, }, ], }, create(context) { var block = (context.options[0] || {}).block || BLOCK_DEFAULTS; var focus = (context.options[0] || {}).focus || FOCUS_DEFAULTS; var fix = !!(context.options[0] || {}).fix; return { Identifier(node) { var parentObject = node.parent && node.parent.object; if (parentObject == null) return; if (focus.indexOf(node.name) === -1) return; var callPath = getCallPath(node.parent).join('.'); // comparison guarantees that matching is done with the beginning of call path if (block.find(b => callPath.split(b)[0] === '')) { context.report({ node, message: callPath + ' not permitted', fix: fix ? fixer => fixer.removeRange([node.range[0] - 1, node.range[1]]) : undefined, }); } }, }; }, }; function getCallPath(node, path = []) { if (node) { const nodeName = node.name || (node.property && node.property.name); if (node.object) { return getCallPath(node.object, [nodeName, ...path]); } if (node.callee) { return getCallPath(node.callee, path); } return [nodeName, ...path]; } return path; }
JavaScript
0
@@ -1248,17 +1248,18 @@ var -block +options = -( cont @@ -1278,17 +1278,41 @@ 0%5D %7C%7C %7B%7D -) +;%0A var block = options .block %7C @@ -1349,34 +1349,15 @@ s = -(context.options%5B0%5D %7C%7C %7B%7D) +options .foc @@ -1398,34 +1398,15 @@ = !! -(context.options%5B0%5D %7C%7C %7B%7D) +options .fix @@ -2201,24 +2201,16 @@ .object) - %7B%0A return @@ -2256,22 +2256,16 @@ path%5D);%0A - %7D%0A if ( @@ -2276,24 +2276,16 @@ .callee) - %7B%0A return @@ -2316,22 +2316,16 @@ path);%0A - %7D%0A retu
6944b842e9dc0759c6168baf01e0f06d911b4189
Use gulp default task to build all
gulpfile.js
gulpfile.js
var path = require('path'); var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var bower_components = require('main-bower-files')(); var gopath = function() { var gpm_dir = __dirname + path.sep + '.godeps'; if (process.env.GOPATH.split(path.delimiter).indexOf(gpm_dir) != -1) { return process.env.GOPATH; } return gpm_dir + path.delimiter + process.env.GOPATH; } gulp.task('css', function() { return gulp.src(bower_components) .pipe($.filter('**/*.css')) .pipe($.concat('main.css')) .pipe($.minifyCss()) .pipe(gulp.dest('./public')); }); gulp.task('js', function() { return gulp.src(bower_components) .pipe($.filter('**/*.js')) .pipe($.concat('main.js')) .pipe($.uglify()) .pipe(gulp.dest('./public')); }); gulp.task('go', function() { var newenv = process.env; newenv.GOPATH = gopath(); return $.run('go build -o goose', {env: newenv}).exec(); }); gulp.task('default', function() { // place code for your default task here });
JavaScript
0
@@ -944,64 +944,41 @@ t', -function() %7B%0A // place code for your default task here%0A +%5B'go', 'css', 'js'%5D, function() %7B %7D);%0A
8ffc112cf73e948d5819d4f673be61751bb91554
fix intl test
packages/app-extensions/src/intl/intl.spec.js
packages/app-extensions/src/intl/intl.spec.js
import fetchMock from 'fetch-mock' import cache from '../cache' import {setLocale, getUserLocale, loadTextResources} from './intl' describe('tocco-util', () => { describe('intl', () => { beforeEach(() => { fetchMock.reset() fetchMock.restore() cache.clearAll() }) describe('setLocale', () => { test('call dispatch on store', done => { const body = { test: 'test' } fetchMock.get('*', body) const dispatchSpy = sinon.spy() const store = { dispatch: dispatchSpy } setLocale(store, ['merge'], 'de_CH').then(() => { expect(dispatchSpy).to.have.calledWith(sinon.match({ type: '@@intl/UPDATE' })) expect(fetchMock.called()).to.be.true done() }) }) }) describe('getUserLocale', () => { test('should load user locale with fetch', async() => { const usernameRequestBody = { locale: 'de_CH' } fetchMock.get('/nice2/username', usernameRequestBody) const result = await getUserLocale() expect(result).to.eql('de_CH') }) test('should read from cache after first fetch', async() => { const cachedLocale = 'fr' cache.addLongTerm('user', 'locale', cachedLocale) const result = await getUserLocale() expect(result).to.eql(cachedLocale) }) }) describe('loadTextResources', () => { test('should fetch text resources and cache them individually', async() => { const mergeMessages = { 'client.merge': 'test' } const componentsMessages = { 'client.components': 'test2' } const actionTitles = { 'client.actions.delete.title': 'Löschen', 'client.actions.input-edit.title': 'Noteneingabe' } const textResourceResponse = { ...mergeMessages, ...componentsMessages, ...actionTitles } fetchMock.getOnce( '/nice2/textresource?locale=en-GB&module=(merge|components|actions.[^.]*\\.title)', textResourceResponse ) const resources = await loadTextResources('en-GB', ['merge', 'components', 'actions.[^.]*\\.title']) expect(resources).to.eql(resources) const resources2 = await loadTextResources('en-GB', ['merge', 'components', 'actions.[^.]*\\.title']) expect(resources2).to.eql(resources) expect(cache.getLongTerm('textResource', 'merge')).to.eql(mergeMessages) expect(cache.getLongTerm('textResource', 'components')).to.eql(componentsMessages) expect(cache.getLongTerm('textResource', 'actions.[^.]*\\.title')).to.eql(actionTitles) }) }) }) })
JavaScript
0.000003
@@ -70,19 +70,8 @@ rt %7B -setLocale, getU @@ -98,16 +98,27 @@ esources +, setLocale %7D from ' @@ -2086,15 +2086,14 @@ ule= -( merge -%7C +, comp @@ -2102,9 +2102,9 @@ ents -%7C +, acti @@ -2120,17 +2120,16 @@ %5C%5C.title -) ',%0A
0cf9a7b552a8036158d5b158f875057b9aaf5fc0
Fix last label undefined
client/components/activities/activities.js
client/components/activities/activities.js
const activitiesPerPage = 20; BlazeComponent.extendComponent({ onCreated() { // XXX Should we use ReactiveNumber? this.page = new ReactiveVar(1); this.loadNextPageLocked = false; const sidebar = this.parentComponent(); // XXX for some reason not working sidebar.callFirstWith(null, 'resetNextPeak'); this.autorun(() => { let mode = this.data().mode; const capitalizedMode = Utils.capitalize(mode); let thisId, searchId; if (mode === 'linkedcard' || mode === 'linkedboard') { thisId = Session.get('currentCard'); searchId = Cards.findOne({ _id: thisId }).linkedId; mode = mode.replace('linked', ''); } else { thisId = Session.get(`current${capitalizedMode}`); searchId = thisId; } const limit = this.page.get() * activitiesPerPage; const user = Meteor.user(); const hideSystem = user ? user.hasHiddenSystemMessages() : false; if (searchId === null) return; this.subscribe('activities', mode, searchId, limit, hideSystem, () => { this.loadNextPageLocked = false; // If the sibear peak hasn't increased, that mean that there are no more // activities, and we can stop calling new subscriptions. // XXX This is hacky! We need to know excatly and reactively how many // activities there are, we probably want to denormalize this number // dirrectly into card and board documents. const nextPeakBefore = sidebar.callFirstWith(null, 'getNextPeak'); sidebar.calculateNextPeak(); const nextPeakAfter = sidebar.callFirstWith(null, 'getNextPeak'); if (nextPeakBefore === nextPeakAfter) { sidebar.callFirstWith(null, 'resetNextPeak'); } }); }); }, loadNextPage() { if (this.loadNextPageLocked === false) { this.page.set(this.page.get() + 1); this.loadNextPageLocked = true; } }, checkItem() { const checkItemId = this.currentData().checklistItemId; const checkItem = ChecklistItems.findOne({ _id: checkItemId }); return checkItem.title; }, boardLabel() { return TAPi18n.__('this-board'); }, cardLabel() { return TAPi18n.__('this-card'); }, cardLink() { const card = this.currentData().card(); return ( card && Blaze.toHTML( HTML.A( { href: card.absoluteUrl(), class: 'action-card', }, card.title, ), ) ); }, lastLabel() { const lastLabelId = this.currentData().labelId; if (!lastLabelId) return null; const lastLabel = Boards.findOne(Session.get('currentBoard')).getLabelById( lastLabelId, ); if (lastLabel.name === undefined || lastLabel.name === '') { return lastLabel.color; } else { return lastLabel.name; } }, lastCustomField() { const lastCustomField = CustomFields.findOne( this.currentData().customFieldId, ); if (!lastCustomField) return null; return lastCustomField.name; }, lastCustomFieldValue() { const lastCustomField = CustomFields.findOne( this.currentData().customFieldId, ); if (!lastCustomField) return null; const value = this.currentData().value; if ( lastCustomField.settings.dropdownItems && lastCustomField.settings.dropdownItems.length > 0 ) { const dropDownValue = _.find( lastCustomField.settings.dropdownItems, item => { return item._id === value; }, ); if (dropDownValue) return dropDownValue.name; } return value; }, listLabel() { return this.currentData().list().title; }, sourceLink() { const source = this.currentData().source; if (source) { if (source.url) { return Blaze.toHTML( HTML.A( { href: source.url, }, source.system, ), ); } else { return source.system; } } return null; }, memberLink() { return Blaze.toHTMLWithData(Template.memberName, { user: this.currentData().member(), }); }, attachmentLink() { const attachment = this.currentData().attachment(); // trying to display url before file is stored generates js errors return ( attachment && attachment.url({ download: true }) && Blaze.toHTML( HTML.A( { href: attachment.url({ download: true }), target: '_blank', }, attachment.name(), ), ) ); }, customField() { const customField = this.currentData().customField(); if (!customField) return null; return customField.name; }, events() { return [ { // XXX We should use Popup.afterConfirmation here 'click .js-delete-comment'() { const commentId = this.currentData().commentId; CardComments.remove(commentId); }, 'submit .js-edit-comment'(evt) { evt.preventDefault(); const commentText = this.currentComponent() .getValue() .trim(); const commentId = Template.parentData().commentId; if (commentText) { CardComments.update(commentId, { $set: { text: commentText, }, }); } }, }, ]; }, }).register('activities');
JavaScript
0.999982
@@ -2715,16 +2715,30 @@ ;%0A if + (lastLabel && (lastLa @@ -2785,16 +2785,17 @@ === '') +) %7B%0A
5f75bb268565499f6cc6d543aa0723ce0fd5d912
Update user.js
examples/express/models/user.js
examples/express/models/user.js
'use strict'; var model = require('../../../index').model; var User = model('user', { table: 'user', fields: ['id', 'name', 'email'], primary: ['id'] });
JavaScript
0.000001
@@ -8,16 +8,74 @@ rict';%0A%0A +//change to var model = require('mysql-easy-model').model%0A var mode @@ -209,8 +209,9 @@ id'%5D%0A%7D); +%0A
25f7a21d29f7ea69a6bf35ef4d07d8ebed676386
Use persistent file watches
wrapper.js
wrapper.js
/** * Hooks into `require()` to watch for modifications of required files. * If a modification is detected, the process exits with code `101`. */ var fs = require('fs'); var Path = require('path'); var vm = require('vm'); var spawn = require('child_process').spawn; /** Remove wrapper.js from the argv array */ process.argv.splice(1, 1); /** Resolve the location of the main script relative to cwd */ var main = Path.resolve(process.cwd(), process.argv[1]); /** * Logs a message to the console. The level is displayed in ANSI colors, * either bright red in case of an error or green otherwise. */ function log(msg, level) { var csi = level == 'error' ? '1;31' : '32'; console.log('[\x1B[' + csi + 'm' + level.toUpperCase() + '\x1B[0m] ' + msg); } /** * Displays a desktop notification (see notify.sh) */ function notify(title, msg, level) { level = level || 'info'; log(title || msg, level); spawn(__dirname + '/notify.sh', [ title || 'node.js', msg, __dirname + '/icons/node_' + level + '.png' ]); } /** * Triggers a restart by terminating the process with a special exit code. */ function triggerRestart() { process.removeListener('exit', checkExitCode); process.exit(101); } /** * Sanity check to prevent an infinite loop in case the program * calls `process.exit(101)`. */ function checkExitCode(code) { if (code == 101) { notify('Invalid Exit Code', 'The exit code (101) has been rewritten to prevent an infinite loop.', 'error'); process.reallyExit(1); } } /** * Watches the specified file and triggers a restart upon modification. */ function watch(file) { fs.watchFile(file, {interval: 500, persistent: false}, function(cur, prev) { if (cur && +cur.mtime !== +prev.mtime) { notify('Restarting', file + ' has been modified'); triggerRestart(); } }); } var origs = {}; var hooks = {}; function createHook(ext) { return function(module, filename) { if (module.id == main) { /** If the main module is required conceal the wrapper */ module.id = '.'; module.parent = null; process.mainModule = module; } if (!module.loaded) { watch(module.filename); } /** Invoke the original handler */ origs[ext](module, filename); /** Make sure the module did not hijack the handler */ updateHooks(); }; } /** * (Re-)installs hooks for all registered file extensions. */ function updateHooks() { var handlers = require.extensions; for (var ext in handlers) { // Get or create the hook for the extension var hook = hooks[ext] || (hooks[ext] = createHook(ext)); if (handlers[ext] !== hook) { // Save a reference to the original handler origs[ext] = handlers[ext]; // and replace the handler by our hook handlers[ext] = hook; } } } updateHooks(); /** * Patches the specified method to watch the file at the given argument * index. */ function patch(obj, method, fileArgIndex) { var orig = obj[method]; obj[method] = function() { var file = arguments[fileArgIndex]; if (file) { watch(file); } return orig.apply(this, arguments); }; } /** Patch the vm module to watch files executed via one of these methods: */ patch (vm, 'createScript', 1); patch(vm, 'runInThisContext', 1); patch(vm, 'runInNewContext', 2); patch(vm, 'runInContext', 2); /** * Error handler that displays a notification and logs the stack to stderr. */ process.on('uncaughtException', function(err) { notify(err.name, err.message, 'error'); console.error(err.stack || err); }); process.on('exit', checkExitCode); if (Path.extname(main) == '.coffee') { require('coffee-script'); } require(main);
JavaScript
0.000001
@@ -1672,12 +1672,11 @@ nt: -fals +tru e%7D,
2d4c5a500cc77ad7433cf326a1dda9ec35fb8db1
update story with Marker component
src/components/emptyState/emptyState.stories.js
src/components/emptyState/emptyState.stories.js
import React from 'react'; import { select, text } from '@storybook/addon-knobs'; import { addStoryInGroup, MID_LEVEL_BLOCKS } from '../../../.storybook/utils'; import EmptyState from './EmptyState'; const sizes = ['small', 'medium', 'large']; export default { title: addStoryInGroup(MID_LEVEL_BLOCKS, 'EmptyState'), parameters: { design: { type: 'figma', url: 'https://www.figma.com/file/LHH25GN90ljQaBEUNMsdJn/Desktop-components?node-id=1898%3A0', }, }, }; export const basic = () => <EmptyState metaText={text('Meta text', 'I am the meta information of the EmptyState')} />; export const withTitle = () => ( <EmptyState metaText={text( 'Meta text', 'I am the meta information and I basically explain that you can start adding content via the add button above.', )} size={select('Size', sizes, 'medium')} title={text('Title', 'I am the empty state title that highlights a keyword')} /> );
JavaScript
0
@@ -39,14 +39,8 @@ lect -, text %7D f @@ -186,16 +186,56 @@ yState'; +%0Aimport %7B Marker %7D from '../typography'; %0A%0Aconst @@ -271,16 +271,120 @@ large'%5D; +%0Aconst title = (%0A %3C%3E%0A I am the empty state title that %3CMarker%3Ehighlights%3C/Marker%3E a keyword%0A %3C/%3E%0A); %0A%0Aexport @@ -672,28 +672,9 @@ ext= -%7Btext('Meta text', ' +%22 I am @@ -712,19 +712,17 @@ ptyState -')%7D +%22 /%3E;%0A%0Aex @@ -783,41 +783,9 @@ ext= -%7Btext(%0A 'Meta text',%0A ' +%22 I am @@ -893,17 +893,9 @@ ove. -',%0A )%7D +%22 %0A @@ -950,76 +950,12 @@ e=%7Bt -ext('Title', 'I am the empty state title that highlights a keyword') +itle %7D%0A
4548964db11a6ddf049517a916b5f286652bdd1b
Allow grouping of custom components
src/fields/form/index.js
src/fields/form/index.js
import React, { Component } from 'react'; import { View, Text } from 'native-base'; import GenerateForm from '../../formBuilder'; export default class FormField extends Component { static propTypes = { attributes: React.PropTypes.object, theme: React.PropTypes.object, updateValue: React.PropTypes.func, autoValidation: React.PropTypes.bool, customValidation: React.PropTypes.func, } constructor(props) { super(props); this.onValueChange = this.onValueChange.bind(this); } componentDidMount() { this.props.updateValue(this.props.attributes.name, this.group.getValues()); } onValueChange() { this.props.updateValue(this.props.attributes.name, this.group.getValues()); } handleChange(text) { this.setState({ value: text, }, () => this.props.updateValue(this.props.attributes.name, text)); } render() { const { attributes, theme, autoValidation, customValidation, } = this.props; return ( <View> <View style={{ paddingHorizontal: 15, paddingVertical: 5 }}> <Text style={{ fontWeight: '500', fontSize: 17 }}>{attributes.label}</Text> </View> <View style={{ paddingHorizontal: 10 }}> <GenerateForm ref={(c) => { this.group = c; }} onValueChange={this.onValueChange} autoValidation={autoValidation} customValidation={customValidation} showErrors fields={attributes.fields} theme={theme} /> </View> </View> ); } }
JavaScript
0.000001
@@ -398,20 +398,66 @@ s.func,%0A + customComponents: React.PropTypes.object,%0A %7D%0A - constr @@ -997,24 +997,48 @@ Validation,%0A + customComponents,%0A %7D = this @@ -1443,32 +1443,32 @@ autoValidation%7D%0A - cust @@ -1491,32 +1491,80 @@ stomValidation%7D%0A + customComponents=%7BcustomComponents%7D%0A show
62b5fecb05c3c5c2a247b71e7fd2311cb98b4736
Clear the code
src/botPage/common/SmartChartTicksService.js
src/botPage/common/SmartChartTicksService.js
import { Map } from 'immutable'; import { doUntilDone } from '../bot/tools'; import TicksService from './TicksService'; export default class SmartChartTicksService extends TicksService { unsubscribeAllAndSubscribeListeners(symbol) { const ohlcSubscriptions = this.subscriptions.getIn(['ohlc', symbol]); const tickSubscription = this.subscriptions.getIn(['tick', symbol]); const subscription = [ ...(ohlcSubscriptions ? Array.from(ohlcSubscriptions.values()) : []), ...(tickSubscription || []), ]; Promise.all(subscription.map(id => doUntilDone(() => this.api.unsubscribeByID(id)))); this.subscriptions = new Map(); } updateTicksAndCallListeners(symbol, ticks) { if (this.ticks.get(symbol) === ticks) { return; } this.ticks = this.ticks.set(symbol, ticks); const listeners = this.tickListeners.get(symbol); if (listeners) { listeners.forEach(callback => callback(ticks)); } } updateCandlesAndCallListeners(address, candles) { if (this.ticks.getIn(address) === candles) { return; } this.candles = this.candles.setIn(address, candles); const listeners = this.ohlcListeners.getIn(address); if (listeners) { listeners.forEach(callback => callback(candles)); } } observe() { this.api.events.on('tick', r => { const { tick, tick: { symbol, id }, } = r; if (this.ticks.has(symbol)) { this.subscriptions = this.subscriptions.setIn(['tick', symbol], id); this.updateTicksAndCallListeners(symbol, r); } }); this.api.events.on('ohlc', r => { const { ohlc, ohlc: { symbol, granularity, id }, } = r; if (this.candles.hasIn([symbol, Number(granularity)])) { this.subscriptions = this.subscriptions.setIn(['ohlc', symbol, Number(granularity)], id); const address = [symbol, Number(granularity)]; this.updateCandlesAndCallListeners(address, r); } }); } requestTicks(options) { const { symbol, granularity, style } = options; return new Promise((resolve, reject) => { doUntilDone(() => this.api.getTickHistory(symbol, { subscribe : 1, end : 'latest', count : 1000, granularity: granularity ? Number(granularity) : undefined, style, }) ) .then(r => { if (style === 'ticks') { // const ticks = historyToTicks(r.history); this.updateTicksAndCallListeners(symbol, r); // resolve(ticks); } else { // const candles = parseCandles(r.candles); this.updateCandlesAndCallListeners([symbol, Number(granularity)], r); // resolve(candles); } }) .catch(reject); }); } }
JavaScript
0.999998
@@ -699,714 +699,8 @@ %7D%0A%0A - updateTicksAndCallListeners(symbol, ticks) %7B%0A if (this.ticks.get(symbol) === ticks) %7B%0A return;%0A %7D%0A this.ticks = this.ticks.set(symbol, ticks);%0A%0A const listeners = this.tickListeners.get(symbol);%0A%0A if (listeners) %7B%0A listeners.forEach(callback =%3E callback(ticks));%0A %7D%0A %7D%0A%0A updateCandlesAndCallListeners(address, candles) %7B%0A if (this.ticks.getIn(address) === candles) %7B%0A return;%0A %7D%0A this.candles = this.candles.setIn(address, candles);%0A%0A const listeners = this.ohlcListeners.getIn(address);%0A%0A if (listeners) %7B%0A listeners.forEach(callback =%3E callback(candles));%0A %7D%0A %7D%0A%0A @@ -777,30 +777,8 @@ t %7B%0A - tick,%0A @@ -1112,30 +1112,8 @@ t %7B%0A - ohlc,%0A @@ -2065,76 +2065,8 @@ ) %7B%0A - // const ticks = historyToTicks(r.history);%0A @@ -2154,127 +2154,16 @@ - // resolve(ticks);%0A %7D else %7B%0A // const candles = parseCandles(r.candles); +%7D else %7B %0A @@ -2257,53 +2257,8 @@ r);%0A - // resolve(candles);%0A
0dc86b2b1a331694e9012301151e02bc5718ac2f
create app into directory with app name
generators/app/index.js
generators/app/index.js
var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var yosay = require('yosay'); var _ = require('lodash'); var path = require('path'); var helpers = require('../../helpers'); module.exports = yeoman.generators.Base.extend({ prompting: function () { var done = this.async(); this.log(yosay( 'Welcome to the awesome ' + chalk.red('slack-slash') + ' app generator!' )); this.log('This generator will create a new ' + chalk.red('slack-slash') + ' app.'); this.log('To create a new slack-slash handler instead, run ' + chalk.yellow('yo slack-slash:handler') + '.\n'); var prompts = [{ type: 'input', name: 'appName', message: 'Name your app:', default: 'slack-slash' }, { type: 'confirm', name: 'initialHandlers', message: 'Set up inital handlers?', default: false }, { type: 'input', name: 'handlers', message: 'List handlers to use (comma separated):', validate: helpers.stringNotEmpty, filter: helpers.filterHandlers, when: function (answers) { return answers.initialHandlers; } }]; this.prompt(prompts, function (props) { this.props = props; done(); }.bind(this)); }, handlersSetup: function () { if (this.props.handlers && this.props.handlers.length) { var done = this.async(); var prompts = []; _.each(this.props.handlers, function (handler) { var commandPrompt = { type: 'input', name: handler + '_command', message: 'What is the /:command for ' + handler + '?', filter: helpers.cleanSlashCmd, default: handler }; var tokenVarPrompt = { type: 'input', name: handler + '_token', message: 'Environment variable for your slack token:', default: helpers.pkgToTokenVar(handler) }; prompts.push(commandPrompt, tokenVarPrompt); }); this.prompt(prompts, function (props) { _.assign(this.props, props); done(); }.bind(this)); } }, createHandlersObj: function () { var self = this; this.props.h = []; _.each(this.props.handlers, function (handler) { self.props.h.push({ pkgName: handler, command: self.props[handler + '_command'], token: self.props[handler + '_token'] }); }); }, writing: { app: function () { var self = this; var basePath = path.join(__dirname, '..', '..'); var ssPath = path.join(basePath, 'node_modules', 'slack-slash'); var ssFiles = ['.npmignore', 'LICENSE.md', 'README.md', 'server.js']; _.each(ssFiles, function (file) { self.fs.copy( path.join(ssPath, file), self.destinationPath(file) ); }); this.fs.copyTpl( this.templatePath('www'), this.destinationPath('bin', '/www'), this.props ); this.fs.copy( path.join(ssPath, 'routes', '*'), this.destinationPath('routes') ); }, templates: function () { this.fs.copyTpl( this.templatePath('_package.json'), this.destinationPath('package.json'), this.props ); this.fs.copyTpl( this.templatePath('_handlers.json'), this.destinationPath('handlers.json'), this.props ); this.fs.copy( this.templatePath('jshintrc'), this.destinationPath('.jshintrc') ); } }, install: function () { this.npmInstall(); }, end: function () { var handlersMsg = 'Be sure to set your handler token environment variables '; var noHandlersMsg = 'Now go add some handlers '; var endMsg = 'then run ' + chalk.yellow('npm start') + ' to start the app.\n'; this.log('\nCongratulations! ' + chalk.red(this.props.appName) + ' is now installed.\n'); this.log((this.props.initialHandlers ? handlersMsg : noHandlersMsg) + endMsg); } });
JavaScript
0.000001
@@ -2410,16 +2410,142 @@ ;%0A %7D,%0A%0A + paths: function () %7B%0A // Save app into directory with app name%0A this.destinationRoot(this.props.appName + '/');%0A %7D,%0A%0A writin
d0004e40df6129effd9f9cb511017ca25ea392a5
modify swagger
server/config/config.js
server/config/config.js
require('dotenv').config(); module.exports = { development: { username: 'andeladeveloper', password: null, database: 'docmanager-dev', host: '127.0.0.1', port: 5432, dialect: 'postgres' }, test: { username: 'andeladeveloper', password: null, database: 'docmanager-test', host: '127.0.0.1', port: 5432, dialect: 'postgres' }, production: { use_env_variable: 'PRODUCTION_DB', dialect: 'postgres' } };
JavaScript
0.000005
@@ -232,148 +232,31 @@ use -rname: 'andeladeveloper',%0A password: null,%0A database: 'docmanager-test',%0A host: '127.0.0.1',%0A port: 5432,%0A dialect: 'postgres +_env_variable: 'TEST_DB '%0A
29070db505642956070b59cf78c553c479711b96
Insert Coin...
Tools/WebpackPlugins/babylonWebpackConfig.js
Tools/WebpackPlugins/babylonWebpackConfig.js
const webpack = require('webpack'); const babylonExternals = require('./babylonExternals'); const config = require("../Config/config.js"); module.exports = function defaultConfig(options) { if (!options) { throw "Options are mandatory to create the config."; } const module = options.module; const settings = config[module]; options.resolveExtensions = options.resolveExtensions || []; options.moduleRules = options.moduleRules || []; options.plugins = options.plugins || []; options.entry = options.entry || { [settings.build.umd.packageName]: settings.libraries[0].computed.entryPath }; options.output = options.output || { path: settings.computed.distDirectory, filename: settings.libraries[0].output .replace(".min.", ".") .replace(".max.", "."), libraryTarget: 'umd', library: { root: settings.build.umd.webpackRoot.split("."), amd: settings.build.umd.packageName, commonjs: settings.build.umd.packageName }, umdNamedDefine: true, globalObject: '(typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this)' }; return { context: settings.computed.srcDirectory, entry: options.entry, output: options.output, resolve: options.resolve || { extensions: [".ts", ...options.resolveExtensions] }, externals: [babylonExternals()], devtool: "none", module: { rules: [{ test: /\.tsx?$/, loader: 'ts-loader', options: { configFile: settings.computed.tsConfigPath, compilerOptions: { declaration: false, } } }, ...options.moduleRules] }, mode: "production", performance: { hints: false }, plugins: [ new webpack.WatchIgnorePlugin([ /\.js$/, /\.d\.ts$/, /\.fx$/ ]), ...options.plugins ] } };
JavaScript
0
@@ -1850,24 +1850,131 @@ on: false,%0D%0A + exclude: %5B%0D%0A 'node_modules'%0D%0A %5D%0D%0A
8ca9b8df81d313548290a3c03851c5c2a7b3d08c
Fix logging permissions
generators/app/index.js
generators/app/index.js
const fs = require('fs'); const Generator = require('yeoman-generator'); const buildPolicy = (serviceName, stage, region) => { return { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Action: [ 'cloudformation:List*', 'cloudformation:Get*', 'cloudformation:PreviewStackUpdate' ], Resource: ['*'] }, { Effect: 'Allow', Action: [ 'cloudformation:CreateStack', 'cloudformation:CreateUploadBucket', 'cloudformation:DeleteStack', 'cloudformation:DescribeStackEvents', 'cloudformation:DescribeStackResource', 'cloudformation:DescribeStackResources', 'cloudformation:UpdateStack', 'cloudformation:DescribeStacks' ], Resource: [ `arn:aws:cloudformation:${region}:*:stack/${serviceName}-${stage}/*` ] }, { Effect: 'Allow', Action: ['lambda:Get*', 'lambda:List*', 'lambda:CreateFunction'], Resource: ['*'] }, { Effect: 'Allow', Action: ['s3:CreateBucket'], Resource: [`arn:aws:s3:::${serviceName}*serverlessdeploymentbucket*`] }, { Effect: 'Allow', Action: [ 's3:PutObject', 's3:GetObject', 's3:ListBucket', 's3:DeleteObject', 's3:DeleteBucket', 's3:ListBucketVersions' ], Resource: [`arn:aws:s3:::${serviceName}*serverlessdeploymentbucket*`] }, { Effect: 'Allow', Action: [ 'lambda:AddPermission', 'lambda:CreateAlias', 'lambda:DeleteFunction', 'lambda:InvokeFunction', 'lambda:PublishVersion', 'lambda:RemovePermission', 'lambda:Update*' ], Resource: [ `arn:aws:lambda:${region}:*:function:${serviceName}-${stage}-*` ] }, { Effect: 'Allow', Action: [ 'apigateway:GET', 'apigateway:POST', 'apigateway:PUT', 'apigateway:DELETE' ], Resource: [ 'arn:aws:apigateway:*::/restapis', 'arn:aws:apigateway:*::/restapis/*/*' ] }, { Effect: 'Allow', Action: ['iam:PassRole'], Resource: ['arn:aws:iam::*:role/*'] }, { Effect: 'Allow', Action: 'kinesis:*', Resource: [ `arn:aws:kinesis:*:*:stream/${serviceName}-${stage}-${region}` ] }, { Effect: 'Allow', Action: 'iam:*', Resource: [ `arn:aws:iam::*:role/${serviceName}-${stage}-${region}-lambdaRole` ] }, { Effect: 'Allow', Action: 'sqs:*', Resource: [`arn:aws:sqs:*:*:${serviceName}-${stage}-${region}`] }, { Effect: 'Allow', Action: ['cloudwatch:GetMetricStatistics'], Resource: ['*'] }, { Effect: 'Allow', Action: [ 'logs:DescribeLogStreams', 'logs:DescribeLogGroups', 'logs:FilterLogEvents' ], Resource: ['*'] }, { Effect: 'Allow', Action: ['events:Put*', 'events:Remove*', 'events:Delete*'], Resource: [`arn:aws:events:*:*:rule/${serviceName}-${stage}-${region}`] } ] }; }; const escapeValFilename = function(val) { return val === '*' ? '_star_' : val; }; module.exports = class extends Generator { constructor(args, opts) { super(args, opts); this.option('project', { description: 'The name of the Serverless project', type: String }); this.option('stage', { description: 'The name of a single stage to target', type: String, default: '*' }); this.option('region', { description: 'The name of a single region to target', type: String, default: '*' }); } prompting() { return this.prompt([ { type: 'input', name: 'name', message: 'Your Serverless service name', default: this.appname // Default to current folder name }, { type: 'input', name: 'stage', message: 'You can specify a specific stage, if you like:', default: '*' }, { type: 'input', name: 'region', message: 'You can specify a specific region, if you like:', default: '*' }, { type: 'confirm', name: 'dynamodb', message: 'Does your service rely on DynamoDB?' } ]).then(answers => { this.slsSettings = { name: answers.name, stage: answers.stage, region: answers.region, dynamodb: answers.dynamodb }; this.log('app name', answers.name); this.log('app stage', answers.stage); this.log('app region', answers.region); }); } writing() { const done = this.async(); const project = this.slsSettings.name; const stage = this.slsSettings.stage; const region = this.slsSettings.region; const policy = buildPolicy(project, stage, region); if (this.slsSettings.dynamodb) { policy.Statement.push({ Effect: 'Allow', Action: ['dynamodb:*'], Resource: ['arn:aws:dynamodb:*:*:table/*'] }); } const policyString = JSON.stringify(policy, null, 2); const fileName = `${project}-${escapeValFilename(stage)}-${escapeValFilename(region)}-policy.json`; this.log(`Writing to ${fileName}`); fs.writeFile(fileName, policyString, done); } };
JavaScript
0.000002
@@ -2983,32 +2983,318 @@ %7D,%0A %7B%0A + Action: %5B'logs:CreateLogGroup', 'logs:CreateLogStream'%5D,%0A Resource: %5B%60arn:aws:logs:$%7Bregion%7D:*:*%60%5D,%0A Effect: 'Allow'%0A %7D,%0A %7B%0A Action: %5B'logs:PutLogEvents'%5D,%0A Resource: %5B%60arn:aws:logs:$%7Bregion%7D:*:*%60%5D,%0A Effect: 'Allow'%0A %7D,%0A %7B%0A Effect:
0d4e29b18b4926a760933e952b5b95173cf0be9c
Add option to filter form fields to be sent
src/plugins/Multipart.js
src/plugins/Multipart.js
const Plugin = require('./Plugin') const UppySocket = require('../core/UppySocket') const Utils = require('../core/Utils') module.exports = class Multipart extends Plugin { constructor (core, opts) { super(core, opts) this.type = 'uploader' this.id = 'Multipart' this.title = 'Multipart' // Default options const defaultOptions = { fieldName: 'files[]', responseUrlFieldName: 'url', bundle: true, headers: {}, getUploadUrl (xhr) { const resp = JSON.parse(xhr.response) return resp[this.responseUrlFieldName] } } // Merge default options with the ones set by user this.opts = Object.assign({}, defaultOptions, opts) this.handleUpload = this.handleUpload.bind(this) } upload (file, current, total) { const opts = Object.assign({}, this.opts, file.multipart || {}) this.core.log(`uploading ${current} of ${total}`) return new Promise((resolve, reject) => { // turn file into an array so we can use bundle // if (!opts.bundle) { // files = [files[current]] // } // for (let i in files) { // formPost.append(opts.fieldName, files[i]) // } const formPost = new FormData() Object.keys(file.meta).forEach((item) => { formPost.append(item, file.meta[item]) }) formPost.append(opts.fieldName, file.data) const xhr = new XMLHttpRequest() xhr.upload.addEventListener('progress', (ev) => { if (ev.lengthComputable) { this.core.emitter.emit('core:upload-progress', { uploader: this, id: file.id, bytesUploaded: ev.loaded, bytesTotal: ev.total }) } }) xhr.addEventListener('load', (ev) => { if (ev.target.status >= 200 && ev.target.status < 300) { const uploadURL = opts.getUploadUrl(xhr) this.core.emitter.emit('core:upload-success', file.id, uploadURL) if (uploadURL) { this.core.log(`Download ${file.name} from ${file.uploadURL}`) } return resolve(file) } else { this.core.emitter.emit('core:upload-error', file.id, xhr) return reject('Upload error') } // var upload = {} // // if (opts.bundle) { // upload = {files: files} // } else { // upload = {file: files[current]} // } }) xhr.addEventListener('error', (ev) => { this.core.emitter.emit('core:upload-error', file.id) return reject('Upload error') }) xhr.open('POST', opts.endpoint, true) Object.keys(opts.headers).forEach((header) => { xhr.setRequestHeader(header, opts.headers[header]) }) xhr.send(formPost) this.core.emitter.on('core:upload-cancel', (fileID) => { if (fileID === file.id) { xhr.abort() } }) this.core.emitter.on('core:cancel-all', () => { // const files = this.core.getState().files // if (!files[file.id]) return xhr.abort() }) this.core.emitter.emit('core:upload-started', file.id) }) } uploadRemote (file, current, total) { const opts = Object.assign({}, this.opts, file.multipart || {}) return new Promise((resolve, reject) => { this.core.emitter.emit('core:upload-started', file.id) fetch(file.remote.url, { method: 'post', credentials: 'include', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(Object.assign({}, file.remote.body, { endpoint: opts.endpoint, size: file.data.size, fieldname: opts.fieldName })) }) .then((res) => { if (res.status < 200 && res.status > 300) { return reject(res.statusText) } res.json().then((data) => { const token = data.token const host = Utils.getSocketHost(file.remote.host) const socket = new UppySocket({ target: `${host}/api/${token}` }) socket.on('progress', (progressData) => Utils.emitSocketProgress(this, progressData, file)) socket.on('success', (data) => { this.core.emitter.emit('core:upload-success', file.id, data.url) socket.close() return resolve() }) }) }) }) } selectForUpload (files) { files.forEach((file, i) => { const current = parseInt(i, 10) + 1 const total = files.length if (file.isRemote) { this.uploadRemote(file, current, total) } else { this.upload(file, current, total) } }) // if (this.opts.bundle) { // uploaders.push(this.upload(files, 0, files.length)) // } else { // for (let i in files) { // uploaders.push(this.upload(files, i, files.length)) // } // } } handleUpload (fileIDs) { if (fileIDs.length === 0) { this.core.log('Multipart: no files to upload!') return Promise.resolve() } this.core.log('Multipart is uploading...') const files = fileIDs.map(getFile, this) function getFile (fileID) { return this.core.state.files[fileID] } this.selectForUpload(files) return new Promise((resolve) => { this.core.bus.once('core:upload-complete', resolve) }) } install () { this.core.addUploader(this.handleUpload) } uninstall () { this.core.removeUploader(this.handleUpload) } }
JavaScript
0
@@ -381,16 +381,40 @@ les%5B%5D',%0A + metaFields: null,%0A re @@ -1251,32 +1251,163 @@ ormData()%0A%0A + const metaFields = Array.isArray(opts.metaFields)%0A ? opts.metaFields%0A // Send along all fields by default.%0A : Object.keys(fil @@ -1413,16 +1413,33 @@ le.meta) +%0A metaFields .forEach
dc1c90ec27b601c728987deb114a1c2db0f392e9
Fix some spacing
RESTular.js
RESTular.js
$(document).ready(function() { $(".submission-box").on("keyup", function() { setGoldenText(this); }) $('tr.route').mouseover(function(){ addClassHover(this); }); $('tr.route').mouseout(function(){ removeClassHover(this); }); $(".route").on("click", function() { toggleNext(this); toggleTRClass(this); squadLove(); }); //############ ZeroClipboard Nightmare ######################### var client = new ZeroClipboard( $(".route-pre") ); client.on( "ready", function( readyEvent ) { client.on("copy", function(event) { console.log(client); var preData = event.target.innerText; client.setText(preData); }) client.on( "aftercopy", function( event ) { $(event.target).siblings(".copy-prompt").text("Copied!"); $(event.target).addClass(".on-click") setTimeout(function(){ $(event.target).siblings(".copy-prompt").text("^click to copy^"); $(event.target).addClass(".on-click"); }, 1000); }); }); //################ Thank god that's over ########################## }); //end of (document).ready() //######################## Functions ############################# function removeClassHover(that) { $(that).removeClass('hover'); } function setGoldenText(that) { $(".golden-text").text($(that).val().toLowerCase()); $(".g-text-singular").text(pluralize(capitalize($(that).val()), 1)); $(".g-text-s-dc").text((pluralize($(that).val(), 1))); } function addClassHover(that) { $(that).addClass('hover'); } function toggleNext(that) { $(that).next().toggle(); } function toggleTRClass(that) { $(that).toggleClass('in-use'); $(that).toggleClass('hover'); } function squadLove() { var rand100 = Math.floor(Math.random() * 100) if (rand100 === 69) { $('.sub-box-under').text("Chi Bobolinks 2015!") } } function capitalize(string) { var lowerCaseString = string.toLowerCase(); return lowerCaseString.charAt(0).toUpperCase() + lowerCaseString.slice(1); }
JavaScript
0.999993
@@ -72,18 +72,17 @@ tion() %7B - %0A + setG @@ -490,17 +490,16 @@ ient.on( - %22ready%22, @@ -687,17 +687,16 @@ ient.on( - %22afterco @@ -1337,20 +1337,16 @@ Case()); - %0A $(%22.g @@ -1996,9 +1996,10 @@ ice(1);%0A - %7D +%0A
100bcdc5e862e29d39767e8d3a6dc979cb2bf1fe
fix property title update
pages/media/js/pages.type.js
pages/media/js/pages.type.js
/* * This file is part of dj-pages released under the MIT license. * See the NOTICE for more information. */ (function($) { $.pages = $.pages || {}; function ResourceType() { this.cache = {}; } $.extend(ResourceType.prototype, { request: function(app, req) { this.app = app; if (req.method === "get") { this.new_type(app, req); } }, new_type: function(app, req) { var self = this; var templates = app.ddoc.templates; var cnt = Mustache.to_html(templates.type, {}); $("#content").html(cnt); $("#admin").html(Mustache.to_html(templates.type_admin, {})); $("#tabs").tabs() $("#new-property").button().click(function() { self.property_add(); return false; }); $(".property").live("mouseover", function(e) { // display toolbar to manage up, down acttions self.type_toolbar(this); }).live("mouseleave", function() { $(".ttool", this).remove(); }); $(".property").live("click", function(e) { if (e.originalTarget.nodeName === "BUTTON") return; $("td.current").removeClass("current"); $(this).addClass("current"); var row = $(this).parent(); console.log("edit"); self.property_edit(row); }); $("#property-detail :input") .live("change", function(e) { var row = $(".current").parent(); $("#properties").trigger("update", [row]); }) .live("keyup", function(e) { var row = $(".current").parent(); $("#properties").trigger("update", [row]); }); $("#properties").bind("update", function(e, row) { console.log("update property"); var prop = {}; $("#property-detail :input").each(function(el) { prop[$(this).attr("id")] = $(this).val(); }); $.data(row[0], "_property", prop); }); }, type_toolbar: function(el) { var templates = this.app.ddoc.templates, tpl = templates.type_toolbar, toolbar = $(Mustache.to_html(tpl, {})), row = $(el).closest("tr").prevAll("tr").length, self=this; if ($(el).has("div").length > 0) { return; } $(".ttool").remove(); $("button:first", toolbar).button({ icons: { primary: "ui-icon-circle-triangle-n" }, text: false }).next().button({ icons: { primary: "ui-icon-circle-triangle-s" }, text: false }).next().button({ icons: { primary: "ui-icon-circle-close" }, text: false }); $("button", toolbar).click(function(e) { e.preventDefault(); if ($(this).hasClass("up")) { if (row === 0) return; console.log("up"); } else if ($(this).hasClass("down")) { if (row === (self.properties.length -1)) return; console.log("down"); } else { var next = $(el).parent().next(); $(el).parent().remove(); if (next.length > 0) { self.property_edit(next); } console.log("close"); } return false; }); toolbar.appendTo($(el)); }, property_add: function() { var templates = this.app.ddoc.templates, properties = $("#properties"), detail = Mustache.to_html(templates.property_row, { rowspan: this.nb_props, name: "New propety" }), nb_rows = $("#properties").attr('rows').length; $(".current").removeClass("current"); var row = $('<tr></tr>'); $('<td class="property current">New property</td>').appendTo(row); if (nb_rows === 1) { pdetail = $('<td id="property-detail"></td>'); pdetail.appendTo(row); } else { pdetail= $("#property-detail"); } pdetail.attr("rowspan", nb_rows-1); pdetail.html(detail); row.appendTo(properties); properties.trigger("update", [row]); $("#name").bind("keyup", function(e) { var el = $("td:first", row[0]); el.html($(this).val()); }); }, property_edit: function(row) { var prop = $.data(row[0], "_property"); templates = this.app.ddoc.templates; var detail = Mustache.to_html(templates.property_row, prop); if ($("#property-detail").length > 0) { td = $("#property-detail"); } else { td = $('<td id="property-detail"></td>'); td.appendTo(row); } td.html(detail); $("#property-detail select").each(function() { if (typeof(prop[this.id]) != "undefined") { $(this).val(prop[this.id]); } }); $(".current").removeClass("current"); $("td:first", row).addClass("current"); } }); $.pages.ResourceType = new ResourceType(); })(jQuery);
JavaScript
0
@@ -1934,32 +1934,135 @@ pdate%22, %5Brow%5D);%0A + if (this.id == %22name%22)%0A $(%22.current%22).html($(this).val()); %0A @@ -5107,163 +5107,8 @@ ; %0A%0A - $(%22#name%22).bind(%22keyup%22, function(e) %7B%0A var el = $(%22td:first%22, row%5B0%5D);%0A el.html($(this).val());%0A %7D);%0A
b359be74a1102b7220235b41821a410cd6f3b7a0
remove superfluous check in while loop
src/renderers/shared/stack/reconciler/ReactUpdates.js
src/renderers/shared/stack/reconciler/ReactUpdates.js
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdates */ 'use strict'; var PooledClass = require('PooledClass'); var ReactFeatureFlags = require('ReactFeatureFlags'); var ReactReconciler = require('ReactReconciler'); var Transaction = require('Transaction'); var invariant = require('invariant'); var dirtyComponents = []; var updateBatchNumber = 0; var batchingStrategy = null; function ensureInjected() { invariant( ReactUpdates.ReactReconcileTransaction && batchingStrategy, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy' ); } var NESTED_UPDATES = { initialize: function() { this.dirtyComponentsLength = dirtyComponents.length; }, close: function() { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } }, }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */ true ); } Object.assign( ReactUpdatesFlushTransaction.prototype, Transaction, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, destructor: function() { this.dirtyComponentsLength = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function(method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.perform.call( this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a ); }, } ); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); return batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; invariant( len === dirtyComponents.length, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length ); // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); // Any updates enqueued while reconciling must be performed after this entire // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and // C, B could update twice in a single batch if C's render enqueues an update // to B (since B would have already updated, we should skip it, and the only // way we can know to do so is by checking the batch counter). updateBatchNumber++; for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if (component._currentElement.type.isReactTopLevelWrapper) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); console.time(markerName); } ReactReconciler.performUpdateIfNecessary( component, transaction.reconcileTransaction, updateBatchNumber ); if (markerName) { console.timeEnd(markerName); } } } var flushBatchedUpdates = function() { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks. while (dirtyComponents.length) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } } }; /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); if (component._updateBatchNumber == null) { component._updateBatchNumber = updateBatchNumber + 1; } } var ReactUpdatesInjection = { injectReconcileTransaction: function(ReconcileTransaction) { invariant( ReconcileTransaction, 'ReactUpdates: must provide a reconcile transaction class' ); ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function(_batchingStrategy) { invariant( _batchingStrategy, 'ReactUpdates: must provide a batching strategy' ); invariant( typeof _batchingStrategy.batchedUpdates === 'function', 'ReactUpdates: must provide a batchedUpdates() function' ); invariant( typeof _batchingStrategy.isBatchingUpdates === 'boolean', 'ReactUpdates: must provide an isBatchingUpdates boolean attribute' ); batchingStrategy = _batchingStrategy; }, getBatchingStrategy: function() { return batchingStrategy; }, }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, }; module.exports = ReactUpdates;
JavaScript
0.000001
@@ -5316,44 +5316,8 @@ ) %7B%0A - if (dirtyComponents.length) %7B%0A @@ -5372,26 +5372,24 @@ etPooled();%0A - transact @@ -5439,26 +5439,24 @@ ction);%0A - ReactUpdates @@ -5494,22 +5494,16 @@ ction);%0A - %7D%0A %7D%0A%7D;%0A%0A
57526356dec26b472748ab3ff6186c1716eaaa8c
Add KLC
univList.js
univList.js
var univNames = [ "Adelphi University", "Boston University", "Carnegie Mellon University", "College of William & Mary", "Ez-zitouna University", "Gabes University", "Gafsa University", "Harvard University", "Manouba University", "Monastir University", "New York University", "Sfax University", "Singapore Management University", "Sousse University", "Stanford University", "Tunis El Manar University", "Tunis University", "UC Berkeley", "University of Carthage", "University of Delaware", "University of Rochester", "University of Jendouba", "University of Texas Rio Grande Valley", "University of Tsukuba", "University of Washington", "University of Waterloo", "가야대", "가천대", "가톨릭대", "가톨릭관동대", "감리교신학대", "강남대", "강릉원주대", "강원대", "건국대", "건양대", "경기대", "경남과학기술대", "경남대", "경동대", "경북대", "경상대", "경성대", "경운대", "경일대", "경주대", "경희대", "계명대", "계명문화대", "고려대", "고신대", "공주대", "광신대", "광운대", "광주가톨릭대", "광주대", "광주여자대", "국민대", "군산대", "극동대", "금강대", "금오공대", "김천대", "꽃동네대", "나사렛대", "남부대", "남서울대", "단국대", "대구가톨릭대", "대구대", "대구예술대", "대구한의대", "대신대", "대전가톨릭대", "대전대", "대전신학대", "대진대", "덕성여대", "동국대", "동덕여대", "동명대", "동서대", "동신대", "동아대", "동양대", "동의대", "루터대", "명지대", "목원대", "목포가톨릭대", "목포대", "목포해양대", "배재대", "백석대", "부경대", "부산가톨릭대", "부산대", "부산외국어대", "부산장신대", "삼육대", "상명대", "서강대", "서경대", "서울대", "서울과학기술대", "서울시립대", "선문대", "성공회대", "성균관대", "세명대", "세종대", "순천대", "순천향대", "숭실대", "숭의여대", "아주대", "연세대", "영남대", "인천대", "유니스트", "유한대", "인하대", "전남대", "전북대", "전주대", "중앙대", "충남대", "충북대", "카이스트", "포항공과대학교", "평택대", "한국기술교육대", "한동대", "한국외국어대", "한국항공대", "한밭대", "한성대", "한양대", "호서대", "홍익대" ];
JavaScript
0.000001
@@ -1736,17 +1736,20 @@ %EB%8C%80%22,%0A %22%ED%95%9C -%EB%8F%99 +%EA%B5%AD%EC%8A%B9%EA%B0%95%EA%B8%B0 %EB%8C%80%22,%0A %22%ED%95%9C @@ -1763,24 +1763,33 @@ %0A %22%ED%95%9C%EA%B5%AD%ED%95%AD%EA%B3%B5%EB%8C%80%22,%0A + %22%ED%95%9C%EB%8F%99%EB%8C%80%22,%0A %22%ED%95%9C%EB%B0%AD%EB%8C%80%22,%0A %22
02b41d9151c1f405560cb6c41bf4e074ef30d447
Add window onload for card.
development/cards.js
development/cards.js
const cardElementsLoad = [ document.getElementsByClassName('card-image'), document.getElementsByClassName('card-gradient'), document.getElementsByClassName('card-header-title'), document.getElementsByClassName('card-header-line'), document.getElementsByClassName('card-header-subtitle'), document.getElementsByClassName('card-header-intro'), document.getElementsByClassName('card-detail-circle'), document.getElementsByClassName('card-detail-day'), document.getElementsByClassName('card-detail-month'), document.getElementsByClassName('card-detail-venue'), document.getElementsByClassName('card-detail-location'), document.getElementsByClassName('card-detail-dates'), document.getElementsByClassName('card-detail-button'), document.getElementsByClassName('ribbon blue'), document.getElementsByClassName('ribbon green'), document.getElementsByClassName('ribbon red'), document.getElementsByClassName('banner blue'), document.getElementsByClassName('banner green'), document.getElementsByClassName('banner red') ] const cardElementsHoverTap = [ document.getElementsByClassName('card-detail-circle load'), document.getElementsByClassName('card-detail-day load'), document.getElementsByClassName('card-detail-month load'), document.getElementsByClassName('card-detail-venue load'), document.getElementsByClassName('card-detail-location load'), document.getElementsByClassName('card-detail-dates load'), document.getElementsByClassName('card-detail-button load'), document.getElementsByClassName('ribbon blue load'), document.getElementsByClassName('ribbon green load'), document.getElementsByClassName('ribbon red load') ] const calendarCards = document.getElementsByClassName('card') const device = getDevice() // Add event listener for hover or tap for (let i = 0; i < calendarCards.length; i++) { // Init on window load onLoad(window, () => cardElementsLoad.forEach(element => element[i].classList.add('on-load'))) // Desktops use `mouseover` response... if (device === 'desktop') { calendarCards[i].addEventListener('mouseover', () => cardElementsHoverTap.forEach(element => element[i].classList.add('on-hover-tap'))) calendarCards[i].addEventListener('mouseout', () => cardElementsHoverTap.forEach(element => element[i].classList.remove('on-hover-tap'))) } // ...mobile and tablet use `tap` response. else { calendarCards[i].addEventListener('click', () => { // Add tap response... cardElementsHoverTap.forEach(element => { // ...if card is already active, deactivate it... if (element[i].classList.contains('on-hover-tap')) { element[i].classList.remove('on-hover-tap') } // ...otherwise, activate it. else { element[i].classList.add('on-hover-tap') } }) // ...and remove active states from all other cards. for (let j = 0; j < calendarCards.length; j++) { if (i !== j) { cardElementsHoverTap.forEach(element => element[j].classList.remove('on-hover-tap')) } } }) } }
JavaScript
0
@@ -1128,16 +1128,19 @@ -circle +on- load'),%0A @@ -1190,16 +1190,19 @@ ail-day +on- load'),%0A @@ -1254,16 +1254,19 @@ l-month +on- load'),%0A @@ -1318,16 +1318,19 @@ l-venue +on- load'),%0A @@ -1385,16 +1385,19 @@ ocation +on- load'),%0A @@ -1449,16 +1449,19 @@ l-dates +on- load'),%0A @@ -1514,16 +1514,19 @@ -button +on- load'),%0A @@ -1572,16 +1572,19 @@ on blue +on- load'),%0A @@ -1631,16 +1631,19 @@ n green +on- load'),%0A @@ -1688,16 +1688,19 @@ bon red +on- load')%0A%5D
ef40cb9956f9685ef741193d5b664cb4c7de90b3
test window for browser
spec/bower/bower.spec.js
spec/bower/bower.spec.js
var window = {}; commonSpec('Bower', Opal, Opal.Asciidoctor);
JavaScript
0.000005
@@ -1,8 +1,4 @@ -var wind
7e6746d32bdd8cf664179c0b129223ed0b553ab1
Use closure actions to only advance page number if fetchResults is successful.
addon/components/osf-paginator/component.js
addon/components/osf-paginator/component.js
import Ember from 'ember'; import layout from './template'; // Ember component that is very similar to osf/website/static/js/paginator.js export default Ember.Component.extend({ layout, currentPage: 1, pages: Ember.computed('totalSearchResults', function() { let totalSearchResults = this.get('totalSearchResults'); return Math.ceil(totalSearchResults / 10); }), paginators: Ember.computed('currentPage', 'pages', function() { let currentPage = this.get('currentPage') - 1; var MAX_PAGES_ON_PAGINATOR = 7; var MAX_PAGES_ON_PAGINATOR_SIDE = 5; var pages = this.get('pages'); var paginator = Ember.A(); if (pages > 1) { paginator.pushObject('<'); paginator.pushObject(1); } if (pages <= MAX_PAGES_ON_PAGINATOR) { for (var i = 1; i < pages - 1; i++) { paginator.pushObject(i + 1); } } else if (currentPage < MAX_PAGES_ON_PAGINATOR_SIDE - 1) { for (var j = 1; j < MAX_PAGES_ON_PAGINATOR_SIDE; j++) { paginator.pushObject(j + 1); } paginator.pushObject('...'); } else if (currentPage > pages - MAX_PAGES_ON_PAGINATOR_SIDE) { paginator.pushObject('...'); for (var k = pages - MAX_PAGES_ON_PAGINATOR_SIDE; k < pages - 1; k++) { paginator.pushObject(k + 1); } } else { paginator.pushObject('...'); for (var l = currentPage - 1; l <= currentPage + 1; l++) { paginator.pushObject(l + 1); } paginator.pushObject('...'); } paginator.push(pages); paginator.push('>'); return paginator; }), actions: { findResults(query, page) { this.sendAction('fetchResults', query, page); this.set('currentPage', page); }, nextPage(query) { var page = this.get('currentPage'); if (page < this.get('pages')) { this.send('findResults', query, page + 1); } }, previousPage(query) { var page = this.get('currentPage'); if (page > 1) { this.send('findResults', query, page - 1); } } } });
JavaScript
0
@@ -1837,20 +1837,14 @@ his. -sendAction(' +attrs. fetc @@ -1847,27 +1847,25 @@ fetchResults -', +( query, page) @@ -1860,26 +1860,42 @@ query, page) -;%0A +.then(() =%3E %7B%0A @@ -1925,16 +1925,33 @@ page);%0A + %7D);%0A%0A
c8aaa44979ebc80bb888318b01adff0e4d6e9e00
Update checks.js
app/src/renderer/checks.js
app/src/renderer/checks.js
let checks = [ { title: 'Routine Dental Care Recommended/<em>Se recomienda Atencion Dental de Rutina</em>', options: { A: 'Dental Cleaning recommended/<em>Se recomienda limpieza dental</em>', B: 'Screen for cavities between the teeth (interproximal caries)/<em>Se recomienda examinar por caries entre los dientes (inter proximal)</em>', C: 'Sealants application recommended/<em>Se recomienda aplicacion de sellantes</em>', D: 'Stained teeth, please evaluate for cavities(caries)/<em>Manchas dentales, evaluar por caries</em>', E: 'Orthodontic work recommended (e.g. braces)/<em>Trabajo de ortodoncia recomendado (frenos recomendados)</em>' } }, { title: 'Urgent Dental Care Needed/<em>Cuidado Dental urgente es necesario</em>', options: { A: 'Mild to moderate cavities (caries)/<em>Caries leve a moderado</em>', B: 'Gum disease/<em>Enfermedad de las encias</em>', C: 'Soft tissue lesion/<em>Lesiones de tejido blando</em>', D: 'Recent trauma/<em>Trauma reciente</em>', E: 'Ectopic eruption(tooth entering the mouth in an abnormal way, e.g. crowding of baby teeth with adult teeth)/<em>' + 'Erupcion ectopica(dientes saliendo en posicion incorrecta. Ejemplo: dientes infantiles amontonando con dientes de adultos)</em>' } }, { title: 'Emergency Care Needed/<em>Se Necesita Atencion de Emergencia</em>', options: { A: 'Infection/<em>Infeccion</em>', B: 'Pain/<em>Dolor</em>', C: 'Severe cavities (caries)/<em>Caries profundas</em>' } } ] function calculateCheckList (checks) { console.log('Processing check levels...') let checkLevels = [] for (let i = 0; i < checks.length; i++) { let check = checks[i] let checkLevel = {index: i + 1, title: check.title} let options = [] for (var optionLetter in check.options) { let option = { letter: optionLetter, index: checkLevel.index, value: `${checkLevel.index}/${optionLetter}`, text: check.options[optionLetter] } options.push(option) } options.sort((a, b) => a.letter.charCodeAt(0) - b.letter.charCodeAt(0)) checkLevel['options'] = options checkLevels.push(checkLevel) } return checkLevels } const checkLevels = calculateCheckList(checks) export { checkLevels }
JavaScript
0.000001
@@ -140,17 +140,17 @@ 'Dental -C +c leaning
ba4a0c9b977dac3831ffaf2ddf5d87be0ca61a67
enforce OS-specific line breaks
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var jshintStylish = require('jshint-stylish'); var gutil = require('gulp-util'); // Currently unused, but gulp strongly suggested I install... var jshint = require('gulp-jshint'); var jscs = require('gulp-jscs'); var replace = require('gulp-replace'); var jsHintOptions = { "nonbsp": true, "nonew": true, "noarg": true, "loopfunc": true, "latedef": 'nofunc', "freeze": true, "immed": true, "undef": true, // style "smarttabs": true, "trailing": true, "newcap": true, "sub": true, "evil": true, "esnext": true, "node": true, "eqeqeq": true, "globals": { "Config": false, "ResourceMonitor": false, "toId": false, "toName": false, "string": false, "LoginServer": false, "Users": false, "Rooms": false, "Verifier": false, "CommandParser": false, "Simulator": false, "Tournaments": false, "Dnsbl": false, "Cidr": false, "Sockets": false, "Tools": false, "TeamValidator": false } }; var jscsOptions = { "excludeFiles": ["./**/pokedex.js", "./**/formats-data.js", "./**/learnsets.js", "./**/learnsets-g6.js", "./config/config.js"], "preset": "google", "requireCurlyBraces": null, "requireCamelCaseOrUpperCaseIdentifiers": null, "maximumLineLength": null, "validateIndentation": "\t", "validateQuoteMarks": null, "disallowMixedSpacesAndTabs": "smart", "disallowMultipleVarDecl": null, "requireSpaceAfterKeywords": true, "requireSpaceBeforeBinaryOperators": true, "disallowSpacesInAnonymousFunctionExpression": null, "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true }, "validateJSDoc": null, "requireBlocksOnNewline": 1, "disallowPaddingNewlinesInBlocks": true, "disallowEmptyBlocks": true, "disallowNewlineBeforeBlockStatements": true, "requireCommaBeforeLineBreak": true, "requireOperatorBeforeLineBreak": true, "disallowSpaceAfterObjectKeys": true, "disallowSpaceAfterPrefixUnaryOperators": true, "disallowSpaceBeforePostfixUnaryOperators": true, "disallowTrailingComma": true, "validateLineBreaks": process.platform === 'win32' ? null : "LF", "validateParameterSeparator": ", ", "requireCapitalizedConstructors": true }; gulp.task('data', function () { var directories = ['./data/*.js', './mods/*/*.js']; jsHintOptions['es3'] = true; // Replacing `var` with `let` is sort of a hack that stops jsHint from // complaining that I'm using `var` like `let` should be used, but // without having to deal with iffy `let` support. return gulp.src(directories) .pipe(jscs(jscsOptions)) .pipe(replace(/\bvar\b/g, 'let')) .pipe(jshint(jsHintOptions)) .pipe(jshint.reporter(jshintStylish)) .pipe(jshint.reporter('fail')) .pipe(jscs(jscsOptions)); }); gulp.task('fastlint', function () { var directories = ['./*.js', './tournaments/*.js', './chat-plugins/*.js', './config/*.js']; delete jsHintOptions['es3']; return gulp.src(directories) .pipe(jscs(jscsOptions)) .pipe(replace(/\bvar\b/g, 'let')) .pipe(jshint(jsHintOptions)) .pipe(jshint.reporter(jshintStylish)) .pipe(jshint.reporter('fail')); }); gulp.task('default', ['fastlint', 'data']); gulp.task('lint', ['fastlint', 'data']);
JavaScript
0.000035
@@ -2046,50 +2046,25 @@ s%22: -process.platform === 'win32' ? null : %22LF%22 +require('os').EOL ,%0A%09%22
17db807f605aabee2eb6c34a9a5ee0933ffd7047
add Grid module (empty)
app/scripts/common/forms/inputSelector/index.js
app/scripts/common/forms/inputSelector/index.js
define(function(require) { "use strict"; var Marionette = require('backbone.marionette'), Backbone = require('backbone'); var Dropdown = require('common/forms/dropdown/index'); var hbs = require('handlebars'); var Selector = Marionette.Layout.extend({ template: require('hbs!./template'), regions: { dropdown: '.input-group' }, ui: { input: 'input' }, events: { 'change input': 'onChange' }, initialize: function(options) { this.options = options; this.predefined = new Backbone.Collection(options.predefined || {}); }, onRender: function() { // console.info('Selector::onRender'); this.renderDropdown(); }, serializeData: function() { return { predefined: this.options.predefined, value: this.options.value, name: this.options.name }; }, renderDropdown: function() { var dropdown = new Dropdown({ collection: new Backbone.Collection(this.options.predefined), align: 'right' }); this.listenTo(dropdown, 'dropdown:select', this.onSelect); this.$('.input-group').append(dropdown.render().el); }, onSelect: function(value) { console.info('onSelect: ', value); this.ui.input .val(value) .trigger('change'); }, onChange: function() { this.trigger('change', this.ui.input.val()); } }); return Selector; });
JavaScript
0
@@ -590,49 +590,8 @@ ) %7B%0A -//%09%09%09console.info('Selector::onRender');%0A %09%09%09t @@ -1087,46 +1087,8 @@ ) %7B%0A -%09%09%09console.info('onSelect: ', value);%0A %09%09%09t
52a0adccb82445755b136f027969bb0efb0e1c23
Update variable name
pouchdb/02-create-remote-database.js
pouchdb/02-create-remote-database.js
// Create a remote PouchDB database var db = new PouchDB("https://bradley-holt.cloudant.com/smart-meter"); // Delete the database db.destroy().then(function() { console.log("Database deleted"); }).catch(function(error) { console.log(error); });
JavaScript
0.000003
@@ -33,17 +33,23 @@ ase%0Avar -d +remoteD b = new
15f94d37327f6574a1ea16070a0134b76247caa8
Update checkbox
src/components/views/terms/InlineTermsAgreement.js
src/components/views/terms/InlineTermsAgreement.js
/* Copyright 2019 The Matrix.org Foundation C.I.C. 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 PropTypes from "prop-types"; import {_t, pickBestLanguage} from "../../../languageHandler"; import * as sdk from "../../.."; import {objectClone} from "../../../utils/objects"; export default class InlineTermsAgreement extends React.Component { static propTypes = { policiesAndServicePairs: PropTypes.array.isRequired, // array of service/policy pairs agreedUrls: PropTypes.array.isRequired, // array of URLs the user has accepted onFinished: PropTypes.func.isRequired, // takes an argument of accepted URLs introElement: PropTypes.node, }; constructor() { super(); this.state = { policies: [], busy: false, }; } componentDidMount() { // Build all the terms the user needs to accept const policies = []; // { checked, url, name } for (const servicePolicies of this.props.policiesAndServicePairs) { const availablePolicies = Object.values(servicePolicies.policies); for (const policy of availablePolicies) { const language = pickBestLanguage(Object.keys(policy).filter(p => p !== 'version')); const renderablePolicy = { checked: false, url: policy[language].url, name: policy[language].name, }; policies.push(renderablePolicy); } } this.setState({policies}); } _togglePolicy = (index) => { const policies = objectClone(this.state.policies); policies[index].checked = !policies[index].checked; this.setState({policies}); }; _onContinue = () => { const hasUnchecked = !!this.state.policies.some(p => !p.checked); if (hasUnchecked) return; this.setState({busy: true}); this.props.onFinished(this.state.policies.map(p => p.url)); }; _renderCheckboxes() { const rendered = []; for (let i = 0; i < this.state.policies.length; i++) { const policy = this.state.policies[i]; const introText = _t( "Accept <policyLink /> to continue:", {}, { policyLink: () => { return ( <a href={policy.url} rel='noreferrer noopener' target='_blank'> {policy.name} <span className='mx_InlineTermsAgreement_link' /> </a> ); }, }, ); rendered.push( <div key={i} className='mx_InlineTermsAgreement_cbContainer'> <div>{introText}</div> <div className='mx_InlineTermsAgreement_checkbox'> <input type='checkbox' onChange={() => this._togglePolicy(i)} checked={policy.checked} /> {_t("Accept")} </div> </div>, ); } return rendered; } render() { const AccessibleButton = sdk.getComponent("views.elements.AccessibleButton"); const hasUnchecked = !!this.state.policies.some(p => !p.checked); return ( <div> {this.props.introElement} {this._renderCheckboxes()} <AccessibleButton onClick={this._onContinue} disabled={hasUnchecked || this.state.busy} kind="primary_sm" > {_t("Continue")} </AccessibleButton> </div> ); } }
JavaScript
0.000002
@@ -783,16 +783,73 @@ bjects%22; +%0Aimport StyledCheckbox from %22../elements/StyledCheckbox%22; %0A%0Aexport @@ -3495,32 +3495,23 @@ - %3Cinput type='c +%3CStyledC heckbox -' onC @@ -3570,18 +3570,16 @@ checked%7D - / %3E%0A @@ -3607,24 +3607,64 @@ (%22Accept%22)%7D%0A + %3C/StyledCheckbox%3E%0A
30590e9a8f9a303ef193930e38b71f964795dfaf
remove bare options for coffee compiler
gulpfile.js
gulpfile.js
var path = require('path'), gulp = require('gulp'), watch = require('gulp-watch'), sass = require('gulp-sass') include = require('gulp-include'), coffee = require('gulp-coffee'), slim = require("gulp-slim"), prefix = require('gulp-autoprefixer'); var ROOT_PATH = __dirname, COFFEESCRIPTS_PATH = path.join(ROOT_PATH, 'javascripts/*.coffee'), SASS_PATH = path.join(ROOT_PATH, 'stylesheets/**/*.scss'), STYLESHEETS_PATH = path.join(ROOT_PATH, 'public/stylesheets'), JAVASCRIPTS_PATH = path.join(ROOT_PATH, 'public/javascripts'); function buildSCSS (files) { files.pipe( sass() ) .pipe( prefix("last 5 Chrome versions") ) .pipe( gulp.dest(STYLESHEETS_PATH) ) } function buildCoffee (files) { files.pipe( include() ) .pipe( coffee({ bare: true }) ) .pipe( gulp.dest(JAVASCRIPTS_PATH) ) } function buildSlim (files) { files.pipe(slim({ pretty: true })) .pipe(gulp.dest("public")); } gulp.task('default', ['sass-watch', 'coffee-watch', 'slim-watch', 'vendor-stylesheets']); gulp.task('build', ['sass-build', 'coffee-build', 'slim-build', 'vendor-stylesheets']); gulp.task('sass-watch', function () { gulp.src(SASS_PATH) .pipe(watch(buildSCSS)) }); gulp.task("coffee-watch", function () { gulp.src(COFFEESCRIPTS_PATH) .pipe(watch(buildCoffee)) }); gulp.task('slim-watch', function() { gulp.src("views/*.slim") .pipe(watch(buildSlim)) }); gulp.task('sass-build', function () { buildSCSS(gulp.src(SASS_PATH)) }); gulp.task("coffee-build", function () { buildCoffee(gulp.src(COFFEESCRIPTS_PATH)) }); gulp.task('slim-build', function() { buildSlim(gulp.src("views/*.slim")) }); gulp.task('vendor-stylesheets', function () { gulp.src([ 'node_modules/normalize.css/normalize.css', 'node_modules/emoji/lib/emoji.css' ]).pipe( gulp.dest(STYLESHEETS_PATH) ) });
JavaScript
0
@@ -838,22 +838,8 @@ fee( -%7B bare: true %7D ) )%0A
5b9582ba12778e024b37a57e61c52c9e30454b31
Update attach.js
frappe/public/js/frappe/form/controls/attach.js
frappe/public/js/frappe/form/controls/attach.js
frappe.ui.form.ControlAttach = frappe.ui.form.ControlData.extend({ make_input: function() { var me = this; this.$input = $('<button class="btn btn-default btn-sm btn-attach">') .html(__("Attach")) .prependTo(me.input_area) .on("click", function() { me.onclick(); }); this.$value = $('<div style="margin-top: 5px;">\ <div class="ellipsis" style="display: inline-block; width: 90%;">\ <i class="fa fa-paper-clip"></i> \ <a class="attached-file" target="_blank"></a>\ </div>\ <a class="close">&times;</a></div>') .prependTo(me.input_area) .toggle(false); this.input = this.$input.get(0); this.set_input_attributes(); this.has_input = true; this.$value.find(".close").on("click", function() { me.clear_attachment(); }); }, clear_attachment: function() { var me = this; if(this.frm) { me.frm.attachments.remove_attachment_by_filename(me.value, function() { me.parse_validate_and_set_in_model(null); me.refresh(); me.frm.save(); }); } else { this.dataurl = null; this.fileobj = null; this.set_input(null); this.refresh(); } }, onclick: function() { var me = this; if(this.doc) { var doc = this.doc.parent && frappe.model.get_doc(this.doc.parenttype, this.doc.parent) || this.doc; if (doc.__islocal) { frappe.msgprint(__("Please save the document before uploading.")); return; } } if(!this.dialog) { this.dialog = new frappe.ui.Dialog({ title: __(this.df.label || __("Upload")), fields: [ {fieldtype:"HTML", fieldname:"upload_area"}, {fieldtype:"HTML", fieldname:"or_attach", options: __("Or")}, {fieldtype:"Select", fieldname:"select", label:__("Select from existing attachments") }, {fieldtype:"Button", fieldname:"clear", label:__("Clear Attachment"), click: function() { me.clear_attachment(); me.dialog.hide(); } }, ] }); } this.dialog.show(); this.dialog.get_field("upload_area").$wrapper.empty(); // select from existing attachments var attachments = this.frm && this.frm.attachments.get_attachments() || []; var select = this.dialog.get_field("select"); if(attachments.length) { attachments = $.map(attachments, function(o) { return o.file_url; }); select.df.options = [""].concat(attachments); select.toggle(true); this.dialog.get_field("or_attach").toggle(true); select.refresh(); } else { this.dialog.get_field("or_attach").toggle(false); select.toggle(false); } select.$input.val(""); // show button if attachment exists this.dialog.get_field('clear').$wrapper.toggle(this.get_model_value() ? true : false); this.set_upload_options(); frappe.upload.make(this.upload_options); }, set_upload_options: function() { var me = this; this.upload_options = { parent: this.dialog.get_field("upload_area").$wrapper, args: {}, allow_multiple: 0, max_width: this.df.max_width, max_height: this.df.max_height, options: this.df.options, btn: this.dialog.set_primary_action(__("Upload")), on_no_attach: function() { // if no attachmemts, // check if something is selected var selected = me.dialog.get_field("select").get_value(); if(selected) { me.parse_validate_and_set_in_model(selected); me.dialog.hide(); me.frm.save(); } else { frappe.msgprint(__("Please attach a file or set a URL")); } }, callback: function(attachment) { me.on_upload_complete(attachment); me.dialog.hide(); }, onerror: function() { me.dialog.hide(); } }; if ("is_private" in this.df) { this.upload_options.is_private = this.df.is_private; } if(this.frm) { this.upload_options.args = { from_form: 1, doctype: this.frm.doctype, docname: this.frm.docname }; } else { this.upload_options.on_attach = function(fileobj, dataurl) { me.dialog.hide(); me.fileobj = fileobj; me.dataurl = dataurl; if(me.on_attach) { me.on_attach(); } if(me.df.on_attach) { me.df.on_attach(fileobj, dataurl); } me.on_upload_complete(); }; } }, set_input: function(value, dataurl) { this.value = value; if(this.value) { this.$input.toggle(false); if(this.value.indexOf(",")!==-1) { var parts = this.value.split(","); var filename = parts[0]; dataurl = parts[1]; } this.$value.toggle(true).find(".attached-file") .html(filename || this.value) .attr("href", dataurl || this.value); } else { this.$input.toggle(true); this.$value.toggle(false); } }, get_value: function() { if(this.frm) { return this.value; } else { return this.fileobj ? (this.fileobj.filename + "," + this.dataurl) : null; } }, on_upload_complete: function(attachment) { if(this.frm) { this.parse_validate_and_set_in_model(attachment.file_url); this.refresh(); this.frm.attachments.update_attachment(attachment); this.frm.save(); } else { this.value = this.get_value(); this.refresh(); } }, });
JavaScript
0.000085
@@ -427,17 +427,16 @@ fa-paper -- clip%22%3E%3C/
8d2ed08e5c49cb96e9cc0aa7fff5556b8d2317f3
Update user.js
js/user.js
js/user.js
const User = (function(){ function User(container, nick){ this.container = container; this.isOp = false; this.isVoice = false; this.nick = nick; } User.prototype.remove = function(){ removeNode(this.container); }; User.prototype.op = function(){ const nick = this.container.getElementsByClassName("nick")[0]; nick.innerHTML = "@"+this.nick; nick.className += " op"; this.isOp = true; }; User.prototype.deop = function(){ const nick = this.container.getElementsByClassName("nick")[0]; if(this.isVoice){ nick.innerHTML = "+"+this.nick; }else{ nick.innerHTML = this.nick; } var split = nick.className.split(" "); split.splice(split.indexOf("op"), 1); nick.className = split.join(" "); this.isOp = false; }; User.prototype.voice = function(){ var nick = this.container.getElementsByClassName("nick")[0]; nick.className += " voice"; if(!this.isOp){ nick.innerHTML = "+"+this.nick; } this.isVoice = true; }; User.prototype.devoice = function(){ const nick = this.container.getElementsByClassName("nick")[0]; if(!this.isOp){ nick.innerHTML = this.nick; } var split = nick.className.split(" "); split.splice(split.indexOf("voice"), 1); nick.className = split.join(" "); this.isVoice = false; }; User.prototype.inaktiv = function(){ this.container.getElementsByClassName("nick")[0].className += " inaktiv"; }; User.prototype.uninaktiv = function(){ const dom = this.container.getElementsByClassName("nick")[0]; var className = dom.className.split(" "); var pos; if((pos = className.indexOf("inaktiv")) !== -1){ className.splice(pos, 1); } dom.className = className.join(" "); }; User.prototype.updateNick = function(nick){ const dom = this.container.getElementsByClassName("nick")[0]; if(this.isOp){ dom.innerHTML = "@"+nick; }else if(this.isVoice){ dom.innerHTML = "+"+nick; }else{ dom.innerHTML = nick; } this.nick = nick; }; return User; })();
JavaScript
0.000001
@@ -35,16 +35,24 @@ on User( +system, containe @@ -164,16 +164,42 @@ = nick;%0A + this.system = system;%0A %7D%0A%0A U
3cbcf228c05ad7d199f8cd9a4aa39d0c92c29f27
add tsv to object list
parser/node_modules/utils.js
parser/node_modules/utils.js
var moment = require('moment-timezone'); exports.parseInteger = function (text) { if (text == '') return undefined; if (text == '#NV') return undefined; if (/[0-9]+/.test(text)) return parseInt(text, 10); console.error('Was für ein Integer ist "'+text+'"?'); } exports.parseDateTime = function (date) { var m = moment.tz(date, 'DD.MM.YY HH:mm:ss', 'Europe/Zurich'); if (!m.isValid()) console.log(date); return m.unix(); } exports.decToHex = function (v, n) { var t = v.toString(16).toUpperCase(); if (n && (t.length < n)) { t = ('0000000000000000'+t).substr(16+t.length-n); } return t; }
JavaScript
0
@@ -33,16 +33,40 @@ ezone'); +%0Avar fs = require('fs'); %0A%0Aexport @@ -620,8 +620,325 @@ urn t;%0A%7D +%0A%0Aexports.readListOfObjects = function (file) %7B%0A%09file = fs.readFileSync(file, 'utf8').split('%5Cn');%0A%09var header = file.shift().split('%5Ct');%0A%09var list = file.map(function (line) %7B%0A%09%09var obj = %7B%7D;%0A%09%09line.split('%5Ct').forEach(function (value, index) %7B%0A%09%09%09obj%5Bheader%5Bindex%5D%5D = value;%0A%09%09%7D)%0A%09%09return obj;%0A%09%7D);%0A%09return list;%0A%7D
febb26e935c40e59e3b6e8172c874dd8fab77b5c
allow button of different sizes in df
frappe/public/js/frappe/form/controls/button.js
frappe/public/js/frappe/form/controls/button.js
frappe.ui.form.ControlButton = frappe.ui.form.ControlData.extend({ can_write() { // should be always true in case of button return true; }, make_input: function() { var me = this; const btn_type = this.df.primary ? 'btn-primary': 'btn-default'; this.$input = $(`<button class="btn btn-xs ${btn_type}">`) .prependTo(me.input_area) .on("click", function() { me.onclick(); }); this.input = this.$input.get(0); this.set_input_attributes(); this.has_input = true; this.toggle_label(false); }, onclick: function() { if (this.frm && this.frm.doc) { if (this.frm.script_manager.has_handlers(this.df.fieldname, this.doctype)) { this.frm.script_manager.trigger(this.df.fieldname, this.doctype, this.docname); } else { if (this.df.options) { this.run_server_script(); } } } else if (this.df.click) { this.df.click(); } }, run_server_script: function() { // DEPRECATE var me = this; if(this.frm && this.frm.docname) { frappe.call({ method: "run_doc_method", args: {'docs': this.frm.doc, 'method': this.df.options }, btn: this.$input, callback: function(r) { if(!r.exc) { me.frm.refresh_fields(); } } }); } }, hide() { this.$input.hide(); }, set_input_areas: function() { this._super(); $(this.disp_area).removeClass().addClass("hide"); }, set_empty_description: function() { this.$wrapper.find(".help-box").empty().toggle(false); }, set_label: function(label) { if (label) { this.df.label = label; } label = (this.df.icon ? frappe.utils.icon(this.df.icon) : "") + __(this.df.label); $(this.label_span).html("&nbsp;"); this.$input && this.$input.html(label); } });
JavaScript
0
@@ -249,16 +249,98 @@ fault';%0A +%09%09const btn_size = this.df.btn_size%0A%09%09%09? %60btn-$%7Bthis.df.btn_size%7D%60%0A%09%09%09: %22btn-xs%22;%0A %09%09this.$ @@ -369,22 +369,27 @@ ss=%22btn +$%7B btn --xs +_size%7D $%7Bbtn_t
0a9fcce055761f5e5d2f61e114c8eba8ea5447ae
fix eslint
src/presets/obfs-http.js
src/presets/obfs-http.js
import fs from 'fs'; import crypto from 'crypto'; import {IPreset} from './defs'; /** * parse text file into {request: response} pairs * @param file * @returns {Array} */ function parseFile(file) { const txt = fs.readFileSync(file, {encoding: 'utf-8'}); const lines = txt.split(/\r\n|\n|\r/); const parts = []; let part = ''; for (const line of lines) { switch (line[0]) { case '=': case '-': if (part !== '') { part += '\r\n'; parts.push(part); part = ''; } break; default: part += line; part += '\r\n'; break; } } const pairs = []; for (let i = 0; i < parts.length; i += 2) { const prev = parts[i]; const next = parts[i + 1]; pairs.push({ request: Buffer.from(prev), response: Buffer.from(next) }); } return pairs; } /** * @description * Wrap packet with pre-shared HTTP header in the first request/response. * * @params * file: A text file which contains several HTTP header paris. * * @examples * { * "name": "obfs-http", * "params": { * "file": "http-fake.txt" * } * } * * @protocol * * C ---- [http header][data] ---> S * C <---------- [data] ---------> S * */ export default class ObfsHttpPreset extends IPreset { static pairs = null; _isHeaderSent = false; _isHeaderRecv = false; _response = null; static checkParams({file}) { if (typeof file !== 'string' || file === '') { throw Error('\'file\' must be a non-empty string'); } } static onInit({file}) { ObfsHttpPreset.pairs = parseFile(file); } onDestroy() { this._response = null; } clientOut({buffer, next}) { if (!this._isHeaderSent) { const {pairs} = ObfsHttpPreset; this._isHeaderSent = true; const index = crypto.randomBytes(1)[0] % pairs.length; const {request} = pairs[index]; return Buffer.concat([request, buffer]); } else { return buffer; } } serverIn({buffer, next, fail}) { if (!this._isHeaderRecv) { const found = ObfsHttpPreset.pairs.find(({request}) => buffer.indexOf(request) === 0); if (found !== undefined) { this._isHeaderRecv = true; this._response = found.response; return buffer.slice(found.request.length); } else { return fail('http header mismatch'); } } else { return buffer; } } serverOut({buffer}) { if (!this._isHeaderSent) { this._isHeaderSent = true; return Buffer.concat([this._response, buffer]); } else { return buffer; } } clientIn({buffer, next, fail}) { if (!this._isHeaderRecv) { const found = ObfsHttpPreset.pairs.find(({response}) => buffer.indexOf(response) === 0); if (found !== undefined) { this._isHeaderRecv = true; return buffer.slice(found.response.length); } else { return fail('http header mismatch'); } } else { return buffer; } } }
JavaScript
0.000007
@@ -1713,22 +1713,16 @@ (%7Bbuffer -, next %7D) %7B%0A @@ -2022,38 +2022,32 @@ erverIn(%7Bbuffer, - next, fail%7D) %7B%0A if @@ -2647,14 +2647,8 @@ fer, - next, fai
3ebd0e0d57c504650daed075584387e1d2b2695e
Remove evolve alias
generators/app/utils.js
generators/app/utils.js
'use strict'; const R = require('ramda'); /** * Turn a string into a nice title. * @param {String} * @returns {String} * @example toTitle('some-slug_string'); => Some Slug String */ const toTitle = R.pipe( // String => Array R.split(/[\W_]+/), // Array => Array R.map(word => word.replace(/^\w/, R.toUpper)), // Array => String R.join(' ') ); /** * Turn a string into a slug. * Inspired by https://gist.github.com/juanmhidalgo/3146760 * @param {String} * @returns {String} * @example toSlug('Nice Title!'); => nice-title */ const toSlug = R.pipe( R.toLower, // Replace accent chars (TODO: needed?) R.replace(/[\u00C0-\u00C5]/ig, 'a'), R.replace(/[\u00C8-\u00CB]/ig, 'e'), R.replace(/[\u00CC-\u00CF]/ig, 'i'), R.replace(/[\u00D2-\u00D6]/ig, 'o'), R.replace(/[\u00D9-\u00DC]/ig, 'u'), R.replace(/[\u00D1]/ig, 'n'), R.replace(/[^a-z0-9 ]+/gi, ''), R.trim, R.replace(/\s/g, '-'), R.replace(/[\-]{2}/g, ''), R.replace(/[^a-z\- ]*/gi, '') ); /** * Is a string a valid "slug"? * @param {String} * @returns {Boolean} * @example isSlug('no way Jose'); => false */ const isSlug = R.test(/^[a-z]{1}[a-z0-9\-]*[^\-]$/); /** * Is an object's `length` sufficient? * @param {Number} * @param {Array|String} * @returns {Boolean} * @example isLongAs(3, [1,2,3]); => true * @example isLongAs(5, 'abcde'); => true * @example isLongAs(4, [1,2,3]); => false */ const isLongAs = R.curry((len, obj) => obj.length >= len); /** * @see http://ramdajs.com/docs/#evolve * @param {Object} * @param {Object} * @returns {Object} * @example * evolve({name: toSlug}, {name: 'Ricky Bobby'}); * => {name: 'ricky-bobby'} */ const evolve = R.evolve; module.exports = { evolve, isLongAs, isSlug, toSlug, toTitle };
JavaScript
0.000002
@@ -1464,233 +1464,8 @@ );%0A%0A -/**%0A * @see http://ramdajs.com/docs/#evolve%0A * @param %7BObject%7D%0A * @param %7BObject%7D%0A * @returns %7BObject%7D%0A * @example%0A * evolve(%7Bname: toSlug%7D, %7Bname: 'Ricky Bobby'%7D);%0A * =%3E %7Bname: 'ricky-bobby'%7D%0A */%0Aconst evolve = R.evolve;%0A%0A modu @@ -1483,18 +1483,8 @@ = %7B%0A - evolve,%0A is
5c3518e8e834e38e3d8d21dbe73b6131ab87085b
create a copy of options before modifying to prevent problems in callbacks
google-api-async.js
google-api-async.js
// kill logs var Log = function () {} GoogleApi = { // host component, shouldn't change _host: 'https://www.googleapis.com', _callAndRefresh: function(method, path, options, callback) { var self = this; options = options || {}; self._call(method, path, options, // need to bind the env here so we can do mongo writes in the callback // (when refreshing), if we call this on the server Meteor.bindEnvironment(function(error, result) { if (error && error.response && error.response.statusCode == 401) { Log('google-api attempting token refresh'); return self._refresh(options.user, function(error) { if (error) return callback(error); // if we have the user, we'll need to re-fetch them, as their // access token will have changed. if (options.user) options.user = Meteor.users.findOne(options.user._id); self._call(method, path, options, callback); }); } else { callback(error, result); } }, 'Google Api callAndRefresh')); }, // call a GAPI Meteor.http function if the accessToken is good _call: function(method, path, options, callback) { Log('GoogleApi._call, path:' + path); options = options || {}; var user = options.user || Meteor.user(); delete options.user; if (user && user.services && user.services.google && user.services.google.accessToken) { options.headers = options.headers || {}; options.headers.Authorization = 'Bearer ' + user.services.google.accessToken; HTTP.call(method, this._host + '/' + path, options, function(error, result) { callback(error, result && result.data); }); } else { callback(new Meteor.Error(403, "Auth token not found." + "Connect your google account")); } }, _refresh: function(user, callback) { Log('GoogleApi._refresh'); Meteor.call('exchangeRefreshToken', user && user._id, function(error, result) { callback(error, result && result.access_token) }); } } // setup HTTP verbs httpVerbs = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']; _.each(httpVerbs, function(verb) { GoogleApi[verb.toLowerCase()] = wrapAsync(function(path, options, callback) { if (_.isFunction(options)) { callback = options; options = {}; } return this._callAndRefresh(verb, path, options, callback); }) });
JavaScript
0
@@ -237,24 +237,16 @@ %7C%7C %7B%7D;%0A - %0A sel @@ -275,23 +275,16 @@ options, - %0A / @@ -352,17 +352,16 @@ callback - %0A / @@ -720,29 +720,17 @@ error);%0A - %0A + @@ -945,21 +945,9 @@ d);%0A - %0A + @@ -1118,19 +1118,17 @@ );%0A %7D,%0A - %0A + // cal @@ -1283,41 +1283,83 @@ h);%0A +%0A -%0A options = options %7C%7C %7B%7D; +// copy existing options to modify%0A options = _.extend(%7B%7D, options) %0A @@ -1659,20 +1659,16 @@ sToken;%0A - %0A H
e0b9629326b851c8e8799c79296b5520b4eb8542
Put MDAO in context so it works
src/foam/nanos/crunch/lite/CapableAdapterDAO.js
src/foam/nanos/crunch/lite/CapableAdapterDAO.js
/** * @license * Copyright 2020 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.nanos.crunch.lite', name: 'CapableAdapterDAO', extends: 'foam.dao.AbstractDAO', javaImports: [ 'foam.dao.DAO', 'foam.dao.MDAO', 'java.util.Arrays' ], documentation: ` Adapts a Capable object to the DAO interface. `, properties: [ { name: 'capable', class: 'FObjectProperty', of: 'foam.nanos.crunch.lite.Capable' }, // { // name: 'of', // value: 'foam.nanos.crunch.lite.CapablePayloads' // } ], methods: [ { name: 'put_', javaCode: ` CapablePayload payload = (CapablePayload) obj; CapablePayload[] payloads = getCapable().getCapablePayloads(); for ( int i = 0 ; i < payloads.length ; i++ ) { if ( payload.getCapability().getId().equals( payloads[i].getCapability().getId() ) ) { payloads[i] = payload; return obj; } } payloads = Arrays.copyOf(payloads, payloads.length + 1); payloads[payloads.length - 1] = payload; getCapable().setCapablePayloads(payloads); return obj; ` }, { name: 'remove_', javaCode: ` return obj; // TODO ` }, { name: 'find_', javaCode: ` String idString = null; if ( id instanceof CapablePayload ) { idString = ((CapablePayload) id).getCapability().getId(); } else { idString = (String) id; } CapablePayload[] payloads = getCapable().getCapablePayloads(); for ( int i = 0 ; i < payloads.length ; i++ ) { if ( payloads[i].getCapability().getId().equals(idString) ) { return payloads[i]; } } return null; ` }, { name: 'select_', javaCode: ` DAO mdao = new MDAO(CapablePayload.getOwnClassInfo()); CapablePayload[] payloads = getCapable().getCapablePayloads(); for ( int i = 0 ; i < payloads.length ; i++ ) { mdao.put_(x,payloads[i]); } return mdao.select_(x, sink, skip, limit, order, predicate); ` } ] });
JavaScript
0.000186
@@ -245,24 +245,43 @@ aImports: %5B%0A + 'foam.core.X',%0A 'foam.da @@ -2072,16 +2072,68 @@ nfo());%0A + X xTmp = x.put(%22capablePayloadMDAO%22, mdao);%0A @@ -2265,20 +2265,74 @@ -m +DAO dao = (DAO) xTmp.get(%22capablePayloadMDAO%22);%0A dao.put -_(x, +( payl
38058dfdb5aaa1dc1396620125c5b1ef733c0be7
Fix bad Require annotation.
projects/bugtrace/js/src/BugTrace.js
projects/bugtrace/js/src/BugTrace.js
/* * Copyright (c) 2014 airbug inc. http://airbug.com * * bugtrace may be freely distributed under the MIT license. */ //------------------------------------------------------------------------------- // Annotations //------------------------------------------------------------------------------- //@Export('bugtrace.BugTrace') //@Require('Class') //@Require('Obj') //@Require('Proxy') //@Require('Trace') //------------------------------------------------------------------------------- // Context //------------------------------------------------------------------------------- require('bugpack').context("*", function(bugpack) { //------------------------------------------------------------------------------- // BugPack //------------------------------------------------------------------------------- var Class = bugpack.require('Class'); var Obj = bugpack.require('Obj'); var Proxy = bugpack.require('Proxy'); var Tracer = bugpack.require('Tracer'); //------------------------------------------------------------------------------- // Declare Class //------------------------------------------------------------------------------- /** * @class * @extends {Obj} */ var BugTrace = Class.extend(Obj, { _name: "bugtrace.BugTrace" }); //------------------------------------------------------------------------------- // Proxy Static Methods //------------------------------------------------------------------------------- Proxy.proxy(BugTrace, Proxy.object(Tracer), [ "$error", "$name", "$trace", "$traceWithError", "enable", "getNamedStack" ]); //------------------------------------------------------------------------------- // Export //------------------------------------------------------------------------------- bugpack.export('bugtrace.BugTrace', BugTrace); });
JavaScript
0
@@ -401,24 +401,25 @@ quire('Trace +r ')%0A%0A%0A//-----
d2f3e1e1162b68176b5fc21bc8655b31f6916606
Add rmdir and unlink methods to WebDAV client
lib/protocols/webdav.js
lib/protocols/webdav.js
'use strict'; var events = require('events'); var fs = require('fs'); var http = require('http'); var path = require('path'); var url = require('url'); var util = require('util'); var merge = require('merge'); var request = require('request'); function WebDAVClient(options) { this.options = options; this.baseURL = url.parse(options.baseURL); } util.inherits(WebDAVClient, events.EventEmitter); WebDAVClient.prototype.request = function (method, remotePath, body, callback) { if (typeof body === 'function') { callback = body; body = null; } var options = (typeof method === 'string') ? {method: method} : method; options.url = url.format(merge(true, this.baseURL, {pathname: path.join(this.baseURL.pathname, remotePath)})); options.auth = this.options.credentials; if (body) { options.body = body; } return request(options, function (err, response, body) { if (typeof callback === 'function') { if (err) { return callback(err); } if (response.statusCode > 300) { var error = new Error('WebDAV request error'); error.statusCode = response.statusCode; error.statusMessage = response.statusMessage || http.STATUS_CODES[response.statusCode]; return callback(error); } return callback(err, body); } }); }; WebDAVClient.prototype.propfind = function (path, depth, callback) { if (typeof depth === 'function') { callback = depth; depth = 0; } this.request({ method: 'PROPFIND', headers: { 'Content-Type': 'text/xml', 'Depth': depth, } }, path, callback); }; WebDAVClient.prototype.connect = function () { var self = this; self.propfind('/', function (error, body) { if (error) { self.emit('error', error); } else { self.emit('ready'); } }); }; WebDAVClient.prototype.createReadStream = function (path, options) { return this.request('GET', path).on('response', function (response) { if (response.statusCode >= 400) { var error = new Error('WebDAV request error'); error.statusCode = response.statusCode; error.statusMessage = response.statusMessage || http.STATUS_CODES[response.statusCode]; response.destroy(error); } }); }; WebDAVClient.prototype.createWriteStream = function (path, options) { return this.request('PUT', path).on('response', function (response) { if (response.statusCode >= 400) { var error = new Error('WebDAV request error'); error.statusCode = response.statusCode; error.statusMessage = response.statusMessage || http.STATUS_CODES[response.statusCode]; response.destroy(error); } }); }; WebDAVClient.prototype.get = function(remote, local, callback) { var stream = this.createReadStream(remote).on('error', callback).pipe(fs.createWriteStream(local)); stream.on('finish', callback); stream.on('error', callback); }; WebDAVClient.prototype.mkdir = function(path, mode, callback) { if (typeof mode === 'function') { callback = mode; mode = null; } this.request('MKCOL', path, function (error) { return callback(error); }); }; WebDAVClient.prototype.put = function(local, remote, callback) { var stream = fs.createReadStream(local).on('error', callback).pipe(this.createWriteStream(remote)); stream.on('finish', callback); stream.on('error', callback); }; module.exports = WebDAVClient;
JavaScript
0
@@ -3422,16 +3422,446 @@ k);%0A%7D;%0A%0A +WebDAVClient.prototype.rmdir = function (path, callback) %7B%0A if (path.charAt(path.length - 1) !== '/') %7B%0A path += '/';%0A %7D%0A%0A this.request(%7B%0A method: 'DELETE',%0A headers: %7B%0A 'Depth': 'infinity',%0A %7D%0A %7D, path, function (error) %7B%0A return callback(error);%0A %7D);%0A%7D;%0A%0AWebDAVClient.prototype.unlink = function (path, callback) %7B%0A this.request('DELETE', path, function (error) %7B%0A return callback(error);%0A %7D);%0A%7D;%0A%0A module.e
593c8dce853fba4889f904b2931a1a4560fa89d2
use rpid rather than dcid
client/js/modules/dc/views/reprocessoverview.js
client/js/modules/dc/views/reprocessoverview.js
define(['marionette', 'collections/reprocessings', 'collections/reprocessingparameters', 'collections/reprocessingimagesweeps', 'views/table', 'utils/table'], function(Marionette, Reprocessings, ReprocessingParamters, ReprocessingImageSweeps, TableView, table) { var StatusCell = Backgrid.Cell.extend({ render: function() { var icons = { 2: '<i class="fa icon grey fa-pause alt="Waiting" title="Waiting"></i>', null: '<i class="fa icon grey fa-cog fa-spin alt="Running" title="Running"></i>', 1: '<i class="fa icon green fa-check alt="Completed" title="Completed"></i>', 0: '<i class="fa icon red fa-times alt="Failed" title="Failed"></i>', } if (this.model.get('STATUS') in icons) this.$el.append(icons[this.model.get('STATUS')]) return this } }) var ArgsCell = Backgrid.Cell.extend({ initialize: function(options) { ArgsCell.__super__.initialize.call(this, options) this.params = new ReprocessingParamters() console.log('col', this.column, 'opts', options) this.listenTo(this.column.get('params'), 'sync reset', this.syncParams) this.syncParams() this.sweeps = new ReprocessingImageSweeps() this.listenTo(this.column.get('sweeps'), 'sync reset', this.syncSweeps) this.syncSweeps() }, syncParams: function() { var sw = this.column.get('params').where({ PROCESSINGJOBID: this.model.get('PROCESSINGJOBID') }) this.params.reset(sw) }, syncSweeps: function() { var sw = this.column.get('sweeps').where({ PROCESSINGJOBID: this.model.get('PROCESSINGJOBID') }) this.sweeps.reset(sw) }, render: function() { var columns = [ { name: 'PARAMETERKEY', label: 'Key', cell: 'string', editable: false }, { name: 'PARAMETERVALUE', label: 'Value', cell: 'string', editable: false }, ] var ptable = new TableView({ collection: this.params, columns: columns, loading: false, pages: false, backgrid: { emptyText: 'No parameters found' }, }) this.$el.html(ptable.render().$el) var columns = [ { label: 'Files', cell: table.TemplateCell, editable: false, template: '<a href="/dc/visit/<%-VISIT%>/id/<%-DATACOLLECTIONID%>"><%-IMAGEDIRECTORY%><%-IMAGEPREFIX%>_<%-DATACOLLECTIONNUMBER%></a>' }, { label: 'Image #', cell: table.TemplateCell, editable: false, template: '<%-STARTIMAGE%> - <%-ENDIMAGE%>' }, ] var stable = new TableView({ collection: this.sweeps, columns: columns, loading: false, pages: false, backgrid: { emptyText: 'No image sweeps found' }, }) this.$el.append(stable.render().$el) return this }, }) var ResultsCell = Backgrid.Cell.extend({ render: function() { if (this.model.get('RLOW')) { var columns = [ { name: 'KEY', label: '', cell: 'string', editable: false }, { name: 'VALUE', label: 'Overall', cell: 'string', editable: false }, ] var results = [] _.each({ 'Low Resolution': 'RLOW', 'High Resolution': 'RHIGH', 'Total Observations': 'NTOBS', 'Multiplicity': 'MULTIPLICITY', 'Rmerge': 'RMERGE', 'I/sig(I)': 'ISIGI', 'Completeness': 'COMPLETENESS', }, function(v, k) { results.push({ KEY: k, VALUE: this.model.get(v) }) }, this) this.results = new Backbone.Collection(results) console.log('results', this.results) var rtable = new TableView({ collection: this.results, columns: columns, loading: false, pages: false, backgrid: { emptyText: 'No results found' }, }) this.$el.html(rtable.render().$el) } return this }, }) return Marionette.LayoutView.extend({ template: _.template('<% if (!EMBED) { %><h1>Reprocessing</h1><p class="help">Here you can find all reprocessing jobs and their statuses</p><% } %><div class="filter"></div><div class="wrapper"></div>'), className: 'content', regions: { rwrap: '.wrapper', rflt: '.filter', }, templateHelpers: function() { return { EMBED: this.getOption('embed') } }, initialize: function(options) { if (!options.collection) { this.collection = new Reprocessings() this.collection.queryParams.visit = options.visit this.collection.fetch() } this.parameters = new ReprocessingParamters() this.parameters.queryParams.visit = options.visit this.parameters.state.pageSize = 9999 this.sweeps = new ReprocessingImageSweeps() this.sweeps.queryParams.visit = options.visit this.sweeps.state.pageSize = 9999 this.listenTo(this.collection, 'sync', this.refreshArgs) }, refreshArgs: function() { var ids = this.collection.pluck('DATACOLLECTIONID') this.sweeps.fetch({ data: { ids: ids } }) this.parameters.fetch({ data: { ids: ids } }) }, onRender: function() { var columns = [ { label: 'Status', cell: StatusCell, editable: false }, { label: 'Sample', cell: table.TemplateCell, editable: false, template: '<a href="/samples/sid/<%-BLSAMPLEID%>"><%-SAMPLE%></a> - <a href="/proteins/pid/<%-PROTEINID%>"><%-PROTEIN%></a>' }, { label: 'DC', cell: table.TemplateCell, editable: false, template: '<a href="/dc/visit/<%-VISIT%>/id/<%-DATACOLLECTIONID%>"><%-IMAGEPREFIX%></a>' }, { name: 'DISPLAYNAME', label: 'Process', cell: 'string', editable: false }, { name: 'COMMENTS', label: 'Comments', cell: 'string', editable: false }, { name: 'LASTUPDATETIMESTAMP', label: 'Last Updated', cell: 'string', editable: false }, { name: 'PROCESSINGMESSAGE', label: 'Last Message', cell: 'string', editable: false }, { label: 'Arguments', cell: ArgsCell, editable: false, sweeps: this.sweeps, params: this.parameters }, ] if (this.getOption('results')) columns.push( { label: 'Results', cell: ResultsCell, editable: false } ) this.rwrap.show(new TableView({ columns: columns, collection: this.collection, backgrid: { emptyText: 'No reprocessings found' }, })) }, onDestroy: function() { this.collection.stop() }, }) })
JavaScript
0.000003
@@ -6357,30 +6357,29 @@ .pluck(' -DATACOLLECTION +PROCESSINGJOB ID')%0A
d393270d4ee1a541b089c6214e8d71f3d368fd4d
Update test value
lib/node_modules/@stdlib/string/utf16-to-utf8-array/test/test.js
lib/node_modules/@stdlib/string/utf16-to-utf8-array/test/test.js
'use strict'; // MODULES // var tape = require( 'tape' ); var utf16ToUTF8Array = require( './../lib' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.strictEqual( typeof utf16ToUTF8Array, 'function', 'main export is a function' ); t.end(); }); tape( 'the function throws an error if not provided a string', function test( t ) { var values; var i; values = [ 5, NaN, true, false, null, void 0, [], {}, function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { utf16ToUTF8Array( value ); }; } }); tape( 'the function converts a UTF-16 encoded string to an array of integers using UTF-8 encoding', function test( t ) { var expected; var values; var out; var i; values = [ '0123456789', 'abcdefghij', 'klmnopqrst', 'uvwxyz', 'ABCDEFGHIJ', 'KLMNOPQRST', 'UVWXYZ', '☃', // 3 bytes 'æ', // 2 bytes '\ud801\udc37' // surrogate pair ]; /* * U+10437 (𐐷) => 00000000 00000001 00000100 00110111 * * To convert U+10437 to a UTF-8 array, pack the bit sequence (more specifically, the last 21 bits) into 4 bytes using UTF-8 encoding. * * ``` text * 00000000 000 00001 00000100 00110111 * * 00001 00000100 00110111 * * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * * 11110000 10010000 10010000 10110111 * ``` * * To determine the surrogate pair, * * * Subtract 0x10000. * * ``` text * 0x10437 - 0x10000 = 0x00437 => 0000 0000 0100 0011 0111 * ``` * * * Split into high and low 10-bits. * * ``` text * 0000 0000 01 * 00 0011 0111 * ``` * * * Add 0xD800 to high 10-bits to get high surrogate. * * ``` text * 0xD800 + 0x0001 = 0xD801 => 1101100000000001 * ``` * * * Add 0xDC00 to low 10-bits to get low surrogate. * * ``` text * 0xDC00 + 0x0037 = 0xDC37 => 1101110000110111 * ``` */ expected = [ [ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 ], [ 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ], [ 107, 108, 109, 110, 111, 112, 113, 114, 115, 116 ], [ 117, 118, 119, 120, 121, 122 ], [ 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 ], [ 75, 76, 77, 78, 79, 80, 81, 82, 83, 84 ], [ 85, 86, 87, 88, 89, 90 ], [ 226, 152, 131 ], [ 195, 166 ], [ 240, 144, 144, 183 ] ]; for ( i = 0; i < values.length; i++ ) { out = utf16ToUTF8Array( values[ i ] ); t.deepEqual( out, expected[ i ], 'returns expected value for '+values[i] ); } t.end(); });
JavaScript
0.000001
@@ -1077,20 +1077,9 @@ %0A%09%09' -%5Cud801%5Cudc37 +%F0%90%90%B7 ' //
8328f6803349876780bf112db45ccf9d606d0331
Comment out ratelimit isolate level
server/db/ratelimits.js
server/db/ratelimits.js
'use strict'; // 3rd const assert = require('better-assert'); const debug = require('debug')('db:ratelimits'); const _ = require('lodash'); // 1st const dbUtil = require('./util'); // maxDate (Required Date): the maximum, most recent timestamp that the user // can have if they have a row in the table. i.e. if user can only post // every 5 minutes, maxDate will be 5 min in the past. // // If user is ratelimited, it throws the JSDate that the ratelimit expires // that can be shown to the user (e.g. try again in 24 seconds) exports.bump = function * (userId, ipAddress, maxDate) { debug('[bump] userId=%j, ipAddress=%j, maxDate=%j', userId, ipAddress, maxDate); assert(Number.isInteger(userId)); assert(typeof ipAddress === 'string'); assert(_.isDate(maxDate)); const sql = { recentRatelimit: ` SELECT * FROM ratelimits WHERE ip_root(ip_address) = ip_root($1) ORDER BY id DESC LIMIT 1 `, insertRatelimit: ` INSERT INTO ratelimits (user_id, ip_address) VALUES ($1, $2) `, }; return yield dbUtil.withTransaction(function * (client) { yield client.queryPromise('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE'); // Get latest ratelimit for this user const row = yield client.queryOnePromise(sql.recentRatelimit, [ipAddress]); // If it's too soon, throw the Date when ratelimit expires if (row && row.created_at > maxDate) { const elapsed = new Date() - row.created_at; // since ratelimit const duration = new Date() - maxDate; // ratelimit length const expires = new Date(Date.now() + duration - elapsed); throw expires; } // Else, insert new ratelimit yield client.queryPromise(sql.insertRatelimit, [userId, ipAddress]); }); };
JavaScript
0
@@ -1100,24 +1100,97 @@ lient) %7B%0A + // Temporarily disabled as a longshot attempt to prevent issue%0A // -- yield clien
10b60b11099b380e2a0070cd01803f24a910dce0
fix editor shortcut key
demo/index.js
demo/index.js
/* jshint browser: true, devel: true */ /* global SCScript, CodeMirror */ window.onload = function() { "use strict"; var editor; var prev = ""; var update = function(source) { if (prev !== source) { window.location.replace("#" + encodeURIComponent(source)); prev = source; } }; var getCode = function(editor) { var code, cursor, line, range, callback; code = editor.getSelection(); if (!code) { cursor = editor.getCursor(); line = cursor.line; range = getRange(editor, line); if (range) { editor.setSelection({ line: range[0], ch: 0 }, { line: range[1], ch: Infinity }); code = editor.getSelection(); callback = function() { editor.setSelection(cursor); }; } } blink(".codemirror-focused .codemirror-selected", callback); return code; }; var getRange = function(editor, begin) { var lookAt, end, last, line; var depth, code; code = null; lookAt = begin; end = begin; last = editor.lineCount(); depth = 0; while (true) { line = editor.getLine(lookAt); for (var i = 0; i < line.length; ++i) { var ch = line.charAt(i); if (ch === "(" || ch === "[" || ch === "{") { depth += 1; } else if (ch === "}" || ch === "]" || ch === ")") { depth -= 1; } } if (depth === 0) { return [ begin, end ]; } else if (depth < 0) { begin -= 1; if (begin < 0) { return; } lookAt = begin; } else if (depth > 0) { end += 1; if (end > last) { return; } lookAt = end; } } }; var getCssRule = (function() { var cache = {}; return function(selector) { if (!cache[selector]) { [].slice.call(document.styleSheets).forEach(function(sheet) { [].slice.call(sheet.cssRules || sheet.rules).forEach(function(rule) { if (rule.selectorText && rule.selectorText.indexOf(selector) !== -1) { cache[selector] = rule; } }); }); } return cache[selector]; }; })(); var blink = function(selector, callback) { var rule = getCssRule(selector); if (rule) { setTimeout(function() { rule.style.setProperty("-webkit-animation", null); if (callback) { callback(); } }, 250); rule.style.setProperty("-webkit-animation", "blink 0.5s"); } }; editor = CodeMirror.fromTextArea(document.getElementById("editor"), { mode: "SCScript", theme: "sc-mode", indentUnit: 2, tabSize: 2, lineWrapping: true, lineNumbers: true, showCursorWhenSelecting: true, matchBrackets: true, extraKeys: { "Ctrl-Enter": function() { var code, result; code = SCScript.compile(getCode(editor)); result = eval.call(null, code); if (result) { result = result.valueOf(); } console.log(result); } } }); editor.on("keyup", function() { update(editor.getValue()); }); if (window.location.hash) { prev = decodeURIComponent(window.location.hash.substr(1)); editor.setValue(prev); } };
JavaScript
0.000001
@@ -2531,16 +2531,241 @@ %7D%0A %7D;%0A%0A + var execute = function() %7B%0A var code, result;%0A%0A code = SCScript.compile(getCode(editor));%0A%0A result = eval.call(null, code);%0A%0A if (result) %7B%0A result = result.valueOf();%0A %7D%0A%0A console.log(result);%0A %7D;%0A%0A editor @@ -3055,246 +3055,44 @@ r%22: -function() %7B%0A var code, result;%0A%0A code = SCScript.compile(getCode(editor));%0A%0A result = eval.call(null, code);%0A%0A if (result) %7B%0A result = result.valueOf();%0A %7D%0A%0A console.log(result);%0A %7D +execute,%0A %22Cmd-Enter%22 : execute %0A
2f715739ca15c48fd97dd3c520723be54993d4d5
Fix custom emoji display in suggestions (#2519)
src/components/Chat/Input/EmojiSuggestion.js
src/components/Chat/Input/EmojiSuggestion.js
import React from 'react'; import PropTypes from 'prop-types'; import ListItemAvatar from '@mui/material/ListItemAvatar'; import ListItemText from '@mui/material/ListItemText'; import Suggestion from './Suggestion'; import emojiUrl from '../../../utils/emojiUrl'; const shortcode = (emoji) => `:${emoji.shortcode}:`; function EmojiSuggestion({ value: emoji, ...props }) { const url = emojiUrl(emoji.image); return ( <Suggestion {...props}> <ListItemAvatar> <span className="EmojiSuggestion-image" style={{ backgroundImage: `url(${CSS.escape(url.href)})` }} /> </ListItemAvatar> <ListItemText primary={shortcode(emoji)} /> </Suggestion> ); } EmojiSuggestion.propTypes = { value: PropTypes.shape({ shortcode: PropTypes.string, image: PropTypes.string, }).isRequired, }; export default EmojiSuggestion;
JavaScript
0
@@ -166,24 +166,67 @@ tItemText';%0A +import %7B useSelector %7D from 'react-redux';%0A import Sugge @@ -299,16 +299,95 @@ ojiUrl'; +%0Aimport %7B customEmojiNamesSelector %7D from '../../../selectors/configSelectors'; %0A%0Aconst @@ -493,16 +493,140 @@ ps%0A%7D) %7B%0A + const customEmojiNames = useSelector(customEmojiNamesSelector);%0A const isCustom = customEmojiNames.has(emoji.shortcode);%0A const @@ -651,16 +651,26 @@ ji.image +, isCustom );%0A%0A re
e3a4f75ec5500f7b2896d2d875b28478bf93169d
fix a typo
packages/core-js/internals/is-callable.js
packages/core-js/internals/is-callable.js
// `isCallable` abstract operation // https://tc39.es/ecma262/#sec-iscallable module.exports = function (argument) { return typeof argument === 'function'; };
JavaScript
1
@@ -1,13 +1,13 @@ // %60 -i +I sCallabl
dc2ca3a2833831ac4074d092767fd0fadaf67775
Add `Ember.Subarray.prototype.toString`.
packages/ember-runtime/lib/system/subarray.js
packages/ember-runtime/lib/system/subarray.js
var get = Ember.get, forEach = Ember.EnumerableUtils.forEach, RETAIN = 'r', FILTER = 'f'; function Operation (type, count) { this.type = type; this.count = count; } /** An `Ember.SubArray` tracks an array in a way similar to, but more specialized than, `Ember.TrackedArray`. It is useful for keeping track of the indexes of items within a filtered array. @class SubArray @namespace Ember */ Ember.SubArray = function (length) { if (arguments.length < 1) { length = 0; } if (length > 0) { this._operations = [new Operation(RETAIN, length)]; } else { this._operations = []; } }; Ember.SubArray.prototype = { /** Track that an item was added to the tracked array. @method addItem @param {number} index The index of the item in the tracked array. @param {boolean} match `true` iff the item is included in the subarray. @return {number} The index of the item in the subarray. */ addItem: function(index, match) { var returnValue = -1, itemType = match ? RETAIN : FILTER, self = this; this._findOperation(index, function(operation, operationIndex, rangeStart, rangeEnd, seenInSubArray) { var newOperation, splitOperation; if (itemType === operation.type) { ++operation.count; } else if (index === rangeStart) { // insert to the left of `operation` self._operations.splice(operationIndex, 0, new Operation(itemType, 1)); } else { newOperation = new Operation(itemType, 1); splitOperation = new Operation(operation.type, rangeEnd - index + 1); operation.count = index - rangeStart; self._operations.splice(operationIndex + 1, 0, newOperation, splitOperation); } if (match) { if (operation.type === RETAIN) { returnValue = seenInSubArray + (index - rangeStart); } else { returnValue = seenInSubArray; } } self._composeAt(operationIndex); }, function(seenInSubArray) { self._operations.push(new Operation(itemType, 1)); if (match) { returnValue = seenInSubArray; } self._composeAt(self._operations.length-1); }); return returnValue; }, /** Track that an item was removed from the tracked array. @method removeItem @param {number} index The index of the item in the tracked array. @return {number} The index of the item in the subarray, or `-1` if the item was not in the subarray. */ removeItem: function(index) { var returnValue = -1, self = this; this._findOperation(index, function (operation, operationIndex, rangeStart, rangeEnd, seenInSubArray) { if (operation.type === RETAIN) { returnValue = seenInSubArray + (index - rangeStart); } if (operation.count > 1) { --operation.count; } else { self._operations.splice(operationIndex, 1); self._composeAt(operationIndex); } }); return returnValue; }, _findOperation: function (index, foundCallback, notFoundCallback) { var operationIndex, len, operation, rangeStart, rangeEnd, seenInSubArray = 0; // OPTIMIZE: change to balanced tree // find leftmost operation to the right of `index` for (operationIndex = rangeStart = 0, len = this._operations.length; operationIndex < len; rangeStart = rangeEnd + 1, ++operationIndex) { operation = this._operations[operationIndex]; rangeEnd = rangeStart + operation.count - 1; if (index >= rangeStart && index <= rangeEnd) { foundCallback(operation, operationIndex, rangeStart, rangeEnd, seenInSubArray); return; } else if (operation.type === RETAIN) { seenInSubArray += operation.count; } } notFoundCallback(seenInSubArray); }, _composeAt: function(index) { var op = this._operations[index], otherOp; if (!op) { // Composing out of bounds is a no-op, as when removing the last operation // in the list. return; } if (index > 0) { otherOp = this._operations[index-1]; if (otherOp.type === op.type) { op.count += otherOp.count; this._operations.splice(index-1, 1); } } if (index < this._operations.length-1) { otherOp = this._operations[index+1]; if (otherOp.type === op.type) { op.count += otherOp.count; this._operations.splice(index+1, 1); } } } };
JavaScript
0
@@ -4496,15 +4496,214 @@ %7D%0A %7D%0A + %7D,%0A%0A toString: function () %7B%0A var str = %22%22;%0A forEach(this._operations, function (operation) %7B%0A str += %22 %22 + operation.type + %22:%22 + operation.count;%0A %7D);%0A return str.substring(1);%0A %7D%0A%7D;%0A
fcdcf55f599e200c471a16377f549b2f0221b789
add surveyid questionBySurveyId
app/controllers/questions.server.controller.js
app/controllers/questions.server.controller.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Question = mongoose.model('Question'), _ = require('lodash'); /** * Create a Question */ exports.create = function(req, res) { var question = new Question(req.body); question.user = req.user; question.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(question); } }); }; /** * Show the current Question */ exports.read = function(req, res) { res.jsonp(req.question); }; /** * Update a Question */ exports.update = function(req, res) { var question = req.question ; question = _.extend(question , req.body); question.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(question); } }); }; /** * Delete an Question */ exports.delete = function(req, res) { var question = req.question ; question.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(question); } }); }; /** * List of Questions */ exports.list = function(req, res) { Question.find().sort('-created').populate('user', 'displayName').exec(function(err, questions) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(questions); } }); }; /** * Question middleware */ exports.questionByID = function(req, res, next, id) { Question.findById(id).populate('user', 'displayName').exec(function(err, question) { if (err) return next(err); if (! question) return next(new Error('Failed to load Question ' + id)); req.question = question ; next(); }); }; exports.questionBySurveyId= function(req, res, next, id) { Question.find({ surveyId: '' }).populate('user', 'displayName').exec(function(err, question) { if (err) return next(err); if (! question) return next(new Error('Failed to load Question ' + id)); req.question = question ; next(); }); }; /** * Question authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.question.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
JavaScript
0.000832
@@ -1940,16 +1940,40 @@ veyId: ' +55209d8d4416313c18bceb20 ' %7D).pop
d2e6aee0b93c0c4cfa790426d843f201936d601d
Update run.js
Time/run.js
Time/run.js
module.exports = function(context, req) { context.log('Node.js HTTP trigger function processed a request. RequestUri=%s', req.originalUrl); if (req.query.text || (req.body && req.body.text)) { var now = new Date(); context.res = { // status: 200, /* Defaults to 200 */ response_type: "in_channel", body: "Hello " + (req.query.text || req.body.text) + ", it's " + now }; } else { context.res = { status: 400, body: "Please pass a text on the query string or in the request body" }; } context.done(); };
JavaScript
0.000001
@@ -313,16 +313,40 @@ + body: %7B text: %22hello%22, respon @@ -366,17 +366,18 @@ channel%22 -, + %7D %0A @@ -381,22 +381,18 @@ -body: +// %22Hello %22
a7b30b89cd7000283fa77d439c6595a662db8b41
Remove old comment
server/discord/index.js
server/discord/index.js
// Get the required shit together const Discord = require('eris'); const config = require('config'); const utils = require('./utils.js'); require('colors'); const client = new Discord.Client(config.get('api').discord.token); const prefixes = config.get('discord').prefix.user.concat(config.get('discord').prefix.guild); let prefix = null; // Setup commands and util objects. const commands = require('./cogs.js'); client.on('shardReady', (id) => { console.log(`Shard ${id} is online`.green); }); client.on('ready', () => { // Set up regex for the bot. // It's "man's essential illness" // Use this regex for testing in regexr.com // /^(mss).?(ping)\s?([\s\S]*)/ // /(\w+)rly/ prefix = new RegExp(`^(${prefixes.join('|')}).?(${Object.keys(commands).join('|')})\\s?([\\s\\S]*)`, 'i'); // Add mentions to the prefix list prefixes.push(`<@${client.user.id}>`); console.log('All shards are online'.green.bold); // Set up currently playing game client.editStatus('online', { name: 'dmail help', type: 0, url: 'https://discordmail.com/' }); // Send DBOTS info if it was provided. if (config.get('api').botsdiscordpw) { utils.botsdiscordpw(client); setInterval(() => { utils.botsdiscordpw(client); }, 1800000); } // Send FAKEDBOTS info if it was provided. if (config.get('api').discordbotsorg) { utils.discordbotsorg(client); setInterval(() => { utils.discordbotsorg(client); }, 1800000); } // Check for bot collection servers utils.collection.check(client); setInterval(() => { utils.collection.check(client); }, 1800000); client.on('messageCreate', (message) => { // It crashed on this before. No explaination. if (!message.author) return; // Disallow if the author is a bot if (message.author.bot) return; // Test the message content on the regular expression for prefixed commands. const pre = prefix.exec(message.content); // If there's a result, do this crap. if (pre) { message.prefix = pre[1]; message.command = pre[2]; message.input = pre[3] || null; message.name = message.author.username.replace(/ /g, '+') .replace(/\W/g, '=') .toLowerCase(); message.context = config.get('discord').prefix.user.includes(message.prefix.toLowerCase()) ? 'user' : 'guild'; message.inbox = message.context === 'user' ? message.author.id : (message.channel.guild && message.channel.guild.id) || 'Not inside a guild'; // message.words = pre[3].split(/\n+|\s+/g); // Run the actual command commands[message.command.toLowerCase()].command(message, client); } }); }); client.connect(); module.exports = client;
JavaScript
0
@@ -2400,56 +2400,8 @@ ld'; -%0A%09%09%09// message.words = pre%5B3%5D.split(/%5Cn+%7C%5Cs+/g); %0A%0A%09%09
5bf531487ca95f5abbee911d8c88d1ecef132b69
Make close shortcut close focused window, not store window
app/stores/window-store.js
app/stores/window-store.js
'use strict' let AppActions = require('../actions/app-actions') let AppDispatcher = require('../dispatcher/app-dispatcher') let AppConstants = require('../constants/app-constants') let Store = require('./store') let app = require('electron').app let BrowserWindow = require('electron').BrowserWindow let window let quitting = false let WindowStore = Object.assign(new Store('window-store'), { with: (f) => { if (!window) return f(window) } }) function show () { if (window) { AppActions.gain_focus() window.show() return } let width = 1200 let height = 720 window = new BrowserWindow({ title: 'itch', icon: './static/images/itchio-tray-x4.png', width, height, center: true, show: false, 'title-bar-style': 'hidden' }) window.on('close', (e) => { console.log(`window event: close. quitting? ${quitting}`) if (quitting) return e.preventDefault() window.hide() }) window.on('focus', (e) => { console.log(`window event: focus`) AppActions.gain_focus() }) window.webContents.on('dom-ready', (e) => { AppActions.window_ready() window.show() }) window.loadURL(`file://${__dirname}/../index.html`) if (process.env.DEVTOOLS === '1') { window.webContents.openDevTools({detach: true}) } } function hide () { WindowStore.with(w => w.hide()) } function _eval (payload) { if (!window) return let web = window.webContents if (!web) return web.executeJavaScript(payload.code) } AppDispatcher.register('window-store', Store.action_listeners(on => { on(AppConstants.BOOT, show) on(AppConstants.FOCUS_WINDOW, show) on(AppConstants.HIDE_WINDOW, hide) on(AppConstants.EVAL, _eval) on(AppConstants.QUIT, () => { quitting = true app.quit() }) on(AppConstants.CHANGE_USER, () => { if (!window) return let web = window.webContents if (!web) return web.executeJavaScript(` var yes = window.confirm('Are you sure you want to log out?') if (yes) { require('./actions/app-actions').logout() } `) }) on(AppConstants.APPLY_SELF_UPDATE, () => { quitting = true AppActions.apply_self_update_for_realsies() }) })) app.on('before-quit', e => { quitting = true }) app.on('window-all-closed', e => { if (quitting) { console.log(`app event: window-all-closed; quitting, all good`) return } console.log(`app event: window-all-closed; preventing default`) e.preventDefault() }) module.exports = WindowStore
JavaScript
0.000001
@@ -1322,39 +1322,77 @@ %7B%0A -WindowStore.with(w =%3E w.hid +let w = BrowserWindow.getFocusedWindow()%0A if (!w) return%0A w.clos e() -) %0A%7D%0A%0A
5c3e8e68673485f5646458b9d7af8a1eafa41ff1
resolve issue with default plugin instantiation
packages/core/src/service/plugin/index.js
packages/core/src/service/plugin/index.js
// @flow import uuid from 'uuid' import { satisfies } from 'semver' import { ContentPlugin, LayoutPlugin, Plugin } from './classes' import defaultPlugin from './default' import missing from './missing' const find = (name: string, version: string = '*') => (plugin: Plugin): boolean => plugin.name === name && satisfies(plugin.version, version) /** * Iterate through an editable content tree and generate ids where missing. */ export const generateMissingIds = (props: Object): Object => { const { rows, cells, id } = props if ((rows || []).length > 0) { props.rows = rows.map(generateMissingIds) } else if ((cells || []).length > 0) { props.cells = cells.map(generateMissingIds) } return { ...props, id: id || uuid.v4() } } /** * PluginService is a registry of all content and layout plugins known to the editor. */ export default class PluginService { plugins: { content: Array<ContentPlugin>, layout: Array<LayoutPlugin>, } /** * Instantiate a new PluginService instance. You can provide your own set of content and layout plugins here. */ constructor({ content = [], layout = [] }: { content: [], layout: []} = {}) { this.plugins = { content: [defaultPlugin, ...content].map((config: any) => new ContentPlugin(config)), layout: layout.map((config: any) => new LayoutPlugin(config)), } } setLayoutPlugins(plugins: Array<any> = []) { this.plugins.layout = [] plugins.forEach((plugin: any) => this.addLayoutPlugin(plugin)) } addLayoutPlugin(config: any) { this.plugins.layout.push(new LayoutPlugin(config)) } removeLayoutPlugin(name: string) { this.plugins.layout = this.plugins.layout.filter((plugin: LayoutPlugin) => plugin.name !== name) } setContentPlugins(plugins: Array<any> = []) { this.plugins.content = [defaultPlugin] plugins.forEach((plugin: any) => this.addContentPlugin(plugin)) } addContentPlugin(config: any) { this.plugins.content.push(new ContentPlugin(config)) } removeContentPlugin(name: string) { this.plugins.content = this.plugins.content.filter((plugin: ContentPlugin) => plugin.name !== name) } /** * Finds a layout plugin based on its name and version. */ findLayoutPlugin(name: string, version: string): LayoutPlugin { const plugin = this.plugins.layout.find(find(name, version)) // TODO return a default layout plugin here instead if (!plugin) { throw new Error(`Plugin ${name} with version ${version} not found`) } return plugin } /** * Finds a content plugin based on its name and version. */ findContentPlugin(name: string, version: string): ContentPlugin { const plugin = this.plugins.content.find(find(name, version)) return plugin || new ContentPlugin(missing({ name, version })) } /** * Returns a list of all known plugin names. */ getRegisteredNames(): Array<string> { return [ ...this.plugins.content.map(({ name }: Plugin) => name), ...this.plugins.layout.map(({ name }: Plugin) => name) ] } unserialize = (state: any): Object => { const { rows = [], cells = [], content = {}, layout = {}, inline, size, id } = state const newState: Object = { id, inline, size } const { plugin: { name: contentName = null, version: contentVersion = '*' } = {}, state: contentState } = content || {} const { plugin: { name: layoutName = null, version: layoutVersion = '*' } = {}, state: layoutState } = layout || {} if (contentName) { const plugin = this.findContentPlugin(contentName, contentVersion) newState.content = { plugin, state: plugin.unserialize(contentState) } } if (layoutName) { const plugin = this.findLayoutPlugin(layoutName, layoutVersion) newState.layout = { plugin, state: plugin.unserialize(layoutState) } } if ((rows || []).length) { newState.rows = rows.map(this.unserialize) } if ((cells || []).length) { newState.cells = cells.map(this.unserialize) } return generateMissingIds(newState) } serialize = (state: Object): Object => { const { rows = [], cells = [], content, layout, inline, size, id } = state const newState: Object = { id, inline, size } if (content && content.plugin) { newState.content = { plugin: { name: content.plugin.name, version: content.plugin.version }, state: content.plugin.serialize(content.state) } } if (layout && layout.plugin) { newState.layout = { plugin: { name: layout.plugin.name, version: layout.plugin.version }, state: layout.plugin.serialize(layout.state) } } if (rows.length) { newState.rows = rows.map(this.serialize) } if (cells.length) { newState.cells = cells.map(this.serialize) } return newState } }
JavaScript
0.000001
@@ -210,16 +210,19 @@ find = ( +%0A name: st @@ -218,32 +218,34 @@ %0A name: string, +%0A version: string @@ -250,16 +250,17 @@ ng = '*' +%0A ) =%3E (pl @@ -1159,16 +1159,17 @@ yout: %5B%5D + %7D = %7B%7D) @@ -1821,16 +1821,71 @@ ontent = + %5B%5D; // semicolon is required to avoid syntax error%0A %5Bdefaul @@ -1891,29 +1891,29 @@ ltPlugin -%5D%0A +, ... plugins +%5D .forEach
48180f28ba34e84bf47851e34ec25986aeda2100
add weinre
biz/index.js
biz/index.js
var url = require('url'); var https = require('https'); var http = require('http'); var util = require('../util'); var config = util.config; var FULL_WEINRE_HOST = config.WEINRE_HOST + ':' + config.weinreport; function request(req, res, port) { var options = url.parse(util.getFullUrl(req)); options.host = '127.0.0.1'; options.method = req.method; options.hostname = null; if (port) { options.port = port; } req.headers['x-forwarded-for'] = util.getClientIp(req); options.headers = req.headers; req.pipe(http.request(options, function(_res) { res.writeHead(_res.statusCode || 0, _res.headers); res.src(_res); })); } module.exports = function(req, res, next) { var host = req.headers.host; if (host == config.localUIHost) { request(req, res, config.uiport); } else if (host == config.WEINRE_HOST || host == FULL_WEINRE_HOST) { request(req, res, config.weinreport); } else { next(); } };
JavaScript
0.000104
@@ -372,16 +372,42 @@ = null;%0A +%09options.protocol = null;%0A %09if (por
7175724b1282b5eaff096ec60b85a51fbee09802
define indexOfO in jquery
src/public/src/js/app.js
src/public/src/js/app.js
function _App () { var self = this // Configure bower_components path requirejs.config({ paths: { 'localstorage': '../bower_components/local-storage-api/dist/storage.min', 'jquery': '../bower_components/jquery/dist/jquery.min', 'jquery-ui': '../bower_components/jquery-ui/jquery-ui.min', 'vue': '../bower_components/vue/dist/vue.min', 'jquery.ui.touch-punch': '../bower_components/jquery-ui-touch-punch-improved/jquery.ui.touch-punch-improved', 'tablesorter': '../bower_components/tablesorter/jquery.tablesorter.min', 'notify-me': '../bower_components/notify.me/dist/js/notify-me', 'popup': '../bower_components/popupjs/dist/popup.min' } }) // load modules requirejs([ 'vue', 'localstorage', 'jquery', 'jquery-ui', 'format' ], function (v, ls, jq, jqui, f) { self.Vue = v self.Storage = new Storage() requirejs([ 'jquery.ui.touch-punch', 'tablesorter', 'notify-me', 'popup' ], function (jquit, ts, notif, pop) { requirejs([ 'loading', 'top-menu', 'config', 'list' ], function (load, tm, conf, l) { requirejs([ 'left-menu', 'directory' ], function(lm, dir){ requirejs([ 'left-menu' ], function(){ // Update Directory and Hash self.hash = document.location.hash.substring(1) self.TopMenu.setAriane(self.getDirFromHash()) self.Directory.getDir(function(dir){ self.Directory.append(dir) }) $(window).bind('hashchange', function () { self.hash = document.location.hash.substring(1) self.TopMenu.setAriane(self.getDirFromHash()) App.TopMenu.setActions({ download: 'hide', rename: 'hide', remove: 'hide', info: 'hide' }) self.List.clearLines() self.Directory.getDir(function(dir){ self.Directory.append(dir) }) }) // Trigger keydown event $(window).keydown(function (event) { switch (event.keyCode) { case 13: // trigger start / search torrent break } }) // Everithing is loaded self.Loading.hide() }) }) }) }) }) } _App.prototype.getDirFromHash = function () { var dir = this.hash.split('/') || '' for (var i in dir) { if (dir[i] === '') { dir.splice(i, 1) } } return dir } // Global var with all the modules var App = new _App() Array.prototype.indexOfO = function(compFunc){ for(var key in this){ if(compFunc(this[key])){ return key } } return -1 }
JavaScript
0.000003
@@ -892,16 +892,190 @@ torage() +%0A%0A $.indexOfO = function(array, compFunc)%7B%0A for(var key in array)%7B%0A if(compFunc(array%5Bkey%5D))%7B%0A return key%0A %7D%0A %7D%0A return -1%0A %7D%0A %0A req @@ -2909,146 +2909,4 @@ p()%0A -%0AArray.prototype.indexOfO = function(compFunc)%7B%0A for(var key in this)%7B%0A if(compFunc(this%5Bkey%5D))%7B%0A return key%0A %7D%0A %7D%0A return -1%0A%7D%0A
bccc4745b6d8586011400b76d674aee8eb5f7678
Update BaseCollection.methods.js
app/imports/api/base/BaseCollection.methods.js
app/imports/api/base/BaseCollection.methods.js
import { Meteor } from 'meteor/meteor'; import { CallPromiseMixin } from 'meteor/didericis:callpromise-mixin'; import { Roles } from 'meteor/alanning:roles'; import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { _ } from 'meteor/erasaur:meteor-lodash'; import { RadGrad } from '../radgrad/RadGrad'; import { ROLE } from '../role/Role'; import { loadCollectionNewDataOnly } from '../utilities/load-fixtures'; import { Feeds } from '../feed/FeedCollection'; /** * Allows admins to create and return a JSON object to the client representing a snapshot of the RadGrad database. * @memberOf api/base */ export const dumpDatabaseMethod = new ValidatedMethod({ name: 'base.dumpDatabase', validate: null, run() { if (!this.userId) { throw new Meteor.Error('unauthorized', 'You must be logged in to dump the database..', '', Error().stack); } else if (!Roles.userIsInRole(this.userId, [ROLE.ADMIN])) { throw new Meteor.Error('unauthorized', 'You must be an admin to dump the database.', '', Error().stack); } // Don't do the dump except on server side (disable client-side simulation). // Return an object with fields timestamp and collections. if (Meteor.isServer) { const collections = _.sortBy(RadGrad.collectionLoadSequence.map(collection => collection.dumpAll()), entry => entry.name); const timestamp = new Date(); return { timestamp, collections }; } return null; }, }); export const loadFixtureMethod = new ValidatedMethod({ name: 'base.loadFixture', validate: null, run(fixtureData) { if (!this.userId) { throw new Meteor.Error('unauthorized', 'You must be logged in to load a fixture.', '', Error().stack); } else if (!Roles.userIsInRole(this.userId, [ROLE.ADMIN])) { throw new Meteor.Error('unauthorized', 'You must be an admin to load a fixture.', '', Error().stack); } if (Meteor.isServer) { let ret = ''; _.each(RadGrad.collectionLoadSequence, collection => { ret = `${ret} ${loadCollectionNewDataOnly(collection, fixtureData, true)}`; }); // console.log(`loadFixtureMethod ${ret}`); const trimmed = ret.trim(); if (trimmed.length === 0) { ret = 'Defined no new instances.'; } return ret; } return ''; }, }); /** * Meteor method used to define new instances of the given collection name. * @param collectionName the name of the collection. * @param definitionDate the object used in the collection.define method. * @memberOf api/base */ export const defineMethod = new ValidatedMethod({ name: 'BaseCollection.define', mixins: [CallPromiseMixin], validate: null, run({ collectionName, definitionData }) { if (collectionName === Feeds.getCollectionName()) { if (Meteor.isServer) { const collection = RadGrad.getCollection(collectionName); collection.assertValidRoleForMethod(this.userId); return collection.define(definitionData); } } else { const collection = RadGrad.getCollection(collectionName); collection.assertValidRoleForMethod(this.userId); return collection.define(definitionData); } }, }); export const updateMethod = new ValidatedMethod({ name: 'BaseCollection.update', mixins: [CallPromiseMixin], validate: null, run({ collectionName, updateData }) { const collection = RadGrad.getCollection(collectionName); collection.assertValidRoleForMethod(this.userId); collection.update(updateData.id, updateData); return true; }, }); export const removeItMethod = new ValidatedMethod({ name: 'BaseCollection.removeIt', mixins: [CallPromiseMixin], validate: null, run({ collectionName, instance }) { const collection = RadGrad.getCollection(collectionName); collection.assertValidRoleForMethod(this.userId); collection.removeIt(instance); return true; }, });
JavaScript
0.000001
@@ -3195,16 +3195,31 @@ ;%0A %7D%0A + return '';%0A %7D,%0A%7D);
578d4e52ba22da01af0ef44b7619dee09177bfc7
Add Gecko 16 nsITransferable.init() support.
modules/util/newUserScript.js
modules/util/newUserScript.js
Components.utils.import('resource://greasemonkey/parseScript.js'); Components.utils.import('resource://greasemonkey/util.js'); const EXPORTED_SYMBOLS = ['newUserScript']; const gClipboard = Components.classes["@mozilla.org/widget/clipboard;1"] .getService(Components.interfaces.nsIClipboard); const gWindowWatcher = Components .classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher); function newUserScript(aWin) { var clipText = ''; try { var transferable = Components.classes["@mozilla.org/widget/transferable;1"] .createInstance(Components.interfaces.nsITransferable); transferable.addDataFlavor('text/unicode'); gClipboard.getData(transferable, gClipboard.kGlobalClipboard); var str = new Object(), strLen = new Object(); transferable.getTransferData('text/unicode', str, strLen); if (str) { str = str.value.QueryInterface(Components.interfaces.nsISupportsString); clipText = str.data.substring(0, strLen.value / 2); } } catch (e) { dump('Error reading clipboard:\n' + e + '\n'); } // If there is a valid script with metadata on the clipboard ... if (clipText && extractMeta(clipText)) { // ... just install it! GM_util.installScriptFromSource(clipText); } else { // Otherwise do GUIfied script creation. gWindowWatcher.openWindow(aWin, "chrome://greasemonkey/content/newscript.xul", null, "chrome,dependent,centerscreen,resizable,dialog", null); } }
JavaScript
0.000003
@@ -640,16 +640,73 @@ rable);%0A + if ('init' in transferable) transferable.init(null);%0A tran
d9847f51e5a6f3aaf013928e54079b7628330946
fix hidden flag
packages/heroku-orgs/commands/orgs/default.js
packages/heroku-orgs/commands/orgs/default.js
'use strict'; let cli = require('heroku-cli-util'); let co = require('co'); function* run () { cli.error(`orgs:default is no longer in the CLI.\nUse the HEROKU_ORGANIZATION environment variable instead.\nSee ${cli.color.cyan('https://devcenter.heroku.com/articles/develop-orgs#default-org')} for more info.`); } module.exports = { topic: 'orgs', command: 'default', hidden: 'true', run: cli.command(co.wrap(run)) };
JavaScript
0.000003
@@ -409,14 +409,12 @@ -' true -' ,%0A
c8da2505ddd722e0a9cb1eb83c9c44e96f3c5c30
Include artist articles
schema/artist/index.js
schema/artist/index.js
import { defaults } from 'lodash'; import cached from '../fields/cached'; import initials from '../fields/initials'; import markdown from '../fields/markdown'; import Image from '../image'; import Artwork from '../artwork'; import PartnerShow from '../partner_show'; import ArtworkSorts from '../sorts/artwork_sorts'; import PartnerShowSorts from '../sorts/partner_show_sorts'; import ArtistCarousel from './carousel'; import ArtistStatuses from './statuses'; import gravity from '../../lib/loaders/gravity'; import { GraphQLObjectType, GraphQLBoolean, GraphQLString, GraphQLNonNull, GraphQLList, GraphQLInt, } from 'graphql'; const ArtistType = new GraphQLObjectType({ name: 'Artist', fields: () => { return { cached, id: { type: GraphQLString, }, href: { type: GraphQLString, resolve: (artist) => `/artist/${artist.id}`, }, sortable_id: { type: GraphQLString, description: 'Use this attribute to sort by when sorting a collection of Artists', }, name: { type: GraphQLString, }, initials: initials('name'), years: { type: GraphQLString, }, public: { type: GraphQLBoolean, }, nationality: { type: GraphQLString, }, blurb: markdown(), is_shareable: { type: GraphQLBoolean, resolve: (artist) => artist.published_artworks_count > 0, }, counts: { type: new GraphQLObjectType({ name: 'counts', fields: { artworks: { type: GraphQLInt, resolve: ({ published_artworks_count }) => published_artworks_count, }, follows: { type: GraphQLInt, resolve: ({ follow_count }) => follow_count, }, auction_lots: { type: GraphQLInt, resolve: ({ auction_lots_count }) => auction_lots_count, }, }, }), resolve: (artist) => artist, }, artworks: { type: new GraphQLList(Artwork.type), args: { size: { type: GraphQLInt, description: 'The number of Artworks to return', }, sort: ArtworkSorts, published: { type: GraphQLBoolean, defaultValue: true, }, }, resolve: ({ id }, options) => gravity(`artist/${id}/artworks`, options), }, image: Image, artists: { type: new GraphQLList(Artist.type), // eslint-disable-line no-use-before-define args: { size: { type: GraphQLInt, description: 'The number of Artists to return', }, exclude_artists_without_artworks: { type: GraphQLBoolean, defaultValue: true, }, }, resolve: (artist, options) => { return gravity(`related/layer/main/artists`, defaults(options, { artist: [artist.id], })); }, }, carousel: ArtistCarousel, statuses: ArtistStatuses, partner_shows: { type: new GraphQLList(PartnerShow.type), args: { size: { type: GraphQLInt, description: 'The number of PartnerShows to return', }, solo_show: { type: GraphQLBoolean, }, top_tier: { type: GraphQLBoolean, }, sort: PartnerShowSorts, }, resolve: ({ id }, options) => { return gravity('related/shows', defaults(options, { artist_id: id, displayable: true, sort: '-end_at', })); }, }, }; }, }); const Artist = { type: ArtistType, description: 'An Artist', args: { id: { description: 'The slug or ID of the Artist', type: new GraphQLNonNull(GraphQLString), }, }, resolve: (root, { id }) => gravity(`artist/${id}`), }; export default Artist;
JavaScript
0
@@ -183,16 +183,50 @@ image';%0A +import Article from '../article';%0A import A @@ -536,16 +536,67 @@ avity';%0A +import positron from '../../lib/loaders/positron';%0A import %7B @@ -3833,24 +3833,240 @@ %7D,%0A %7D, +%0A%0A articles: %7B%0A type: new GraphQLList(Article.type),%0A resolve: (%7B _id %7D) =%3E%0A positron('articles', %7B artist_id: _id, published: true %7D)%0A .then((%7B results %7D) =%3E results),%0A %7D, %0A %7D;%0A %7D,
2110b40851584943689ece4c5f4db2dfc2102a15
Fix for issue #10
js/zoom.js
js/zoom.js
+function ($) { "use strict"; /** * The zoom service */ function ZoomService () { this._activeZoom = this._initialScrollPosition = this._initialTouchPosition = this._touchMoveListener = null this._$document = $(document) this._$window = $(window) this._$body = $(document.body) } ZoomService.prototype.listen = function () { this._$body.on('click', '[data-action="zoom"]', $.proxy(this._zoom, this)) } ZoomService.prototype._zoom = function (e) { var target = e.target if (!target || target.tagName != 'IMG') return if (e.metaKey) return window.open(e.target.src, '_blank') if (target.width >= (window.innerWidth - Zoom.OFFSET)) return this._activeZoomClose(true) this._activeZoom = new Zoom(target) this._activeZoom.zoomImage() // todo(fat): probably worth throttling this this._$window.on('scroll.zoom', $.proxy(this._scrollHandler, this)) this._$document.on('click.zoom', $.proxy(this._clickHandler, this)) this._$document.on('keyup.zoom', $.proxy(this._keyHandler, this)) this._$document.on('touchstart.zoom', $.proxy(this._touchStart, this)) e.stopPropagation() } ZoomService.prototype._activeZoomClose = function (forceDispose) { if (!this._activeZoom) return if (forceDispose) { this._activeZoom.dispose() } else { this._activeZoom.close() } this._$window.off('.zoom') this._$document.off('.zoom') this._activeZoom = null } ZoomService.prototype._scrollHandler = function (e) { if (this._initialScrollPosition === null) this._initialScrollPosition = window.scrollY var deltaY = this._initialScrollPosition - window.scrollY if (Math.abs(deltaY) >= 40) this._activeZoomClose() } ZoomService.prototype._keyHandler = function (e) { if (e.keyCode == 27) this._activeZoomClose() } ZoomService.prototype._clickHandler = function (e) { e.stopPropagation() e.preventDefault() this._activeZoomClose() } ZoomService.prototype._touchStart = function (e) { this._initialTouchPosition = e.touches[0].pageY $(e.target).on('touchmove.zoom', $.proxy(this._touchMove, this)) } ZoomService.prototype._touchMove = function (e) { if (Math.abs(e.touches[0].pageY - this._initialTouchPosition) > 10) { this._activeZoomClose() $(e.target).off('touchmove.zoom') } } /** * The zoom object */ function Zoom (img) { this._fullHeight = this._fullWidth = this._overlay = this._targetImageWrap = null this._targetImage = img this._$body = $(document.body) } Zoom.OFFSET = 80 Zoom._MAX_WIDTH = 2560 Zoom._MAX_HEIGHT = 4096 Zoom.prototype.zoomImage = function () { var img = document.createElement('img') img.onload = $.proxy(function () { this._fullHeight = Number(img.height) this._fullWidth = Number(img.width) this._zoomOriginal() }, this) img.src = this._targetImage.src } Zoom.prototype._zoomOriginal = function () { this._targetImageWrap = document.createElement('div') this._targetImageWrap.className = 'zoom-img-wrap' this._targetImage.parentNode.insertBefore(this._targetImageWrap, this._targetImage) this._targetImageWrap.appendChild(this._targetImage) $(this._targetImage) .addClass('zoom-img') .attr('data-action', 'zoom-out') this._overlay = document.createElement('div') this._overlay.className = 'zoom-overlay' document.body.appendChild(this._overlay) this._calculateZoom() this._triggerAnimation() } Zoom.prototype._calculateZoom = function () { this._targetImage.offsetWidth // repaint before animating var originalFullImageWidth = this._fullWidth var originalFullImageHeight = this._fullHeight var scrollTop = window.scrollY var maxScaleFactor = originalFullImageWidth / this._targetImage.width var viewportHeight = (window.innerHeight - Zoom.OFFSET) var viewportWidth = (window.innerWidth - Zoom.OFFSET) var imageAspectRatio = originalFullImageWidth / originalFullImageHeight var viewportAspectRatio = viewportWidth / viewportHeight if (originalFullImageWidth < viewportWidth && originalFullImageHeight < viewportHeight) { this._imgScaleFactor = maxScaleFactor } else if (imageAspectRatio < viewportAspectRatio) { this._imgScaleFactor = (viewportHeight / originalFullImageHeight) * maxScaleFactor } else { this._imgScaleFactor = (viewportWidth / originalFullImageWidth) * maxScaleFactor } } Zoom.prototype._triggerAnimation = function () { this._targetImage.offsetWidth // repaint before animating var imageOffset = $(this._targetImage).offset() var scrollTop = window.scrollY var viewportY = scrollTop + (window.innerHeight / 2) var viewportX = (window.innerWidth / 2) var imageCenterY = imageOffset.top + (this._targetImage.height / 2) var imageCenterX = imageOffset.left + (this._targetImage.width / 2) this._translateY = viewportY - imageCenterY this._translateX = viewportX - imageCenterX $(this._targetImage).css('transform', 'scale(' + this._imgScaleFactor + ')') $(this._targetImageWrap).css('transform', 'translate(' + this._translateX + 'px, ' + this._translateY + 'px) translateZ(0)') this._$body.addClass('zoom-overlay-open') } Zoom.prototype.close = function () { this._$body .removeClass('zoom-overlay-open') .addClass('zoom-overlay-transitioning') // we use setStyle here so that the correct vender prefix for transform is used $(this._targetImage).css('transform', '') $(this._targetImageWrap).css('transform', '') $(this._targetImage) .one($.support.transition.end, $.proxy(this.dispose, this)) .emulateTransitionEnd(300) } Zoom.prototype.dispose = function () { if (this._targetImageWrap && this._targetImageWrap.parentNode) { $(this._targetImage) .removeClass('zoom-img') .attr('data-action', 'zoom') this._targetImageWrap.parentNode.replaceChild(this._targetImage, this._targetImageWrap) this._overlay.parentNode.removeChild(this._overlay) this._$body.removeClass('zoom-overlay-transitioning') } } new ZoomService().listen() }(jQuery)
JavaScript
0
@@ -587,32 +587,91 @@ 'IMG') return%0A%0A + if (this._$body.hasClass('zoom-overlay-open')) return%0A%0A if (e.metaKe
6971cf99fe0aaff0e216a46776e95a3e84c88b49
Add build:docs task
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var gutil = require('gulp-util'); var gulpif = require('gulp-if'); var browserify = require('browserify'); var watchify = require('watchify'); var buffer = require('vinyl-buffer'); var uglify = require('gulp-uglify'); var size = require('gulp-size'); var source = require('vinyl-source-stream'); var sequence = require('run-sequence'); var rename = require('gulp-rename'); var minifyCss = require('gulp-minify-css'); var autoprefixer = require('gulp-autoprefixer'); var browserSync = require('browser-sync'); var jshint = require('gulp-jshint'); var sourcemaps = require('gulp-sourcemaps'); var concat = require('gulp-concat'); var ngAnnotate = require('browserify-ngannotate'); var templateCache = require('gulp-angular-templatecache'); var ghPages = require('gulp-gh-pages'); var config = { dragular: { scripts: './src/*.js', styles: './src/*.css', dest: './dist' }, docs: { src: './docs/src/examples', scripts: './docs/src/examples/**/*.js', styles: './docs/src/**/*.css', templates: './docs/src/examples/**/*.html', dest: './docs/dist' }, browserSync: { port: '3000', server: './docs' }, browserify: { dragular: { entryPoint: './src/dragularModule.js', bundleName: 'dragular.js', dest: './dist', }, docs: { entryPoint: './docs/src/examples/examplesApp.js', bundleName: 'examples.js', dest: './docs/dist' } }, isProd: false }; var browserifyDefaults = config.browserify.dragular; function handleErrors(err) { gutil.log(err.toString()); this.emit('end'); } function buildScript() { var bundler = browserify({ entries: browserifyDefaults.entryPoint, debug: true, cache: {}, packageCache: {}, fullPaths: true }, watchify.args); var transforms = [ 'brfs', 'bulkify', ngAnnotate ]; if (!config.isProd) { bundler = watchify(bundler); bundler.on('update', function() { rebundle(); }); } transforms.forEach(function(transform) { bundler.transform(transform); }); function rebundle() { var stream = bundler.bundle(); return stream.on('error', handleErrors) .pipe(source(browserifyDefaults.bundleName)) .pipe(buffer()) .pipe(gulpif(config.isProd, sourcemaps.init())) .pipe(gulpif(config.isProd, uglify({ compress: { drop_console: true } }))) .pipe(gulpif(config.isProd, rename({ suffix: '.min' }))) .pipe(size({ title: 'Scripts: ' })) .pipe(gulpif(config.isProd, sourcemaps.write('./'))) .pipe(gulp.dest(browserifyDefaults.dest)) .pipe(browserSync.stream()); } return rebundle(); } gulp.task('browserify', function() { return buildScript(); }); gulp.task('styles', function() { return gulp.src(config.dragular.styles) .pipe(autoprefixer({ browsers: [ 'last 15 versions', '> 1%', 'ie 8', 'ie 7' ], cascade: false })) .pipe(concat('dragular.css')) .pipe(gulpif(config.isProd, minifyCss())) .pipe(gulpif(config.isProd, rename({ suffix: '.min' }))) .pipe(size({ title: 'Styles: ' })) .pipe(gulp.dest(config.dragular.dest)) .pipe(gulpif(browserSync.active, browserSync.stream())); }); gulp.task('styles:docs', function() { return gulp.src([ config.docs.styles, config.dragular.styles ]) .pipe(autoprefixer({ browsers: [ 'last 15 versions', '> 1%', 'ie 8', 'ie 7' ], cascade: false })) .pipe(concat('examples.css')) .pipe(gulp.dest(config.docs.dest)) .pipe(gulpif(browserSync.active, browserSync.stream())); }); gulp.task('lint', function() { return gulp.src([config.dragular.scripts]) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('lint:docs', function() { return gulp.src(config.docs.scripts) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('serve', function () { browserSync({ port: config.browserSync.port, server: { baseDir: config.browserSync.server, }, logConnections: true, logFileChanges: true, notify: true }); }); gulp.task('templates:docs', function() { return gulp.src(config.docs.templates) .pipe(templateCache({ moduleSystem: 'Browserify', standalone: true, })) .pipe(gulp.dest(config.docs.src)); }); gulp.task('watch', ['serve'], function() { gulp.watch(config.dragular.styles, ['styles']); }); gulp.task('watch:docs', ['serve'], function() { gulp.watch(config.docs.styles, ['styles:docs']); gulp.watch(config.docs.templates, ['templates:docs']); }); gulp.task('dev', function() { config.isProd = false; browserifyDefaults = config.browserify.dragular; sequence(['browserify', 'styles'], 'watch'); }); gulp.task('dev:docs', function() { config.isProd = false; browserifyDefaults = config.browserify.docs; sequence(['browserify', 'styles:docs', 'templates:docs'], 'watch:docs'); }); gulp.task('build', function() { config.isProd = true; sequence(['browserify', 'styles']); }); gulp.task('deploy:docs', function() { return gulp.src('./docs/**/*') .pipe(ghPages()); });
JavaScript
0.000012
@@ -2313,16 +2313,32 @@ ps.init( +%7BloadMaps: true%7D )))%0A @@ -5029,32 +5029,260 @@ ', function() %7B%0A + config.isProd = true;%0A browserifyDefaults = config.browserify.dragular;%0A%0A sequence(%5B'browserify', 'styles'%5D);%0A%7D);%0A%0Agulp.task('build:docs', function() %7B%0A config.isProd = true;%0A browserifyDefaults = config.browserify.docs;%0A%0A config.isProd
d4486729119d85c559b40ebe7b9e034967086df0
Use post.update to set the latest post
server/handlers/post.js
server/handlers/post.js
const Boom = require('boom') const Logger = require('franston')('handlers/post') const Slug = require('slug') const DateSort = require('../helpers/date-sort') const IsAuthorized = require('../helpers/is-authorized') const Post = require('../models/post') exports.create = function (request, reply) { Logger.debug('post.create') const post = Object.assign({}, request.payload) post.slug = Slug(`${post.category} ${title}`, { lower: true }) Post.create(post, (err, created) => { if (err) return (Logger.error(err), reply(Boom.badRequest(err))) const query = { slug: { $ne: created.slug } } Post.update(query, { isLatest: false }, { multi: true }, (err, count) => { if (err) return (Logger.error(err), reply(Boom.badRequest(err))) return reply(created).code(201) }) }) } exports.get = function (request, reply) { Logger.debug('post.get') const query = { slug: request.params.slug } if (!IsAuthorized(request.auth)) query.isPreview = false Post.findOne(query, (err, post) => { if (err) return (Logger.error(err), reply(Boom.badRequest(err))) if (!post) return reply(Boom.notFound('Post not found')) return reply(post) }) } exports.getAll = function (request, reply) { Logger.debug('post.getAll') const query = {} if (request.query && request.query.latest) query.isLatest = true if (!IsAuthorized(request.auth)) query.isPreview = false Post.find(query, (err, posts) => { if (err) return (Logger.error(err), reply(Boom.badRequest(err))) posts.sort(DateSort.bind(null, 1)) return reply(posts) }) } exports.remove = function (request, reply) { Logger.debug('post.remove') Post.remove({ slug: request.params.slug }, (err) => { if (err) return (Logger.error(err), reply(Boom.badRequest(err))) return reply().code(204) }) } exports.update = function (request, reply) { Logger.debug('post.update') const query = { slug: request.params.slug } const post = Object.assign({}, request.payload) if (post.tags) { post.$push = { tags: { $each: post.tags } } delete post.tags } post.updatedAt = new Date().toISOString() Post.update(query, post, (err) => { if (err) return (Logger.error(err), reply(Boom.badRequest(err))) return reply().code(204) }) }
JavaScript
0
@@ -415,16 +415,21 @@ gory%7D $%7B +post. title%7D%60, @@ -453,258 +453,48 @@ %0A%0A -Post.create(post, (err, created) =%3E %7B%0A if (err) return (Logger.error(err), reply(Boom.badRequest(err)))%0A%0A const query = %7B%0A slug: %7B $ne: created.slug %7D%0A %7D%0A%0A Post.update(query, %7B isLatest: false %7D, %7B multi: true %7D, (err, count +new Post(post).save((err, created ) =%3E %7B%0A - @@ -562,18 +562,16 @@ )))%0A - return r @@ -598,15 +598,8 @@ 01)%0A - %7D)%0A %7D) @@ -1892,51 +1892,225 @@ %7D%0A - post.updatedAt = new Date().toISOString() +%0A let isLatest = false%0A if (post.hasOwnProperty('isLatest') && post.isLatest === true) %7B%0A isLatest = post.isLatest%0A %7D%0A%0A post.updatedAt = new Date().toISOString() // TODO see if mongoose-timestamp should do this %0A%0A @@ -2206,35 +2206,51 @@ dRequest(err)))%0A +%0A + if (!isLatest) return reply(). @@ -2246,28 +2246,292 @@ rn reply().code(204) +%0A%0A const query = %7B%0A slug: %7B $ne: request.params.slug %7D%0A %7D%0A%0A return Post.update(query, %7B isLatest: false %7D, %7B multi: true %7D, (err, count) =%3E %7B%0A if (err) return (Logger.error(err), reply(Boom.badRequest(err)))%0A return reply().code(204)%0A %7D) %0A %7D)%0A%7D%0A
aae8159de83f743814682fd87c38dfbe30e5d78e
better output
lib/index.js
lib/index.js
var _ = require('lodash'); var request = require('request'); var BatchManager = function (opts) { // http xhr request batch api handler for outbound rest/rpc like calls // (c) 2013 davehigginbotham@gmail.com var options = opts || null; this.prefix = 'batchman'; this.middleware = []; this.key = 'batchman'; this.end = null; if (options) { _.merge(this, options); }; var self = this; var processRequests = function (reqs, fn) { var reqs = reqs || null; var respArray = []; var i = 0; var ln = reqs.length; while (ln--) { if (reqs[i].hasOwnProperty('url')) { self.request(reqs[i], function (err, body) { respArray.push(body); if (respArray.length === reqs.length) { return fn(null, respArray); }; }); } i++; }; }; this.batchRequests = function (req, res, next) { if (req.body) { processRequests(req.body, function (err, resp) { req[self.key] = resp; return next(); }); }; }; if (!this.end) { this.end = function (req, res) { res.send(req[self.key]); }; }; return this; }; BatchManager.prototype.request = function (opts, fn) { var defaults = { url: null, qs: null, method: 'get', form: {} }; var options = opts || null; if (options) { _.merge(defaults, options); } else { return fn('You must provide options for request to work properly.', null); }; if (defaults.url) { request(defaults, function (err, resp, body) { if (err) { return fn(err, null); }; return fn(null, JSON.parse(body)); }); } else { return fn('You must provide a url string', null); }; }; BatchManager.prototype.mount = function (app, fn) { var app = (typeof app != 'undefined') ? app : null; if (!app) { return new Error('You must provide access to express/connect for this to mount routes correctly.'); }; // give routes here var self = this; var prefix = '/' + self.prefix; app.post(prefix, self.middleware, self.batchRequests, self.end); var out = 'Successfully mounted batchman to `' + prefix + '`'; return (typeof fn != 'undefined') ? fn(out) : true; }; module.exports = BatchManager;
JavaScript
0.999999
@@ -1653,56 +1653,219 @@ %7B %0A - %0A if (err) %7B%0A return fn(err, +%0A var output = %7B%0A path: defaults.url,%0A method: defaults.method,%0A body: (body) ? JSON.parse(body) : null,%0A status: (resp) ? resp.statusCode : null,%0A err: (err) ? err : null -); %0A @@ -1866,25 +1866,24 @@ ll%0A %7D;%0A - %0A retur @@ -1893,32 +1893,22 @@ n(null, -JSON.parse(body) +output );%0A %0A @@ -2231,33 +2231,8 @@ ;%0A %0A - // give routes here%0A %0A va
8adfdd5aead935a83008aad1da5fdd9ab24389f8
Fix spelling mistakes
extension/src/content_script.js
extension/src/content_script.js
// Check if active view mode is List or Gallery mode let soldQuantitySelector; let stringToReplace; let itemHeight; const viewMode = document.querySelector('.ico'); const viewModeActive = viewMode.className.includes('list selected') ? 'list' : 'gallery'; if (viewModeActive === 'gallery') { soldQuantitySelector = '.sold-quantity'; locationSelector = '.info-shipping'; listSelector = '.gallery-large'; itemHeight = 90; } else if (viewModeActive === 'list') { soldQuantitySelector = '.extra-info-sold'; locationSelector = '.extra-info-location'; listSelector = '.list-view'; itemHeight = 60; } // Add "0 vendidos" to those products that didn't sell nothing yet const rowItems = [...document.querySelectorAll('.results-item')]; rowItems.forEach(row => { const info = row.querySelector(soldQuantitySelector); if (!info) { row .querySelector(locationSelector) .insertAdjacentHTML('beforebegin', `<li class="${soldQuantitySelector.replace('.', '')}">0 vendidos</li>`); } }); // Sort all the quantity of sold products descendly const rowItemsUpdated = [...document.querySelectorAll('.results-item')]; const rowItemsSorted = rowItemsUpdated.sort((a, b) => { const valueA = a.querySelector(soldQuantitySelector).innerText.replace(/\D/g, ''); const valueB = b.querySelector(soldQuantitySelector).innerText.replace(/\D/g, ''); return valueA - valueB; }); // Lets clean all items inside the list const listView = document.querySelector(listSelector); listView.innerHTML = null; // Now lets insert all the items ordered descendendly rowItemsSorted.forEach(row => listView.insertAdjacentElement('afterbegin', row));
JavaScript
1
@@ -1394,14 +1394,9 @@ %0A// -Lets c +C lean @@ -1512,18 +1512,9 @@ %0A// -Now lets i +I nser @@ -1533,13 +1533,12 @@ ems +s or -der +t ed d @@ -1543,19 +1543,16 @@ descend -end ly%0ArowIt
9155ba8cf71f36ae44d29ab48b1601f1000c815b
Handle multiple plug-in install at once
app-web/src/main/webapp/main/system/plugin/plugin.js
app-web/src/main/webapp/main/system/plugin/plugin.js
define(function () { var current = { initialize: function () { _('table').dataTable({ ajax: REST_PATH + 'plugin', dataSrc: '', sAjaxDataProp: '', dom: '<"row"<"col-sm-6"B><"col-sm-6"f>r>t', pageLength: -1, destroy: true, order: [[1, 'asc']], columns: [ { data: null, orderable: false, render: function(data) { return data.plugin.type === 'feature' ? '<i class="fa fa-wrench"></i>' : current.$main.toIcon(data.node); } }, { data: 'id' }, { data: 'name' }, { data: 'vendor', className: 'hidden-xs hidden-sm' }, { data: 'plugin.version', className: 'truncate' }, { data: 'plugin.type', className: 'hidden-xs hidden-sm' }, { data: 'nodes', className: 'icon', render: function(nb, _i, plugin) { return plugin.plugin.type === 'feature' ? '' : nb; } }, { data: 'subscriptions', className: 'icon', render: function(nb, _i, plugin) { return plugin.plugin.type === 'feature' ? '' : nb; } } ], buttons: [ { extend: 'create', text: 'install', action: function () { bootbox.prompt(current.$messages.name, current.install); } } ] }); }, install : function(name) { name && $.ajax({ type: 'POST', url: REST_PATH + 'plugin/' + encodeURIComponent(name), dataType: 'text', contentType: 'application/json', success: function () { notifyManager.notify(Handlebars.compile(current.$messages.downloaded)(name)); current.table && current.table.api().ajax.reload(); } }); } }; return current; });
JavaScript
0
@@ -1308,46 +1308,801 @@ %09%0A%09%09 -install : function(name) %7B%0A%09%09%09name && +/**%0A%09%09 * Install the requested plug-ins.%0A%09%09 * @param The plug-in identifier or null. When null, a prompt is displayed.%0A%09%09 */%0A%09%09install : function(name) %7B%0A%09%09%09if (name) %7B%0A%09%09%09%09current.installNext(plugin.split(','), 0);%0A%09%09%09%7D%0A%09%09%7D,%0A%09%09%0A%09%09/**%0A%09%09 * Install a the plug-ins from the one at the specified index, and then the next ones.%0A%09%09 * There is one AJAX call by plug-in, and stops at any error.%0A%09%09 * @param plugins The plug-in identifiers array to install.%0A%09%09 * @param index The starting plug-in index within the given array.%0A%09%09 */%0A%09%09installNext : function(plugins, index) %7B%0A%09%09%09if (index %3E= plugins.length) %7B%0A%09%09%09%09// All plug-ins are installed%0A%09%09%09%09current.table && current.table.api().ajax.reload();%0A%09%09%09%09return;%0A%09%09%09%7D%0A%0A%09%09%09// Install this plug-in%0A%09%09%09var plugin = plugins%5Bi%5D.trim();%0A%09%09%09if (plugin) %7B%0A%09%09%09%09 $.aj @@ -2106,16 +2106,17 @@ .ajax(%7B%0A +%09 %09%09%09%09type @@ -2125,16 +2125,17 @@ 'POST',%0A +%09 %09%09%09%09url: @@ -2182,15 +2182,18 @@ ent( -name +plugin ),%0A +%09 %09%09%09%09 @@ -2214,16 +2214,17 @@ t',%0A%09%09%09%09 +%09 contentT @@ -2252,16 +2252,17 @@ n',%0A%09%09%09%09 +%09 success: @@ -2272,24 +2272,25 @@ nction () %7B%0A +%09 %09%09%09%09%09notifyM @@ -2356,85 +2356,259 @@ ed)( -name +%7Bplugin, index, plugins.length%7D ));%0A +%0A%09 %09%09%09%09%09 -current.table && current.table.api().ajax.reload();%0A%09%09%09%09%7D +// Install the next plug-in%0A%09%09%09%09%09%09current.installNext(plugins, index + 1);%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D);%0A%09%09%09%7D else %7B%0A%09%09%09%09// The token was empty, install the next real plug-in%0A%09%09%09%09current.installNext(plugins, index + 1); %0A%09%09%09%7D -); %0A%09%09%7D
97beb4bcefee81dcbb98e77ede391dadb3ba2fe1
Make positive condition and use it in the main func
lib/grainstore/paths/from23To30.js
lib/grainstore/paths/from23To30.js
'use strict'; var postcss = require('postcss'); var symbolyzers = [ 'polygon', 'line', 'marker', 'shield', 'text' ]; module.exports = function (cartoCss) { return postcss() .use(postcssCartocssMigrator()) .process(cartoCss) .css; }; var postcssCartocssMigrator = postcss.plugin('postcss-cartocss-migrator', function (options) { options = options || {}; return function (css) { css.walkRules(function (rule) { symbolyzers.forEach(function (symbolyzer) { setClipDefaultToTrue(rule, symbolyzer); setPatternAlignmentDefaultToLocal(rule, symbolyzer); }); }); }; }); function setClipDefaultToTrue(rule, symbolizer) { var property = [symbolizer, 'clip'].join('-'); if (hasPropertySymbolyzer(rule, symbolizer) && !hasPropertyAlreadyDefined(rule, property)) { var clipDecl = postcss.decl({ prop: property, value: true }); rule.append(clipDecl); } } function setPatternAlignmentDefaultToLocal(rule, symbolizer) { if (symbolizer !== 'polygon') { return; } var property = [symbolizer, 'pattern-aligment'].join('-'); if (hasPropertySymbolyzer(rule, symbolizer) && !hasPropertyAlreadyDefined(rule, property)) { var patternAlignmentDecl = postcss.decl({ prop: property, value: 'local' }); rule.append(patternAlignmentDecl); } } function hasPropertyAlreadyDefined(rule, property) { var hasPropertyAlreadyDefined = false; rule.walkDecls(function (decl) { if (decl.prop === property) { hasPropertyAlreadyDefined = true; } }); return hasPropertyAlreadyDefined; } function hasPropertySymbolyzer(rule, symbolyzer) { var hasPropertySymbolyzer = false; rule.walkDecls(function (decl) { var property = decl.prop; if (property.indexOf(symbolyzer) === 0) { hasPropertySymbolyzer = true; } }); return hasPropertySymbolyzer; }
JavaScript
0.019283
@@ -597,16 +597,85 @@ +%0A if (symbolizer === 'polygon') %7B%0A setPatte @@ -711,32 +711,50 @@ e, symbolyzer);%0A + %7D%0A %7D);%0A @@ -1153,67 +1153,8 @@ ) %7B%0A - if (symbolizer !== 'polygon') %7B%0A return;%0A %7D%0A%0A
be94f47d93bc6b4ac3ee14633214e02be55b27fe
Simplify the dependency.js.
dependency.js
dependency.js
path = require('path'); dirname = path.relative('.', __dirname); console.log(path.join(dirname, 'binding.gyp:native_mate'));
JavaScript
0.000028
@@ -1,70 +1,4 @@ -path = require('path');%0A%0Adirname = path.relative('.', __dirname);%0A cons @@ -9,18 +9,31 @@ log( +require(' path +') .join( +__ dirn
6535f89937c2170f650a85544a0855e8f0da3b41
fix Buffer deprecation
lib/raw-image-stream.js
lib/raw-image-stream.js
var inherits = require('util').inherits var Transform = require('stream').Transform module.exports = RawImageStream function RawImageStream (frameSize) { Transform.call(this) this.frameSize = frameSize this.buffer = new Buffer(0) } inherits(RawImageStream, Transform) RawImageStream.prototype._transform = function (chunk, encoding, callback) { var size = this.buffer.length + chunk.length if (size < this.frameSize) { this.buffer = Buffer.concat([this.buffer, chunk], size) } else { // buffer = Buffer.concat([buffer, data.slice(0, rest)]) this.buffer = Buffer.concat([this.buffer, chunk], this.frameSize) this.push(this.buffer) // rest of chunk this.buffer = chunk.slice(chunk.length - (size - this.frameSize)) } callback() }
JavaScript
0.000035
@@ -220,19 +220,21 @@ er = - new Buffer +.alloc (0)%0A
6d1412dbf60922f3c178fc5c6f986cb76385291d
simplify Layout
plant/twigs/Layout/Layout.js
plant/twigs/Layout/Layout.js
import React, { PropTypes } from 'react'; import * as layouts from './index'; const Layout = ({ name, children }) => { const CustomLayout = layouts[name]; return ( <CustomLayout children={children} /> ); }; Layout.propTypes = { name: PropTypes.string.isRequired, children: PropTypes.node, }; export default Layout;
JavaScript
0.99831
@@ -3,15 +3,8 @@ port - React, %7B P @@ -11,16 +11,31 @@ ropTypes +, createElement %7D from @@ -123,107 +123,50 @@ =%3E -%7B%0A const CustomLayout = layouts%5Bname%5D;%0A%0A return (%0A %3CCustomLayout children=%7Bchildren%7D /%3E%0A );%0A%7D +createElement(layouts%5Bname%5D, %7B children %7D) ;%0A%0AL