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
a50d73b02bb83c4f2876cf7f082fc81a47a41b82
Switch to image
dashboard/app/scripts/views/graphwall-view.js
dashboard/app/scripts/views/graphwall-view.js
/*global define*/ define(['jquery', 'underscore', 'backbone', 'templates', 'helpers/graph-utils', 'marionette'], function($, _, Backbone, JST, gutils) { 'use strict'; var GraphwallView = Backbone.Marionette.ItemView.extend({ template: JST['app/scripts/templates/graphwall-view.ejs'], className: 'graph-mode span12', ui: { 'title': '.title' }, initialize: function() { this.App = Backbone.Marionette.getOption(this, 'App'); this.graphiteHost = Backbone.Marionette.getOption(this, 'graphiteHost'); this.baseUrl = gutils.makeBaseUrl(this.graphiteHost); this.cpuTargets = gutils.makeTargets(gutils.makeCPUTargets(['system', 'user', 'idle'])); this.heightWidth = gutils.makeHeightWidthParams(282, 167); this.makeCPUGraphUrl = gutils.makeGraphURL('png', this.baseUrl, this.heightWidth, this.cpuTargets); this.osdOpLatencyTargets = gutils.makeTargets(gutils.makeOpLatencyTargets(['op_r_latency', 'op_w_latency', 'op_rw_latency'])); this.makeOpsLatencyGraphUrl = gutils.makeGraphURL('png', this.baseUrl, this.heightWidth, this.osdOpLatencyTargets); }, makeHostUrls: function() { var hosts = this.App.ReqRes.request('get:hosts'); var fn = this.makeCPUGraphUrl; return _.map(hosts, function(host) { return fn(host); }); }, selectors: ['0-1', '0-2', '0-3', '1-1', '1-2', '1-3', '2-1', '2-2', '2-3'], populateAll: function() { var urls = this.makeHostUrls(); var self = this; this.ui.title.text('CPU Load for Cluster'); _.each(urls, function(url, index) { var $graph = self.$('.graph' + self.selectors[index]); $graph.html('<embed src=' + url + '></embed>'); }); } }); return GraphwallView; });
JavaScript
0.000009
@@ -1848,21 +1848,19 @@ .html('%3C -embed +img src=' + @@ -1872,16 +1872,8 @@ + '%3E -%3C/embed%3E ');%0A
23f14812ebedd49490632f2f3cdb805add4cd388
Add config for cssVarLoaderLiquidPath
slate.config.js
slate.config.js
/* eslint-disable no-undef */ const path = require('path'); const alias = { jquery: path.resolve('./node_modules/jquery'), 'lodash-es': path.resolve('./node_modules/lodash-es'), }; module.exports = { extends: { dev: {resolve: {alias}}, prod: {resolve: {alias}}, }, };
JavaScript
0
@@ -200,16 +200,129 @@ rts = %7B%0A + slateCssVarLoader: %7B%0A cssVarLoaderLiquidPath: %5B'src/snippets/css-variables.liquid'%5D,%0A %7D,%0A slateTools: %7B%0A extend @@ -322,24 +322,26 @@ extends: %7B%0A + dev: %7Bre @@ -357,16 +357,18 @@ lias%7D%7D,%0A + prod @@ -389,16 +389,23 @@ lias%7D%7D,%0A + %7D,%0A %7D,%0A%7D;%0A
312c890bc6077464de63c853c4e73d2a11a954fb
Add dataset namespace
snabbdom-jsx.js
snabbdom-jsx.js
"use strict"; var SVGNS = 'http://www.w3.org/2000/svg'; var modulesNS = ['hook', 'on', 'style', 'class', 'props', 'attrs']; var slice = Array.prototype.slice; function isPrimitive(val) { return typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean' || typeof val === 'symbol' || val === null || val === undefined; } function normalizeAttrs(attrs, nsURI, defNS, modules) { var map = { ns: nsURI }; for (var i = 0, len = modules.length; i < len; i++) { var mod = modules[i]; if(attrs[mod]) map[mod] = attrs[mod]; } for(var key in attrs) { if(key !== 'key' && key !== 'classNames' && key !== 'selector') { var idx = key.indexOf('-'); if(idx > 0) addAttr(key.slice(0, idx), key.slice(idx+1), attrs[key]); else if(!map[key]) addAttr(defNS, key, attrs[key]); } } return map; function addAttr(namespace, key, val) { var ns = map[namespace] || (map[namespace] = {}); ns[key] = val; } } function buildFromStringTag(nsURI, defNS, modules, tag, attrs, children) { if(attrs.selector) { tag = tag + attrs.selector; } if(attrs.classNames) { var cns = attrs.classNames; tag = tag + '.' + ( Array.isArray(cns) ? cns.join('.') : cns.replace(/\s+/g, '.') ); } return { sel : tag, data : normalizeAttrs(attrs, nsURI, defNS, modules), children : children.map( function(c) { return isPrimitive(c) ? {text: c} : c; }), key: attrs.key }; } function buildFromComponent(nsURI, defNS, modules, tag, attrs, children) { var res; if(typeof tag === 'function') res = tag(attrs, children); else if(tag && typeof tag.view === 'function') res = tag.view(attrs, children); else if(tag && typeof tag.render === 'function') res = tag.render(attrs, children); else throw "JSX tag must be either a string, a function or an object with 'view' or 'render' methods"; res.key = attrs.key; return res; } function flatten(nested, start, flat) { for (var i = start, len = nested.length; i < len; i++) { var item = nested[i]; if (Array.isArray(item)) { flatten(item, 0, flat); } else { flat.push(item); } } } function maybeFlatten(array) { if (array) { for (var i = 0, len = array.length; i < len; i++) { if (Array.isArray(array[i])) { var flat = array.slice(0, i); flatten(array, i, flat); array = flat; break; } } } return array; } function buildVnode(nsURI, defNS, modules, tag, attrs, children) { attrs = attrs || {}; children = maybeFlatten(children); if(typeof tag === 'string') { return buildFromStringTag(nsURI, defNS, modules, tag, attrs, children) } else { return buildFromComponent(nsURI, defNS, modules, tag, attrs, children) } } function JSX(nsURI, defNS, modules) { return function jsxWithCustomNS(tag, attrs, children) { if(arguments.length > 3 || !Array.isArray(children)) children = slice.call(arguments, 2); return buildVnode(nsURI, defNS || 'props', modules || modulesNS, tag, attrs, children); }; } module.exports = { html: JSX(undefined), svg: JSX(SVGNS, 'attrs'), JSX: JSX };
JavaScript
0.00012
@@ -115,16 +115,27 @@ 'attrs' +, 'dataset' %5D;%0Avar s
fbd491890a57aab51c145ce5f118d5020b979193
add content type to asmx response
lib/federationServerService.js
lib/federationServerService.js
var templates = require('./templates'); var thumbprint = require('thumbprint'); var URL_PATH = '/wsfed/adfs/fs/federationserverservice.asmx'; function getLocation (req) { var protocol = req.headers['x-iisnode-https'] && req.headers['x-iisnode-https'] == 'ON' ? 'https' : (req.headers['x-forwarded-proto'] || req.protocol); return protocol + '://' + req.headers['host'] + req.originalUrl; } function certToPem (cert) { var pem = /-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g.exec(cert.toString()); if (pem.length > 0) { return pem[1].replace(/[\n|\r\n]/g, ''); } return null; } function getEndpointAddress (req, endpointPath) { endpointPath = endpointPath || (req.originalUrl.substr(0, req.originalUrl.length - URL_PATH.length)); var protocol = req.headers['x-iisnode-https'] && req.headers['x-iisnode-https'] == 'ON' ? 'https' : (req.headers['x-forwarded-proto'] || req.protocol); return protocol + '://' + req.headers['host'] + endpointPath; } module.exports.wsdl = function (req, res) { res.set('Content-Type', 'text/xml; charset=UTF-8'); if(req.query.wsdl){ return res.send(templates.federationServerServiceWsdl()); } res.send(templates.federationServerService({ location: getLocation(req) })); }; module.exports.thumbprint = function (options) { var cert = certToPem(options.cert); var tp = thumbprint.calculate(cert).toUpperCase(); return function (req, res) { res.send(templates.federationServerServiceResponse({ location: getEndpointAddress(req, options.endpointPath), cert: cert, thumbprint: tp })); }; };
JavaScript
0
@@ -1510,24 +1510,80 @@ req, res) %7B%0A + res.set('Content-Type', 'text/xml; charset=UTF-8');%0A res.send
f4534b2660904f3895774b11c26ba0814112f167
add test_base.html
gfx/tests/module.js
gfx/tests/module.js
dojo.provide("dojox.gfx.tests.module"); try{ dojo.require("dojox.gfx.tests.matrix"); dojo.require("dojox.gfx.tests.decompose"); doh.registerUrl("GFX: Utils", dojo.moduleUrl("dojox", "gfx/tests/test_utils.html"), 3600000); }catch(e){ doh.debug(e); }
JavaScript
0.000001
@@ -219,16 +219,109 @@ 00000);%0A +%09doh.registerUrl(%22GFX: Base%22, dojo.moduleUrl(%22dojox%22, %22gfx/tests/test_base.html%22), 3600000);%0A %7Dcatch(e
09d283ff9d4f003619d16434c657d7a9983279e6
Fix bug in server image
requestHandlers.js
requestHandlers.js
var fs = require("fs"); var queryString = require("querystring"); function start(response, postData) { console.log("Request handler 'start' was called."); fs.readFile("./public/index.html", "utf8", function(error, data) { response.writeHead(200, { "Content-Type": "text/html" }); response.write(data); response.end(); }); } function upload(response, postData) { console.log("Request handler 'upload' was called."); response.writeHead(200, { "Content-Type": "text/plain" }); response.write("You have sent: " + queryString.parse(postData).text); response.end(); } function show(response) { console.log("Request handler 'show' was called."); response.writeHead(200, { "Content-Type": "image/png" }); fs.createReadStream("/tmp/text.png").pipe(response); } exports.start = start; exports.upload = upload; exports.show = show;
JavaScript
0.000001
@@ -778,16 +778,17 @@ am(%22 +. /tmp/te -x +s t.pn
7e0313a60eef6d67c844af476a6881f512b58347
move tag creation before git push in release script
scripts/release.js
scripts/release.js
const fs = require("fs"); const path = require("path"); const execa = require("execa"); async function execCommand(...args) { let res; try { res = await execa(...args); } catch (e) { console.error(e.all); process.exit(1); } return res.stdout; } async function main() { console.log("Running release script"); process.chdir(path.join(__dirname, "/..")); console.log(`CWD: ${process.cwd()}`); console.log(""); console.log("Running validate script"); await execCommand("npm", ["run", "validate"]); console.log(" OK"); console.log("Getting version from CHANGELOG.md"); const changelog = fs.readFileSync(path.join(__dirname, "../CHANGELOG.md"), "utf8"); const isUnreleased = Boolean(changelog.match(/^## \[Unreleased\]+/im)); if (isUnreleased) { console.error(` "Unreleased" version in changelog, exiting`); return; } const versionMatch = changelog.match(/^## \[(.+)\]+/m); const versionChangelog = Array.isArray(versionMatch) && versionMatch[1] ? versionMatch[1] : null; if (!versionChangelog) { console.error(" Could not parse version from changelog, exiting"); return; } else { console.log(` OK, version: "${versionChangelog}"`); } console.log(`Checking if there is correct version in package.json`); const packageJsonString = fs.readFileSync(path.join(__dirname, "../package.json"), "utf8"); const packageJson = JSON.parse(packageJsonString); const versionPackageJson = packageJson.version; if (versionPackageJson !== versionChangelog) { console.error( ` Version from package.json "${versionPackageJson}" is not equal to version from changelog "${versionChangelog}", exiting`, ); return; } else { console.log(" OK"); } console.log(`Checking if there is correct version in public/manifest.json`); const manifestString = fs.readFileSync(path.join(__dirname, "../public/manifest.json"), "utf8"); const manifest = JSON.parse(manifestString); const versionManifest = manifest.version; if (versionManifest !== versionChangelog) { console.error( ` Version from public/manifest.json "${versionManifest}" is not equal to version from changelog "${versionChangelog}", exiting`, ); return; } else { console.log(" OK"); } console.log(`Pulling git tags`); await execCommand("git", ["pull", "--tags"]); console.log(" OK"); console.log(`Checking if current branch is master`); const branchName = await execCommand("git", ["rev-parse", "--abbrev-ref", "HEAD"]); if (branchName !== "master") { console.error(` Current Git branch is "${branchName}", it must be "master", exiting`); return; } else { console.log(" OK"); } console.log(`Checking if there are any uncommitted changes`); const gitStatus = await execCommand("git", ["status", "-s"]); if (gitStatus) { console.error(` There are uncommitted changes, exiting`); return; } else { console.log(" OK"); } const gitTag = `v${versionChangelog}`; console.log(`Check if tag "${gitTag}" does not already exist`); const gitTagExists = await execCommand("git", ["tag", "--list", gitTag]); if (gitTagExists) { console.error(` Git tag "${gitTag}" already exists, exiting`); return; } else { console.log(" OK"); } console.log(`Building the app`); await execCommand("npm", ["run", "build"]); console.log(" OK"); console.log(`Creating the zip of builded app`); await execCommand("npm", ["run", "zip"]); console.log(" OK"); console.log(`Git commit release`); await execCommand("git", ["commit", "--allow-empty", "--message", `release ${versionChangelog}`]); console.log(" OK"); console.log(`Git push`); await execCommand("git", ["push"]); console.log(" OK"); console.log(`Creating tag "${gitTag}"`); await execCommand("git", ["tag", "--annotate", gitTag, "--message", gitTag]); console.log(` OK`); console.log(`Pushing tags`); await execCommand("git", ["push", "origin", gitTag]); // Tags are not pushed by regular `git push`. console.log(` OK`); console.log(""); console.log("DONE"); } main();
JavaScript
0
@@ -3673,97 +3673,8 @@ );%0A%0A - console.log(%60Git push%60);%0A await execCommand(%22git%22, %5B%22push%22%5D);%0A console.log(%22 OK%22);%0A%0A co @@ -3808,32 +3808,121 @@ e.log(%60 OK%60);%0A%0A + console.log(%60Git push%60);%0A await execCommand(%22git%22, %5B%22push%22%5D);%0A console.log(%22 OK%22);%0A%0A console.log(%60P
aba97371b5f50d74f5311695dbecf6753d5edb67
Fix protractor setup
protractor.conf.js
protractor.conf.js
const crew = require('serenity-js/lib/stage_crew'); const path = require('path'), protractor = require.resolve('protractor'), node_modules = protractor.substring(0, protractor.lastIndexOf('node_modules') + 12); exports.config = { seleniumServerJar: path.resolve(node_modules, 'protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.4.0.jar'), localSeleniumStandaloneOpts: { jvmArgs: [`-Dwebdriver.gecko.driver=${path.resolve(node_modules, 'protractor/node_modules/webdriver-manager/selenium')}/geckodriver-v0.18.0`] }, baseUrl: 'http://google.com', allScriptsTimeout: 110000, framework: 'custom', frameworkPath: require.resolve('serenity-js'), serenity: { dialect: 'cucumber', crew: [ crew.serenityBDDReporter(), crew.consoleReporter(), crew.Photographer.who(_ => _ .takesPhotosOf(_.Tasks_and_Interactions) .takesPhotosWhen(_.Activity_Finishes) ) ] }, specs: [ 'features/**/*.feature' ], cucumberOpts: { require: [ 'features/**/*.ts' ], format: 'pretty', compiler: 'ts:ts-node/register' }, capabilities: { browserName: 'chrome', chromeOptions: { args: [ // 'incognito', // 'disable-extensions', // 'show-fps-counter=true' ] }, // execute tests using 2 browsers running in parallel shardTestFiles: true, maxInstances: 2 }, restartBrowserBetweenTests: true };
JavaScript
0.000001
@@ -1,768 +1,764 @@ -const crew = require('serenity-js/lib/stage_crew');%0A%0Aconst path = require('path'),%0A protractor = require.resolve('protractor'),%0A node_modules = protractor.substring(0, protractor.lastIndexOf('node_modules') + 12);%0A%0Aexports.config = %7B%0A%0A seleniumServerJar: path.resolve(node_modules, 'protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.4.0.jar'),%0A%0A localSeleniumStandaloneOpts: %7B%0A jvmArgs: %5B%60-Dwebdriver.gecko.driver=$%7Bpath.resolve(node_modules, 'protractor/node_modules/webdriver-manager/selenium')%7D/geckodriver-v0.18.0%60%5D%0A %7D,%0A%0A baseUrl: 'http://google.com',%0A%0A allScriptsTimeout: 110000,%0A%0A framework: 'custom',%0A frameworkPath: require.resolve('serenity-js'),%0A serenity: %7B%0A dialect: 'cucumber', +// Protractor configuration file, see link for more information%0A// https://github.com/angular/protractor/blob/master/lib/config.ts%0Aconst crew = require('serenity-js/lib/stage_crew');%0A%0Aexports.config = %7B%0A%0A capabilities: %7B%0A 'browserName': 'chrome'%0A %7D,%0A%0A directConnect: true,%0A%0A // Framework definition - tells Protractor to use Serenity/JS%0A framework: 'custom',%0A frameworkPath: require.resolve('serenity-js'),%0A specs: %5B 'features/**/*.feature' %5D,%0A%0A cucumberOpts: %7B%0A require: %5B 'features/**/step_definitions/*.ts' %5D, // loads step definitions%0A format: 'pretty', // enable console output%0A compiler: 'ts:ts-node/register' // interpret step definitions as TypeScript%0A %7D,%0A%0A serenity: %7B %0A @@ -767,16 +767,19 @@ crew: + %5B%0A @@ -1005,297 +1005,59 @@ es)%0A -)%0A%5D%0A%7D,%0A%0Aspecs: %5B 'features/**/*.feature' %5D,%0A cucumberOpts: %7B%0A require: %5B 'features/**/*.ts' %5D,%0A format: 'pretty',%0A compiler: 'ts:ts-node/register'%0A%7D,%0A%0Acapabilities: %7B%0A browserName: 'chrome',%0A chromeOptions: %7B%0A args: %5B%0A // 'incognito + )%0A %5D,%0A dialect: 'cucumber ',%0A @@ -1067,237 +1067,74 @@ - // 'disable-extensions',%0A // 'show-fps-counter=true'%0A %5D%0A %7D,%0A%0A // execute tests using 2 browsers running in parallel%0A shardTestFiles: true,%0A maxInstances: 2%0A%7D,%0A%0ArestartBrowserBetweenTests: true +stageCueTimeout: 30 * 1000 // up to 30 seconds by default%0A %7D%0A %0A%7D; +%0A
a9f6329ba17dcb1d8d90137ba3d452a11d14a1f3
Fix absolute value of cartesian (was previously x*x+y*y, but should be Sqrt[x^2+y^2])
src/14.Expression.polar.js
src/14.Expression.polar.js
Expression.prototype.polar = function() { var ri = this.realimag(); var two = new Expression.Integer(2); return Expression.List.ComplexPolar([ ri[0]['^'](two)['+'](ri[1]['^'](two)), Global.atan2.default(Expression.Vector([ri[1], ri[0]])) ]); }; Expression.prototype.abs = function() { console.warn('SLOW?'); var ri = this.realimag(); return ri[0]['*'](ri[0])['+'](ri[1]['*'](ri[1])); }; Expression.prototype.arg = function() { console.warn('Slow?'); var ri = this.realimag(); return Global.atan2.default(Expression.Vector([ri[1], ri[0]])); };
JavaScript
0.000344
@@ -141,16 +141,36 @@ lar(%5B%0A%09%09 +Global.sqrt.default( ri%5B0%5D%5B'%5E @@ -198,16 +198,17 @@ '%5D(two)) +) ,%0A%09%09Glob @@ -363,31 +363,87 @@ );%0A%09 -return +var two = new Expression.Integer(2);%0A%09return Global.sqrt.default( ri%5B0%5D%5B' -*'%5D(ri%5B0%5D +%5E'%5D(two )%5B'+ @@ -456,17 +456,16 @@ 1%5D%5B' -*'%5D(ri%5B1%5D +%5E'%5D(two) ));%0A
1c322cabf0fd49d14b858ff6f176f3755970a2a7
Fix showing countries count in countries' actions map
app/javascript/app/components/sectors-agriculture/countries-actions/ndcs-map/ndcs-map-selectors.js
app/javascript/app/components/sectors-agriculture/countries-actions/ndcs-map/ndcs-map-selectors.js
import { createSelector } from 'reselect'; import { getColorByIndex, createLegendBuckets } from 'utils/map'; import uniqBy from 'lodash/uniqBy'; import sortBy from 'lodash/sortBy'; import { generateLinkToDataExplorer } from 'utils/data-explorer'; import worldPaths from 'app/data/world-50m-paths'; import { europeSlug, europeanCountries } from 'app/data/european-countries'; import { PATH_LAYERS } from 'app/data/constants'; const getSearch = state => state.search || null; const getCountries = state => state.countries || null; const getCategoriesData = state => state.categories || null; const getIndicatorsData = state => state.indicators || null; const PERMITTED_AGRICULTURE_INDICATOR = ['m_agriculture', 'a_agriculture']; export const getISOCountries = createSelector([getCountries], countries => countries.map(country => country.iso_code3) ); export const getIndicatorsParsed = createSelector( [getIndicatorsData, getISOCountries], (indicators, isos) => { if (!indicators || !indicators.length) return null; return sortBy( uniqBy( indicators.map(i => { const legendBuckets = createLegendBuckets( i.locations, i.labels, isos ); return { label: i.name, value: i.slug, categoryIds: i.category_ids, locations: i.locations, legendBuckets }; }), 'value' ), 'label' ); } ); export const getAgricultureIndicators = createSelector( [getIndicatorsParsed], indicatorsParsed => { if (!indicatorsParsed) return null; const agricultureIndicators = indicatorsParsed.filter(indicator => PERMITTED_AGRICULTURE_INDICATOR.includes(indicator.value) ); return agricultureIndicators; } ); export const getCountriesCountWithProposedActions = createSelector( [getAgricultureIndicators], indicators => { if (!indicators) return 0; const SECTORAL_ACTION_SPECIFIED_IDS = [56, 98]; const locations = indicators.map(ind => ind.locations); const countriesWithActionsSpecified = locations.map(location => Object.keys(location).filter(countryIso => SECTORAL_ACTION_SPECIFIED_IDS.includes(location[countryIso].label_id) ) ); return [...new Set(countriesWithActionsSpecified.flat())].length; } ); export const getCategories = createSelector( [getCategoriesData, getAgricultureIndicators], (categories, indicators) => { if (!categories || !indicators) return null; const indicatorsCategoryIds = indicators.map(ind => ind.categoryIds); const uniqueIndicatorsCategoryIds = [ ...new Set(indicatorsCategoryIds.flat()) ]; return sortBy( Object.keys(categories) .filter(category => uniqueIndicatorsCategoryIds.includes(parseInt(category, 10)) ) .map(category => ({ label: categories[category].name, value: categories[category].slug, id: category })), 'label' ); } ); export const getSelectedCategory = createSelector( [state => state.categorySelected, getCategories], (selected, categories = []) => { if (!categories || !categories.length) return null; const defaultCategory = categories.find(cat => cat.value === 'unfccc_process') || categories[0]; if (selected) { return ( categories.find(category => category.value === selected) || defaultCategory ); } return defaultCategory; } ); const countryStyles = { default: { fill: '#e9e9e9', fillOpacity: 1, stroke: '#f5f6f7', strokeWidth: 1, outline: 'none' }, hover: { fill: '#e9e9e9', fillOpacity: 1, stroke: '#f5f6f7', strokeWidth: 1, outline: 'none' }, pressed: { fill: '#e9e9e9', fillOpacity: 1, stroke: '#f5f6f7', strokeWidth: 1, outline: 'none' } }; export const MAP_COLORS = [ ['#0677B3', '#1ECDB0'], ['#0677B3', '#1ECDB0', '#00A0CA'], ['#0677B3', '#1ECDB0', '#00A0CA', '#00B4D2'] ]; export const getSelectedIndicator = createSelector( [getSelectedCategory, getAgricultureIndicators], (selectedCategory, agricultureIndicators) => { if (!selectedCategory || !agricultureIndicators) return null; return agricultureIndicators.find(ind => ind.categoryIds.includes(parseInt(selectedCategory.id, 10)) ); } ); export const getPathsWithStyles = createSelector( [getSelectedIndicator], selectedIndicator => { if (!selectedIndicator) return []; const paths = []; worldPaths.forEach(path => { if (path.properties.layer !== PATH_LAYERS.ISLANDS) { const { locations, legendBuckets } = selectedIndicator; if (!locations) { paths.push({ ...path, countryStyles }); return null; } const iso = path.properties && path.properties.id; const isEuropeanCountry = europeanCountries.includes(iso); const countryData = isEuropeanCountry ? locations[europeSlug] : locations[iso]; let style = countryStyles; if (countryData && countryData.label_id) { const legendData = legendBuckets[countryData.label_id]; const color = getColorByIndex( legendBuckets, legendData.index, MAP_COLORS ); style = { ...countryStyles, default: { ...countryStyles.default, fill: color, fillOpacity: 1 }, hover: { ...countryStyles.hover, fill: color, fillOpacity: 1 } }; } paths.push({ ...path, style }); } return null; }); return paths; } ); export const getLinkToDataExplorer = createSelector([getSearch], search => { const section = 'ndc-content'; return generateLinkToDataExplorer(search, section); }); export default { getCategories, getSelectedIndicator, getAgricultureIndicators, getSelectedCategory, getPathsWithStyles, getCountriesCountWithProposedActions };
JavaScript
0.002227
@@ -170,24 +170,66 @@ sh/sortBy';%0A +import lowerCase from 'lodash/lowerCase';%0A import %7B gen @@ -2002,48 +2002,37 @@ nst -SECTORAL_ACTION_SPECIFIED_IDS = %5B56, 98%5D +KEY_WORD_FOR_NO_ACTION = 'no' ;%0A%0A @@ -2193,16 +2193,25 @@ .filter( +%0A countryI @@ -2228,76 +2228,106 @@ -SECTORAL_ACTION_SPECIFIED_IDS.includes(location%5BcountryIso%5D.label_id + !lowerCase(location%5BcountryIso%5D.value).startsWith(%0A KEY_WORD_FOR_NO_ACTION%0A )%0A
57372472554341529fb071273e3bcd1c16794d4e
Unify require style
lib/hacks/grid-rows-columns.js
lib/hacks/grid-rows-columns.js
const Declaration = require('../declaration'); const { changeRepeat } = require('./grid-utils'); class GridRowsColumns extends Declaration { static names = [ 'grid-template-rows', 'grid-template-columns', 'grid-rows', 'grid-columns' ]; /** * Change property name for IE */ prefixed(prop, prefix) { if (prefix === '-ms-') { return prefix + prop.replace('template-', ''); } else { return super.prefixed(prop, prefix); } } /** * Change IE property back */ normalize(prop) { return prop.replace(/^grid-(rows|columns)/, 'grid-template-$1'); } /** * Change repeating syntax for IE */ set(decl, prefix) { if (prefix === '-ms-' && decl.value.indexOf('repeat(') !== -1) { decl.value = changeRepeat(decl.value); } return super.set(decl, prefix); } } module.exports = GridRowsColumns;
JavaScript
0.999294
@@ -50,24 +50,13 @@ nst -%7B changeRepeat %7D +utils = r @@ -825,16 +825,22 @@ value = +utils. changeRe
17b1d71536609c6deabcf3b13ec9be0ec9fd793f
Fix following_counter plural to include "one" (#14342)
app/javascript/mastodon/components/common_counter.js
app/javascript/mastodon/components/common_counter.js
// @ts-check import React from 'react'; import { FormattedMessage } from 'react-intl'; /** * Returns custom renderer for one of the common counter types * * @param {"statuses" | "following" | "followers"} counterType * Type of the counter * @param {boolean} isBold Whether display number must be displayed in bold * @returns {(displayNumber: JSX.Element, pluralReady: number) => JSX.Element} * Renderer function * @throws If counterType is not covered by this function */ export function counterRenderer(counterType, isBold = true) { /** * @type {(displayNumber: JSX.Element) => JSX.Element} */ const renderCounter = isBold ? (displayNumber) => <strong>{displayNumber}</strong> : (displayNumber) => displayNumber; switch (counterType) { case 'statuses': { return (displayNumber, pluralReady) => ( <FormattedMessage id='account.statuses_counter' defaultMessage='{count, plural, one {{counter} Toot} other {{counter} Toots}}' values={{ count: pluralReady, counter: renderCounter(displayNumber), }} /> ); } case 'following': { return (displayNumber, pluralReady) => ( <FormattedMessage id='account.following_counter' defaultMessage='{count, plural, other {{counter} Following}}' values={{ count: pluralReady, counter: renderCounter(displayNumber), }} /> ); } case 'followers': { return (displayNumber, pluralReady) => ( <FormattedMessage id='account.followers_counter' defaultMessage='{count, plural, one {{counter} Follower} other {{counter} Followers}}' values={{ count: pluralReady, counter: renderCounter(displayNumber), }} /> ); } default: throw Error(`Incorrect counter name: ${counterType}. Ensure it accepted by commonCounter function`); } }
JavaScript
0
@@ -1273,16 +1273,42 @@ plural, + one %7B%7Bcounter%7D Following%7D other %7B
2d0c854827a7f45fe3474a335ff6abb731e5f8b9
Remove development variable
app/js/controllers/init/create/IdentityController.js
app/js/controllers/init/create/IdentityController.js
"use strict"; var conf = require('js/lib/conf/conf'); module.exports = ($scope, $state, PubkeyGenerator) => { setTimeout(() => { $('select').material_select(); }, 500); $scope.accept = () => { let modal = $('#modal1'); if (modal.css('display') == 'none') { $('#modal1').openModal(); } }; PubkeyGenerator($scope); conf.dev_autoconf = true; if (conf.dev_autoconf) { $scope.$parent.conf.idty_uid = 'dev_' + ~~(Math.random() * 2147483647); $scope.$parent.conf.idty_entropy = ~~(Math.random() * 2147483647) + ""; $scope.$parent.conf.idty_password = ~~(Math.random() * 2147483647) + ""; $state.go('configure.create.network'); } };
JavaScript
0
@@ -348,36 +348,8 @@ );%0A%0A - conf.dev_autoconf = true;%0A if
f47d9010181740a4e0f21799e900da9ef80ae0a2
update lib/middleware/source_files to ES6
lib/middleware/source_files.js
lib/middleware/source_files.js
var querystring = require('querystring') var _ = require('lodash') var common = require('./common') var logger = require('../logger') var log = logger.create('middleware:source-files') // Files is a Set var findByPath = function (files, path) { return _.find(Array.from(files), function (file) { return file.path === path }) } var composeUrl = function (url, basePath, urlRoot, mustEscape) { return (mustEscape ? querystring.unescape(url) : url) .replace(urlRoot, '/') .replace(/\?.*$/, '') .replace(/^\/absolute/, '') .replace(/^\/base/, basePath) } // Source Files middleware is responsible for serving all the source files under the test. var createSourceFilesMiddleware = function (filesPromise, serveFile, basePath, urlRoot) { return function (request, response, next) { var requestedFilePath = composeUrl(request.url, basePath, urlRoot, true) // When a path contains HTML-encoded characters (e.g %2F used by Jenkins for branches with /) var requestedFilePathUnescaped = composeUrl(request.url, basePath, urlRoot, false) request.pause() log.debug('Requesting %s', request.url, urlRoot) log.debug('Fetching %s', requestedFilePath) return filesPromise.then(function (files) { // TODO(vojta): change served to be a map rather then an array var file = findByPath(files.served, requestedFilePath) || findByPath(files.served, requestedFilePathUnescaped) var rangeHeader = request.headers['range'] if (file) { serveFile(file.contentPath || file.path, rangeHeader, response, function () { if (/\?\w+/.test(request.url)) { // files with timestamps - cache one year, rely on timestamps common.setHeavyCacheHeaders(response) } else { // without timestamps - no cache (debug) common.setNoCacheHeaders(response) } }, file.content, file.doNotCache) } else { next() } request.resume() }) } } createSourceFilesMiddleware.$inject = [ 'filesPromise', 'serveFile', 'config.basePath', 'config.urlRoot' ] // PUBLIC API exports.create = createSourceFilesMiddleware
JavaScript
0.000003
@@ -1,11 +1,27 @@ -var +'use strict'%0A%0Aconst queryst @@ -54,38 +54,13 @@ g')%0A -var _ = require('lodash')%0A%0Avar +const com @@ -89,18 +89,18 @@ n')%0A -var +%0Aconst log -ger = r @@ -122,25 +122,8 @@ er') -%0Avar log = logger .cre @@ -158,51 +158,27 @@ ')%0A%0A -// Files is a Set%0Avar findByPath = function +function findByPath (fi @@ -203,15 +203,8 @@ urn -_.find( Arra @@ -220,38 +220,23 @@ les) -, function (file) %7B%0A return +.find((file) =%3E fil @@ -254,20 +254,21 @@ path -%0A %7D )%0A%7D%0A%0A -var +function com @@ -275,27 +275,16 @@ poseUrl -= function (url, ba @@ -302,20 +302,8 @@ Root -, mustEscape ) %7B%0A @@ -315,54 +315,11 @@ urn -(mustEscape ? querystring.unescape(url) : url) +url %0A @@ -528,19 +528,24 @@ e test.%0A -var +function createS @@ -569,19 +569,8 @@ are -= function (fil @@ -658,27 +658,29 @@ next) %7B%0A -var +const requestedFi @@ -733,14 +733,8 @@ Root -, true )%0A @@ -833,19 +833,21 @@ /)%0A -var +const request @@ -871,32 +871,53 @@ ed = composeUrl( +querystring.unescape( request.url, bas @@ -903,32 +903,33 @@ cape(request.url +) , basePath, urlR @@ -935,15 +935,8 @@ Root -, false )%0A%0A @@ -1180,19 +1180,21 @@ y%0A -var +const file = @@ -1243,25 +1243,8 @@ ) %7C%7C -%0A fin @@ -1303,11 +1303,13 @@ -var +const ran @@ -1499,24 +1499,62 @@ %0A + common.setHeavyCacheHeaders(response) // files wi @@ -1604,16 +1604,35 @@ estamps%0A + %7D else %7B%0A @@ -1637,37 +1637,34 @@ common.set -Heavy +No CacheHeaders(res @@ -1673,39 +1673,8 @@ nse) -%0A %7D else %7B%0A // @@ -1715,55 +1715,8 @@ ug)%0A - common.setNoCacheHeaders(response)%0A @@ -1955,22 +1955,8 @@ %0A%5D%0A%0A -// PUBLIC API%0A expo
f254ed4615c22e4f5c39f63f737011f0c2b972ac
Use changed is-selected class also in the specs
spec/file-list-component-spec.js
spec/file-list-component-spec.js
/** @babel */ import {GitRepositoryAsync} from 'atom' import etch from 'etch' import FileList from '../lib/file-list' import FileListViewModel from '../lib/file-list-view-model' import FileListComponent from '../lib/file-list-component' import GitService from '../lib/git-service' import {createFileDiffsFromPath, buildMouseEvent, copyRepository} from './helpers' function createFileList (filePath, gitService) { let fileDiffs = createFileDiffsFromPath(filePath) let fileList = new FileList(fileDiffs, gitService) return new FileListViewModel(fileList) } describe('FileListComponent', function () { let viewModel, component, element, gitService function getFileElements () { return element.querySelectorAll('.git-FileSummary') } function getFileElement (index) { return getFileElements()[index] } beforeEach(function () { const repoPath = copyRepository() gitService = new GitService(GitRepositoryAsync.open(repoPath)) viewModel = createFileList('fixtures/two-file-diff.txt', gitService) component = new FileListComponent({fileListViewModel: viewModel}) element = component.element jasmine.attachToDOM(component.element) spyOn(etch, 'update').andCallFake((component) => { return etch.updateSync(component) }) }) it('renders correctly', function () { let fileElements = getFileElements() expect(fileElements).toHaveLength(2) expect(fileElements[0]).toHaveClass('selected') expect(fileElements[1]).not.toHaveClass('selected') }) describe('keyboard selection of files', function () { it('arrows through the list with core move commands', function () { spyOn(component, 'selectionDidChange').andCallFake(() => { return etch.updateSync(component) }) expect(getFileElement(0)).toHaveClass('selected') atom.commands.dispatch(element, 'core:move-down') expect(getFileElement(1)).toHaveClass('selected') atom.commands.dispatch(element, 'core:move-up') expect(getFileElement(0)).toHaveClass('selected') }) }) describe('keyboard staging of files', function () { it('toggle stagedness on core:confirm', () => { expect(viewModel.getSelectedFile().getStageStatus()).toBe('unstaged') atom.commands.dispatch(element, 'core:confirm') expect(viewModel.getSelectedFile().getStageStatus()).toBe('staged') atom.commands.dispatch(element, 'core:confirm') expect(viewModel.getSelectedFile().getStageStatus()).toBe('unstaged') }) }) describe('mouse clicks', () => { const expectedURI = 'atom://git/diff/src/config.coffee' it("displays the file's diff in the pending state on single click", () => { spyOn(atom.workspace, 'open') const element = getFileElement(0) element.dispatchEvent(buildMouseEvent('click', {target: element})) const args = atom.workspace.open.mostRecentCall.args const uri = args[0] const options = args[1] expect(options.pending).toBe(true) expect(uri).toBe(expectedURI) }) it("displays the file's diff in the normal state on double click", () => { spyOn(atom.workspace, 'open') const element = getFileElement(0) element.dispatchEvent(buildMouseEvent('dblclick', {target: element})) const args = atom.workspace.open.mostRecentCall.args const uri = args[0] const options = args[1] expect(options.pending).toBe(false) expect(uri).toBe(expectedURI) }) }) })
JavaScript
0
@@ -1433,32 +1433,35 @@ %5D).toHaveClass(' +is- selected')%0A e @@ -1492,32 +1492,35 @@ ot.toHaveClass(' +is- selected')%0A %7D)%0A @@ -1802,32 +1802,35 @@ )).toHaveClass(' +is- selected')%0A%0A @@ -1816,32 +1816,32 @@ ('is-selected')%0A - %0A atom.comm @@ -1918,32 +1918,35 @@ )).toHaveClass(' +is- selected')%0A%0A @@ -1995,16 +1995,16 @@ ve-up')%0A - ex @@ -2040,16 +2040,19 @@ eClass(' +is- selected
061aa798de61969db3adcbb912e9100e71b7bc6b
Class=double
test/turnjs4/samples/quickguide/js/quickguide.js
test/turnjs4/samples/quickguide/js/quickguide.js
/* QuickGuide book */ function updateDepth(book, newPage) { var page = book.turn('page'), pages = book.turn('pages'), depthWidth = 16*Math.min(1, page*2/pages); newPage = newPage || page; if (newPage>2) $('.sj-book .p2 .depth').css({ width: depthWidth, left: 20 - depthWidth }); else $('.sj-book .p2 .depth').css({width: 0}); depthWidth = 16*Math.min(1, (pages-page)*2/pages); if (newPage<pages-2) $('.sj-book .p111 .depth').css({ width: depthWidth, right: 20 - depthWidth }); else $('.sj-book .p111 .depth').css({width: 0}); } function loadPage(page) { $.ajax({url: 'pages/page' + page + '.html'}). done(function(pageHtml) { $('.sj-book .p' + page).html(pageHtml.replace('samples/quickguide/', '')); }); } function addPage(page, book) { var id, pages = book.turn('pages'); if (!book.turn('hasPage', page)) { var element = $('<div />', {'class': 'own-size', css: {width: 920, height: 582} }). html('<div class="loader"></div>'); if (book.turn('addPage', element, page)) { loadPage(page); } } } function numberOfViews(book) { return book.turn('pages') / 2 + 1; } function getViewNumber(book, page) { return parseInt((page || book.turn('page'))/2 + 1, 10); } function zoomHandle(e) { if ($('.sj-book').data().zoomIn) zoomOut(); else if (e.target && $(e.target).hasClass('zoom-this')) { zoomThis($(e.target)); } } function zoomThis(pic) { var position, translate, tmpContainer = $('<div />', {'class': 'zoom-pic'}), transitionEnd = $.cssTransitionEnd(), tmpPic = $('<img />'), zCenterX = $('#book-zoom').width()/2, zCenterY = $('#book-zoom').height()/2, bookPos = $('#book-zoom').offset(), picPos = { left: pic.offset().left - bookPos.left, top: pic.offset().top - bookPos.top }, completeTransition = function() { $('#book-zoom').unbind(transitionEnd); if ($('.sj-book').data().zoomIn) { tmpContainer.appendTo($('body')); $('body').css({'overflow': 'hidden'}); tmpPic.css({ margin: position.top + 'px ' + position.left+'px' }). appendTo(tmpContainer). fadeOut(0). fadeIn(500); } }; $('.sj-book').data().zoomIn = true; $('.sj-book').turn('disable', true); $(window).resize(zoomOut); tmpContainer.click(zoomOut); tmpPic.load(function() { var realWidth = $(this)[0].width, realHeight = $(this)[0].height, zoomFactor = realWidth/pic.width(), picPosition = { top: (picPos.top - zCenterY)*zoomFactor + zCenterY + bookPos.top, left: (picPos.left - zCenterX)*zoomFactor + zCenterX + bookPos.left }; position = { top: ($(window).height()-realHeight)/2, left: ($(window).width()-realWidth)/2 }; translate = { top: position.top-picPosition.top, left: position.left-picPosition.left }; $('.samples .bar').css({visibility: 'hidden'}); $('#slider-bar').hide(); $('#book-zoom').transform( 'translate('+translate.left+'px, '+translate.top+'px)' + 'scale('+zoomFactor+', '+zoomFactor+')'); if (transitionEnd) $('#book-zoom').bind(transitionEnd, completeTransition); else setTimeout(completeTransition, 1000); }); tmpPic.attr('src', pic.attr('src')); } function zoomOut() { var transitionEnd = $.cssTransitionEnd(), completeTransition = function(e) { $('#book-zoom').unbind(transitionEnd); $('.sj-book').turn('disable', false); $('body').css({'overflow': 'auto'}); moveBar(false); }; $('.sj-book').data().zoomIn = false; $(window).unbind('resize', zoomOut); moveBar(true); $('.zoom-pic').remove(); $('#book-zoom').transform('scale(1, 1)'); $('.samples .bar').css({visibility: 'visible'}); $('#slider-bar').show(); if (transitionEnd) $('#book-zoom').bind(transitionEnd, completeTransition); else setTimeout(completeTransition, 1000); } function moveBar(yes) { if (Modernizr && Modernizr.csstransforms) { $('#slider .ui-slider-handle').css({zIndex: yes ? -1 : 10000}); } } function setPreview(view) { var previewWidth = 115, previewHeight = 73, previewSrc = 'pages/preview.jpg', preview = $(_thumbPreview.children(':first')), numPages = (view==1 || view==$('#slider').slider('option', 'max')) ? 1 : 2, width = (numPages==1) ? previewWidth/2 : previewWidth; _thumbPreview. addClass('no-transition'). css({width: width + 15, height: previewHeight + 15, top: -previewHeight - 30, left: ($($('#slider').children(':first')).width() - width - 15)/2 }); preview.css({ width: width, height: previewHeight }); if (preview.css('background-image')==='' || preview.css('background-image')=='none') { preview.css({backgroundImage: 'url(' + previewSrc + ')'}); setTimeout(function(){ _thumbPreview.removeClass('no-transition'); }, 0); } preview.css({backgroundPosition: '0px -'+((view-1)*previewHeight)+'px' }); } function isChrome() { // Chrome's unsolved bug // http://code.google.com/p/chromium/issues/detail?id=128488 return navigator.userAgent.indexOf('Chrome')!=-1; }
JavaScript
0.999976
@@ -892,16 +892,40 @@ iv /%3E',%0A +%09%09%09%7B'class': 'double'%0A// %09%09%09%7B'cla @@ -941,16 +941,18 @@ -size',%0A +// %09%09%09%09css: @@ -964,10 +964,10 @@ th: -92 +46 0, h
182a7de71a8d9223692e88592a20cc1e470c3c90
clean up
public/app/main.js
public/app/main.js
$(function() { 'use strict'; var board; (function() { var xx = $(window).width() / 17, yy = $(window).height() / 15.7; /* Board Options */ JXG.Options.angle.orthoType = "root"; JXG.Options.angle.radius = 25; JXG.Options.polygon.fillOpacity = 0.46; JXG.Options.polygon.fillColor = "#0ece16"; JXG.Options.elements.fixed = false; board = JXG.JSXGraph.initBoard('grid', { boundingbox: [-xx,yy,xx,-yy], keepaspectratio: true, showCopyright: false, showNavigation: false }); board.points = {}; board.shapes = []; board.xx = xx; board.yy = yy; board.axx = board.create('axis',[[0,0],[1,0]]); board.axy = board.create('axis',[[0,0],[0,1]]); board.unsuspendUpdate(); })(); if (!$('#application').hasClass('paste')) { /* Subscribe to application */ var App = window.App = require('./subscribe')(board); require('./helper/helpers') (App, board); /* various UI helpers */ require('./decorators/mouse')(App); /* drag decoration */ } else { /* Play Paste */ require('./helper/play')($AppPaste, board); $('.play').click(); // Replay button $('.replay').click(function() { require('./helper/play')($AppPaste, board); }); // Start new button $('.new').click(function() { window.location.href = '/'; }); } });
JavaScript
0.000001
@@ -938,21 +938,8 @@ pp = - window.App = req @@ -1096,16 +1096,20 @@ /* drag +ging decorat
693c38670ca64338eee8fde07dea4adb97a8435d
Better terse output
lib/reporters/console-terse.js
lib/reporters/console-terse.js
'use strict'; var d = require('es5-ext/lib/Object/descriptor') , deferred = require('deferred') , Base = require('./console').Reporter , Reporter; Reporter = function () { Base.apply(this, arguments); }; Reporter.prototype = Object.create(Base.prototype, { constructor: d(Reporter), logFile: d(function (name, report, limit, pos) { if (!report.length) return; this.log((limit ? report.slice(0, limit) : report).map(function (msg) { return report.path + '(' + msg.line + '):' + msg.message; }).join('\n')); }), logStatus: d(function () {}) }); module.exports = exports = function (reports/*, options*/) { var options = Object(arguments[1]); return deferred.map(reports.map(function (report) { deferred.validPromise(report); return (new Reporter(report, options)).init(); })); }; exports.returnsPromise = true; exports.Reporter = Reporter;
JavaScript
0.999745
@@ -476,17 +476,17 @@ path + ' -( +: ' + msg. @@ -497,14 +497,40 @@ + ' -) :' + +msg.character + ':' +%0A%09%09%09%09%09 msg.
df1fcf3a930e44764a16b79516b3efe3ddb202c8
Update hasOwn example for readability (#1988)
live-examples/js-examples/object/object-hasown.js
live-examples/js-examples/object/object-hasown.js
const object1 = {}; object1.prop = 'exists'; if (Object.hasOwn(object1, 'prop')) { console.log('\'prop\' is own property'); // expected output: 'prop' is own property } // Property values can be null or undefined object1.nullPropertyValue = null; console.log(Object.hasOwn(object1, 'nullPropertyValue')); // expected output: true object1.undefinedPropertyValue = undefined; console.log(Object.hasOwn(object1, 'undefinedPropertyValue')); // expected output: true // Inherited and undeclared values return false console.log(Object.hasOwn(object1, 'toString')); // expected output: false (inherited) console.log(Object.hasOwn(object1, 'undeclaredPropertyValue')); // expected output: false (not declared)
JavaScript
0
@@ -14,367 +14,29 @@ = %7B -%7D;%0Aobject1.prop = 'exists';%0Aif (Object.hasOwn(object1, 'prop')) %7B%0A console.log('%5C'prop%5C' is own property'); // expected output: 'prop' is own property%0A%7D%0A// Property values can be null or undefined%0Aobject1.nullPropertyValue = null;%0Aconsole.log(Object.hasOwn(object1, 'nullPropertyValue')); // expected output: true%0Aobject1.undefinedPropertyValue = undefined; +%0A prop: 'exists'%0A%7D;%0A %0Acon @@ -72,36 +72,17 @@ 1, ' -undefinedPropertyValue +prop ')); - +%0A // e @@ -106,55 +106,8 @@ rue%0A -// Inherited and undeclared values return false %0Acon @@ -147,26 +147,25 @@ toString')); - +%0A // expected @@ -181,20 +181,9 @@ alse - (inherited) +%0A %0Acon @@ -242,18 +242,17 @@ alue')); - +%0A // expec @@ -272,20 +272,5 @@ alse - (not declared) %0A
ec01a2e0b5dc430adab9da28dec427dc0c9c218a
remove `autobind` from `IssueDetailView`
lib/views/issue-detail-view.js
lib/views/issue-detail-view.js
import React, {Fragment} from 'react'; import {graphql, createRefetchContainer} from 'react-relay'; import PropTypes from 'prop-types'; import cx from 'classnames'; import IssueTimelineController from '../controllers/issue-timeline-controller'; import Octicon from '../atom/octicon'; import IssueishBadge from '../views/issueish-badge'; import GithubDotcomMarkdown from '../views/github-dotcom-markdown'; import EmojiReactionsView from '../views/emoji-reactions-view'; import PeriodicRefresher from '../periodic-refresher'; import {autobind} from '../helpers'; import {addEvent} from '../reporter-proxy'; export class BareIssueDetailView extends React.Component { static propTypes = { relay: PropTypes.shape({ refetch: PropTypes.func.isRequired, }), switchToIssueish: PropTypes.func.isRequired, repository: PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, owner: PropTypes.shape({ login: PropTypes.string, }), }), issue: PropTypes.shape({ __typename: PropTypes.string.isRequired, id: PropTypes.string.isRequired, title: PropTypes.string, url: PropTypes.string.isRequired, bodyHTML: PropTypes.string, number: PropTypes.number, state: PropTypes.oneOf([ 'OPEN', 'CLOSED', ]).isRequired, author: PropTypes.shape({ login: PropTypes.string.isRequired, avatarUrl: PropTypes.string.isRequired, url: PropTypes.string.isRequired, }).isRequired, reactionGroups: PropTypes.arrayOf( PropTypes.shape({ content: PropTypes.string.isRequired, users: PropTypes.shape({ totalCount: PropTypes.number.isRequired, }).isRequired, }), ).isRequired, }).isRequired, } state = { refreshing: false, } constructor(props) { super(props); autobind(this, 'handleRefreshClick', 'refresh', 'renderIssueBody', 'recordOpenInBrowserEvent'); } componentDidMount() { this.refresher = new PeriodicRefresher(BareIssueDetailView, { interval: () => 5 * 60 * 1000, getCurrentId: () => this.props.issue.id, refresh: this.refresh, minimumIntervalPerId: 2 * 60 * 1000, }); // auto-refresh disabled for now until pagination is handled // this.refresher.start(); } componentWillUnmount() { this.refresher.destroy(); } renderIssueBody(issue) { return ( <Fragment> <GithubDotcomMarkdown html={issue.bodyHTML || '<em>No description provided.</em>'} switchToIssueish={this.props.switchToIssueish} /> <EmojiReactionsView reactionGroups={issue.reactionGroups} /> <IssueTimelineController issue={issue} switchToIssueish={this.props.switchToIssueish} /> </Fragment> ); } render() { const repo = this.props.repository; const issue = this.props.issue; return ( <div className="github-IssueishDetailView native-key-bindings"> <div className="github-IssueishDetailView-container"> <header className="github-IssueishDetailView-header"> <div className="github-IssueishDetailView-headerRow"> <div className="github-IssueishDetailView-headerGroup"> <a className="github-IssueishDetailView-avatar" href={issue.author.url}> <img className="github-IssueishDetailView-avatarImage" src={issue.author.avatarUrl} title={issue.author.login} alt={issue.author.login} /> </a> <a className="github-IssueishDetailView-title" href={issue.url}>{issue.title}</a> </div> <div className="github-IssueishDetailView-headerGroup"> <Octicon icon="repo-sync" className={cx('github-IssueishDetailView-headerRefreshButton', {refreshing: this.state.refreshing})} onClick={this.handleRefreshClick} /> </div> </div> <div className="github-IssueishDetailView-headerRow"> <div className="github-IssueishDetailView-headerGroup"> <IssueishBadge className="github-IssueishDetailView-headerBadge" type={issue.__typename} state={issue.state} /> <a className="github-IssueishDetailView-headerLink" title="open on GitHub.com" href={issue.url} onClick={this.recordOpenInBrowserEvent}> {repo.owner.login}/{repo.name}#{issue.number} </a> </div> </div> </header> {this.renderIssueBody(issue)} <footer className="github-IssueishDetailView-footer"> <a className="github-IssueishDetailView-footerLink icon icon-mark-github" href={issue.url}>{repo.owner.login}/{repo.name}#{issue.number} </a> </footer> </div> </div> ); } handleRefreshClick(e) { e.preventDefault(); this.refresher.refreshNow(true); } recordOpenInBrowserEvent() { addEvent('open-issue-in-browser', {package: 'github', component: this.constructor.name}); } refresh() { if (this.state.refreshing) { return; } this.setState({refreshing: true}); this.props.relay.refetch({ repoId: this.props.repository.id, issueishId: this.props.issue.id, timelineCount: 100, timelineCursor: null, }, null, () => { this.setState({refreshing: false}); }, {force: true}); } } export default createRefetchContainer(BareIssueDetailView, { repository: graphql` fragment issueDetailView_repository on Repository { id name owner { login } } `, issue: graphql` fragment issueDetailView_issue on Issue @argumentDefinitions( timelineCount: {type: "Int!"}, timelineCursor: {type: "String"}, ) { __typename ... on Node { id } ... on Issue { state number title bodyHTML author { login avatarUrl ... on User { url } ... on Bot { url } } ...issueTimelineController_issue @arguments(timelineCount: $timelineCount, timelineCursor: $timelineCursor) } ... on UniformResourceLocatable { url } ... on Reactable { reactionGroups { content users { totalCount } } } } `, }, graphql` query issueDetailViewRefetchQuery ( $repoId: ID!, $issueishId: ID!, $timelineCount: Int!, $timelineCursor: String, ) { repository:node(id: $repoId) { ...issueDetailView_repository @arguments( timelineCount: $timelineCount, timelineCursor: $timelineCursor ) } issue:node(id: $issueishId) { ...issueDetailView_issue @arguments( timelineCount: $timelineCount, timelineCursor: $timelineCursor, ) } } `);
JavaScript
0
@@ -522,45 +522,8 @@ r';%0A -import %7Bautobind%7D from '../helpers';%0A impo @@ -1814,154 +1814,8 @@ %7D%0A%0A - constructor(props) %7B%0A super(props);%0A autobind(this, 'handleRefreshClick', 'refresh', 'renderIssueBody', 'recordOpenInBrowserEvent');%0A %7D%0A%0A co @@ -4956,11 +4956,17 @@ lick -(e) + = (e) =%3E %7B%0A @@ -5056,18 +5056,24 @@ serEvent -() + = () =%3E %7B%0A a @@ -5175,18 +5175,24 @@ refresh -() + = () =%3E %7B%0A i
af8db6790ee93762bb0e0f364da38eff3e0ec509
rename TweetCache to FetchCache
service/twitter.js
service/twitter.js
window.Twitter = (function() { "use strict"; const CONSUMER_KEY = "vbUQPCkkyFYUiomrSk9Nnysh0"; const CONSUMER_SECRET = "2EEZCi4nDKHK8rc4Y43iBQ3Nl9HSLbmaZeVigip1grhcmL8ajF"; const REFRESH_INTERVAL_MS = 10 * 60 * 1000; // 10 mins const CACHE_LIFETIME_MS = 5 * 1000; // 5 seconds function hashKey(source, params) { if (!$.isDefined(params)) { params = {}; } return `${source}:${JSON.stringify(params)}`; } // => func(resolve, reject) function fetchPromiseFuncFactory(client, source, params) { return function(resolve, reject) { console.log('[twitter]', source, params); return client.__call(source, params, (reply, rate, err) => { if (err) { console.error(`[twitter] error:`, err, source, params); Notify.error(`[twitter] error in API ${source} fetch: ${err}`); reject(err.error); } if (reply.httpstatus === 400) { console.error(`[twitter] rate exceeded!`, rate, source, params); Notify.error(`[twitter] API ${source} rate exceeded!`); reject(err.error); } else { console.log(`[twitter] rate limit:`, rate); } if (reply.errors) { reply.errors.forEach((error) => { console.error(`[twitter] error in reply:`, error.code, error.message, source, params); Notify.error(`[twitter] error in API ${source} reply: ${error.code}: ${error.message}`); }); reject(reply.errors); } if (reply) { resolve(reply); } reject("No reply"); }); }; } class TweetCache { constructor(func) { this.func = func; this.value = null; this.timestamp = new Date(0); // data at 1969 } getValuePromise() { var now = new Date(); return new Promise((resolve, reject) => { if (this.timestamp !== null && ((now - this.timestamp) < CACHE_LIFETIME_MS)) { // TweetCache is valid! resolve(this.value); } else { // Otherwise fetch it! this.func(resolve, reject); } }); } } class Twitter { constructor(token, token_secret) { this.client = new Codebird(); this.client.setConsumerKey(CONSUMER_KEY, CONSUMER_SECRET); this.setToken(token, token_secret); this.cache = {}; // String => TweetCache } setToken(token, secret) { console.debug('Set token: ', token, secret); this.client.setToken(token, secret); } auth(callback) { this.client.__call("oauth_requestToken", { oauth_callback: "oob" }, (reply) => { // This is the request token, not final accessToken. this.client.setToken(reply.oauth_token, reply.oauth_token_secret); // gets the authorize screen URL this.client.__call("oauth_authorize", {}, (auth_url) => { if (callback) { callback(auth_url); } else { window.codebird_auth = window.open(auth_url); } }); }); } verify(pinCode, callback) { this.client.__call("oauth_accessToken", { oauth_verifier: pinCode }, (reply) => { console.log('twitter.verify', reply); // store the authenticated token, which may be different from the request token (!) this.setToken(reply.oauth_token, reply.oauth_token_secret); if (callback) { callback(reply); } }); } // try to get the cache or fetch it // => Promise fetch(source, params) { if (!$.isDefined(params)) { params = {}; } var key = hashKey(source, params); if (!(key in this.cache)) { this.cache[key] = new TweetCache(fetchPromiseFuncFactory(this.client, source, params)); } return this.cache[key].getValuePromise(); } // => Promise post(source, params) { if (!$.isDefined(params)) { params = {}; } return new Promise((resolve, reject) => { fetchPromiseFuncFactory(this.client, source, params)(resolve, reject); }); } } return Twitter; })();
JavaScript
0.001444
@@ -1608,21 +1608,21 @@ class -Tweet +Fetch Cache %7B%0A @@ -1953,21 +1953,21 @@ // -Tweet +Fetch Cache is @@ -2360,21 +2360,21 @@ ring =%3E -Tweet +Fetch Cache%0A @@ -3727,13 +3727,13 @@ new -Tweet +Fetch Cach
fd44e1fe4cab1bc8967f14b889151a1e0600a61d
update AnchorButton
src/AnchorButton/AnchorButton.js
src/AnchorButton/AnchorButton.js
/** * @file AnchorButton component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import BaseButton from '../_BaseButton'; import TipProvider from '../TipProvider'; import Theme from '../Theme'; import Position from '../_statics/Position'; import Util from '../_vendors/Util'; class AnchorButton extends Component { static Theme = Theme; static TipPosition = Position; constructor(props, ...restArgs) { super(props, ...restArgs); this.startRipple = ::this.startRipple; this.endRipple = ::this.endRipple; } startRipple(e) { this.refs.baseButton.startRipple(e); } endRipple() { this.refs.baseButton.endRipple(); } render() { const {children, className, ...restProps} = this.props, buttonClassName = classNames('anchor-button', { [className]: className }); return ( <BaseButton {...restProps} ref="baseButton" className={buttonClassName}> {children} </BaseButton> ); } } AnchorButton.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * The button theme.Can be primary,highlight,success,warning,error. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * If true,the button will have rounded corners. */ isRounded: PropTypes.bool, /** * If true,the button will be round. */ isCircular: PropTypes.bool, /** * The text of the button. */ value: PropTypes.any, /** * The type of button.Can be reset,submit or button. */ type: PropTypes.string, /** * Disables the button if set to true. */ disabled: PropTypes.bool, /** * If true,the button will be have loading effect. */ isLoading: PropTypes.bool, /** * If true,the element's ripple effect will be disabled. */ disableTouchRipple: PropTypes.bool, /** * Use this property to display an icon.It will display on the left. */ iconCls: PropTypes.string, /** * Use this property to display an icon.It will display on the right. */ rightIconCls: PropTypes.string, /** * If true,the ripple effect will be display centered. */ rippleDisplayCenter: PropTypes.bool, tip: PropTypes.string, tipPosition: PropTypes.oneOf(Util.enumerateValue(TipProvider.Position)), /** * You can create a complicated renderer callback instead of value prop. */ renderer: PropTypes.func, /** * Callback function fired when the button is touch-tapped. */ onClick: PropTypes.func }; AnchorButton.defaultProps = { theme: Theme.DEFAULT, isRounded: false, isCircular: false, value: '', disabled: false, type: 'button', isLoading: false, disableTouchRipple: false, rippleDisplayCenter: false, tipPosition: TipProvider.Position.BOTTOM }; export default AnchorButton;
JavaScript
0
@@ -1781,32 +1781,110 @@ ropTypes.bool,%0A%0A + /**%0A * The title of the button.%0A */%0A title: PropTypes.string,%0A%0A /**%0A * T
26b9c144d9610d94900ed79b8407c6885ce12abd
normalize undefined to null on create, update
lib/waterline/core/typecast.js
lib/waterline/core/typecast.js
/** * Module dependencies */ var types = require('../utils/types'); /** * Cast Types * * Will take values and cast they to the correct type based on the * type defined in the schema. * * Especially handy for converting numbers passed as strings to the * correct integer type. * * Should be run before sending values to an adapter. */ var Cast = module.exports = function() { this._types = {}; return this; }; /** * Builds an internal _types object that contains each * attribute with it's type. This can later be used to * transform values into the correct type. * * @param {Object} attrs */ Cast.prototype.initialize = function(attrs) { for(var key in attrs) { this._types[key] = ~types.indexOf(attrs[key].type) ? attrs[key].type : 'string'; } }; /** * Converts a set of values into the proper types * based on the Collection's schema. * * Just do strings and numbers for now. * * @param {Object} key/value set of model values * @return {Object} values casted to proper types */ Cast.prototype.run = function(values) { var self = this; Object.keys(values).forEach(function(key) { if(!self._types[key] || values[key] == null || !values.hasOwnProperty(key)) return; // Find the value's type var type = self._types[key]; // Casting Function switch(type) { case 'string': values[key] = values[key].toString(); break; case 'integer': if(!values[key]) break; values[key] = parseInt(values[key], 10); break; case 'float': if(!values[key]) break; values[key] = parseFloat(values[key]); break; // Nicely Cast 0,1 to false/true case 'boolean': if(parseInt(values[key], 10) === 0) values[key] = false; if(parseInt(values[key], 10) === 1) values[key] = true; break; } }); return values; };
JavaScript
0
@@ -1127,24 +1127,109 @@ tion(key) %7B%0A +%0A // Set undefined to null%0A if(values%5Bkey%5D === undefined) values%5Bkey%5D = null;%0A%0A if(!self @@ -1258,16 +1258,17 @@ %5Bkey%5D == += null %7C%7C
1e1c08d7359f0104a60fd6bfaf6d3e93edb98aac
Update http.js - Add support for headers
lib/winston/transports/http.js
lib/winston/transports/http.js
var util = require('util'), winston = require('../../winston'), http = require('http'), https = require('https'), Stream = require('stream').Stream, TransportStream = require('winston-transport'); // // ### function Http (options) // #### @options {Object} Options for this instance. // Constructor function for the Http transport object responsible // for persisting log messages and metadata to a terminal or TTY. // var Http = module.exports = function (options) { TransportStream.call(this, options); options = options || {}; this.name = 'http'; this.ssl = !!options.ssl; this.host = options.host || 'localhost'; this.port = options.port; this.auth = options.auth; this.path = options.path || ''; this.agent = options.agent; if (!this.port) { this.port = this.ssl ? 443 : 80; } }; util.inherits(Http, TransportStream); // // Expose the name of this Transport on the prototype // Http.prototype.name = 'http'; // // ### function log (meta) // #### @meta {Object} **Optional** Additional metadata to attach // Core logging method exposed to Winston. // Http.prototype.log = function (info, callback) { var self = this; this._request(info, function (err, res) { if (res && res.statusCode !== 200) { err = new Error('Invalid HTTP Status Code: ' + res.statusCode); } if (err) { self.emit('warn', err); } else { self.emit('logged'); } }); // // Remark: (jcrugzz) Fire and forget here so requests dont cause buffering // and block more requests from happening? // if (callback) { setImmediate(callback); } }; // // ### function query (options, callback) // #### @options {Object} Loggly-like query options for this instance. // #### @callback {function} Continuation to respond to when complete. // Query the transport. Options object is optional. // Http.prototype.query = function (options, callback) { if (typeof options === 'function') { callback = options; options = {}; } var self = this, options = this.normalizeQuery(options); options = { method: 'query', params: options }; if (options.params.path) { options.path = options.params.path; delete options.params.path; } if (options.params.auth) { options.auth = options.params.auth; delete options.params.auth; } this._request(options, function (err, res, body) { if (res && res.statusCode !== 200) { err = new Error('HTTP Status Code: ' + res.statusCode); } if (err) return callback(err); if (typeof body === 'string') { try { body = JSON.parse(body); } catch (e) { return callback(e); } } callback(null, body); }); }; // // ### function stream (options) // #### @options {Object} Stream options for this instance. // Returns a log stream for this transport. Options object is optional. // Http.prototype.stream = function (options) { options = options || {}; var self = this, stream = new Stream, req, buff; stream.destroy = function () { req.destroy(); }; options = { method: 'stream', params: options }; if (options.params.path) { options.path = options.params.path; delete options.params.path; } if (options.params.auth) { options.auth = options.params.auth; delete options.params.auth; } req = this._request(options); buff = ''; req.on('data', function (data) { var data = (buff + data).split(/\n+/), l = data.length - 1, i = 0; for (; i < l; i++) { try { stream.emit('log', JSON.parse(data[i])); } catch (e) { stream.emit('error', e); } } buff = data[l]; }); req.on('error', function (err) { stream.emit('error', err); }); return stream; }; // // ### function _request (options, callback) // #### @callback {function} Continuation to respond to when complete. // Make a request to a winstond server or any http server which can // handle json-rpc. // Http.prototype._request = function (options, callback) { options = options || {}; var auth = options.auth || this.auth, path = options.path || this.path || '', req; delete options.auth; delete options.path; // Prepare options for outgoing HTTP request req = (this.ssl ? https : http).request({ method: 'POST', host: this.host, port: this.port, path: '/' + path.replace(/^\//, ''), headers: { 'Content-Type': 'application/json' }, auth: auth ? (auth.username + ':' + auth.password) : '', agent: this.agent }); req.on('error', callback); req.on('response', function (res) { res.on('end', function () { callback(null, res); }).resume(); }); req.end(new Buffer(JSON.stringify(options), 'utf8')); };
JavaScript
0
@@ -761,16 +761,109 @@ s.agent; +%0A this.headers = options.headers %7C%7C %7B%7D;%0A this.headers%5B'content-type'%5D = 'application/json'; %0A%0A if ( @@ -4549,46 +4549,20 @@ rs: -%7B 'Content-Type': 'application/json' %7D +this.headers ,%0A
e459786f841b706036daef757dabc1972db3d4db
fix gulp watch and Quick startup
gulp/development.js
gulp/development.js
'use strict'; var gulp = require('gulp'), gulpLoadPlugins = require('gulp-load-plugins'), through = require('through'), gutil = require('gulp-util'), plugins = gulpLoadPlugins(), coffee = require('gulp-coffee'), paths = { js: ['*.js', 'test/**/*.js', '!test/coverage/**', '!bower_components/**', '!packages/**/node_modules/**', '!packages/contrib/**/*.js', '!packages/contrib/**/node_modules/**', '!packages/core/**/*.js', '!packages/core/public/assets/lib/**/*.js'], html: ['packages/**/public/**/views/**', 'packages/**/server/views/**'], css: ['!bower_components/**', 'packages/**/public/**/css/*.css', '!packages/contrib/**/public/**/css/*.css', '!packages/core/**/public/**/css/*.css'], less: ['**/public/**/css/*.less'], sass: ['**/public/**/css/*.scss'], coffee: ['packages/**/public/**/*.coffee','*.coffee'], coffees: ['packages/**/server/**/*.coffee'] }; /*var defaultTasks = ['clean', 'jshint', 'less', 'csslint', 'devServe', 'watch'];*/ var defaultTasks = ['coffee','clean', 'less', 'csslint', 'devServe', 'watch']; gulp.task('env:development', function () { process.env.NODE_ENV = 'development'; }); gulp.task('jshint', function () { return gulp.src(paths.js) .pipe(plugins.jshint()) .pipe(plugins.jshint.reporter('jshint-stylish')) .pipe(plugins.jshint.reporter('fail')) .pipe(count('jshint', 'files lint free')); }); gulp.task('csslint', function () { return gulp.src(paths.css) .pipe(plugins.csslint('.csslintrc')) .pipe(plugins.csslint.reporter()) .pipe(count('csslint', 'files lint free')); }); gulp.task('less', function() { return gulp.src(paths.less) .pipe(plugins.less()) .pipe(gulp.dest(function (vinylFile) { return vinylFile.cwd; })); }); gulp.task('devServe', ['env:development'], function () { plugins.nodemon({ script: 'server.js', ext: 'html js', env: { 'NODE_ENV': 'development' } , ignore: ['node_modules/', 'bower_components/', 'logs/', 'packages/*/*/public/assets/lib/', 'packages/*/*/node_modules/', '.DS_Store', '**/.DS_Store', '.bower-*', '**/.bower-*'], nodeArgs: ['--debug'], stdout: false }).on('readable', function() { this.stdout.on('data', function(chunk) { if(/Mean app started/.test(chunk)) { setTimeout(function() { plugins.livereload.reload(); }, 500); } process.stdout.write(chunk); }); this.stderr.pipe(process.stderr); }); }); gulp.task('coffee', function() { gulp.src(paths.coffee) .pipe(coffee({bare: true}).on('error', gutil.log)) .pipe(gulp.dest('./packages')); }); gulp.task('watch', function () { plugins.livereload.listen({interval:500}); gulp.watch(paths.coffee,['coffee']); gulp.watch(paths.js, ['jshint']); gulp.watch(paths.css, ['csslint']).on('change', plugins.livereload.changed); gulp.watch(paths.less, ['less']); }); function count(taskName, message) { var fileCount = 0; function countFiles(file) { fileCount++; // jshint ignore:line } function endStream() { gutil.log(gutil.colors.cyan(taskName + ': ') + fileCount + ' ' + message || 'files processed.'); this.emit('end'); // jshint ignore:line } return through(countFiles, endStream); } gulp.task('development', defaultTasks);
JavaScript
0
@@ -238,24 +238,26 @@ js: %5B' +./ *.js', ' test/**/ @@ -248,20 +248,22 @@ *.js', ' -test +config /**/*.js @@ -270,176 +270,188 @@ ', ' -!test/coverage/**', '!bower_components/**', '!packages/**/node_modules/**', '!packages/contrib/**/*.js', '!packages/contrib/**/node_modules/**', '!packages/core/**/*.js +gulp/**/*.js', 'tools/**/*.js', 'packages/**/*.js', '!packages/**/node_modules/**', '!packages/**/assets/**/lib/**'%5D,%0A html: %5B'packages/**/*.html', '!packages/**/node_modules/** ', ' @@ -464,27 +464,18 @@ ges/ -core/public +** /assets/ lib/ @@ -474,27 +474,25 @@ ets/ +**/ lib/** -/*.js '%5D,%0A html @@ -479,36 +479,35 @@ */lib/**'%5D,%0A -html +css : %5B'packages/**/ @@ -510,30 +510,49 @@ /**/ -public/**/view +*.css', '!packages/**/node_module s/**', ' pack @@ -539,32 +539,33 @@ e_modules/**', ' +! packages/**/serv @@ -564,20 +564,21 @@ /**/ -server/views +assets/**/lib /**' @@ -588,114 +588,66 @@ -c +le ss: %5B' -!bower_components/**', 'packages/**/public/**/css/*.css', '!packages/contrib/**/public/**/css/*.css +packages/**/*.less', '!packages/**/node_modules/** ', ' @@ -660,43 +660,35 @@ ges/ -core +**/assets /**/ -pub li -c +b /** -/css/*.css '%5D,%0A less @@ -687,186 +687,202 @@ -le +sa ss: %5B' -**/public/**/css/*.less'%5D,%0A sass: %5B'**/public/**/css/*.scss'%5D,%0A coffee: %5B'packages/**/public/**/*.coffee','*.coffee'%5D,%0A coffees: %5B'packages/**/server/**/*.coffee +packages/**/*.scss', '!packages/**/node_modules/**', '!packages/**/assets/**/lib/**'%5D,%0A coffee: %5B'packages/**/*.coffee', '!packages/**/node_modules/**', '!packages/**/assets/**/lib/** '%5D%0A @@ -1007,17 +1007,16 @@ 'clean', - 'less', @@ -1280,24 +1280,27 @@ ylish'))%0A + // .pipe(plugi @@ -1326,16 +1326,51 @@ 'fail')) + to avoid shutdown gulp by warnings %0A .pi
be062ae3aa729eb253a17973bf92f00a35b7d961
Update cypress test expected value given new step value for regional pop
e2e/cypress/integration/tests/actions.spec.js
e2e/cypress/integration/tests/actions.spec.js
/// <reference types="cypress" /> context('Actions', () => { beforeEach(() => { cy.visit('http://localhost:8000') }); it('All + elements are clickable', () => { cy.get('.step-up').click( { multiple: true } ); // This gets the "first" input from the sidebar. From clicking step up, // the Regional Population should increase from default 4119405 to 4219405. cy.get('input.st-al') .should('has.value', '4219405') }) });
JavaScript
0
@@ -430,22 +430,22 @@ lue', '4 -2 +1 1940 -5 +6 ')%0A %7D)%0A
9f82d0b6ea6bc977fe6de302a363db5bd444fa77
Fix watch
gulp/tasks/watch.js
gulp/tasks/watch.js
/** * Delete specified directories and all files in them. * * --------------------------------------------------------------- * */ var clean = require('gulp-clean'); var livereload = require('gulp-livereload'); var notify = require('gulp-notify'); var paths = require('../paths'); module.exports = function (gulp) { gulp.task('watch', function () { gulp.watch(paths.css, ['sass']); gulp.watch(paths.scripts, ['copyScriptsToAssets']); gulp.watch(paths.images, ['images']); gulp.watch(paths.jsxTemplates, ['react']); }); };
JavaScript
0.000002
@@ -279,16 +279,52 @@ paths'); +%0Avar scripts = require('./scripts'); %0A%0Amodule @@ -353,16 +353,34 @@ ulp) %7B%0A%0A + scripts(gulp);%0A%0A gulp.t @@ -479,25 +479,13 @@ , %5B' -copyScriptsToAsse +scrip ts'%5D
ca9a03601f86d68358f212b8fa775f5dfaabd2de
fix lint task
gulpy/tasks/lint.js
gulpy/tasks/lint.js
var gulp = require('gulp'), // Gulp JS jshint = require('gulp-jshint'), // JS linter cache = require('gulp-cached'), // Gulp cache module jscs = require('gulp-jscs'), // JS-style checker notify = require('gulp-notify'), // Plugin for notify notifyConfig = require('../../projectConfig').notifyConfig, // Notify config modifyDate = require('../helpers/modifyDateFormatter'); // Date formatter for notify var jsPathsToLint = [ './markup/modules/**/*.js', '!./markup/modules/**/_*.js', '!./markup/modules/**/moduleData.js' ]; if (projectConfig.lintJsCodeBeforeModules) { projectConfig.jsPathsToConcatBeforeModulesJs.forEach(function(path) { jsPathsToLint.push(path) }); } if (projectConfig.lintJsCodeAfterModules) { projectConfig.jsPathsToConcatAfterModulesJs.forEach(function(path) { jsPathsToLint.push(path) }); } // Check JS (code style and errors) module.exports = function() { return gulp.task('lint', function() { return gulp.src(jsPathsToLint) .pipe(cache('linting')) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jscs()) .on('error', notify.onError(function (error) { return 'There are some errors in JS.\nLook in console!'; })); }); };
JavaScript
0.999485
@@ -403,22 +403,23 @@ ify%0A -notify +project Config = @@ -449,16 +449,50 @@ Config') +,%0A notifyConfig = projectConfig .notifyC
f1f3f2c73728fede1835d457b0c5e78ac9b30aa4
Throw if spy doesnt have what to spy on
sinon-spy-react.js
sinon-spy-react.js
var React = require('react'); var ReactDOM = require('react-dom'); var sinon = require('sinon'); function spyOnComponentMethod(reactClass, methodName) { var classProto = reactClassPrototype(reactClass); var spy; var on; var idx; if (classProto.__reactAutoBindMap) { // React 0.14.x spy = classProto.__reactAutoBindMap[methodName] = sinon.spy(classProto.__reactAutoBindMap[methodName]); } else if (classProto.__reactAutoBindPairs) { // React 15.x idx = classProto.__reactAutoBindPairs.indexOf(methodName); if(idx !== -1){ spy = classProto.__reactAutoBindPairs[idx+1] = sinon.spy(classProto.__reactAutoBindPairs[idx+1]); } else { throw new Error('Cannot spy on a function that does not exist'); } } return spy; } function stubComponentMethod(reactClass, methodName) { var classProto = reactClassPrototype(reactClass); var stub; var on; var idx; var i; if (classProto.__reactAutoBindMap) { // React 0.14.x stub = classProto.__reactAutoBindMap[methodName] = sinon.stub(classProto.__reactAutoBindMap, methodName); } else if (classProto.__reactAutoBindPairs) { // React 15.x idx = classProto.__reactAutoBindPairs.indexOf(methodName); if(idx !== -1){ stub = sinon.stub(classProto.__reactAutoBindPairs, idx+1); } else { stub = sinon.stub(); i = classProto.__reactAutoBindPairs.push( methodName ); classProto.__reactAutoBindPairs.push( stub ); stub.restore = function(){ classProto.__reactAutoBindPairs.splice(i-1, 2); } } } return stub; } function reactClassPrototype(reactClass) { var ctor = reactClass.prototype && reactClass.prototype.constructor; if (typeof ctor === 'undefined') throw new Error('A component constructor could not be found for this class. Are you sure you passed in a React component?'); return ctor.prototype; } module.exports.spyOnComponentMethod = spyOnComponentMethod; module.exports.stubComponentMethod = stubComponentMethod;
JavaScript
0
@@ -292,25 +292,105 @@ React 0.14.x -%0A +1%0A if(typeof classProto.__reactAutoBindMap%5BmethodName%5D !== 'undefined' )%7B%0A spy = @@ -483,24 +483,120 @@ thodName%5D);%0A + %7D else %7B%0A throw new Error('Cannot spy on a function that does not exist');%0A %7D%0A %7D else i
c4a0b092c9edb0355c3e9fdb9214879f7d8ced31
Update SecretFU.js
skills/SecretFU.js
skills/SecretFU.js
module.exports = function(skill, info, bot, message, db) { bot.api.users.info({user: message.user}, (error, response) => { let {name, real_name} = response.user; var userData = message.text.match(/\<(.*?)\>/g); console.log('messaage text: ' + message.text); console.log('userdata' + userData); if (userData) { // if there is a user named send ze hugs! for (var i = 0, len = userData.length; i < len; i++) { FU(userData[i].replace(/[^\w\s]/gi, '')); //console.log('userdate[i]' + userData[i]); //console.log('userdate[i]' + userData[i].replace(/[^\w\s]/gi, '')); } //console.log(userData); bot.reply(message,'a fuck you has been sent! :middle_finger:'); } else { bot.reply(message, 'You didn\'t name anyone…dumbass'); } function FU(user) { //DM some shade! bot.api.im.open({ user: user }, function (err, response) { if (err) { return console.log(err) } var fuckArray = [ 'https://giphy.com/gifs/cheezburger-olympics-U7P2vnWfPkIQ8', 'https://giphy.com/gifs/QGzPdYCcBbbZm', 'https://giphy.com/gifs/jennifer-lawrence-fuck-you-middle-finger-EvsmQokxE8wi4', 'https://giphy.com/gifs/yV5xcSTmtVPBS', 'https://giphy.com/gifs/ZCnBUZM3ZgLMQ', 'https://giphy.com/gifs/mrw-system-privileges-u6FIMpM2MmQM', 'https://giphy.com/gifs/sorry-fuck-you-middle-finger-Ebu8aRL2qxMzK', 'https://giphy.com/gifs/angry-fuck-you-middle-finger-mpdNxvbxee5yw', 'https://giphy.com/gifs/tkQ8MFJYh0hyM', 'https://giphy.com/gifs/jon-j98wX5cxjtPva', 'https://giphy.com/gifs/F9zavqlooT63C', 'https://giphy.com/gifs/9JWWMAbUoAtH2', 'https://giphy.com/gifs/middle-finger-martina-hill-10Pj0OFiQieaf6', 'https://giphy.com/gifs/louis-ck-middle-finger-fuck-you-Qd71uU3LzyxXO' ]; var randomFuck = Math.floor(Math.random()* fuckArray.length); var dmChannel = response.channel.id bot.say({channel: dmChannel, text: 'Some one is throwing shade your way... :middle_finger:'}) bot.say({channel: dmChannel, text: fuckArray[randomFuck]}) }) } }) };
JavaScript
0
@@ -1956,17 +1956,16 @@ t: 'Some - one is t
fa1937fa06a5022c8b19ed65a8cb62cfe0312379
fix bug when filtering for arnes requests
src/actions/foiRequests.js
src/actions/foiRequests.js
import R from 'ramda'; import { ORIGIN, FOI_REQUESTS_PAGE_SIZE, FOI_REQUESTS_PATH } from '../globals'; import { fetchAndDispatch } from '../utils/networking'; import { getCurrentAccessTokenOrRefresh } from '../utils/oauth'; import { mapToFakeStatus } from '../utils'; function foiRequestsErrorAction(error) { return { type: 'FOI_REQUESTS_ERROR', error, }; } function foiRequestsErrorClearAction() { return { type: 'FOI_REQUESTS_ERROR_CLEAR', }; } function foiRequestsInvalidateDataAction() { return { type: 'FOI_REQUESTS_INVALIDATE_DATA', }; } function foiRequestsPendingAction() { return { type: 'FOI_REQUESTS_PENDING', }; } function foiRequestsSuccessAction(requests) { return { type: 'FOI_REQUESTS_SUCCESS', requests, }; } function foiRequestsRefreshingAction() { return { type: 'FOI_REQUESTS_REFRESHING', }; } function foiRequestsRefreshingSuccessAction(requests) { return { type: 'FOI_REQUESTS_REFRESHING_SUCCESS', requests, }; } function foiRequestsFilterChangeAction(filter) { return { type: 'FOI_REQUESTS_FILTER_CHANGE', filter, }; } function foiRequestsUpdateFollowerCountsAction(followerCounts) { return { type: 'FOI_REQUESTS_UPDATE_FOLLOWER_COUNTS', followerCounts, }; } function foiRequestsUpdateCampaignAction(campaign) { return { type: 'FOI_REQUESTS_UPDATE_CAMPAIGN', campaign, }; } function buildUrl(getState) { const state = getState(); const { filter, nPage, isRefreshing, campaign } = state.foiRequests; let offset = FOI_REQUESTS_PAGE_SIZE * nPage; // page is still the former value in case the refresh fails if (isRefreshing) { offset = 0; } const url = `${ORIGIN}${FOI_REQUESTS_PATH}`; const params = new Map([ ['limit', `${FOI_REQUESTS_PAGE_SIZE}`], ['offset', `${offset}`], ['is_foi', 'true'], // filter out crappy requests ]); if (filter.status) { const { status, resolution } = mapToFakeStatus(filter.status.param); if (status === 'has_fee') { params.set('costs_min', 1); } else { // fake status and resolition params.set('status', status); if (resolution) { params.set('resolution', resolution); } } } if (filter.publicBody) { params.set('public_body', filter.publicBody.param); params.delete('is_foi'); // show all requests here. it's irritating when the numbers show on the button don't match with the one in the table. } else { // when the requests are filtered by public body, ignore jurisdiction and category if (filter.jurisdiction) { params.set('jurisdiction', filter.jurisdiction.param); } if (filter.category) { params.set('categories', filter.category.param); } // filter by own user id if (filter.user) { params.set('user', filter.user); params.delete('is_foi'); } // filter by requests the user follows if (filter.follower) { params.set('follower', filter.follower); params.delete('is_foi'); } if (campaign !== null) { params.set('campaign', campaign); } } const paramsAsString = [...params].map(x => `${x[0]}=${x[1]}`).join('&'); return `${url}?${paramsAsString}`; } function fetchRequests(beforeFetchDispatchedAction, onSuccessFetch) { return async (dispatch, getState) => { const { filter } = getState().foiRequests; const buildUrlFunc = (function makeBuildUrlFunc() { return () => buildUrl(getState); })(); // only dispatch if the filter is still the same const onSuccess = (function makeOnSuccessFunc( innerDispatch, innerGetState, innerFilter ) { return data => { if (R.equals(innerFilter, innerGetState().foiRequests.filter)) { innerDispatch(onSuccessFetch(data)); } }; })(dispatch, getState, filter); let addiontionalHeaders = {}; if (filter.user !== null || filter.follower !== null) { addiontionalHeaders = { Authorization: `Bearer ${await getCurrentAccessTokenOrRefresh( dispatch, getState )}`, }; } fetchAndDispatch( buildUrlFunc, dispatch, beforeFetchDispatchedAction, onSuccess, foiRequestsErrorAction, filter, addiontionalHeaders ); }; } function foiRequestsFetchData() { return fetchRequests(foiRequestsPendingAction, foiRequestsSuccessAction); } function foiRequestsRefreshData() { return fetchRequests( foiRequestsRefreshingAction, foiRequestsRefreshingSuccessAction ); } function foiRequestsFilterChange(filter) { return dispatch => { dispatch(foiRequestsFilterChangeAction(filter)); // first delete old data dispatch(foiRequestsInvalidateDataAction()); // and second fetch new one dispatch(foiRequestsFetchData()); }; } function foiRequestsCampaignChange(camp) { return dispatch => { dispatch(foiRequestsUpdateCampaignAction(camp)); // first delete old data dispatch(foiRequestsInvalidateDataAction()); // and second fetch new one dispatch(foiRequestsFetchData()); }; } export { foiRequestsFetchData, foiRequestsRefreshData, foiRequestsFilterChange, foiRequestsErrorClearAction, foiRequestsUpdateFollowerCountsAction, foiRequestsCampaignChange, };
JavaScript
0
@@ -3355,23 +3355,85 @@ const %7B - filter +%0A foiRequests: %7B filter %7D,%0A authentication: %7B userId %7D,%0A %7D = get @@ -3439,28 +3439,16 @@ tState() -.foiRequests ;%0A%0A c @@ -3953,32 +3953,40 @@ s = %7B%7D;%0A if ( +%0A ( filter.user !== @@ -3994,10 +3994,43 @@ ull -%7C%7C +&& filter.user === userId) %7C%7C%0A fil @@ -4042,32 +4042,37 @@ ollower !== null +%0A ) %7B%0A addion
137ae294f2fcd61e4c4abcbb87ebcfd6b289c694
Change for utilForEachGeneratedKey
src/adapters/pulsePoint.js
src/adapters/pulsePoint.js
adapterManagerRegisterAdapter((function() { var adapterID = 'pulsePoint', jsLibURL = '//tag.contextweb.com/getjs.static.js', endPoint = '//bid.contextweb.com/header/tag', pubID = 0, constConfigPubID = 'cp', constConfigAdTagID = 'ct', adapterConfigMandatoryParams = [constConfigPubID, constConfigKeyGeneratigPattern, constConfigKeyLookupMap], slotConfigMandatoryParams = [constConfigAdTagID], makeBidRequest = function(bidRequest){ try{ var ppBidRequest = new window.pp.Ad({ cf: bidRequest.cf, cp: bidRequest.cp, ct: bidRequest.ct, cn: 1, ca: window.pp.requestActions.BID, cu: endPoint, adUnitId: bidRequest.aui, callback: bidResponseCallback(bidRequest) }); ppBidRequest.display(); }catch(e){ utilLog(adapterID+constCommonMessage07); utilLog(e); } }, bidResponseCallback = function(bidRequest) { return function (bidResponse) { bidResponseAvailable(bidRequest, bidResponse); }; }, bidResponseAvailable = function(bidRequest, bidResponse) { var ecpm = 0, creativeHTML = "" ; try{ if (bidResponse) { ecpm = bidResponse.bidCpm; creativeHTML = bidResponse.html; } bidManagerSetBidFromBidder( bidRequest.div, adapterID, bidManagerCreateBidObject( ecpm, "", "", creativeHTML, "", bidRequest.bw, bidRequest.bh, bidRequest.kgpv ) ); }catch(e){ utilLog(adapterID+constCommonMessage21); utilLog(e); } }, fetchBids = function(configObject, activeSlots){ utilLog(adapterID+constCommonMessage01); var adapterConfig = utilLoadGlobalConfigForAdapter(configObject, adapterID, adapterConfigMandatoryParams); if(!adapterConfig){ return; } pubID = adapterConfig[constConfigPubID]; var keyGenerationPattern = adapterConfig[constConfigKeyGeneratigPattern]; var keyLookupMap = adapterConfig[constConfigKeyLookupMap]; utilLoadScript(jsLibURL, function(){ utilForEachGeneratedKey( activeSlots, keyGenerationPattern, keyLookupMap, function(generatedKey, kgpConsistsWidthAndHeight, currentSlot, keyConfig, currentWidth, currentHeight){ if(!keyConfig){ utilLog(adapterID+': '+generatedKey+constCommonMessage08); return; } if(!utilCheckMandatoryParams(keyConfig, slotConfigMandatoryParams, adapterID)){ utilLog(adapterID+': '+generatedKey+constCommonMessage09); return; } var adSlotSizes = kgpConsistsWidthAndHeight ? [[currentWidth, currentHeight]] : currentSlot[constAdSlotSizes]; for(var n=0, l=adSlotSizes.length; n<l; n++){ var bidWidth = adSlotSizes[n][0]; var bidHeight = adSlotSizes[n][1]; var bidRequest = { cf: bidWidth + 'x' + bidHeight, cp: pubID, ct: keyConfig[constConfigAdTagID], aui: currentSlot[constCommonDivID] + '@' + bidWidth + 'x' + bidHeight, div: currentSlot[constCommonDivID], bw: bidWidth, bh: bidHeight, kgpv: generatedKey }; makeBidRequest(bidRequest); } } ); }); } ; return { fB: fetchBids, dC: utilDisplayCreative, ID: function(){ return adapterID; } }; })());
JavaScript
0
@@ -2101,16 +2101,64 @@ tedKey(%0A +%09%09%09%09%09adapterID,%0A%09%09%09%09%09slotConfigMandatoryParams,%0A %09%09%09%09%09act @@ -2330,296 +2330,8 @@ )%7B%0A%0A -%09%09%09%09%09%09if(!keyConfig)%7B%0A%09%09%09%09%09%09%09utilLog(adapterID+': '+generatedKey+constCommonMessage08);%0A%09%09%09%09%09%09%09return;%0A%09%09%09%09%09%09%7D%0A%0A%09%09%09%09%09%09if(!utilCheckMandatoryParams(keyConfig, slotConfigMandatoryParams, adapterID))%7B%0A%09%09%09%09%09%09%09utilLog(adapterID+': '+generatedKey+constCommonMessage09);%0A%09%09%09%09%09%09%09return;%0A%09%09%09%09%09%09%7D%0A%0A %09%09%09%09
421c7d1bfe911ffd2478f5b85851f7725137f835
remove unused import
src/app/models/kibitzer.js
src/app/models/kibitzer.js
import { append, drop, dropLast, forEach, forEachObjIndexed, isNil, last, map, prepend, reject, zipObj } from "ramda" import { LEFT, RIGHT } from "~/share/constants/direction" import { BEFORE, PRIMARY, AFTER } from "~/share/constants/role" import { GAME } from "~/share/constants/actions" import { logger } from "~/app/index" import Game from "./game" export default class Kibitzer { constructor({ socket, games, redisMediator }) { this.socket = socket this.games = games this.redisMediator = redisMediator this.watching = [] } async start() { if (await this.games.length() === 0) { return } const first = await this.games.head() const second = await this.games.next(first) const third = await this.games.next(second) const uuids = [first, second, third] const notNilUUIDs = reject(isNil, uuids) const games = await Game.where("uuid", "in", notNilUUIDs).fetchAll({ withRelated: Game.serializeRelated }) const orderedGames = map((uuid) => { return games.find((game) => { return game.get("uuid") === uuid }) }, uuids) forEach(uuid => { this.redisMediator.subscribeGame(uuid) }, notNilUUIDs) forEachObjIndexed( this.sendGame.bind(this), zipObj([BEFORE, PRIMARY, AFTER], orderedGames) ) this.watching = notNilUUIDs if (this.watching.length < 3) { this.redisMediator.subscribeGameCreation() } } watch(serializedGame) { if (this.watching.length === 3) { this.redisMediator.unSubscribeGameCreation() } if (this.watching.length === 0) { this.sendSerializedGame(serializedGame, PRIMARY) } else { this.rotate({ direction: LEFT, of: last(this.watching) }) } } async rotate({ direction, of }) { let uuid, role switch (direction) { case LEFT: uuid = await this.games.before(of) role = AFTER this.appendToWatching(uuid) break case RIGHT: uuid = await this.games.after(of) role = BEFORE this.prependToWatching(uuid) break default: return } const game = await Game.where({ uuid: uuid }).fetch({ withRelated: Game.serializeRelated }) this.redisMediator.subscribeGame(uuid) this.sendGame(game, role) } stop() { forEach(uuid => this.redisMediator.unsubscribeGame(uuid), this.watching) this.watching = [] } sendGame(game, role) { if (isNil(game)) { return } this.socket.send({ action: GAME, role, game: game.serialize() }) } sendSerializedGame(serializedGame, role) { this.socket.send({ action: GAME, role, game: serializedGame }) } appendToWatching(uuid) { const watching = append(uuid, this.watching) if (this.watching.length > 3) { this.watching = drop(1, watching) } else { this.watching = watching } } prependToWatching(uuid) { const watching = prepend(uuid, this.watching) if (this.watching.length > 3) { this.watching = dropLast(1, watching) } else { this.watching = watching } } }
JavaScript
0.000001
@@ -310,46 +310,8 @@ s%22%0A%0A -import %7B logger %7D from %22~/app/index%22%0A%0A impo
5f5ba1a8bc5e1277469b4a0586f4d9bd97042547
Use JSON.parse in AssetManager only if the value is a string. Closes #128
src/asset_manager/index.js
src/asset_manager/index.js
/** * * [add](#add) * * [get](#get) * * [getAll](#getall) * * [remove](#remove) * * [store](#store) * * [load](#load) * * [onClick](#onClick) * * [onDblClick](#onDblClick) * * Before using this methods you should get first the module from the editor instance, in this way: * * ```js * var assetManager = editor.AssetManager; * ``` * * @module AssetManager * @param {Object} config Configurations * @param {Array<Object>} [config.assets=[]] Default assets * @param {String} [config.uploadText='Drop files here or click to upload'] Upload text * @param {String} [config.addBtnText='Add image'] Text for the add button * @param {String} [config.upload=''] Where to send upload data. Expects as return a JSON with asset/s object * as: {data: [{src:'...'}, {src:'...'}]} * @return {this} * @example * ... * { * assets: [ * {src:'path/to/image.png'}, * ... * ], * upload: 'http://dropbox/path', // Set to false to disable it * uploadText: 'Drop files here or click to upload', * } */ module.exports = () => { var c = {}, Assets = require('./model/Assets'), AssetsView = require('./view/AssetsView'), FileUpload = require('./view/FileUploader'), assets, am, fu; return { /** * Name of the module * @type {String} * @private */ name: 'AssetManager', /** * Mandatory for the storage manager * @type {String} * @private */ storageKey: 'assets', /** * Initialize module * @param {Object} config Configurations * @private */ init(config) { c = config || {}; var defaults = require('./config/config'); for (var name in defaults) { if (!(name in c)) c[name] = defaults[name]; } var ppfx = c.pStylePrefix; if(ppfx) c.stylePrefix = ppfx + c.stylePrefix; assets = new Assets(c.assets); var obj = { collection: assets, config: c, }; am = new AssetsView(obj); fu = new FileUpload(obj); return this; }, /** * Add new asset/s to the collection. URLs are supposed to be unique * @param {string|Object|Array<string>|Array<Object>} asset URL strings or an objects representing the resource. * @return {Model} * @example * // In case of strings, would be interpreted as images * assetManager.add('http://img.jpg'); * assetManager.add(['http://img.jpg', './path/to/img.png']); * * // Using objects you could indicate the type and other meta informations * assetManager.add({ * src: 'http://img.jpg', * //type: 'image', //image is default * height: 300, * width: 200, * }); * assetManager.add([{ * src: 'http://img.jpg', * },{ * src: './path/to/img.png', * }]); */ add(asset) { return assets.add(asset); }, /** * Returns the asset by URL * @param {string} src URL of the asset * @return {Object} Object representing the asset * @example * var asset = assetManager.get('http://img.jpg'); */ get(src) { return assets.where({src})[0]; }, /** * Return all assets * @return {Collection} */ getAll() { return assets; }, /** * Remove the asset by its URL * @param {string} src URL of the asset * @return {this} * @example * assetManager.remove('http://img.jpg'); */ remove(src) { var asset = this.get(src); this.getAll().remove(asset); return this; }, /** * Store assets data to the selected storage * @param {Boolean} noStore If true, won't store * @return {Object} Data to store * @example * var assets = assetManager.store(); */ store(noStore) { var obj = {}; var assets = JSON.stringify(this.getAll().toJSON()); obj[this.storageKey] = assets; if(!noStore && c.stm) c.stm.store(obj); return obj; }, /** * Load data from the passed object, if the object is empty will try to fetch them * autonomously from the storage manager. * The fetched data will be added to the collection * @param {Object} data Object of data to load * @return {Object} Loaded assets * @example * var assets = assetManager.load(); * // The format below will be used by the editor model * // to load automatically all the stuff * var assets = assetManager.load({ * assets: [...] * }); * */ load(data) { var d = data || ''; var name = this.storageKey; if(!d && c.stm) d = c.stm.load(name); var assets = []; try{ assets = JSON.parse(d[name]); }catch(err){} if (assets && assets.length) { this.getAll().reset(assets); } return assets; }, /** * Render assets * @param {Boolean} f Force to render, otherwise cached version will be returned * @return {HTMLElement} * @private */ render(f) { if(!this.rendered || f) this.rendered = am.render().$el.add(fu.render().$el); return this.rendered; }, //------- /** * Set new target * @param {Object} m Model * @private * */ setTarget(m) { am.collection.target = m; }, /** * Set callback after asset was selected * @param {Object} f Callback function * @private * */ onSelect(f) { am.collection.onSelect = f; }, /** * Set callback to fire when the asset is clicked * @param {function} func */ onClick(func) { c.onClick = func; }, /** * Set callback to fire when the asset is double clicked * @param {function} func */ onDblClick(func) { c.onDblClick = func; }, }; };
JavaScript
0.000003
@@ -4673,13 +4673,65 @@ s = -%5B%5D;%0A%0A +d%5Bname%5D %7C%7C %5B%5D;%0A%0A if (typeof assets == 'string') %7B%0A @@ -4735,18 +4735,21 @@ try + %7B%0A + @@ -4784,17 +4784,20 @@ ;%0A -%7D + %7D catch(er @@ -4798,17 +4798,26 @@ tch(err) -%7B + %7B%7D%0A %7D%0A%0A
4e2f0fc2e6d0508f3348b573e9c97ccfba16b005
Remove empty block
packages/core/admin/public/directives/editable.js
packages/core/admin/public/directives/editable.js
'use strict'; angular.module('mean.admin').directive('ngEnter', function() { return function(scope, elm, attrs) { elm.bind('keypress', function(e) { if (e.charCode === 13 && !e.ctrlKey) scope.$apply(attrs.ngEnter); }); }; }); angular.module('mean.admin').directive('ngEditable', function() { return { // can be in-lined or async loaded by xhr // or inlined as JS string (using template property) template: '<span class="editable-wrapper">' + '<span data-ng-hide="edit" data-ng-click="edit=true;value=model;">{{model}}</span>' + '<input type="text" data-ng-model="value" data-ng-blur="edit = false; model = value" data-ng-show="edit" data-ng-enter="model=value;edit=false;"/>' + '</span>', scope: { model: '=ngEditableModel', update: '&ngEditable' }, replace: true, link: function(scope, element, attrs) { scope.focus = function() { element.find('input').focus(); }; scope.$watch('edit', function(isEditable) { if (isEditable === false) { scope.update(); } else { // scope.focus(); } }); } }; }); angular.module('mean.admin').directive('ngEditableParagraph', function() { return { // can be in-lined or async loaded by xhr // or inlined as JS string (using template property) template: '<span class="editable-wrapper">' + '<span data-ng-hide="edit" data-ng-click="edit=true;value=model;" class="respect-newline">{{model}}</span>' + '<textarea data-ng-model="value" data-ng-blur="model=value ; edit=false" data-ng-show="edit" data-ng-enter="model=value;edit=false;" class="span8"></textarea>' + '</span>', scope: { model: '=ngEditableModel', update: '&ngEditableParagraph' }, replace: true, link: function(scope, element, attrs) { scope.focus = function() { element.find("input").focus(); }; scope.$watch('edit', function(isEditable) { if (isEditable === false) { scope.update(); } else { scope.focus(); } }); } }; }); angular.module('mean.admin').directive('ngEditableSelect', function() { return { template: '<span class="editable-wrapper">' + '<span data-ng-hide="edit" data-ng-click="edit=true;value=model;"><span data-ng-repeat="m in model">{{m}};</span></span>' + '<select data-ng-model="value" data-ng-show="edit" data-ng-multiple="true" multiple data-ng-options="option for option in options" data-ng-change="model=value;edit=false;">' + '<option value="">Choose Option</option>' + '</select>' + '</span>', scope: { text: '&ngEditableSelectText', model: '=ngEditableSelectModel', options: '=ngEditableSelectOptions', update: '&ngEditableSelect' }, transclude: true, replace: true, link: function(scope, element, attrs) { scope.$watch('edit', function(isEditable) { if (isEditable === false) { scope.update(); } }); } }; });
JavaScript
0.000081
@@ -1161,71 +1161,8 @@ ();%0A - %7D else %7B%0A // scope.focus();%0A
befb39110d9ecbd8d78f64edfda6032dff4f8c80
Fix regex
generators/app/conf.js
generators/app/conf.js
'use strict'; const lit = require('fountain-generator').lit; module.exports = function webpackConf(options) { const conf = { module: { loaders: [ {test: lit`/\.json$/`, loaders: ['json']} ] } }; if (options.test === false) { conf.plugins = [ lit`new webpack.optimize.OccurrenceOrderPlugin()`, lit`new webpack.NoErrorsPlugin()`, lit`new HtmlWebpackPlugin({ template: conf.path.src('index.html'), inject: true })` ]; conf.postcss = lit`() => [autoprefixer]`; } else { conf.plugins = []; } if (options.framework === 'angular2') { // https://github.com/angular/angular/issues/11580 conf.plugins.push(lit`new webpack.ContextReplacementPlugin( /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/, conf.paths.src )`); } if (options.dist === false) { conf.debug = true; conf.devtool = 'cheap-module-eval-source-map'; if (options.test === false) { conf.output = { path: lit`path.join(process.cwd(), conf.paths.tmp)`, filename: 'index.js' }; } } else { conf.output = { path: lit`path.join(process.cwd(), conf.paths.dist)`, filename: '[name]-[hash].js' }; } if (options.js === 'typescript') { conf.resolve = { extensions: ['', '.webpack.js', '.web.js', '.js', '.ts'] }; if (options.framework === 'react') { conf.resolve.extensions.push('.tsx'); if (options.test === true) { conf.externals = lit`{ 'jsdom': 'window', 'cheerio': 'window', 'react/lib/ExecutionEnvironment': true, 'react/lib/ReactContext': 'window', 'text-encoding': 'window' }`; } } } if (options.test === false) { const index = lit`\`./\${conf.path.src('index')}\``; if (options.dist === false && options.framework === 'react') { conf.entry = [ 'webpack/hot/dev-server', 'webpack-hot-middleware/client', index ]; } else if (options.dist === true) { const exceptions = []; let vendor = 'Object.keys(pkg.dependencies)'; if (options.framework === 'angular2') { exceptions.push(`'zone.js'`); } if (options.sample === 'todoMVC') { exceptions.push(`'todomvc-app-css'`); } if (exceptions.length) { vendor += `.filter(dep => [${exceptions.join(', ')}].indexOf(dep) === -1)`; } conf.entry = { app: index, vendor: lit`${vendor}` }; } else { conf.entry = index; } if (options.dist === false && options.framework === 'react') { conf.plugins.push( lit`new webpack.HotModuleReplacementPlugin()` ); } if (options.dist === true && options.framework !== 'angular1') { conf.plugins.push( lit`new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' })` ); } if (options.dist === true) { conf.plugins.push( lit`new webpack.optimize.UglifyJsPlugin({ compress: {unused: true, dead_code: true} // eslint-disable-line camelcase })`, lit`new ExtractTextPlugin('index-[contenthash].css')`, lit`new webpack.optimize.CommonsChunkPlugin({name: 'vendor'})` ); } } if (options.test === false) { let cssLoaders; let test = lit`/\\.css$/`; const mapToLoaders = { scss: 'sass', less: 'less', styl: 'stylus' }; if (options.dist === true) { if (options.css === 'scss') { test = lit`/\\.(css|scss)$/`; } if (options.css === 'less') { test = lit`/\\.(css|less)$/`; } if (options.css === 'styl') { test = lit`/\\.(css|styl|stylus)$/`; } cssLoaders = lit`ExtractTextPlugin.extract({ fallbackLoader: 'style', loader: 'css?minimize!${mapToLoaders[options.css]}!postcss' })`; } else { cssLoaders = ['style', 'css']; if (options.css === 'scss') { cssLoaders.push('sass'); test = lit`/\\.(css|scss)$/`; } if (options.css === 'less') { cssLoaders.push('less'); test = lit`/\\.(css|less)$/`; } if (options.css === 'styl') { cssLoaders.push('stylus'); test = lit`/\\.(css|styl|stylus)$/`; } cssLoaders.push('postcss'); } conf.module.loaders.push({test, loaders: cssLoaders}); } const jsLoaders = []; if (options.test === false && options.dist === false && options.framework === 'react') { jsLoaders.push('react-hot'); } if (options.framework === 'angular1') { jsLoaders.push('ng-annotate'); } if (options.js === 'babel' || options.js === 'js' && options.framework === 'react') { jsLoaders.push('babel'); } if (options.js === 'typescript') { jsLoaders.push('ts'); } if (jsLoaders.length > 0) { const jsLoader = {test: lit`/\\.js$/`, exclude: lit`/node_modules/`, loaders: jsLoaders}; if (options.js === 'typescript') { jsLoader.test = lit`/\\.ts$/`; if (options.framework === 'react') { jsLoader.test = lit`/\\.tsx$/`; } } conf.module.loaders.push(jsLoader); } if (options.framework === 'vue') { const vueLoader = { test: lit`/\.vue$/`, loaders: ['vue'] }; conf.module.loaders.push(vueLoader); } if (options.framework !== 'react' && options.framework !== 'vue') { const htmlLoader = { test: lit`/\.html$/`, loaders: ['html'] }; conf.module.loaders.push(htmlLoader); } if (options.js === 'typescript') { conf.ts = { configFileName: 'tsconfig.json' }; conf.tslint = { configuration: lit`require('../tslint.json')` }; } if (options.test === true && options.js !== 'typescript') { conf.module.loaders.push({ test: lit`/\\.js$/`, exclude: lit`/(node_modules|.*\\.spec\\.js)/`, loader: 'isparta' }); if (options.framework === 'react') { conf.externals = { 'react/lib/ExecutionEnvironment': true, 'react/lib/ReactContext': true }; } } return conf; };
JavaScript
0.999981
@@ -750,17 +750,20 @@ gular(%5C%5C -%7C +%5C%5C%7C%5C %5C/)core( @@ -764,17 +764,20 @@ )core(%5C%5C -%7C +%5C%5C%7C%5C %5C/)(esm( @@ -778,17 +778,20 @@ )(esm(%5C%5C -%7C +%5C%5C%7C%5C %5C/)src%7Cs @@ -796,17 +796,20 @@ %7Csrc)(%5C%5C -%7C +%5C%5C%7C%5C %5C/)linke
397bcb33d6252ff2135f037717e09de3f8b09852
Fix ExtractTextPlugin call to use postcss on build
generators/app/conf.js
generators/app/conf.js
'use strict'; const lit = require('fountain-generator').lit; module.exports = function webpackConf(options) { const conf = { module: { loaders: [ {test: lit`/\.json$/`, loaders: ['json']} ] } }; if (options.test === false) { conf.plugins = [ lit`new webpack.optimize.OccurrenceOrderPlugin()`, lit`new webpack.NoErrorsPlugin()`, lit`new HtmlWebpackPlugin({ template: conf.path.src('index.html'), inject: true })` ]; conf.postcss = lit`() => [autoprefixer]`; } else { conf.plugins = []; } if (options.dist === false) { conf.debug = true; conf.devtool = 'cheap-module-eval-source-map'; if (options.test === false) { conf.output = { path: lit`path.join(process.cwd(), conf.paths.tmp)`, filename: 'index.js' }; } } else { conf.output = { path: lit`path.join(process.cwd(), conf.paths.dist)`, filename: '[name]-[hash].js' }; } if (options.js === 'typescript') { conf.resolve = { extensions: ['', '.webpack.js', '.web.js', '.js', '.ts'] }; if (options.framework === 'react') { conf.resolve.extensions.push('.tsx'); if (options.test === true) { conf.externals = lit`{ 'jsdom': 'window', 'cheerio': 'window', 'react/lib/ExecutionEnvironment': true, 'react/lib/ReactContext': 'window', 'text-encoding': 'window' }`; } } } if (options.test === false) { const index = lit`\`./\${conf.path.src('index')}\``; if (options.dist === false && options.framework === 'react') { conf.entry = [ 'webpack/hot/dev-server', 'webpack-hot-middleware/client', index ]; } else if (options.dist === true) { conf.entry = { app: index }; } else { conf.entry = index; } if (options.dist === false && options.framework === 'react') { conf.plugins.push( lit`new webpack.HotModuleReplacementPlugin()` ); } if (options.dist === true && options.framework !== 'angular1') { conf.plugins.push( lit`new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' })` ); } if (options.dist === true) { conf.plugins.push( lit`new webpack.optimize.UglifyJsPlugin({ compress: {unused: true, dead_code: true} // eslint-disable-line camelcase })`, lit`new SplitByPathPlugin([{ name: 'vendor', path: path.join(__dirname, '../node_modules') }])`, lit`new ExtractTextPlugin('/index-[contenthash].css')` ); } } if (options.test === false) { let cssLoaders; let test = lit`/\\.css$/`; const mapToLoaders = { scss: 'sass', less: 'less', styl: 'stylus' }; if (options.dist === true) { if (options.css === 'scss') { test = lit`/\\.(css|scss)$/`; } if (options.css === 'less') { test = lit`/\\.(css|less)$/`; } if (options.css === 'styl') { test = lit`/\\.(css|styl|stylus)$/`; } cssLoaders = lit`ExtractTextPlugin.extract('style', 'css?minimize!${mapToLoaders[options.css]}', 'postcss')`; } else { cssLoaders = ['style', 'css']; if (options.css === 'scss') { cssLoaders.push('sass'); test = lit`/\\.(css|scss)$/`; } if (options.css === 'less') { cssLoaders.push('less'); test = lit`/\\.(css|less)$/`; } if (options.css === 'styl') { cssLoaders.push('stylus'); test = lit`/\\.(css|styl|stylus)$/`; } cssLoaders.push('postcss'); } conf.module.loaders.push({test, loaders: cssLoaders}); } const jsLoaders = []; if (options.test === false && options.dist === false && options.framework === 'react') { jsLoaders.push('react-hot'); } if (options.framework === 'angular1') { jsLoaders.push('ng-annotate'); } if (options.js === 'babel' || options.js === 'js' && options.framework === 'react') { jsLoaders.push('babel'); } if (options.js === 'typescript') { jsLoaders.push('ts'); } if (jsLoaders.length > 0) { const jsLoader = {test: lit`/\\.js$/`, exclude: lit`/node_modules/`, loaders: jsLoaders}; if (options.js === 'typescript') { jsLoader.test = lit`/\\.ts$/`; if (options.framework === 'react') { jsLoader.test = lit`/\\.tsx$/`; } } conf.module.loaders.push(jsLoader); } if (options.framework !== 'react') { const htmlLoader = { test: lit`/\.html$/`, loaders: ['html'] }; conf.module.loaders.push(htmlLoader); } if (options.js === 'typescript') { conf.ts = { configFileName: 'tsconfig.json' }; conf.tslint = { configuration: lit`require('../tslint.json')` }; } if (options.test === true && options.js !== 'typescript') { conf.module.loaders.push({ test: lit`/\\.js$/`, exclude: lit`/(node_modules|.*\\.spec\\.js)/`, loader: 'isparta' }); if (options.framework === 'react') { conf.externals = { 'react/lib/ExecutionEnvironment': true, 'react/lib/ReactContext': true }; } } return conf; };
JavaScript
0
@@ -3185,20 +3185,17 @@ ns.css%5D%7D -', ' +! postcss'
8cef6c03de05246549a42b5bfec47d3d549ae190
Use else instead of else if
generators/app/conf.js
generators/app/conf.js
/* eslint prefer-spread: 0 */ 'use strict'; const _ = require('lodash'); function series() { const array = []; array.push.apply(array, arguments); array.type = 'series'; return array; } function parallel() { const array = []; array.push.apply(array, arguments); array.type = 'parallel'; return array; } function gulpTasksToString(tasks) { let result; if (_.isArray(tasks)) { result = `gulp.${tasks.type}(${tasks.map(gulpTasksToString).join(', ')})`; } else { result = `'${tasks}'`; } return result; } module.exports = function gulpfileConf(generatorOptions) { const options = Object.assign({}, generatorOptions); if (options.modules === 'webpack') { options.buildTask = series(parallel('other', 'webpack:dist')); } else if (options.modules === 'inject') { options.buildTask = series(parallel('inject', 'other'), 'build'); } else if (options.modules === 'systemjs') { options.buildTask = series(parallel('systemjs', 'systemjs:html', 'styles', 'other'), 'build'); } if (options.framework === 'angular1') { options.buildTask.unshift('partials'); } if (options.modules === 'inject') { options.serveTask = series('inject', 'watch', 'browsersync'); } else if (options.modules === 'webpack') { options.serveTask = series('webpack:watch', 'watch', 'browsersync'); } else if (options.modules === 'systemjs') { options.serveTask = series(parallel('scripts', 'styles'), 'watch', 'browsersync'); } if (options.modules === 'inject') { options.testTask = series('scripts', 'karma:single-run'); options.testAutoTask = series('watch', 'karma:auto-run'); } else { options.testTask = series('karma:single-run'); options.testAutoTask = series('karma:auto-run'); } ['buildTask', 'serveTask', 'testTask', 'testAutoTask'].forEach(task => { options[task] = gulpTasksToString(options[task]); }); return options; };
JavaScript
0.000004
@@ -881,44 +881,8 @@ else - if (options.modules === 'systemjs') %7B%0A @@ -1309,44 +1309,8 @@ else - if (options.modules === 'systemjs') %7B%0A
1c2c70a30581008abeba0641c1760bebbd390738
Remove useless files
generators/app/conf.js
generators/app/conf.js
const lit = require('fountain-generator').lit; module.exports = function karmaConf(props) { const conf = { browsers: props.framework === 'angular2' ? ['Chrome'] : ['PhantomJS'], basePath: '../', singleRun: props.singleRun, autoWatch: !props.singleRun, logLevel: 'INFO', junitReporter: {outputDir: 'test-reports'} }; const pathSrcJs = lit`conf.path.src('index.spec.js')`; const pathSrcHtml = lit`conf.path.src('**/*.html')`; if (props.modules === 'systemjs') { conf.frameworks = props.framework === 'angular2' ? ['jasmine', 'jspm', 'mocha', 'chai', 'sinon-chai'] : ['phantomjs-shim', 'jspm', 'mocha', 'chai', 'sinon-chai']; } else if (props.modules === 'inject' && props.framework === 'angular1') { conf.frameworks = ['phantomjs-shim', 'mocha', 'chai', 'sinon-chai', 'angular-filesort']; } else { conf.frameworks = props.framework === 'angular2' ? ['jasmine', 'mocha', 'chai', 'sinon-chai'] : ['phantomjs-shim', 'mocha', 'chai', 'sinon-chai']; } if (props.modules === 'webpack') { conf.files = [ 'node_modules/es6-shim/es6-shim.js', pathSrcJs ]; if (props.framework === 'angular1') { conf.files.push(pathSrcHtml); } } if (props.modules === 'inject') { conf.files = lit`listFiles()`; } if (props.modules === 'webpack' || props.framework === 'angular1') { conf.preprocessors = {}; } if (props.modules === 'webpack') { conf.preprocessors[pathSrcJs] = ['webpack']; } if (props.framework === 'angular1') { conf.preprocessors[pathSrcHtml] = ['ng-html2js']; if (props.modules === 'systemjs' && props.js === 'typescript') { conf.preprocessors[pathSrcHtml].push('generic'); conf.genericPreprocessor = { rules: [lit`{ process(content, file, done) { file.path = file.path.replace(/\\.js$/, '.ts'); done(content); } }`] }; } } if (props.framework === 'angular1') { conf.ngHtml2JsPreprocessor = {}; if (props.modules !== 'systemjs') { conf.ngHtml2JsPreprocessor.stripPrefix = lit`\`\${conf.paths.src}/\``; } if (props.modules === 'inject') { conf.ngHtml2JsPreprocessor.moduleName = 'app'; conf.angularFilesort = { whitelist: [lit`conf.path.tmp('**/!(*.html|*.spec|*.mock).js')`] }; } } if (props.modules === 'webpack') { conf.reporters = lit`['progress', 'coverage']`; conf.coverageReporter = { type: 'html', dir: 'coverage/' }; conf.webpack = lit`require('./webpack-test.conf')`; conf.webpackMiddleware = {noInfo: true}; } if (props.modules === 'systemjs') { conf.jspm = { loadFiles: [], config: 'jspm.config.js', browser: 'jspm.test.js' }; if (props.framework === 'angular2') { conf.jspm.loadFiles.push( 'jspm_packages/npm/[email protected]/Reflect.js', 'node_modules/es6-shim/es6-shim.js' ); } if (props.js === 'typescript') { if (props.framework === 'react') { conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.tsx')`); } else { conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.ts')`); } } else { conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.js')`); } // if (props.framework !== 'react') { if (props.framework === 'angular1') { conf.jspm.loadFiles.push(lit`conf.path.src('**/*.html')`); } } conf.plugins = [ lit`require('karma-mocha')`, lit`require('karma-chai-plugins')`, lit`require('karma-junit-reporter')`, lit`require('karma-coverage')` ]; if (props.framework === 'angular2') { conf.plugins.push(lit`require('karma-chrome-launcher')`); conf.plugins.push(lit`require('karma-jasmine')`); } else { conf.plugins.push(lit`require('karma-phantomjs-launcher')`); conf.plugins.push(lit`require('karma-phantomjs-shim')`); } if (props.framework === 'angular1') { conf.plugins.push(lit`require('karma-ng-html2js-preprocessor')`); } if (props.modules === 'webpack') { conf.plugins.push(lit`require('karma-webpack')`); } if (props.modules === 'systemjs') { conf.plugins.push(lit`require('karma-jspm')`); } if (props.modules === 'inject' && props.framework === 'angular1') { conf.plugins.push(lit`require('karma-angular-filesort')`); } if (props.modules === 'systemjs' && props.framework === 'angular1' && props.js === 'typescript') { conf.plugins.push(lit`require('karma-generic-preprocessor')`); } return conf; };
JavaScript
0.000002
@@ -2755,205 +2755,8 @@ %7D;%0A%0A - if (props.framework === 'angular2') %7B%0A conf.jspm.loadFiles.push(%0A 'jspm_packages/npm/[email protected]/Reflect.js',%0A 'node_modules/es6-shim/es6-shim.js'%0A );%0A %7D%0A%0A
1c7959e19e060bb55b2ff0d6f085b9e14a150000
correct auth ui
public/js/authSetup.js
public/js/authSetup.js
function authSetup() { var authArea = document.getElementById('auth'); $.ajax({ type: 'GET', url: '/auth', success: function(res, status, xhr) { var html=''; if(Array.isArray(res)) { for(var i=0;i<res.length;i++) { var apiName = res[i].api; var method = res[i].enabled ? 'delete' : 'post'; var toggle = res[i].enabled ? 'disable' : 'enable'; html += '<span class="auth-switch">' html += '<form name="'+apiName+'" method="'+method+'" action="/auth/'+apiName+'">'; html += '<input type="button" value="'+toggle+' '+apiName+'" onclick="'+toggle+'Auth(this.form)" />'; html += '</form></span>'; } } authArea.innerHTML = html; }, error: function(xhr, status, err) { authArea.innerHTML = ''; } }); } function authTeardown() { var authArea = document.getElementById('auth'); authArea.innerHTML = ''; } function enableAuth(form) { form.submit(); } function disableAuth(form) { $.ajax({ type: 'DELETE', url: form.action, success: function(res, status, xhr) { authSetup(); }, error: function(xhr, status, err) { } }); }
JavaScript
0.000049
@@ -18,17 +18,16 @@ p() %7B%0A - var auth @@ -68,17 +68,16 @@ th');%0A - $.ajax(%7B @@ -78,18 +78,16 @@ ajax(%7B %0A - type @@ -95,18 +95,16 @@ 'GET',%0A - url: @@ -118,18 +118,16 @@ ', %0A - success: @@ -159,26 +159,24 @@ r) %7B %0A - var html=''; @@ -182,18 +182,16 @@ ;%0A - - if(Array @@ -203,26 +203,24 @@ ray(res)) %7B%0A - for( @@ -253,26 +253,24 @@ %7B%0A - var apiName @@ -289,26 +289,24 @@ ;%0A - - var method = @@ -342,18 +342,16 @@ 'post';%0A - @@ -404,18 +404,16 @@ nable';%0A - @@ -453,34 +453,32 @@ ch%22%3E'%0A - html += '%3Cform n @@ -541,26 +541,24 @@ iName+'%22%3E';%0A - ht @@ -653,26 +653,24 @@ form)%22 /%3E';%0A - ht @@ -697,30 +697,26 @@ %3E';%0A - %7D%0A +%7D%0A %7D%0A @@ -713,26 +713,24 @@ %7D%0A - - authArea.inn @@ -745,18 +745,16 @@ html; %0A - %7D,%0A @@ -756,18 +756,16 @@ %7D,%0A - error: f @@ -794,26 +794,24 @@ rr) %7B%0A - - authArea.inn @@ -828,22 +828,18 @@ '; %0A - %7D%0A - %7D);%0A%7D%0A
5b1e2893cab3dec2f7fc1721ba1337d9e9ea22fe
Change header on initial render of page
public/src/index.js
public/src/index.js
var LagerApp = React.createClass({ componentWillMount: function() { window.onhashchange = function() { this.setState({page: window.location.hash.substring(1)}); }.bind(this); }, componentDidMount: function() { window.onhashchange = function() { var hash = window.location.hash.substring(1); $('header a.pull-right').attr('href', '/' + hash + '/new'); this.setState({page: hash}); }.bind(this); }, getInitialState: function() { var page = "servers"; if (window.location.hash) { page = window.location.hash.substring(1); } return { logs: [], page: page, services: [ { name: "nginx", server_count: 5 }, { name: "postgresql", server_count: 2 }, { name: "rabbitmq", server_count: 3 } ], servers: [ { host: "app1.sg", ip: "1.1.1.1", status: true }, { host: "app2.sg", ip: "2.2.2.2", status: false }, { host: "db.sg", ip: "3.3.3.3", status: true }, ] }; }, render: function() { var tableView; if (this.state.page === "servers") { tableView = <ServerTableView servers={this.state.servers} /> } else { tableView = <ServiceTableView services={this.state.services} /> } return ( <div> {tableView} <div ref="line"></div> </div> ); } }); var ServiceTableView = React.createClass({ _generateServiceTableViewCells: function() { return this.props.services.map(function(service){ return (<ServiceTableViewCell service={service} key={service.name} />) }); }, render: function() { return ( <div> <ul className="table-view"> {this._generateServiceTableViewCells()} </ul> </div> ); } }); var ServiceTableViewCell = React.createClass({ render: function() { return ( <li className="table-view-cell"> <a className="navigate-right" data-transition="slide-in" href="/log"> <div> <h4>{this.props.service.name}</h4> <p>Server count: {this.props.service.server_count}</p> </div> </a> </li> ); } }); var ServerTableView = React.createClass({ _generateServerTableViewCells: function() { return this.props.servers.map(function(server){ return (<ServerTableViewCell server={server} key={server.ip} />) }); }, render: function() { return ( <div> <ul className="table-view"> {this._generateServerTableViewCells()} </ul> </div> ); } }); var ServerTableViewCell = React.createClass({ render: function() { var statusClass = this.props.server.status ? "btn btn-positive" : "btn btn-negative"; var status = this.props.server.status ? "Up" : "Down"; return ( <li className="table-view-cell"> <a className="navigate-right" href="/servers/new" data-transition="slide-in"> <div style={{float: "left"}}> <h4>{this.props.server.host}</h4> <h5>{this.props.server.ip}</h5> </div> <button className={statusClass} style={{float: "right"}}> {status} </button> </a> </li> ); } }); React.render(<LagerApp />, document.getElementById('content'));
JavaScript
0
@@ -575,24 +575,90 @@ bstring(1);%0A + $('header a.pull-right').attr('href', '/' + page + '/new');%0A %7D%0A re
a199d94513526da98071518a120454af49b8fc9f
Increase sw version
public/sw.js
public/sw.js
/* eslint-env serviceworker, browser */ // sw-offline-google-analytics *must* be imported and initialized before // sw-toolbox, because its 'fetch' event handler needs to run first. importScripts('/sw-offline-google-analytics/offline-google-analytics-import.js'); goog.offlineGoogleAnalytics.initialize(); // Use sw-toolbox importScripts('/sw-toolbox/sw-toolbox.js'); /* global toolbox */ toolbox.options.debug = false; importScripts('/js/sw-assets-precache.js'); /* global ASSETS */ const VERSION = '19'; const PREFIX = 'gulliver'; const CACHE_NAME = `${PREFIX}-v${VERSION}`; const PWA_OPTION = { cache: { name: `PWA-${CACHE_NAME}`, maxAgeSeconds: 60 * 60 * 12, queryOptions: { ignoreSearch: true } } }; const PWA_LIST_OPTION = { cache: { name: `LIST-${CACHE_NAME}`, maxAgeSeconds: 60 * 60 * 6 } }; // URL to return in place of the "offline dino" when client is // offline and requests a URL that's not in the cache. const OFFLINE_URL = '/.app/offline'; const SHELL_URL = '/.app/shell'; const OFFLINE = [ OFFLINE_URL, SHELL_URL, '/?cacheOnly=true', '/favicons/android-chrome-72x72.png', '/manifest.json', '/img/GitHub-Mark-Light-24px.png', '/img/GitHub-Mark-Light-48px.png', '/img/lighthouse-18.png', '/img/lighthouse-36.png', '/messaging-config.json' ]; toolbox.precache(OFFLINE.concat(ASSETS)); toolbox.options.cache.name = CACHE_NAME; /** * Utility method to retrieve a url from the `toolbox.options.cache.name` cache * * @param {*} url url to be requested fromt he cache. */ const getFromCache = url => { return caches.open(toolbox.options.cache.name) .then(cache => cache.match(url)); }; /** * A sw-toolbox handler that tries to serve content using networkFirst, and if * it fails, returns a custom offline page. */ const gulliverHandler = (request, values, options) => { return toolbox.fastest(request, values, options) .catch(_ => { // networkFirst failed (no network and not in cache) getFromCache(OFFLINE_URL).then(response => { return response || new Response('', { status: 500, statusText: 'Offline Page Missing' }); }); }); }; const getContentOnlyUrl = url => { const u = new URL(url); u.searchParams.append('contentOnly', 'true'); return u.toString(); }; toolbox.router.default = (request, values, options) => { if (request.mode === 'navigate') { // Launch and early request to the content URL that will be loaded from the shell. // Since the response has a short timeout, the browser will re-use the request. toolbox.cacheFirst(new Request(getContentOnlyUrl(request.url)), values, options); // Replace the request with the App Shell. return getFromCache(SHELL_URL) .then(response => response || gulliverHandler(request, values, options)); } return gulliverHandler(request, values, options); }; toolbox.router.get(/\/pwas\/\d+/, toolbox.router.default, PWA_OPTION); toolbox.router.get('/pwas/score', toolbox.router.default, PWA_LIST_OPTION); toolbox.router.get('/pwas/newest', toolbox.router.default, PWA_LIST_OPTION); toolbox.router.get('/', (request, values) => { // Replace requests to start_url with the lastest version of the root page. // TODO Make more generic: strip utm_* parameters from *every* request. // TODO Pass through credentials (e.g. cookies) and other request metadata, see // https://github.com/ithinkihaveacat/sw-proxy/blob/master/http-proxy.ts#L249. if (request.url.endsWith('/?utm_source=homescreen')) { request = new Request('/'); } return toolbox.router.default(request, values, PWA_LIST_OPTION); }); toolbox.router.get(/.*\.(js|png|svg|jpg|css)$/, (request, values, options) => { return toolbox.cacheFirst(request, values, options); }); // API request bypass the Shell toolbox.router.get(/\/api\/.*/, (request, values, options) => { return toolbox.networkFirst(request, values, options); }); // Claim all clients and delete old caches that are no longer needed. self.addEventListener('activate', event => { self.clients.claim(); event.waitUntil( caches.keys().then(cacheNames => Promise.all( cacheNames.filter(cacheName => cacheName !== CACHE_NAME && cacheName !== PWA_OPTION.name && cacheName !== PWA_LIST_OPTION.name) .map(cacheName => caches.delete(cacheName)) ) ) ); }); // Make sure the SW the page we register() is the service we use. self.addEventListener('install', () => self.skipWaiting());
JavaScript
0
@@ -502,10 +502,10 @@ = ' -19 +20 ';%0Ac
2c98f44a1f64d279b3d14e28fb2be6c0929998d8
fix argument of R script
server/modules/DADA2.js
server/modules/DADA2.js
const Rexec = require('child_process').exec; const fs = require('fs'); const tools = require('../toolbox'); exports.name = 'DADA2'; exports.category = 'Clustering'; exports.multicore = false; exports.run = function(os,config,callback){ let token = os.token; let directory = '/app/data/' + token + '/'; let tags = directory + config.params.inputs.tags; let by_lib = config.params.params.by_lib; let asvs_seq = config.params.outputs.asvs_seq; let asvs_table = config.params.outputs.asvs_tab; let proc = os.cores; console.log('value of by_lib: ' + by_lib) var command = ['/app/lib/R_scripts/dada2.R',by_lib,tags,asvs_seq,asvs_table,token,proc]; var child = Rexec('Rscript '+command.join(' ')); child.stdout.on('data', function(data) { console.log('STDOUT:' + data); fs.appendFileSync(directory + config.log, data); }); child.stderr.on('data', function(data) { console.log('STDERR:' + data); fs.appendFileSync(directory + config.log, data); }); child.on('close', (code) => { if (code != 0) { console.log("Error code " + code + " during DADA2"); callback(os, code); } else { callback(os, null); } }); }
JavaScript
0.000005
@@ -497,16 +497,94 @@ vs_tab;%0A + let fwd = config.params.outputs.fwd;%0A let rev = config.params.outputs.rev;%0A let pr @@ -733,16 +733,24 @@ ken,proc +,fwd,rev %5D;%0A%0A va
e91ea7d8ff5686ba38bc591d3c2f000a88cc1eb6
Improve code attribute update (work in progress)
collect-web/collect-webapp/frontend/src/components/datamanagement/recordeditor/fields/CodeField.js
collect-web/collect-webapp/frontend/src/components/datamanagement/recordeditor/fields/CodeField.js
import React, { Component, PropTypes } from 'react' import classnames from 'classnames'; import { Label, Input, FormGroup } from 'reactstrap'; import ServiceFactory from 'services/ServiceFactory' import AbstractField from './AbstractField' export default class CodeField extends AbstractField { constructor(props) { super(props) this.state = { value: '', items: [] } this.handleInputChange = this.handleInputChange.bind(this) } componentDidMount() { const parentEntity = this.props.parentEntity if (parentEntity) { this.handleParentEntityChanged(parentEntity) } } componentWillReceiveProps(nextProps) { const parentEntity = nextProps.parentEntity if (parentEntity) { this.handleParentEntityChanged(parentEntity) } } handleParentEntityChanged(parentEntity) { this.loadCodeListItems(parentEntity) const attr = this.getSingleAttribute(parentEntity) const codeVal = attr.fields[0].value this.updateStateValue(codeVal) } updateStateValue(value) { if (value == null) { //set empty option const layout = this.props.fieldDef.layout switch(layout) { case 'DROPDOWN': value = '-1' break; default: value = '' } } this.setState({...this.state, value: value}) } loadCodeListItems(parentEntity) { const attr = this.getSingleAttribute(parentEntity) if (attr) { ServiceFactory.codeListService.findAvailableItems(parentEntity, attr.definition) .then(items => this.setState({...this.state, items: items})) } } handleAttributeUpdatedEvent(event) { super.handleAttributeUpdatedEvent(event) this.updateStateValue(event.code) } handleInputChange(event) { const attr = this.getSingleAttribute() if (attr) { const val = event.target.value this.updateStateValue(val) ServiceFactory.commandService.updateAttribute(attr, 'CODE', { code: val }) } } render() { const parentEntity = this.props.parentEntity const fieldDef = this.props.fieldDef if (! parentEntity || ! fieldDef) { return <div>Loading...</div> } const EMPTY_OPTION = <option key="-1" value="-1">--- Select one ---</option> const attrDef = fieldDef.attributeDefinition const layout = this.props.fieldDef.layout switch(layout) { case 'DROPDOWN': let options = [EMPTY_OPTION] .concat(this.state.items.map(item => <option key={item.code} value={item.code}>{item.label}</option>)) return ( <Input type="select" onChange={this.handleInputChange} value={this.state.value}> {options} </Input> ) case 'RADIO': let radioBoxes = this.state.items.map(item => <FormGroup check key={item.code}> <Label check> <Input type="radio" name={'code_group_' + parentEntity.id + '_' + attrDef.id} value={item.code} checked={this.state.value == item.code} onChange={this.handleInputChange} />{' '} {item.label} </Label> </FormGroup> ) return <div>{radioBoxes}</div> default: return <Input value={this.state.value} onChange={this.handleInputChange} style={{maxWidth: '100px'}} /> } } }
JavaScript
0
@@ -404,17 +404,56 @@ tems: %5B%5D +,%0A uncommittedChanges: false %0A - @@ -522,16 +522,101 @@ d(this)%0A + this.sendAttributeUpdateCommand = this.sendAttributeUpdateCommand.bind(this)%0A %7D%0A%0A @@ -2068,16 +2068,67 @@ t.code)%0A + this.setState(%7BuncommittedChanges: false%7D)%0A %7D%0A%0A @@ -2302,24 +2302,337 @@ eValue(val)%0A + this.setState(%7BuncommittedChanges: true%7D)%0A if (event.target.type != 'text') %7B%0A this.sendAttributeUpdateCommand()%0A %7D%0A %7D%0A %7D%0A%0A sendAttributeUpdateCommand() %7B%0A if (this.state.uncommittedChanges) %7B%0A const attr = this.getSingleAttribute()%0A @@ -2715,19 +2715,32 @@ code: +this.state. val +ue %0A @@ -4225,32 +4225,32 @@ default:%0A - retu @@ -4317,16 +4317,57 @@ tChange%7D + onBlur=%7Bthis.sendAttributeUpdateCommand%7D style=%7B
be68bac665512be847e73b1741f1e1c7a3e5f4e3
fix makeAppointment
packages/opd-model/schemas/appointments-schema.js
packages/opd-model/schemas/appointments-schema.js
Schema.Appointments = new SimpleSchema({ PatientID: { type: String, max: 50, autoform: { type: 'hidden' } }, DepartmentID: { type: String, label: 'แผนก', max: 50, autoform: { options() { return Model.Departments.find() .fetch() .map(dept => { return {label: dept.Name, value: dept._id}; }); } } }, DoctorID: { type: String, label: 'แพทย์', max: 50, autoform: { type: 'hidden' } }, AppDate: { type: Date, label: 'วันที่ต้องการนัดหมาย', autoform: { type: "pickadate", pickadateOptions: { min: true, max: 365, formatSubmit: 'ddd dd//mm/yyyy', selectYears: true, selectMonths: true } } }, AppTime: { type: String, label: "ช่วงเวลา", allowedValues: ['เช้า', 'บ่าย'], autoform: { options: 'allowed' } }, }); Model.Appointments.attachSchema(Schema.Appointments);
JavaScript
0.000049
@@ -502,32 +502,66 @@ : 'hidden'%0A %7D +,%0A optional: true //false later %0A %7D,%0A AppDate: @@ -1033,8 +1033,9 @@ tments); +%0A
0178404ae675543ee19f06beefacea544e6a6089
Update roomList.js
packages/rocketchat-ui-sidenav/client/roomList.js
packages/rocketchat-ui-sidenav/client/roomList.js
/* globals RocketChat */ import _ from 'underscore'; import { UiTextContext } from 'meteor/rocketchat:lib'; Template.roomList.helpers({ rooms() { /* modes: sortby activity/alphabetical merge channels into one list show favorites show unread */ if (this.anonymous) { return RocketChat.models.Rooms.find({t: 'c'}, {sort: {name: 1}}); } const user = Meteor.user(); const sortBy = RocketChat.getUserPreference(user, 'sidebarSortby') || 'alphabetical'; const query = { open: true }; const sort = {}; if (sortBy === 'activity') { sort.t = 1; } else { // alphabetical sort[this.identifier === 'd' && RocketChat.settings.get('UI_Use_Real_Name') ? 'fname' : 'name'] = /descending/.test(sortBy) ? -1 : 1; } if (this.identifier === 'unread') { query.alert = true; query.hideUnreadStatus = {$ne: true}; return ChatSubscription.find(query, {sort}); } const favoritesEnabled = !!(RocketChat.settings.get('Favorite_Rooms') && RocketChat.getUserPreference(user, 'sidebarShowFavorites')); if (this.identifier === 'f') { query.f = favoritesEnabled; } else { let types = [this.identifier]; if (this.identifier === 'merged') { types = ['c', 'p', 'd']; } if (this.identifier === 'unread' || this.identifier === 'tokens') { types = ['c', 'p']; } if (['c', 'p'].includes(this.identifier)) { query.tokens = { $exists: false }; } else if (this.identifier === 'tokens' && user && user.services && user.services.tokenpass) { query.tokens = { $exists: true }; } if (RocketChat.getUserPreference(user, 'sidebarShowUnread')) { query.$or = [ {alert: {$ne: true}}, {hideUnreadStatus: true} ]; } query.t = {$in: types}; if (favoritesEnabled) { query.f = {$ne: favoritesEnabled}; } } if (sortBy === 'activity') { const list = ChatSubscription.find(query, {sort: {rid : 1}}).fetch(); const ids = list.map(sub => sub.rid); const rooms = RocketChat.models.Rooms.find({ _id: { $in : ids} }, { sort : { _id: 1 }, fields: {_updatedAt: 1} }).fetch().reduce((result, room) =>{ result[room._id] = room; return result; }, {}); return _.sortBy(list.map(sub => { const lm = rooms[sub.rid]._updatedAt; return { ...sub, lm: lm && lm.toISOString() }; }), 'lm').reverse(); } return ChatSubscription.find(query, {sort}); }, isLivechat() { return this.identifier === 'l'; }, shouldAppear(group, rooms) { /* if is a normal group ('channel' 'private' 'direct') or is favorite and has one room or is unread and has one room */ return !['unread', 'f'].includes(group.identifier) || (rooms.length || rooms.count && rooms.count()); }, roomType(room) { if (room.header || room.identifier) { return `type-${ room.header || room.identifier }`; } }, noSubscriptionText() { const instance = Template.instance(); const roomType = (instance.data.header || instance.data.identifier); return RocketChat.roomTypes.roomTypes[roomType].getUiText(UiTextContext.NO_ROOMS_SUBSCRIBED) || 'No_channels_yet'; }, showRoomCounter() { return RocketChat.getUserPreference(Meteor.user(), 'roomCounterSidebar'); } });
JavaScript
0.000001
@@ -2252,16 +2252,34 @@ nst lm = + rooms%5Bsub.rid%5D && rooms%5Bs
67d0180b8b39c37c56eb1a2b51487873349ca9c6
Set default index selection to a valid one
webui/assets/main.js
webui/assets/main.js
class REPL { constructor(input, output, button) { this.input = input this.output = output this.button = button this.history = [] this.history_index = 0 this.history_buffer = '' this.result_number = 0 } bind_events() { const repl = this const keys = { ENTER: 13, UP_ARROW: 38, DOWN_ARROW: 40 } this.input.addEventListener("keydown", (e) => { if (e.keyCode == keys.UP_ARROW) { e.preventDefault() if (this.input.value.substring(0, this.input.selectionStart).indexOf('\n') == '-1') { if (this.history_index == 0) { return } else { if (this.history_index == this.history.length) { this.history_buffer = this.input.value } this.history_index-- this.input.value = this.history[this.history_index] this.input.setSelectionRange(this.input.value.length, this.input.value.length) } } } if (e.keyCode == keys.DOWN_ARROW) { e.preventDefault() if (this.input.value.substring(this.input.selectionEnd, this.input.length).indexOf('\n') == '-1') { if (this.history_index == this.history.length) { return } else { this.history_index++ if (this.history_index == this.history.length) { this.input.value = this.history_buffer } else { this.input.value = this.history[this.history_index] } this.input.setSelectionRange(this.input.value.length, this.input.value.length) } } } if (e.keyCode == keys.ENTER && !e.shiftKey) { e.preventDefault() this.submit(); } }) this.button.onclick = function() { repl.submit(); }; } submit() { this.history_buffer = '' this.history_index = this.history.length this.history[this.history_index] = this.input.value this.history_index++ this.process_query(this.input.value) this.input.value = "" } process_query(query) { var xhr = new XMLHttpRequest(); var e = document.getElementById("index-dropdown"); var indexname = e.options[e.selectedIndex].text; xhr.open('POST', '/db/' + indexname + '/query'); // TODO db->index xhr.setRequestHeader('Content-Type', 'application/text'); const repl = this var start_time = new Date().getTime(); xhr.send(query) xhr.onload = function() { var end_time = new Date().getTime() repl.result_number++ repl.createSingleOutput({ "input": query, "output": xhr.responseText, "indexname": indexname, "querytime_ms": end_time - start_time, }) } } createSingleOutput(res) { var node = document.createElement("div"); node.classList.add('output'); var result_class = "result-output" var output = JSON.parse(res['output']) if("error" in output) { result_class = "result-error" } var markup =` <div class="panes"> <div class="pane active"> <div class="result-io"> <div class="result-io-header"> <h5>Input</h5> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <em>Source: ${res.indexname}</em> </div> <div class="result-input"> ${res.input} </div> </div> <div class="result-io"> <div class="result-io-header"> <h5>output</h5> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <em>${res.querytime_ms} ms</em> </div> <div class="${result_class}"> ${res.output} </div> </div> </div> <div class="pane"> <div class="raw"> <a href="${res.url}">Export raw .csv</a> </div> </div> </div> ` node.innerHTML = markup; this.output.insertBefore(node, this.output.firstChild) } populate_index_dropdown() { var xhr = new XMLHttpRequest(); xhr.open('GET', '/schema') // TODO schema->status (?) var select = document.getElementById('index-dropdown') xhr.onload = function() { var schema = JSON.parse(xhr.responseText) for(var i=0; i<schema['dbs'].length; i++) { // TODO db->index var opt = document.createElement('option') opt.innerHTML = schema['dbs'][i]['name'] select.appendChild(opt) } } xhr.send(null) } } const input = document.getElementById('query') const output = document.getElementById('outputs') const button = document.getElementById('query-btn') repl = new REPL(input, output, button) repl.populate_index_dropdown() repl.bind_events()
JavaScript
0.000001
@@ -4911,16 +4911,42 @@ ption')%0A + opt.value = i+1%0A @@ -5028,24 +5028,175 @@ )%0A %7D%0A + // set the active option to one of the populated options, instead of invalid %22Index%22%0A if(i %3E 0) %7B%0A select.value = 1;%0A %7D%0A %7D%0A
2c08ea3a9349cbe97b8047b045b5b8a2c76066f0
Add utils.memoize_hasher
public/src/js/utils.js
public/src/js/utils.js
/* * debugger.io: An interactive web scripting sandbox * * utils.js: utility functions */ define(['config', 'jquery', 'underscore'], function(config, $, _) { 'use strict'; var utils = {}; if (!config.prod) { window.utils = utils; } /** * Log messages to console only in non-production * * @param {Mixed} - messages to log */ utils.log = function() { if (!config.prod) { var args = _.toArray(arguments); args.unshift('==>'); console.log.apply(console, args); } }; /** * Ensure that a value is wrapped with jQuery * * @param {Mixed} value * @return {jQuery} */ utils.ensure_jquery = function(value) { if (value instanceof $) { return value; } if ((value instanceof HTMLElement) || _.isArray(value)) { return $(value); } return $(); }; /** * Ensure that a value is an array * * @param {Mixed} value * @return {Array} */ utils.ensure_array = function(value) { if (value === undefined || value === null) { return []; } return _.isArray(value) ? value : [value]; }; /** * Ensure that a value is a string * * @param {Mixed} value * @return {String} */ utils.ensure_string = function(value) { return _.isString(value) ? value : (value ? value + '' : ''); }; /** * New module is just an empty object, but attach it to the global window * object if config.prod is false * * @param {String} name - name of the module (only relevant to window) * @param {Object} [base] - base object to use * @param {Boolean} [global] - if true, attach to global window object as well * @return {Object} empty module object */ utils.module = function(name, base, global) { var module = base || {}; module._priv = module._priv || {}; if (global || (global === undefined && !config.prod)) { window[name] = module; } return module; }; /** * Remove all double quotes (") from a string * * @param {String} str - input string * @return {String} input string with double quotes removed */ utils.no_quotes = function(str) { return _.isString(str) ? str.replace(/\"/g, '') : ''; }; /** * Get an absolute URI on the debugger.io domain * TODO: if URI is already absolute, return the string unmodified * * @param {String} path - relative or absolute URI * @return {String} absolute URI */ utils.uri = function(path) { return config.root + path; }; /** * Get the extension of a URI or filename * * @param {String} uri - URI or filename * @returns {String} extension */ utils.extension = function(uri) { uri = _.trim(utils.no_quotes(uri)); return _.strRightBack(uri, '.'); }; /** * Get string for a new script element * * @param {String} uri - URI of script * @param {String} [type] - script MIME type, defaults to JavaScript * @return {String} script string */ utils.script_element_string = function(uri, type) { uri = _.trim(utils.no_quotes(uri)); type = type || ext_map['js'].type; return _.sprintf('<script type="%s" src="%s"></script>', type, uri); }; /** * Get string for a new stylesheet link element * * @param {String} uri - URI of stylesheet * @param {String} [type] - style MIME type, defaults to CSS * @return {String} style link string */ utils.style_element_string = function(uri, type) { uri = _.trim(utils.no_quotes(uri)); type = type || ext_map['css'].type; return _.sprintf('<link rel="stylesheet" type="%s" href="%s">', type, uri); }; // map file extensions to functions generating the appropriate element string var ext_map = { 'js': { tag: 'script', type: 'application/javascript', fn: utils.script_element_string }, 'css': { tag: 'link', type: 'text/css', fn: utils.style_element_string } }; /** * Get the tag name that should be used for a resource, based on extension * * @param {String} uri - URI of resource * @return {String} tag name of resource */ utils.resource_tag = function(uri) { var ext = utils.extension(uri); var map = ext_map[ext]; return map ? map.tag : null; }; /** * Get string for a new resource element, based on extension * * @param {String} uri - URI of resource * @return {String} resource element string */ utils.resource_element_string = function(uri) { var ext = utils.extension(uri); var map = ext_map[ext]; return map ? map.fn(uri, map.type) : null; }; /** * Create a promise that resolves to a value now * * @param {Mixed} value - value that the promise will resolve to * @return {Promise} promise to return value */ utils.promise_now = function(value) { return $.Deferred().resolve(value).promise(); }; /** * Return a number clamped by a minimum and maximum * * @param {Number} val - number to clamp * @param {Number} [min] - minimum value, defaults to 0 * @param {Number} [max] - maximum value, defaults to `val` * @return {Number} clamped value */ utils.clamp = function(val, min, max) { val = _.isFinite(val) ? val: 0; min = _.isFinite(min) ? min : Number.NEGATIVE_INFINITY; max = _.isFinite(max) ? max : Number.POSITIVE_INFINITY; return Math.min(Math.max(val, min), max); }; /** * Deep clone an object parsable as JSON * * @param {Object} val * @return {Object} deep copy of `val` */ utils.clone = function(val) { return JSON.parse(JSON.stringify(val)); }; /** * An array of limited capacity * * @param {Number} cap - capacity of the buffer */ utils.Buffer = function(cap) { this._data = []; this.set_cap(cap); }; utils.Buffer.prototype = { /** * Buffer some value(s), then truncate to capacity * * @param {Mixed} - value(s) to buffer * @return {this} */ buf: function() { _.each(arguments, function(arg) { this._data.push(arg); }, this); if (this._data.length > this._cap) { this._data.splice(0, this._data.length - this._cap); } return this; }, set_cap: function(cap) { this._cap = utils.clamp(cap, 0); }, get: function() { return this._data.slice(0); }, flush: function() { this._data = []; } }; return utils; });
JavaScript
0.000003
@@ -5551,32 +5551,246 @@ fy(val));%0A %7D;%0A%0A + /**%0A * Hash function for _.memoize%0A *%0A * @return %7BString%7D joined arguments with hopefully unique separator%0A */%0A utils.memoize_hasher = function() %7B%0A return _.toArray(arguments).join('%3C%3C%3C!%3E%3E%3E');%0A %7D;%0A%0A /**%0A * An ar
a274a4a16ab9461cbf3cf20029e673f8645554dc
Update admin.js
public/js/admin.js
public/js/admin.js
window.admin = {}; $(document).ready(function() { $("#admin-feedback").on("tabOpened", function() { window.api.get("admin/feedback/getList", function(resp) { $("#admin-feedback-list").text(""); for (var feedbackIndex in resp.feedback) { var feedbackItem = resp.feedback[feedbackIndex]; var $feedbackLi = $('<li></li>'); var $feedbackDesc = $('<div></div>'); $feedbackDesc.text(feedbackItem.desc.subStr(0, 75)); $feedbackLi.append($feedbackDesc); var $feedbackName = $('<div></div>'); $feedbackName.text(feedbackItem.name); $feedbackLi.append($feedbackName); $("#admin-feedback-list").append($feedbackLi); }; }); }); });
JavaScript
0.000001
@@ -416,17 +416,16 @@ tem. -desc +msg .sub -S +s tr(0
ae26b8ccb4335041ae62fb89ccaab7f3cd9e229a
Update comment on hmd.ricaleinline
hmd.ricaleinline.js
hmd.ricaleinline.js
// # hmd.ricaleinline (hmd add-on) // - written by ricale // - [email protected] or [email protected] hmd.addInlineRules([ [/--([^-\s]{1,2}|-[^-\s]|[^-\s]-|(?:[^\s].+?[^\s]))--/g, '<del>$1</del>'], [/,,([^,\s]{1,2}|,[^,\s]|[^,\s],|(?:[^\s].+?[^\s])),,/g, '<sub>$1</sub>'], [/\^\^([^\^\s]{1,2}|\^[^\^\s]|[^\^\s]\^|(?:[^\s].+?[^\s]))\^\^/g, '<sup>$1</sup>'] ]);
JavaScript
0
@@ -69,46 +69,20 @@ ale@ -hanmail.net or [email protected] +ricalest.net %0A%0Ahm
0b6cf0a1b2fb6c1bea609198f306238adad94b16
fix queue size and mouseover
public/js/queue.js
public/js/queue.js
//This code is heavily based on code from //http://mbostock.github.io/d3/talk/20111018/tree.html d3.queue = function(d3, canvasID, w, h, data) { var spacing = 140//w / data.length; var defaultSize = 15; var chart = d3.select(canvasID).append("svg") .attr("width", "10000") .attr("height", h) .style("margin-left", 25) var nodes = chart.selectAll("g") .data(data) .enter().append("g") .attr("transform", function(d, i) { size = parseFloat(d.size || defaultSize); return "translate(" + i * spacing + "," + (h / 2 - size / 2) + ")"; }) nodes.append("rect") .attr("height", function(d) { return parseFloat(d.size || defaultSize); }) .attr("width", function(d) { return parseFloat(d.size || defaultSize); }) .style("fill", function(d) { return d.color || "steelblue" }) .style("stroke", "gray") .style("stroke-width", 2) nodes .append("text") .text(function(d) { return d.name }) .attr("x", 0) .attr("y", function(d) { size = parseFloat(d.size||defaultSize) return 15 + size }) .attr("dy", ".35em") //we don't want to process the first node data.pop() var lines = chart.selectAll("line") .data(data) .enter().append("line") .attr("x1", function(d, i) { return (i) * spacing + parseFloat(d.size || defaultSize); }) .attr("x2", function(d, i) { return (i + 1) * spacing }) .attr("y1", h / 2) .attr("y2", h / 2) .style("stroke", "black") }
JavaScript
0
@@ -283,17 +283,17 @@ idth%22, %22 -1 +5 0000%22)%0A @@ -435,24 +435,94 @@ append(%22g%22)%0A + .on(%22mouseover%22, mouseover)%0A .on(%22mouseout%22, mouseout)%0A .att @@ -1133,24 +1133,58 @@ end(%22text%22)%0A + .style(%22display%22, %22none%22)%0A .tex @@ -1815,32 +1815,32 @@ tr(%22y2%22, h / 2)%0A - .style(%22 @@ -1857,10 +1857,779 @@ black%22)%0A +%0A%0Afunction mouseover() %7B%0A%0A d3.select(this).select(%22text%22).transition()%0A .duration(750)%0A .style(%22display%22,%22block%22)%0A /*%0A d3.select(this).select(%22path%22).transition()%0A .duration(750)%0A .attr('d', function (d) %7B%0A return d3.svg.symbol().type(d.shape%7C%7C%22circle%22)%0A .size(scaleSize(40))()%0A %7D) %0A */ %0A%7D%0A%0Afunction mouseout() %7B%0A %0A d3.select(this).select(%22text%22).transition()%0A .duration(750)%0A .style(%22display%22,%22none%22)%0A /*%0A d3.select(this).select(%22path%22).transition()%0A .duration(750)%0A .attr('d', function (d) %7B%0A return d3.svg.symbol().type(d.shape%7C%7C%22circle%22)%0A .size(scaleSize(d.size%7C%7C1))()%0A %7D) %0A */ %0A%7D%0A%0A%0A%0A %7D%0A
823b46f88354d0ddedfc886999083a3660bdf23c
check for log file before opening it
logger.js
logger.js
var jf = require('jsonfile'); var file = './log.json'; var filecontents = jf.readFileSync(file); function readLogs() { return filecontents; } function logMessage(request, response) { filecontents[request.date] = { "request": request, "response" : response }; } function storeLogs() { jf.writeFile(file, filecontents, function(err) { console.log(err); }); } module.exports = { readLogs: readLogs, logMessage: logMessage, storeLogs: storeLogs };
JavaScript
0
@@ -1,12 +1,36 @@ +var fs = require('fs');%0A var jf = req @@ -74,16 +74,131 @@ json';%0A%0A +if (!fs.existsSync(file)) %7B%0A jf.writeFile(file, %7B%7D, function (err) %7B%0A console.error(err);%0A %7D);%0A%7D%0A%0A var file @@ -230,16 +230,20 @@ c(file); + %0A%0Afuncti
ba516f37c73195250e559f8c20cce2ed94e32249
check null timestamp
logger.js
logger.js
var fs = require('fs') var _ = require('lodash'); var request = require('request'); var cheerio = require('cheerio'); var colors = require('colors'); var config = JSON.parse(fs.readFileSync('config.json')) var baseUrl = config.dwUrl; var httpOptions = ***REMOVED*** 'auth': ***REMOVED*** 'user': config.username, 'pass': config.password, 'sendImmediately': true ***REMOVED***, strictSSL: false ***REMOVED***; var logs = ***REMOVED******REMOVED***; var diffLog = ***REMOVED******REMOVED***; function checkLogs() ***REMOVED*** request.get(baseUrl + 'on/demandware.servlet/webdav/Sites/Logs', httpOptions, function(error, response, body) ***REMOVED*** var logFiles = []; $ = cheerio.load(body); var rightNow = new Date(); var searchDate = rightNow.toISOString().slice(0, 10).replace(/-/g, ""); // create a mapping of logs and timestamps $('tr').each(function(i, row) ***REMOVED*** var logName = $(row).find('td:nth-child(1) > a > tt').text(); var fileName = logName.split('.')[0]; var timeStamp = $(row).find('td:nth-child(3) > tt').text(); // if the timestamp changes, download it if (logs[fileName] && (logs[fileName].timeStamp !== timeStamp) && (config.watch.indexOf(logs[fileName].logName.slice(0, -13)) > -1)) ***REMOVED*** // download the new log file... request(logs[fileName].logLink, httpOptions, function(error, response, body) ***REMOVED*** if (error) ***REMOVED*** return console.error(error); ***REMOVED*** if (diffLog[fileName]) ***REMOVED*** _.each(body.trim().split('\n').slice(-Math.max(body.trim().split('\n').length - diffLog[fileName], 1)), function(line) ***REMOVED*** console.log(colors.green(logs[fileName].logName + ": ") + colors.grey(line.match(/\[(.*?)\]/).toString().split(',')[0]), colors.red(line.split('GMT] ')[1])); ***REMOVED***); ***REMOVED*** else ***REMOVED*** var line = body.trim().split('\n').slice(-1)[0]; console.log(colors.green(logs[fileName].logName + ": ") + colors.grey(line.match(/\[(.*?)\]/).toString().split(',')[0]), colors.red(line.split('GMT] ')[1])); ***REMOVED*** diffLog[fileName] = body.trim().split('\n').length; ***REMOVED***) ***REMOVED*** logs[fileName] = ***REMOVED*** 'logName': logName, 'timeStamp': timeStamp, 'logLink': baseUrl + $(row).find('td:nth-child(1) > a').attr('href') ***REMOVED*** ***REMOVED***); ***REMOVED***); ***REMOVED*** setInterval(checkLogs, 1000);
JavaScript
0.000007
@@ -1947,32 +1947,166 @@ ) ***REMOVED***%0A + var message = line.match(/%5C%5B(.*?)%5C%5D/);%0A if (message) ***REMOVED***%0A @@ -2191,39 +2191,23 @@ rs.grey( -line.match(/%5C%5B(.*?)%5C%5D/) +message .toStrin @@ -2255,32 +2255,78 @@ ('GMT%5D ')%5B1%5D));%0A + ***REMOVED***%0A @@ -2483,24 +2483,150 @@ ice(-1)%5B0%5D;%0A + var message = line.match(/%5C%5B(.*?)%5C%5D/);%0A if (message) ***REMOVED***%0A @@ -2711,39 +2711,23 @@ rs.grey( -line.match(/%5C%5B(.*?)%5C%5D/) +message .toStrin @@ -2775,32 +2775,74 @@ ('GMT%5D ')%5B1%5D));%0A + ***REMOVED***%0A
8582116880c79950f41419b63fae20f22e3b48de
Update ProvideActions.js
src/client/actions/ProvideActions.js
src/client/actions/ProvideActions.js
import { dispatch, dispatchAsync } from '../dispatcher/AppDispatcher'; import ProvideConstants from '../constants/ProvideConstants'; import ProvideService from '../services/ProvideService'; export default { updateSimulator: (newValue) => { dispatch(ProvideConstants.UPDATE_SIMULATOR, {newValue}); }, calculate: (profile, pageKey) => { let promise = ProvideService.calculate(profile, pageKey); dispatchAsync(promise, { request: ProvideConstants.CALCULATE, success: ProvideConstants.CALCULATE_SUCCESS, failure: ProvideConstants.DATA_ERROR }, { }); }, getCarList: () => { let promise = ProvideService.getCarList(); dispatchAsync(promise, { request: ProvideConstants.GET_CAR_LIST, success: ProvideConstants.GET_CAR_LIST_SUCCESS, failure: ProvideConstants.DATA_ERROR }, { }); } }
JavaScript
0
@@ -345,23 +345,29 @@ rofile, -pageKey +simulatorInfo ) =%3E %7B%0D%0A @@ -426,15 +426,21 @@ le, -pageKey +simulatorInfo );%0D%0A
6f104a0cfb030952e7bea5ee79a37ff1beef63d7
I said ONE slice
src/client/scripts/helpers/Player.js
src/client/scripts/helpers/Player.js
import SettingsManager from './SettingsManager'; class Player { static instance; // The registered samples samples = []; // An array of audio nodes that are currently playing per sample playing = []; // Used to create audio sources and as destination for the playing samples audioContext = new AudioContext(); // The audio node to connect the created audio to audioDestinationNode; // Whether an animation frame is requested, indicating that no new loop has to be spawned frameRequested = false; static init() { this.instance = new Player(); } constructor() { this.progressStep = this.progressStep.bind(this); // Set up volume control using a gain node const gainNode = this.audioContext.createGain(); gainNode.connect(this.audioContext.destination) // Initial volume gainNode.gain.value = SettingsManager.instance.get('volume'); // Bind to volume changes SettingsManager.instance.on('volume', (volume) => { gainNode.gain.value = volume; }); // Set the gain node as the destination node this.audioDestinationNode = gainNode; } registerSample({ url, onPlay, onStop, onProgress }) { const sample = { url, onPlay, onStop, onProgress, }; const sampleIndex = this.samples.push(sample) - 1; this.playing[sampleIndex] = []; const player = this; sample.play = function(loop) { // Create an audio element source and link it to the context const audio = new Audio(url); audio.crossOrigin = "anonymous"; const source = player.audioContext.createMediaElementSource(audio); source.connect(player.audioDestinationNode); audio.loop = loop; audio.play(); // Add to playing player.playing[sampleIndex].push(audio); // Register audio stop and pause events audio.onended = audio.onpause = function() { // BUG: Removes two every stop, so messes with simultaneous plays. This is because of Array.prototype.indexOf matching by value instead of reference // Remove from playing const spliced = player.playing[sampleIndex].splice(player.playing[sampleIndex].indexOf(audio), 1); // Trigger onStop only when we just removed the last playing intance of this sample if (spliced.length > 0 && player.playing[sampleIndex].length == 0) { sample.onStop(); } }; // Trigger onPlay only when this is the first instance of this sample to start playing if (player.playing[sampleIndex].length == 1) { sample.onPlay(); // Request animation frame (only once) if (!player.frameRequested) { player.frameRequested = true; requestAnimationFrame(player.progressStep); } } }; // Return the ID return sampleIndex; } play(sampleIndex, multiple = false, loop = false) { // Stop all sounds before playing if multiple are not allowed if (!multiple) { this.stopAll(); } this.samples[sampleIndex].play(loop); } stop(sampleIndex) { this.playing[sampleIndex].forEach(function(playing) { playing.pause(); }); } stopAll() { this.playing.forEach((playing, sampleIndex) => { this.stop(sampleIndex); }); } progressStep() { let samplesArePlaying = false; this.playing.forEach((playing, sampleIndex) => { if (playing.length > 0) { // Use the last playing sample to reflect the most recently started sample const progress = playing[playing.length - 1].currentTime / playing[playing.length - 1].duration * 100; this.samples[sampleIndex].onProgress(progress); samplesArePlaying = true; } }); this.frameRequested = samplesArePlaying; // Keep requesting an animation frame until all no samples are playing if (this.frameRequested) { window.requestAnimationFrame(this.progressStep); } } } export default Player;
JavaScript
0.998437
@@ -1907,158 +1907,105 @@ -// BUG: Removes two every stop, so messes with simultaneous plays. This is because of Array.prototype.indexOf matching by value instead of reference%0A%0A +const audioIndex = player.playing%5BsampleIndex%5D.indexOf(audio);%0A%0A if (audioIndex %3E= 0) %7B%0A @@ -2027,24 +2027,26 @@ rom playing%0A + cons @@ -2096,57 +2096,27 @@ ice( -player.playing%5BsampleIndex%5D.indexOf(audio) +audioIndex , 1);%0A%0A + @@ -2215,34 +2215,14 @@ + if ( -spliced.length %3E 0 && play @@ -2262,32 +2262,34 @@ 0) %7B%0A + sample.onStop(); @@ -2285,24 +2285,36 @@ e.onStop();%0A + %7D%0A %7D%0A
c69ce9216a29006520f6285c6db44e16c3e1e8c8
Add JS as a valid option
frappe/public/js/frappe/form/controls/code.js
frappe/public/js/frappe/form/controls/code.js
frappe.ui.form.ControlCode = frappe.ui.form.ControlText.extend({ make_input() { if (this.editor) return; this.load_lib().then(() => this.make_ace_editor()); }, make_ace_editor() { const ace_editor_target = $('<div class="ace-editor-target"></div>') .appendTo(this.input_area); // styling ace_editor_target.addClass('border rounded'); ace_editor_target.css('height', 300); // initialize this.editor = ace.edit(ace_editor_target.get(0)); this.editor.setTheme('ace/theme/tomorrow'); this.set_language(); // events this.editor.session.on('change', frappe.utils.debounce((delta) => { const input_value = this.get_input_value(); this.parse_validate_and_set_in_model(input_value); }, 300)); }, set_language() { const language_map = { 'Javascript': 'ace/mode/javascript', 'HTML': 'ace/mode/html', 'CSS': 'ace/mode/css' } const language = this.df.options; const valid_languages = Object.keys(language_map); if (!valid_languages.includes(language)) { console.warn(`Invalid language option provided for field "${this.df.label}". Valid options are ${valid_languages.join(', ')}.`); } const ace_language_mode = language_map[language] || ''; this.editor.session.setMode(ace_language_mode); }, parse(value) { if (value == null) { value = ""; } return value; }, set_formatted_input(value) { this.library_loaded.then(() => { if (value === this.get_input_value()) return; this.editor.session.setValue(value); }); }, get_input_value() { return this.editor ? this.editor.session.getValue() : ''; }, load_lib() { if (frappe.boot.developer_mode) { this.root_lib_path = '/assets/frappe/js/lib/ace-builds/src-noconflict/'; } else { this.root_lib_path = '/assets/frappe/js/lib/ace-builds/src-min-noconflict/'; } this.library_loaded = new Promise(resolve => { frappe.require(this.root_lib_path + 'ace.js', () => { window.ace.config.set('basePath', this.root_lib_path); resolve(); }); }); return this.library_loaded; } });
JavaScript
0.000014
@@ -807,16 +807,48 @@ cript',%0A +%09%09%09'JS': 'ace/mode/javascript',%0A %09%09%09'HTML
a3cedfc66230928b0b12cbead736bbcdce145c86
Add join script
src/es2015/join.js
src/es2015/join.js
// Description: // 新規参加者用挨拶スクリプト // var slackAPI = require('slackbotapi'); var token = process.env.WEB_SLACK_TOKEN; var slack = new slackAPI({ 'token': token, 'logging': true, 'autoReconnect': true }); module.exports = (robot => { robot.respond(/join all/i, res => { res.send('joined all channels') }) })
JavaScript
0.000001
@@ -18,21 +18,25 @@ / -%E6%96%B0%E8%A6%8F%E5%8F%82%E5%8A%A0%E8%80%85%E7%94%A8%E6%8C%A8%E6%8B%B6%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%97%E3%83%88 +join all channels %0A//%0A @@ -167,29 +167,8 @@ en,%0A - 'logging': true,%0A @@ -268,48 +268,909 @@ %3E %7B%0A -%0A res.send('joined all channels') + let bot = slackAPI.getUser(robot.name);%0A slack.reqAPI(%22channels.list%22,%7B%0A exclude_archived: 1%0A %7D, (data) =%3E %7B%0A if(!data.ok) %7B%0A robot.logger.error(%60something ocuured $%7Bdata%7D%60);%0A return;%0A %7D%0A data.channels%0A .filter((ch) =%3E (ch.substring(0, 1) === 'C') )%0A .forEach((ch) =%3E %7B%0A slack.reqAPI(%22channels.invite%22, %7B%0A channel: ch.id,%0A user: bot.id%0A %7D, (data) %7B%0A if( data.ok ) %7B%0A res.send(%60joined #$%7Bch.name%7D%60)%0A %7D else %7B%0A robot.logger.error(%60failed to join to $%7Bch%7D%60);%0A robot.logger.error(data);%0A %7D%0A %7D);%0A %7D);%0A %7D); %0A
3b2726dc11fb5a6402dd39a8c6126a22af9a64b1
fix NPE in LoadRoutePluginComponents
src/LoadRoutePluginComponents.js
src/LoadRoutePluginComponents.js
/* @flow */ import * as Immutable from 'immutable' import React, {Component, PropTypes} from 'react' import {LoadPluginComponent, PluginComponents} from 'redux-plugins-immutable-react' type Props = { route: { pluginKey?: string | Symbol, componentKey?: string | Symbol, getComponentFromPlugin?: (plugin: Immutable.Map) => any, componentProps?: Object } }; export default class LoadRoutePluginComponents extends Component<void, Props, void> { static propTypes = { route: PropTypes.object }; render(): ?React.Element { const {props: {route}} = this if (!route) return null const {pluginKey, componentKey, getComponentFromPlugin: getComponent, componentProps} = route if (componentKey || getComponent) { if (pluginKey) { return (<LoadPluginComponent pluginKey={pluginKey} componentKey={componentKey} getComponent={getComponent} componentProps={componentProps ? {...componentProps, ...props} : props} />) } else { return (<PluginComponents componentKey={componentKey} getComponent={getComponent} componentProps={componentProps ? {...componentProps, ...props} : props} />) } } return null } }
JavaScript
0
@@ -564,17 +564,8 @@ rops -: %7Broute%7D %7D = @@ -578,16 +578,22 @@ if (! +props. route) r @@ -603,20 +603,16 @@ rn null%0A - %0A con @@ -696,16 +696,22 @@ rops%7D = +props. route%0A
4323441358a9e8caf7869be37506774b9a3eaf30
Fix index issues when triggering events
src/event/index.js
src/event/index.js
const isFunction = require('../is-function'); module.exports = function Event() { const listeners = {}; let count = 0; // Returns an id that can be used to stop listening for the event this.on = function(eventName, cb) { if(!eventName || typeof eventName !== 'string') { throw new Error('Event.on requires a string eventName'); } if(!isFunction(cb)) { throw new Error('Event.on requires a function callback'); } if(!listeners.hasOwnProperty(eventName)) { listeners[eventName] = []; } const id = count++; listeners[eventName].push({ eventName, cb, id }); return id; }; this.off = function() { if(typeof arguments[0] === 'number') { for(const i in listeners) { listeners[i] = listeners[i].filter(listener => { return listener.id !== arguments[0]; }); } } else if(typeof arguments[0] === 'string') { if(isFunction(arguments[1])) { if(listeners.hasOwnProperty(arguments[0])) { listeners[arguments[0]] = listeners[arguments[0]].filter(listener => { return listener.cb !== arguments[1]; }); } } else { delete listeners[arguments[0]]; } } else { throw new Error('Event.off requires an id or eventName & optional callback'); } }; this.trigger = function(eventName, data) { if(!eventName || typeof eventName !== 'string') { throw new Error('Event.trigger requires a string eventName'); } if(listeners.hasOwnProperty(eventName) && listeners[eventName].length) { const makePromise = (cb) => { if(!listeners[eventName].some((listenerInfo) => cb === listenerInfo.cb)) { return Promise.resolve(); } return new Promise((resolve, reject) => cb(resolve, reject, data)) }; let promise = makePromise(listeners[eventName][0].cb); for(let i=1; i<listeners[eventName].length; i++) { promise = promise.then(() => makePromise(listeners[eventName][i].cb)); } return promise; } return Promise.resolve(); }; };
JavaScript
0.000002
@@ -1468,16 +1468,69 @@ ngth) %7B%0A +%09%09%09const incomplete = listeners%5BeventName%5D.slice(0);%0A %09%09%09const @@ -1780,91 +1780,121 @@ ise( -listeners%5BeventName%5D%5B0%5D.cb);%0A%09%09%09for(let i=1; i%3Clisteners%5BeventName%5D +incomplete.splice(0, 1)%5B0%5D.cb);%0A%09%09%09while(incomplete .length -; i++) + %3E 0) %7B%0A +%09%09%09%09const cb = incomplete.splice(0, 1)%5B0%5D.cb;%0A %09%09%09%09 @@ -1938,32 +1938,8 @@ ise( -listeners%5BeventName%5D%5Bi%5D. cb))
faa229db39f854fdec488b9a8422af5b16a8a35b
add myself as contributor
src/Parser/Priest/Holy/CONFIG.js
src/Parser/Priest/Holy/CONFIG.js
import React from 'react'; import { enragednuke } from 'CONTRIBUTORS'; import SPECS from 'common/SPECS'; import CHANGELOG from './CHANGELOG'; export default { // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. contributors: [enragednuke], // The WoW client patch this spec was last updated to be fully compatible with. patchCompatibility: '7.3', // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more. // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component. description: ( <React.Fragment> Hi! Welcome to the Holy Priest analyzer. </React.Fragment> ), // A recent example report to see interesting parts of the spec. Will be shown on the homepage. // exampleReport: '/report/hNqbFwd7Mx3G1KnZ/18-Mythic+Antoran+High+Command+-+Kill+(6:51)/Taffly', // Don't change anything below this line; // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about. spec: SPECS.HOLY_PRIEST, // The contents of your changelog. changelog: CHANGELOG, // The CombatLogParser class for your spec. parser: () => import('./CombatLogParser' /* webpackChunkName: "Priest" */).then(exports => exports.default), // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code. path: __dirname, };
JavaScript
0
@@ -41,16 +41,24 @@ agednuke +, niseko %7D from @@ -472,16 +472,24 @@ agednuke +, niseko %5D,%0A //
b4c742f78e581eea18d91b02e549a3b340937fd2
Add 1 2 Vue sample
.vuepress/config.js
.vuepress/config.js
module.exports = { title: "Cours", description: "Cette documentation est réalisée par Valentin Brosseau (pour le BTS SIO - SLAM 5, mais également l'ESEO), vous retrouverez dans l’ensemble des cours (slide) ainsi que les TP.", plugins: ["@vuepress/last-updated", ["vuepress-plugin-code-copy", true]], lang: "fr-FR", dest: "docs", themeConfig: { docsBranch: 'master', editLinks: true, nextLinks: false, prevLinks: false, displayAllHeaders: true, sidebarDepth: 0, sidebar: [ ["/", "Introduction"], { collapsable: false, title: "Aides mémoires", children: [["cheatsheets/git/", "Git"], ["cheatsheets/cordova/", "Cordova"], ["cheatsheets/docker/", "VueJS"], ["cheatsheets/vuejs/", "Docker"]] }, { collapsable: false, title: "Initiation à Git", children: ["cours/git", "/tp/git_initiation/"] }, { collapsable: false, title: "Git en groupe + GitLab", children: ["cours/gitlab", "/tp/gitlab/"] }, { collapsable: false, title: "Organisation du code", children: ["cours/organisations", "/tp/organisation/introduction"] }, { collapsable: false, title: "Javascript avancé (À venir)", children: ["cours/javascript_avances", "tp/javascript_avances/introduction"] }, { collapsable: false, title: "Programmation sécurisée avec OWASP", children: ["cours/securite_applications", "tp/securite/"] }, { collapsable: false, title: "Laravel", children: ["cours/laravel", "/tp/laravel/introduction", "/tp/laravel/application_todo_list", "/tp/laravel/creation_api"] }, { collapsable: false, title: "Typescript (À venir)", children: ["cours/typescript"] }, { collapsable: false, title: "NodeJS (À venir)", children: ["cours/nodejs", "/tp/nodejs/api", "/tp/nodejs/firebase"] }, { collapsable: false, title: "VueJS", children: ["cours/vuejs", "/tp/vuejs/tp1-vuejs-laravel-api", "/tp/vuejs/tp1", "/tp/vuejs/tp2", "/tp/vuejs/firebase-vuejs"] }, { collapsable: false, title: "VueJS exemple", children: ["cours/demo/vuejs/demo1", "cours/demo/vuejs/counter", "cours/demo/vuejs/clock", "cours/demo/vuejs/timestamp-color", "cours/demo/vuejs/sound"] }, { collapsable: false, title: "Cordova + VueJS", children: ["cours/cordova", "/tp/cordova/decouverte", "/tp/cordova/vuejs_cordova", "/tp/cordova/vuejs_api_led", "/tp/api/doc_api_led"] }, { collapsable: false, title: "Docker", children: [["https://rawgit.com/c4software/bts/master/cours/docker/", "Slides"], "/tp/docker/introduction", "/tp/docker/dockerfile", "/tp/docker/docker_compose"] }, { collapsable: false, title: "GitLab-CI", children: ["cours/gitlabci", "/tp/ci/pages", "/tp/ci/ci-hybride"] }, { collapsable: false, title: "Python : Framework Flask", children: ["cours/python", "/tp/python/flask", "/tp/python/flask_todolist_api"] }, { collapsable: false, title: "Android", children: ["cours/android", "/tp/android/app-ble-network"] } ] } };
JavaScript
0.000143
@@ -2142,16 +2142,42 @@ s/sound%22 +, %22cours/demo/vuejs/12vue%22 %5D%0A
e0fdf6bef9487dd46e97665c09cb13666630a1ab
Update app.js
00-workspace/app.js
00-workspace/app.js
// SET UP THE MAP var mapProjection = new ol.proj.Projection({ code: 'EPSG:3857', extent: [-20037508, -20037508, 20037508, 20037508.34] }) var geoProjection = new ol.proj.Projection({ code: 'EPSG:4326', extent: [-180, -180, 180, 180] }) var map = new ol.Map({ layers:[ new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'https://api.mapbox.com/styles/v1/mapbox/outdoors-v10/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoid2lsbC1icmVpdGtyZXV0eiIsImEiOiItMTJGWEF3In0.HEvuRMMVxBVR5-oDYvudxw' }) }) ], target: 'map', view: new ol.View({ center: ol.proj.transform([-96, 39], geoProjection, mapProjection), zoom: 5 }) }); var app = { mapzenKey:'mapzen-CpAANqF', activeSearch: 'from', typeAhead: function(e) { var el = e.target; var val = el.value; console.log(val); }, queryAutocomplete: throttle(function(text, callback){ $.ajax({ url: 'https://search.mapzen.com/v1/autocomplete?text=' + text + '&api_key=' + app.mapzenKey, success: function(data, status, req){ callback(null, data); }, error: function(req, status, err){ callback(err) } }) }, 150) } $('#search-from-input').on('keyup', {input:'from'}, app.typeAhead);
JavaScript
0.000002
@@ -824,25 +824,123 @@ %09 -console.log(val); +if(val.length %3E 2)%7B%0A app.queryAutocomplete(val, function(err, data)%7B%0A console.log(data);%0A %7D)%0A %7D %0A
5287917050c385d2569d6d22a2de0c1882544816
update constructor and super
src/async-script-loader.js
src/async-script-loader.js
import { Component, createElement } from "react"; import PropTypes from "prop-types"; let SCRIPT_MAP = {}; // A counter used to generate a unique id for each component that uses the function let idCount = 0; export default function makeAsyncScript(getScriptURL, options) { options = options || {}; return function wrapWithAsyncScript(WrappedComponent) { const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || "Component"; class AsyncScriptLoader extends Component { constructor() { super(); this.state = {}; this.__scriptURL = ""; this.assignChildComponent = this.assignChildComponent.bind(this); } asyncScriptLoaderGetScriptLoaderID() { if (!this.__scriptLoaderID) { this.__scriptLoaderID = "async-script-loader-" + idCount++; } return this.__scriptLoaderID; } setupScriptURL() { this.__scriptURL = typeof getScriptURL === "function" ? getScriptURL() : getScriptURL; return this.__scriptURL; } assignChildComponent(ref) { this.__childComponent = ref; } getComponent() { return this.__childComponent; } asyncScriptLoaderHandleLoad(state) { // use reacts setState callback to fire props.asyncScriptOnLoad with new state/entry this.setState(state, () => this.props.asyncScriptOnLoad && this.props.asyncScriptOnLoad(this.state) ); } asyncScriptLoaderTriggerOnScriptLoaded() { let mapEntry = SCRIPT_MAP[this.__scriptURL]; if (!mapEntry || !mapEntry.loaded) { throw new Error("Script is not loaded."); } for (let obsKey in mapEntry.observers) { mapEntry.observers[obsKey](mapEntry); } delete window[options.callbackName]; } componentDidMount() { const scriptURL = this.setupScriptURL(); const key = this.asyncScriptLoaderGetScriptLoaderID(); const { globalName, callbackName } = options; // check if global object already attached to window if (globalName && typeof window[globalName] !== "undefined") { SCRIPT_MAP[scriptURL] = { loaded: true, observers: {} }; } // check if script loading already if (SCRIPT_MAP[scriptURL]) { let entry = SCRIPT_MAP[scriptURL]; // if loaded or errored then "finish" if (entry && (entry.loaded || entry.errored)) { this.asyncScriptLoaderHandleLoad(entry); return; } // if still loading then callback to observer queue entry.observers[key] = entry => this.asyncScriptLoaderHandleLoad(entry); return; } /* * hasn't started loading * start the "magic" * setup script to load and observers */ let observers = {}; observers[key] = entry => this.asyncScriptLoaderHandleLoad(entry); SCRIPT_MAP[scriptURL] = { loaded: false, observers, }; let script = document.createElement("script"); script.src = scriptURL; script.async = true; let callObserverFuncAndRemoveObserver = func => { if (SCRIPT_MAP[scriptURL]) { let mapEntry = SCRIPT_MAP[scriptURL]; let observersMap = mapEntry.observers; for (let obsKey in observersMap) { if (func(observersMap[obsKey])) { delete observersMap[obsKey]; } } } }; if (callbackName && typeof window !== "undefined") { window[callbackName] = () => this.asyncScriptLoaderTriggerOnScriptLoaded(); } script.onload = () => { let mapEntry = SCRIPT_MAP[scriptURL]; if (mapEntry) { mapEntry.loaded = true; callObserverFuncAndRemoveObserver(observer => { if (callbackName) { return false; } observer(mapEntry); return true; }); } }; script.onerror = event => { let mapEntry = SCRIPT_MAP[scriptURL]; if (mapEntry) { mapEntry.errored = true; callObserverFuncAndRemoveObserver(observer => { observer(mapEntry); return true; }); } }; // (old) MSIE browsers may call "onreadystatechange" instead of "onload" script.onreadystatechange = () => { if (this.readyState === "loaded") { // wait for other events, then call onload if default onload hadn't been called window.setTimeout(() => { const mapEntry = SCRIPT_MAP[scriptURL]; if (mapEntry && mapEntry.loaded !== true) { script.onload(); } }, 0); } }; document.body.appendChild(script); } componentWillUnmount() { // Remove tag script const scriptURL = this.__scriptURL; if (options.removeOnUnmount === true) { const allScripts = document.getElementsByTagName("script"); for (let i = 0; i < allScripts.length; i += 1) { if (allScripts[i].src.indexOf(scriptURL) > -1) { if (allScripts[i].parentNode) { allScripts[i].parentNode.removeChild(allScripts[i]); } } } } // Clean the observer entry let mapEntry = SCRIPT_MAP[scriptURL]; if (mapEntry) { delete mapEntry.observers[this.asyncScriptLoaderGetScriptLoaderID()]; if (options.removeOnUnmount === true) { delete SCRIPT_MAP[scriptURL]; } } } render() { const globalName = options.globalName; // remove asyncScriptOnLoad from childProps let { asyncScriptOnLoad, ...childProps } = this.props; // eslint-disable-line no-unused-vars if (globalName && typeof window !== "undefined") { childProps[globalName] = typeof window[globalName] !== "undefined" ? window[globalName] : undefined; } childProps.ref = this.assignChildComponent; return createElement(WrappedComponent, childProps); } } AsyncScriptLoader.displayName = `AsyncScriptLoader(${wrappedComponentName})`; AsyncScriptLoader.propTypes = { asyncScriptOnLoad: PropTypes.func, }; if (options.exposeFuncs) { options.exposeFuncs.forEach(funcToExpose => { AsyncScriptLoader.prototype[funcToExpose] = function() { return this.getComponent()[funcToExpose](...arguments); }; }); } return AsyncScriptLoader; } }
JavaScript
0
@@ -528,16 +528,30 @@ tructor( +props, context ) %7B%0A @@ -560,18 +560,31 @@ super( +props, context ) -; %0A
6311da08c1931769f728ee6d9ce3953e66044148
Add fs.access and refactor cb() further
host/nodeachrome.js
host/nodeachrome.js
#!/Users/admin/.nvm/versions/node/v4.2.4/bin/node // ^ full path to node must be specified above, edit for your system. may also try: // #!/usr/local/bin/node 'use strict'; const process = require('process'); const fs = require('fs'); const nativeMessage = require('chrome-native-messaging'); const input = new nativeMessage.Input(); const transform = new nativeMessage.Transform(messageHandler); const output = new nativeMessage.Output(); process.stdin .pipe(input) .pipe(transform) .pipe(output) .pipe(process.stdout); function encodeError(err) { return {error: { code: err.errno, // must be an integer, but err.code is a string like 'ENOENT' message: err.toString(), } }; } function encodeResult(err, data) { if (err) { return encodeError(err); } else { return {result:data}; } } function createCallback(push, done) { function genericCallback(err, data) { push(encodeResult(err, data)); done(); } return genericCallback; } function messageHandler(msg, push, done) { const method = msg.method; const params = msg.params; if (method === 'echo') { push(msg); done(); /* TODO } else if (method === 'fs.access') { const path = params[0]; if (params.length < 2) { fs.access(path, (err) => { }); */ } else if (method === 'fs.readFile') { const path = params[0]; // TODO: restrict access to only a limited set of files if (params.length < 2) { //const callback = params[1]; fs.readFile(path, createCallback(push, done)); } else { const options = params[1]; //const callback = params[2]; fs.readFile(path, options, createCallback(push, done)); } } else { push({error: { code: -32601, // defined in http://www.jsonrpc.org/specification#response_object message: 'Method not found', data: `invalid method: ${method}`} }); done(); } }
JavaScript
0
@@ -872,167 +872,8 @@ %0A%7D%0A%0A -function createCallback(push, done) %7B%0A function genericCallback(err, data) %7B%0A push(encodeResult(err, data));%0A done();%0A %7D%0A%0A return genericCallback;%0A%7D%0A%0A func @@ -970,16 +970,95 @@ arams;%0A%0A + function cb(err, data) %7B%0A push(encodeResult(err, data));%0A done();%0A %7D%0A%0A if (me @@ -1107,20 +1107,8 @@ ();%0A - /* TODO%0A %7D @@ -1225,33 +1225,94 @@ th, -(err) =%3E %7B%0A%0A %7D);%0A%0A*/ +cb);%0A %7D else %7B%0A const mode = params%5B1%5D;%0A fs.access(path, mode, cb);%0A %7D %0A %7D @@ -1531,33 +1531,9 @@ h, c -reateCallback(push, done) +b );%0A @@ -1651,33 +1651,9 @@ s, c -reateCallback(push, done) +b );%0A
4d51bcbb94beca984512c935985a4142d43d0bf5
Add fetchHarvest and fetchHarvests
src/fetch/fetch.js
src/fetch/fetch.js
export function cancelAllPromise(component) { return component.cancelablePromises.map( promise => promise.cancel()) } export const makeCancelable = (promise) => { let hasCanceled_ = false; const wrappedPromise = new Promise((resolve, reject) => { promise.then((val) => hasCanceled_ ? reject({isCanceled: true}) : resolve(val) ); promise.catch((error) => hasCanceled_ ? reject({isCanceled: true}) : reject(error) ); }); return { promise: wrappedPromise, cancel() { hasCanceled_ = true; }, }; }; function _f(url) { return fetch(url) .then(response => response.json()) .catch((err) => { console.error(err) throw err }) } function waitDataAndSetState(dataPromise, component, stateName) { const cancelablePromise = makeCancelable(dataPromise .then(data => { const update = {}; update[stateName] = data; component.setState(update); }) .catch(err => { if (!component.state.errors.includes(err.message)) { const errors = [...component.state.errors, err.message] component.setState({ errors }) } throw err }) ) if (!component.cancelablePromises) component.cancelablePromises = [] component.cancelablePromises.push(cancelablePromise) return cancelablePromise } export function fetchMetrics(component, catalogId) { if (!catalogId) return Promise.reject(new Error('catalogId is required')) const fetchPromise = _f(`https://inspire.data.gouv.fr/api/geogw/catalogs/${catalogId}/metrics`) return waitDataAndSetState(fetchPromise, component, 'metrics') } export function fetchCatalog(component, catalogId) { if (!catalogId) return Promise.reject(new Error('catalogId is required')) const fetchPromise = _f(`https://inspire.data.gouv.fr/api/geogw/catalogs/${catalogId}`) return waitDataAndSetState(fetchPromise, component, 'catalog') } export function fetchCatalogs(component) { const fetchPromise = _f('https://inspire.data.gouv.fr/api/geogw/catalogs') return waitDataAndSetState(fetchPromise, component, 'catalogs') } export function fetchDatasets(component) { const fetchPromise = _f('https://inspire.data.gouv.fr/api/datasets/metrics') return waitDataAndSetState(fetchPromise, component, 'datasets') }
JavaScript
0.000001
@@ -2080,24 +2080,734 @@ talogs')%0A%7D%0A%0A +export function fetchHarvest(component, catalogId, harvestId) %7B%0A if (!catalogId) return Promise.reject(new Error('catalogId is required'))%0A if (!harvestId) return Promise.reject(new Error('harvestId is required'))%0A const fetchPromise = _f(%60https://inspire.data.gouv.fr/api/geogw/services/$%7BcatalogId%7D/synchronizations/$%7BharvestId%7D%60)%0A return waitDataAndSetState(fetchPromise, component, 'harvest')%0A%7D%0A%0Aexport function fetchHarvests(component, catalogId) %7B%0A if (!catalogId) return Promise.reject(new Error('catalogId is required'))%0A const fetchPromise = _f(%60https://inspire.data.gouv.fr/api/geogw/services/$%7BcatalogId%7D/synchronizations%60)%0A return waitDataAndSetState(fetchPromise, component, 'harvests')%0A%7D%0A%0A export funct
48565343b7d275de59b9e42a9e10ada5e003c94c
Add text prop to DeleteConfirmButtons for configurable text copy
ui/src/shared/components/DeleteConfirmButtons.js
ui/src/shared/components/DeleteConfirmButtons.js
import React, {PropTypes, Component} from 'react' import classnames from 'classnames' import OnClickOutside from 'shared/components/OnClickOutside' import ConfirmButtons from 'shared/components/ConfirmButtons' const DeleteButton = ({onClickDelete, buttonSize}) => <button className={classnames('btn btn-danger table--show-on-row-hover', { [buttonSize]: buttonSize, })} onClick={onClickDelete} > Delete </button> class DeleteConfirmButtons extends Component { constructor(props) { super(props) this.state = { isConfirming: false, } this.handleClickDelete = ::this.handleClickDelete this.handleCancel = ::this.handleCancel } handleClickDelete() { this.setState({isConfirming: true}) } handleCancel() { this.setState({isConfirming: false}) } handleClickOutside() { this.setState({isConfirming: false}) } render() { const {onDelete, item, buttonSize} = this.props const {isConfirming} = this.state return isConfirming ? <ConfirmButtons onConfirm={onDelete} item={item} onCancel={this.handleCancel} buttonSize={buttonSize} /> : <DeleteButton onClickDelete={this.handleClickDelete} buttonSize={buttonSize} /> } } const {func, oneOfType, shape, string} = PropTypes DeleteButton.propTypes = { onClickDelete: func.isRequired, buttonSize: string, } DeleteConfirmButtons.propTypes = { item: oneOfType([(string, shape())]), onDelete: func.isRequired, buttonSize: string, } DeleteConfirmButtons.defaultProps = { buttonSize: 'btn-sm', } export default OnClickOutside(DeleteConfirmButtons)
JavaScript
0
@@ -257,14 +257,20 @@ Size +, text %7D) =%3E%0A - %3Cb @@ -422,22 +422,22 @@ %3E%0A -Delete +%7Btext%7D %0A %3C/but @@ -939,16 +939,22 @@ ttonSize +, text %7D = this @@ -1202,24 +1202,46 @@ eleteButton%0A + text=%7Btext%7D%0A on @@ -1408,16 +1408,43 @@ pes = %7B%0A + text: string.isRequired,%0A onClic @@ -1486,32 +1486,83 @@ ize: string,%0A%7D%0A%0A +DeleteButton.defaultProps = %7B%0A text: 'Delete',%0A%7D%0A%0A DeleteConfirmBut @@ -1580,16 +1580,32 @@ pes = %7B%0A + text: string,%0A item:
863a244051ecd126b14b01622ecdf5ca4a3f717d
Add Upbit accounts
src/app/utils/BadActorList.js
src/app/utils/BadActorList.js
const list = ` acx aex.com allcoin.com appreciater bbittrex bcex bellyrub biitrex biittrex bit-z bitex bitfinex.com bitfinix bitflip bithumb bithumb.com bitifinex bitkrx bitnaru bitre bitreex bitrex bitrexx bitrix bitrrex bitrtex bitrx bitsane bitsane.com bitstamp.net bitt bitteex bitter bitterex bitterx bittex bitthai bittrax bittre bittrec bittrecs bittred bittreex bittrek bittres bittresx bittrev bittrex-deposit bittrex.com bittrexe bittrexs bittrext bittrexx bittrexxx bittrez bittrix bittrrex bittrrx bittrx bittrxe bitttec bitttex bitttrex bittylicious bittylicious.com blcktrades blcoktrades bleutrade bleutrade.com block-trades block-trades-com blockrade blockrades blockrtades blocktades blocktardes blocktraades blocktrad blocktrade blocktraded blocktradee blocktradees blocktrader blocktraders blocktrades-com blocktrades-info blocktrades-us blocktrades.com blocktrades.info blocktrades.us blocktradess blocktradesss blocktradez blocktrads blocktradse blocktraeds blocktraes blocktrdaes blocktrdes blocktredes blockttrades bloctkrades bloctrades blokctrades bloktrades bloocktrades bocktrades bolcktrades boooster boostar booste boosterr boostr boostre boostter boster btc-alpha btc-alpha.com btcalpha btcmarkets btcmarkets.net btitrex btrex bttrex bttrx buildawale buildawhile buildwhale c-cex.com ccex cexio changellly changelly.com changely coin-room coinbase.com coinegg coinegg.com coinpayments coinpia coinroom.com coinsmarkets coinsmarkets.com coinspot coinzest coolcoin.com etherdelta etherdelta.com exrates exx.com fyrstiken gatecoin.com gatehub gatehub.net gdax.com gemini.com gopax gtapps hitbtc.com hitbtcexchange hotstuff huobi.pro idex.market ittrex ittrexx kcx kocostock koinex kraken.com kucoin linkcoin litebit livecoin.com livecoinnet livingroomofsato localtrade localtrade.pro mercatox.com minnnowbooster minnoowbooster minnowboooster minnowboost minnowbooste minnowboosted minnowboosteer minnowboosterr minnowboostr minnowboostre minnowbootser minnowboster minnowhelp minnowpond minnowpooster minnowsuport minnowsupports minnowwbooster minobooster minowbooster minowboster minowhelper nanabaakan neraex neraex.com okex.com olonie oloniex openledgerdex pextokens plolniex ploniex plooniex polaniex poleniex poliniex polionex pollniex polloniex polloniexx pollonix polniex polnoiex polobiex poloex poloiex poloinex pololniex polomiex polon poloneex poloneiex poloneix polonex poloni poloniax polonie poloniec poloniecs polonied poloniee polonieex poloniek polonieks polonies poloniet poloniets poloniew poloniex.com poloniexcold poloniexcom poloniexe poloniexs poloniext poloniexwalle poloniexwallet poloniexx poloniexxx poloniey poloniez poloniiex poloniix poloniks poloniox polonium polonix polonixe polonixx polonniex polonoiex polonox polonx polonyex polooniex poluniex pononiex poolniex pooloniex pooniex poooniex qryptos qryptos.com randomwhale randowale randowhal randwhale scoin shapeshif shapeshift steemitpay steempay steempays sweetsj sweetssj sweetssssj tdax tdax.com thebiton therocktrading tidex.com topbtc upbit.com viabtc vittrex wallet.bitshares www.aex.com www.binance.com www.bit-z.com www.bitfinex.com www.bithumb.com www.bitstamp.net www.bittrex.com www.coinbase.com www.coinegg.com www.coolcoin.com www.exx.com www.gatecoin.com www.gatehub.net www.gdax.com www.huobi.pro www.kraken.com www.livecoin.net www.okex.com www.poloniex.com www.qryptos.com www.quebex.comw www.wavesplatfor www.xbtce.com xbtce.com yobit yobit.net youbit zeniex ` .trim() .split('\n'); export default list;
JavaScript
0
@@ -3054,14 +3054,34 @@ %0Aupb -it.com +bit%0Aupbit%0Aupbit.com%0Aupbitt %0Avia
26c9afd56888d6ea78bae80fb25730922a9e664f
Remove no longer used field related functions
src/field/index.js
src/field/index.js
import { Map } from 'immutable'; import trim from 'trim'; import * as cc from './country_codes'; export function setField(m, field, value, validator, ...validatorExtraArgs) { const prevValue = m.getIn(["field", field, "value"]); const prevShowInvalid = m.getIn(["field", field, "showInvalid"], false); const valid = !!validator(value, ...validatorExtraArgs); return m.mergeIn(["field", field], Map({ value: value, valid: valid, showInvalid: prevShowInvalid && prevValue === value })); } export function isFieldValid(m, field) { return m.getIn(["field", field, "vlaid"]); } export function isFieldVisiblyInvalid(m, field) { return m.getIn(["field", field, "showInvalid"], false) && !m.getIn(["field", field, "valid"]); } export function setFieldShowInvalid(m, field, value) { return m.setIn(["field", field, "showInvalid"], value); } export function clearFields(m, fields) { let keyPaths; if (!fields || fields.length === 0) { keyPaths = ["field"]; } else { keyPaths = fields.map(x => ["field", x]); } return keyPaths.reduce((r, v) => r.removeIn(v), m); } function valid(lock, field) { return lock.getIn(["field", field, "valid"]); } function showInvalid(lock, field) { return lock.getIn(["field", field, "showInvalid"], false); } function setShowInvalid(lock, field, value) { return lock.setIn(["field", field, "showInvalid"], value); } function visiblyInvalid(lock, field) { return showInvalid(lock, field) && !valid(lock, field); } // phone number export function fullPhoneNumber(lock) { return `${phoneDialingCode(lock) || ""}${phoneNumber(lock) || ""}`.replace(/[\s-]+/g, ''); } export function fullHumanPhoneNumber(m) { const code = phoneDialingCode(m); const number = phoneNumber(m); return `${code} ${number}`; } export function setPhoneLocation(m, value) { return m.setIn(["field", "phoneNumber", "location"], value); } function phoneLocation(m) { return m.getIn(["field", "phoneNumber", "location"], cc.defaultLocation); } export function phoneLocationString(m) { return cc.locationString(phoneLocation(m)); } export function phoneDialingCode(m) { return cc.dialingCode(phoneLocation(m)); } export function phoneIsoCode(m) { return cc.isoCode(phoneLocation(m)); } export function phoneNumber(lock) { return lock.getIn(["field", "phoneNumber", "value"], ""); } // email export function email(lock) { return lock.getIn(["field", "email", "value"], ""); } // vcode export function vcode(lock) { return lock.getIn(["field", "vcode", "value"], ""); } // password export function password(lock) { return lock.getIn(["field", "password", "value"], ""); } // username export function username(lock) { return lock.getIn(["field", "username", "value"], ""); }
JavaScript
0
@@ -1110,403 +1110,8 @@ %0A%7D%0A%0A -%0A%0A%0A%0Afunction valid(lock, field) %7B%0A return lock.getIn(%5B%22field%22, field, %22valid%22%5D);%0A%7D%0A%0Afunction showInvalid(lock, field) %7B%0A return lock.getIn(%5B%22field%22, field, %22showInvalid%22%5D, false);%0A%7D%0A%0Afunction setShowInvalid(lock, field, value) %7B%0A return lock.setIn(%5B%22field%22, field, %22showInvalid%22%5D, value);%0A%7D%0A%0Afunction visiblyInvalid(lock, field) %7B%0A return showInvalid(lock, field) && !valid(lock, field);%0A%7D%0A%0A // p
9be898bd2268c348767ca581b73c684e4875de13
Add copyright
src/fixed-thead.js
src/fixed-thead.js
!function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.FixedThead = factory(); } }(this, function () { 'use strict'; // shortcuts var forEach = Array.prototype.forEach; var map = Array.prototype.map; var $$ = document.querySelectorAll.bind(document); var tables, fixedTheads; var offsetLeft, offsetTop, backgroundImage, backgroundColor, enabled; function eachInit(table) { var table, thead, cloneThead; if(table.nodeName !== 'TABLE') { throw new Error('Target selectors must be a table element.'); } thead = table.querySelector('thead'); if(!thead) { throw new Error('Table must have a thead.'); } cloneThead = thead.cloneNode(true); table.insertBefore(cloneThead, table.firstChild); cloneThead.style.display = 'none'; cloneThead.style.position = 'fixed'; cloneThead.style.top = offsetTop + 'px'; cloneThead.style.marginLeft = -parseInt(getStyle(table, 'border-spacing')) + offsetLeft + 'px'; forEach.call(cloneThead.children, function(tr) { forEach.call(tr.children, function(cell) { cell.style.boxSizing = 'border-box'; }); }); if(backgroundColor) cloneThead.style.backgroundColor = backgroundColor; if(backgroundImage) cloneThead.style.backgroundImage = backgroundImage; window.addEventListener('scroll', scrollEvent); window.addEventListener('resize', debounce(computeWidth, 500)); function computeWidth() { forEach.call(thead.children, function(tr, trIndex) { forEach.call(tr.children, function(cell, cellIndex) { cloneThead.children[trIndex].children[cellIndex].style.width = cell.clientWidth + 'px'; }); }); } function scrollEvent() { if(!enabled) return; var isShown = table.offsetTop - offsetTop - window.scrollY > 0 || table.offsetTop - offsetTop + table.clientHeight - thead.clientHeight < window.scrollY; var enterTable = cloneThead.getAttribute('data-fixed-thead') === null var leaveTable = cloneThead.getAttribute('data-fixed-thead') === ''; if (isShown && leaveTable) disableFixed(); else if (!isShown && enterTable) enableFixed(); } function disableFixed() { cloneThead.removeAttribute('data-fixed-thead'); cloneThead.style.display = 'none'; } function enableFixed() { computeWidth(); cloneThead.setAttribute('data-fixed-thead', ''); cloneThead.style.display = 'table-header-group'; } function changeStatus() { enabled ? scrollEvent() : disableFixed(); } this.changeStatus = changeStatus; return this; } function debounce(func, wait) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; func.apply(context, args); }; var callNow = !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; } function getStyle(element, styleProp){ if (element.currentStyle) var y = element.currentStyle[styleProp]; else if (window.getComputedStyle) var y = document.defaultView.getComputedStyle(element, null).getPropertyValue(styleProp); return y; } function FixedThead(selector, option) { tables = $$(selector); option = option || {}; offsetLeft = option.offsetLeft || 0; offsetTop = option.offsetTop || 0; enabled = typeof option.enabled !== 'undefined' ? option.enabled : true; backgroundImage = option.backgroundImage; backgroundColor = option.backgroundColor || '#fff'; fixedTheads = map.call(tables, function(table) { return new eachInit(table); }); Object.defineProperty(this, 'enabled', { get: function() { return enabled; }, set: function(bool) { enabled = bool; fixedTheads.forEach(function(fixedThead) { fixedThead.changeStatus(); }); } }); }; return FixedThead; });
JavaScript
0.001145
@@ -1,8 +1,100 @@ +// Fixed-thead 1.0.0%0A// https://github.com/sunya9/fixed-thead%0A// (c) 2016 sunya9(_X_y_z_)%0A %0A !functio
7d36bd51220fc373d5ef020b7248ff31550f9026
use the right lengths for pool tables
src/commands/Promocodes/ListPools.js
src/commands/Promocodes/ListPools.js
'use strict'; const rpad = require('right-pad'); const Command = require('../../models/Command.js'); const { createGroupedArray, createPageCollector } = require('../../CommonFunctions.js'); class ListPools extends Command { constructor(bot) { super(bot, 'promocode.pools.managed', 'glyphs list managed', 'List claimed codes.'); this.regex = new RegExp(`^${this.call}`, 'i'); this.allowDM = true; } async run(message) { const pools = await this.settings.getPoolsUserManages(message.author); const longestName = pools.length ? pools.map(pool => pool.name) .reduce((a, b) => (a.length > b.length ? a : b)) : ''; const longestId = pools.length ? pools.map(pool => pool.pool_id) .reduce((a, b) => (a.length > b.length ? a : b)) : ''; pools.unshift({ pool_id: 'Pool Id', name: 'Pool Name', len: '# of Codes' }); this.logger.debug(`name: ${longestName} | id: ${longestId}`); const groupPools = createGroupedArray(pools, 27); const poolOfPools = createGroupedArray(groupPools, 4); const pages = []; poolOfPools.forEach((poolGroup) => { const embed = { title: 'Managed Pools', color: 0xd30000, fields: poolGroup.map(group => ({ name: '_ _', value: group.map(pool => `\`${rpad(pool.pool_id, longestName.length, ' ')} ` + `| ${rpad(pool.name, longestId.length, ' ')} | ${pool.len}\``).join('\n'), })), }; pages.push(embed); }); if (pages.length) { const msg = await this.messageManager.embed(message, pages[0], false, false); if (pages.length > 1) { await createPageCollector(msg, pages, message.author); } } if (parseInt(await this.settings.getChannelSetting(message.channel, 'delete_after_respond'), 10) && message.deletable) { message.delete(10000); } return pools.length > 0 ? this.messageManager.statuses.SUCCESS : this.messageManager.statuses.FAILURE; } } module.exports = ListPools;
JavaScript
0.000037
@@ -1301,20 +1301,18 @@ longest -Name +Id .length, @@ -1354,34 +1354,36 @@ ol.name, longest -Id +Name .length, ' ')%7D %7C
a3009c13e1f3f7e71c3ad753e98a2500b581a4b5
set conditional to use virtual service url in getLegendUrl
src/common/legend/LegendDirective.js
src/common/legend/LegendDirective.js
(function() { var module = angular.module('loom_legend_directive', []); var legendOpen = false; module.directive('loomLegend', function($rootScope, mapService, serverService) { return { restrict: 'C', replace: true, templateUrl: 'legend/partial/legend.tpl.html', // The linking function will add behavior to the template link: function(scope, element) { scope.mapService = mapService; scope.serverService = serverService; var openLegend = function() { angular.element('#legend-container')[0].style.visibility = 'visible'; angular.element('#legend-panel').collapse('show'); legendOpen = true; }; var closeLegend = function() { angular.element('#legend-panel').collapse('hide'); legendOpen = false; //the timeout is so the transition will finish before hiding the div setTimeout(function() { angular.element('#legend-container')[0].style.visibility = 'hidden'; }, 350); }; scope.toggleLegend = function() { if (legendOpen === false) { if (angular.element('.legend-item').length > 0) { openLegend(); } } else { closeLegend(); } }; scope.getLegendUrl = function(layer) { var url = null; var server = serverService.getServerById(layer.get('metadata').serverId); url = server.url + '?request=GetLegendGraphic&format=image%2Fpng&width=20&height=20&layer=' + layer.get('metadata').name + '&transparent=true&legend_options=fontColor:0xFFFFFF;' + 'fontAntiAliasing:true;fontSize:14;fontStyle:bold;'; return url; }; scope.$on('layer-added', function() { if (legendOpen === false) { openLegend(); } }); scope.$on('layerRemoved', function() { //close the legend if the last layer is removed if (legendOpen === true && angular.element('.legend-item').length == 1) { closeLegend(); } }); } }; }); }());
JavaScript
0
@@ -1616,24 +1616,215 @@ -url = server.url +if (goog.isDefAndNotNull(server.virtualServiceUrl)) %7B%0A domain = server.virtualServiceUrl;%0A %7D else %7B%0A domain = server.url;%0A %7D%0A url = domain + '
94d8164a03415a0642c2ec712ea2aa6b4f334f02
Return SuperAgent's promise
src/gapi-client.js
src/gapi-client.js
import request from 'superagent'; import GapiResources from './gapi-resources'; const path = require ('path'); // TODO: Accept integer resourcesIds for `get`, `patch`, and `del`; right now only string are allowed // TODO: Errors // 2. Every request will at least need one resource call // and one call to either `get`, `list`, `all`, `post`, `patch`, `del` // before `end()` could be called // TODO: Authentication export default class Gapi extends GapiResources{ constructor ({url='https://rest.gadventures.com', key, proxy}){ super(); if( !key ) { throw 'A gapi key is required when instantiating Gapi' } this.baseUrl = url; this.key = key; this.proxy = proxy; this.query = {}; } _setHeaders() { this.request.accept('application/json'); this.request.type('application/json'); this.request.set('X-Application-Key', this.key); this.request.set('X-Fastly-Bypass', 'pass'); // Temporary } _getUrl(...ids) { /** * Builds the full gapi request URL based on the resource provided * `this.resource` is set by `GapiResource` getter methods. **/ if( ! this.resource ) { throw 'No resource has been provided.'; // TODO: Something more declarative. } return path.join(this.baseUrl, this.resource, ...ids); } get( ...resourceIds ) { /** * Support for multiple resource Ids * For resources that accept more than one id. e.g. `itineraries/123/456/` **/ const url = this._getUrl(...resourceIds); this.request = request.get(url); this._setHeaders(); return this; } list() { /** * By default will look for the first 20 items **/ const url = this._getUrl(); this.request = request.get(url); this.page(); this._setHeaders(); return this; } page(number=1, size=20) { this.query = Object.assign({}, this.query, {page: number, max_per_page: size}); return this; } order(...args) { // TODO: Not implemented return this; } post () { const url = this._getUrl(); this.request = request.post(url); this._setHeaders(); return this; } patch (...resourceIds) { const url = this._getUrl(...resourceIds); this.request = request.patch(url); this._setHeaders(); return this; } del (...resourceIds) { const url = this._getUrl(...resourceIds); this.request = request.del(url); this._setHeaders(); return this; } send ( args ) { this.request.send( args ); return this; } end (callback) { this.request.query(this.query); this.request.end(callback); return this; } }
JavaScript
0.000021
@@ -2651,10 +2651,89 @@ s;%0A %7D%0A%0A + then (resolve, reject) %7B%0A return this.request.then(resolve, reject);%0A %7D%0A%0A %7D%0A
f0b22b5387944b5f4fd7bac41fb8547f86b2f3a7
Call polling
src/component/notification-center.js
src/component/notification-center.js
//Dependencies import React, { Component , PropTypes } from 'react'; import NotificationGroup from './notification-group'; import NotificationAdd from './notification-add'; import NotificationCenterIcon from './notification-center-icon'; import { connect } from 'react-redux'; import { addNotification, readNotification, readNotificationGroup, setVisibilityFilter, openCenter, closeCenter } from '../actions'; import { fetchNotifications } from '../actions/fetch-notifications'; // Notification center component class NotificationCenter extends Component { render() { const {dispatch, hasAddNotif, notificationList, isOpen, isFetching} = this.props; //display only the undred notifications const unreadNotifs = notificationList.filter( n => !n.read); return ( <div data-focus='notification-center'> <NotificationCenterIcon number={unreadNotifs.length} openCenter={ () => dispatch(openCenter())}/> {!isOpen && <div data-focus='notification-receiver'></div>} { isOpen && <div data-fetching={isFetching} data-focus='notification-center-panel'> <button data-focus='notification-center-close' className='mdl-button mdl-button--icon' onClick={() => dispatch(closeCenter())}> <i className="material-icons">clear</i> </button> <h1 onClick={() => dispatch(fetchNotifications())}>{`Notification center (${unreadNotifs.length})`}</h1> { hasAddNotif && <NotificationAdd onAddClick={data => dispatch(addNotification(data))} /> } <NotificationGroup data={unreadNotifs} onGroupRead={data => dispatch(readNotificationGroup(data))} onSingleRead={data => dispatch(readNotification(data))} /> </div> } </div> ); } } NotificationCenter.displayName = 'NotificationCenter'; NotificationCenter.defaultProps = { hasAddNotif: false }; NotificationCenter.propTypes = { dispatch: PropTypes.func, hasAddNotif: PropTypes.bool, isOpen: PropTypes.bool, notificationList: PropTypes.array } // Select the notification from the state. function selectNotifications(notificationList, filter) { return notificationList; } // Select the part of the state. function select(state) { const {notificationList, visibilityFilter, ...otherStateProperties} = state; return { //select the notification list from the state notificationList: selectNotifications(notificationList, visibilityFilter), visibilityFilter, ...otherStateProperties }; } // connect the notification center to the state. export default connect(select)(NotificationCenter);
JavaScript
0
@@ -472,16 +472,54 @@ tions';%0A +import polling from '../util/polling'; %0A// Noti @@ -593,16 +593,521 @@ t %7B%0A +componentWillMount() %7B%0A //build a polling timeout.%0A const %7BpollingTimer, dispatch%7D = this.props;%0A polling(() =%3E %7B%0A dispatch(fetchNotifications(this.lastFetch));%0A this.lastFetch = new Date().toISOString();%0A %7D, pollingTimer);%0A dispatch(fetchNotifications());%0A this.lastFetch = new Date().toISOString();%0A %7D%0A //componentWillUnMount() %7B%0A // clearTimeout(this.pollingTimeoutID)%0A //%7D%0A //Should be replaced by a promise.cancel%0A render() @@ -1108,17 +1108,16 @@ nder() %7B -%0A %0A @@ -2674,16 +2674,53 @@ f: false +,%0A pollingTimer: 60 * 1000 //1 min %0A%7D;%0ANoti @@ -2876,16 +2876,52 @@ es.array +,%0A pollingTimer: PropTypes.number %0A%7D%0A%0A// S
c72028425c0c5a2f2efc8090dda95bfcc5ccc3eb
replace lazy.js with lodash
src/components/BoardSection.react.js
src/components/BoardSection.react.js
var React = require("react"), Lazy = require("lazy.js"), Immutable = require("immutable"), BoardStore = require("../stores/BoardStore"), SettingsStore = require("../stores/SettingsStore"), RowSection = require("./RowSection.react"); function getStateFromStores() { return {data: Immutable.Map({"board": BoardStore.getBoard()})}; } var markers = "abcdefghijklmnopqrstuvwxyz"; var BoardSection = React.createClass({ getInitialState: function() { return getStateFromStores(); }, componentDidMount: function() { BoardStore.addChangeListener(this._onChange); }, componentWillUnmount: function() { BoardStore.removeChangeListener(this._onChange); }, render: function() { var board = this.state.data.get("board"), rowColLength = SettingsStore.getRowColumnLength(), i = 0, markerItems = Lazy(markers).take(rowColLength) .map(function(a) { return <div key={"x-marker" + a} className="board__x-marker">{a.toUpperCase()}</div>; }) .value(), rowListItems = board.map(function(row) { i++; return <RowSection row={row} id={i} key={"row" + row.getIn([0, "row"])} />; }); markerItems = [<div key="x-marker0" className="board__x-marker"> </div>].concat(markerItems); return ( <div className="board"> <div className="board__x-markers">{markerItems}</div> {rowListItems} </div> ); }, _onChange: function() { this.setState(getStateFromStores()); } }); module.exports = BoardSection;
JavaScript
0.999983
@@ -27,20 +27,22 @@ %22),%0A -Lazy +lodash = requi @@ -50,14 +50,13 @@ e(%22l -azy.js +odash %22),%0A @@ -904,20 +904,27 @@ s = -Lazy +lodash.take (markers ).ta @@ -923,15 +923,10 @@ kers -).take( +, rowC @@ -935,23 +935,16 @@ Length)%0A - @@ -982,31 +982,24 @@ nction(a) %7B%0A - @@ -1144,64 +1144,9 @@ - %7D)%0A .value( +%7D ),%0A
b1b21bcd05c78f133fdec1d55b5b3c9d3d3eca34
Fix EditPaymentMethods list re-rendering on change
src/components/EditPaymentMethods.js
src/components/EditPaymentMethods.js
import React from 'react'; import PropTypes from 'prop-types'; import { Button } from 'react-bootstrap'; import { defineMessages } from 'react-intl'; import withIntl from '../lib/withIntl'; import EditPaymentMethod from './EditPaymentMethod'; class EditPaymentMethods extends React.Component { static propTypes = { paymentMethods: PropTypes.arrayOf(PropTypes.object).isRequired, collective: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = {}; this.state.paymentMethods = props.paymentMethods.length === 0 ? [{}] : props.paymentMethods; this.renderPaymentMethod = this.renderPaymentMethod.bind(this); this.addPaymentMethod = this.addPaymentMethod.bind(this); this.removePaymentMethod = this.removePaymentMethod.bind(this); this.editPaymentMethod = this.editPaymentMethod.bind(this); this.onChange = props.onChange.bind(this); this.defaultType = this.props.defaultType || 'TICKET'; this.messages = defineMessages({ 'paymentMethods.add': { id: 'paymentMethods.add', defaultMessage: 'add another payment method', }, 'paymentMethods.remove': { id: 'paymentMethods.remove', defaultMessage: 'remove payment method', }, }); } editPaymentMethod(index, obj) { if (obj === null) return this.removePaymentMethod(index); const paymentMethods = [...this.state.paymentMethods]; paymentMethods[index] = { ...paymentMethods[index], ...obj }; this.setState({ paymentMethods }); this.onChange({ paymentMethods }); } addPaymentMethod(paymentMethod) { const paymentMethods = [...this.state.paymentMethods]; paymentMethods.push(paymentMethod || {}); this.setState({ paymentMethods }); } removePaymentMethod(index) { let paymentMethods = this.state.paymentMethods; if (index < 0 || index > paymentMethods.length) return; paymentMethods = [ ...paymentMethods.slice(0, index), ...paymentMethods.slice(index + 1), ]; this.setState({ paymentMethods }); this.onChange({ paymentMethods }); } renderPaymentMethod(paymentMethod, index) { const { collective } = this.props; return ( <div className="paymentMethod" key={`paymentMethod-${index}`}> <EditPaymentMethod paymentMethod={paymentMethod} onChange={pm => this.editPaymentMethod(index, pm)} editMode={paymentMethod.id ? false : true} monthlyLimitPerMember={collective.type === 'ORGANIZATION'} currency={collective.currency} slug={collective.slug} /> </div> ); } render() { const { intl } = this.props; const hasNewPaymentMethod = Boolean( this.state.paymentMethods.find(pm => !pm.id), ); return ( <div className="EditPaymentMethods"> <style jsx> {` :global(.paymentMethodActions) { text-align: right; font-size: 1.3rem; } :global(.field) { margin: 1rem; } .editPaymentMethodsActions { text-align: right; margin-top: -1rem; } :global(.paymentMethod) { margin: 3rem 0; } `} </style> <div className="paymentMethods"> <h2>{this.props.title}</h2> {this.state.paymentMethods.map(this.renderPaymentMethod)} </div> {!hasNewPaymentMethod && ( <div className="editPaymentMethodsActions"> <Button bsStyle="primary" onClick={() => this.addPaymentMethod({})}> {intl.formatMessage(this.messages['paymentMethods.add'])} </Button> </div> )} </div> ); } } export default withIntl(EditPaymentMethods);
JavaScript
0.000001
@@ -2222,24 +2222,69 @@ this.props;%0A + const keyId = paymentMethod.id %7C%7C 'new';%0A return ( @@ -2343,21 +2343,21 @@ ethod-$%7B -index +keyId %7D%60%7D%3E%0A
0de1782cf5f945edb4896848a78d58ed004f6ad2
add ApolloProvider to test
src/components/Layout/Layout.test.js
src/components/Layout/Layout.test.js
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-env jest */ /* eslint-disable padded-blocks, no-unused-expressions */ import React from 'react'; import renderer from 'react-test-renderer'; import configureStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import App from '../App'; import Layout from './Layout'; const middlewares = [thunk]; const mockStore = configureStore(middlewares); const initialState = {}; describe('Layout', () => { it('renders children correctly', () => { const store = mockStore(initialState); const wrapper = renderer .create( <App context={{ insertCss: () => {}, store }}> <Layout> <div className="child" /> </Layout> </App>, ) .toJSON(); expect(wrapper).toMatchSnapshot(); }); });
JavaScript
0
@@ -490,16 +490,106 @@ thunk';%0A +import ApolloClient from 'apollo-client';%0Aimport %7B ApolloProvider %7D from 'react-apollo';%0A%0A import A @@ -868,42 +868,342 @@ nst -wrapper = renderer%0A .create(%0A +apolloClient = new ApolloClient(%7B%0A networkInterface: %7B%0A async query() %7B%0A // Just an empty dataset for testing purposes for now.%0A return %7B data: %5B%5D %7D;%0A %7D,%0A %7D,%0A queryDeduplication: true,%0A %7D);%0A%0A const wrapper = renderer%0A .create(%0A %3CApolloProvider client=%7BapolloClient%7D%3E%0A @@ -1263,16 +1263,18 @@ + %3CLayout%3E @@ -1266,32 +1266,34 @@ %3CLayout%3E%0A + %3Cdiv @@ -1324,16 +1324,18 @@ + %3C/Layout @@ -1348,14 +1348,42 @@ + %3C/App%3E +%0A %3C/ApolloProvider%3E ,%0A
c6dfb3b24307f5a3e368135d7add665e81b5460f
add a field for on_pay_result_verify
routes/fly_flow.js
routes/fly_flow.js
/** * Created by King Lee on 14-10-14. */ var redis_fly_flow_wrapper = require('./nosql/redis_fly_flow_wrapper'); var NodeRSA = require('node-rsa'); var key = new NodeRSA({b: 1024}); var log4js = require('log4js'); var log_json = require('../config/log.json'); log4js.configure(log_json); var http_logger = log4js.getLogger('http-logger'); exports.on_pay_result = function(req,res){ http_logger.debug(req.body); var order_info = {}; order_info.florderid = req.body['florderid']; order_info.orderid = req.body['orderid']; order_info.productid = req.body['productid']; order_info.cardno = req.body['cardno']; order_info.amount = req.body['amount']; order_info.amountunit = req.body['amountunit']; order_info.ret = req.body['ret']; order_info.cardstatus = req.body['cardstatus']; order_info.merpriv = req.body['merpriv']; var verifystring = req.body['verifystring']; /* try{ var decrypted_verifystring = key.decrypt(verifystring, 'utf8'); http_logger.debug(decrypted_verifystring); var decrypted_verifystring_array = decrypted_verifystring.split('|'); http_logger.debug(decrypted_verifystring_array); } catch (e){ http_logger.error(e.message); } */ redis_fly_flow_wrapper.set(order_info.orderid,order_info,function(reply){ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' }); var code = "0"; var tips = "接收成功"; if(reply){ console.log("set ok"); } res.end(JSON.stringify({"code":code,"tips":tips})); }); };
JavaScript
0.000003
@@ -928,24 +928,62 @@ ystring'%5D;%0D%0A + http_logger.debug(verifystring);%0D%0A /*%0D%0A
d7e21016f5cf93a0c60f0354a16f1f3f9d50ae7e
update example description
routes/services.js
routes/services.js
_ = require("underscore"); request = require('request'); Promise = require('promise'); // example of a service that takes in a url and returns json function url_service(url){ // $SERVICE_NAME { key: value } return new Promise( function( resolve, reject ) { resolve( { url: url } ); } ); } function herdict_service(url) { return new Promise( function( resolve, reject ) { var countryReportUrl = 'http://www.herdict.org/api/reports/countries?days=365&url=' + url; request( { url: countryReportUrl, json: true }, function ( e, r, body ) { if (!e && r.statusCode == 200) { console.log( body ); resolve( { herdict: body } ); } } ); } ); } function wayback_machine_service(url){ console.log('loading wayback'); var rval = {}; request.get({url:'http://archive.org/wayback/available?url=' + encodeURIComponent(url), json:true}, function (error, response, body) { rval["status"] = response.statusCode; if (!error && response.statusCode == 200) { rval = _.extend(rval,body); } }); return {"wayback": rval} } // validation method function validate_url(url){ if(url!= null && url!=""){ return true; } return false; } exports.herdict = function (req, res) { var url = req.url.substring(req.url.indexOf('?')+1,req.url.length); if ( !validate_url( url ) ) { res.status( 400 ); return; } Promise.all( [ url_service( url ), herdict_service( url ) ] ) .then( function( result ) { res.json(result); } ) .catch(function (e) { res.status( 500, { error: e } ); }); }; /* exports.herdict = function (req, res) { var url = req.url.substring(req.url.indexOf('?')+1,req.url.length); rval = {}; // query string validation if (validate_url( url ) ) { // merge the results of the url service into the results values //_.extend(rval, url_service(url)); herdict_service(url).then( function( result ) { _.extend(rval, result); res.json(rval); } ); //_.extend(rval, herdict_service(url)); } }; */ exports.all = function (req, res) { url = req.url.substring(req.url.indexOf('?')+1,req.url.length) rval = {}; // query string validation if(validate_url(url)){ // merge the results of the url service into the results values _.extend(rval, url_service(url)); _.extend(rval, herdict_service(url)); _.extend(rval, wayback_machine_service(url)); } res.json(rval); };
JavaScript
0.000001
@@ -81,17 +81,16 @@ ise');%0A%0A -%0A // examp @@ -137,16 +137,30 @@ returns +a promise for json%0Afun @@ -192,9 +192,10 @@ // -$ +%7B SERV @@ -202,16 +202,17 @@ ICE_NAME +: %7B key: @@ -218,16 +218,18 @@ value %7D + %7D %0A retur
51b01e432e5e7b79ec5158987f5750f84a84e12d
add random delay to rpc request calls
rpc-service/app.js
rpc-service/app.js
var timers = require('timers'), http = require('http'), querystring = require('querystring'), async = require('async'), express = require('express'); var services = require('./services'), servicesParser = require('./services/parser'); var app = express(), argv = require('minimist')(process.argv.slice(2)); var servicesIndex = servicesParser.parseServices(argv.services); app.get('/:serviceName/:indentLevel?', function (req, res) { var indentLevel = req.params.indentLevel ? parseInt(req.params.indentLevel) : 0, service = services.findService('/' + req.params.serviceName, servicesIndex); if (service) { console.log(Array(80).join('-')); console.log(Array(indentLevel * 3).join(' '), service.label, '->', service.url); if (service.children) { var funcs = [], urlParams = (indentLevel + 1); for (var i = 0; i < service.children.urls.length; i++) { funcs.push(function(path) { return function (next) { http.get('http://' + argv.address +':'+ argv['proxy-port'] + path, function (res) { next(); }); }; }( service.children.urls[i]) ); } //console.log('>> flow', '-', service.children.flow); if (service.children.flow === 'serial') { async.series(funcs, function (err, results) { res.send(); }); } else if (service.children.flow === 'parallel') { async.parallel(funcs, function (err, results) { res.send(); }); } } else { res.send(); } } else { res.status(404).send(); } }); var server = app.listen(argv.port, argv.address, function() { var address = server.address().address, port = server.address().port; console.log(argv.service + ' server listening at http://%s:%d', address, port); console.log(''); });
JavaScript
0
@@ -620,16 +620,185 @@ ndex);%0A%0A +%0A var randomTimeInSeconds;%0A%0A // wait between 0 - 1.5 records before delivering any results back%0A randomDelayTimeInSeconds = (Math.random() * 1.5).toFixed(2) * 1000;%0A%0A if (se @@ -1522,37 +1522,122 @@ ults) %7B%0A - res.send(); +%0A timers.setTimeout(function() %7B%0A res.send();%0A %7D, randomDelayTimeInSeconds);%0A %0A @@ -1760,80 +1760,240 @@ ) %7B%0A - res.send();%0A %7D);%0A%0A %7D%0A %7D else %7B%0A%0A res.send( +%0A timers.setTimeout(function() %7B%0A res.send();%0A %7D, randomDelayTimeInSeconds);%0A%0A %7D);%0A%0A %7D%0A %7D else %7B%0A%0A timers.setTimeout(function() %7B%0A res.send();%0A %7D, randomDelayTimeInSeconds );%0A%0A
22ae9389b9a08d92984794794ee990ccf1a1d5ec
change input
solutions/day10.js
solutions/day10.js
'use strict'; const fs = require('fs'); const input = fs.readFileSync('../input/day10.txt').toString().split(`\n`).map(s => s.trim()); function process (input) { let result = ''; const max = input.length; let previous = input.charAt(0); let current = null; let counter = 0; let count = 1; while (counter < max) { current = input.charAt(counter + 1); if (previous === current) { count++; } else { // Append result + reset counter result += `${count}${previous}`; count = 1; } previous = current; counter++; } return result; } // Part 1 let string = '1113222113'; for (let counter = 0; counter < 40; counter++) { string = process(string); } console.log(string.length); // Part 2 string = '1113222113'; for (let counter = 0; counter < 50; counter++) { string = process(string); } console.log(string.length);
JavaScript
0.000199
@@ -40,20 +40,20 @@ ;%0Aconst -inpu +star t = fs.r @@ -100,39 +100,8 @@ ng() -.split(%60%5Cn%60).map(s =%3E s.trim()) ;%0A%0A%0A @@ -657,36 +657,29 @@ et string = -'1113222113' +start ;%0Afor (let c @@ -802,20 +802,13 @@ g = -'1113222113' +start ;%0Afo
f606bb8527752d12cd9489e6953dc77363a91112
fix postgresql idle connection closed determination
src/adapter/socket/postgresql.js
src/adapter/socket/postgresql.js
'use strict'; import Base from './base.js'; /** * postgres socket class * @return {} [] */ export default class extends Base { /** * init * @param {Object} config [] * @return {} [] */ init(config){ super.init(config); config.port = config.port || 5432; //config.password = config.pwd; //delete config.pwd; this.config = config; } /** * get pg * @return {} [] */ async getPG(){ if(this.pg){ return this.pg; } let pg = await think.npm('pg'); //set poolSize if(this.config.poolSize){ pg.defaults.poolSize = this.config.poolSize; } //set poolIdleTimeout, change default `30 seconds` to 8 hours pg.defaults.poolIdleTimeout = this.config.poolIdleTimeout * 1000 || 8 * 60 * 60 * 1000; //when has error, close connection pg.on('error', () => { this.close(); }); pg.on('end', () => { this.close(); }); pg.on('close', () => { this.close(); }); this.pg = pg; return pg; } /** * get connection * @return {} [] */ async getConnection(){ if(this.connection){ return this.connection; } let pg = await this.getPG(); let config = this.config; let connectionStr = `postgres://${config.user}:${config.password}@${config.host}:${config.port}/${config.database}`; return think.await(connectionStr, () => { let deferred = think.defer(); pg.connect(this.config, (err, client, done) => { this.logConnect(connectionStr, 'postgre'); if(err){ deferred.reject(err); }else{ this.connection = client; this.release = done; deferred.resolve(client); } }); return deferred.promise; }); } /** * query * @return {Promise} [] */ async query(sql){ let connection = await this.getConnection(); let startTime = Date.now(); let fn = think.promisify(connection.query, connection); let promise = fn(sql).then(data => { this.release(); if (this.config.log_sql) { think.log(sql, 'SQL', startTime); } return data.rows; }).catch(err => { //when socket is closed, try it if(err.message === 'This socket is closed.'){ this.close(); return this.query(sql); } this.release(); if (this.config.log_sql) { think.log(sql, 'SQL', startTime); } return Promise.reject(err); }); return think.error(promise); } /** * execute sql * @param {Array} args [] * @return {Promise} [] */ execute(...args){ return this.query(...args); } /** * close connection * @return {} [] */ close(){ if(this.connection){ this.connection.end(); this.connection = null; } } }
JavaScript
0
@@ -2212,50 +2212,32 @@ + if(err. -messag +cod e === ' -This socket is closed. +EPIPE ')%7B%0A
ab106fdb04778321305e17cb3ef3e0f438704f52
Stop using aggressive merging plugin
src/config/getWebpackClientConfig.js
src/config/getWebpackClientConfig.js
const path = require("path"); const webpack = require("webpack"); const WebpackIsomorphicToolsPlugin = require("webpack-isomorphic-tools/plugin"); const getAssetPath = require("../lib/getAssetPath").default; const buildWebpackEntries = require("../lib/buildWebpackEntries").default; const detectEnvironmentVariables = require("../lib/detectEnvironmentVariables"); const getWebpackAdditions = require("../lib/getWebpackAdditions").default; const { additionalLoaders, additionalPreLoaders, additionalExternals, vendor, plugins } = getWebpackAdditions(); const webpackSharedConfig = require("./webpack-shared-config"); const ASSET_PATH = getAssetPath(); export function getExposedEnvironmentVariables(config) { const exposedEnvironmentVariables = {}; // The config is consumed on both the server side and the client side. // However, we want developers to have access to environment // variables in there so they can override defaults with an environment // variable. For that reason we are going to perform static analysis on that // file to determine all of the environment variables that are used in that // file and make sure that webpack makes those available in the application. const configEnvVariables = detectEnvironmentVariables(config); configEnvVariables.push("NODE_ENV"); configEnvVariables.forEach((v) => { exposedEnvironmentVariables[v] = JSON.stringify(process.env[v]); }); return exposedEnvironmentVariables; } export function getEnvironmentPlugins(isProduction) { const webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require("../config/webpack-isomorphic-tools-config")) .development(!isProduction); let environmentPlugins = []; if (isProduction) { environmentPlugins = environmentPlugins.concat([ webpackIsomorphicToolsPlugin, new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]); } else { environmentPlugins = environmentPlugins.concat([ webpackIsomorphicToolsPlugin, new webpack.HotModuleReplacementPlugin(), ]); } return environmentPlugins; } export default function (appRoot, appConfigFilePath, isProduction) { const OUTPUT_FILE = `app${isProduction ? "-[chunkhash]" : ""}.bundle.js`; return { context: appRoot, devtool: isProduction ? null : "cheap-module-eval-source-map", entry: { ...buildWebpackEntries(isProduction), vendor: vendor }, module: { loaders: [ { test: /\.js$/, loader: "babel-loader", query: { plugins: [ "babel-plugin-gluestick" ], presets: [ "react", "es2015", "stage-0" ] }, include: [ path.join(appRoot, "src/config/application.js"), ] } ].concat(webpackSharedConfig.loaders, additionalLoaders), preLoaders: [ // only place client specific preLoaders here ].concat(webpackSharedConfig.preLoaders, additionalPreLoaders), }, node: { fs: "empty" }, output: { path: path.join(appRoot, "build"), filename: `[name]-${OUTPUT_FILE}`, chunkFilename: `[name]-chunk-${OUTPUT_FILE}`, publicPath: ASSET_PATH, }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.NoErrorsPlugin(), new webpack.DefinePlugin({ "process.env": getExposedEnvironmentVariables(appConfigFilePath) }), // Make it so *.server.js files return empty function in client new webpack.NormalModuleReplacementPlugin(/\.server(\.js)?$/, () => {}), new webpack.optimize.CommonsChunkPlugin("vendor", `vendor${isProduction ? "-[hash]" : ""}.bundle.js`), new webpack.optimize.CommonsChunkPlugin("commons", `commons${isProduction ? "-[hash]" : ""}.bundle.js`), new webpack.optimize.AggressiveMergingPlugin() ].concat(getEnvironmentPlugins(isProduction), webpackSharedConfig.plugins, plugins), resolve: { ...webpackSharedConfig.resolve }, externals: { ...additionalExternals } }; }
JavaScript
0.000011
@@ -3951,62 +3951,8 @@ js%60) -,%0A new webpack.optimize.AggressiveMergingPlugin() %0A
2eaafd87781facf03e50de00f16de374571a05c4
Fix lambda memory leak
src/deep-core/lib/Runtime/Sandbox.js
src/deep-core/lib/Runtime/Sandbox.js
/** * Created by AlexanderC on 1/21/16. */ 'use strict'; import domain from 'domain'; import process from 'process'; export class Sandbox { /** * @param {Function} func */ constructor(func) { this._func = func; this._onFail = Sandbox.ON_FAIL_CB; } /** * @returns {Function} */ get func() { return this._func; } /** * @returns {Sandbox} */ run(...args) { let execDomain = domain.create(); let failCb = (error) => { try { execDomain.exit(); } catch (e) {/* silent fail */} setImmediate(() => { this._onFail(error); }); }; execDomain.once('error', failCb); // domain "unhandledRejection" are throw in global scope process.on('unhandledRejection', failCb); try { execDomain.run(this._func, ...args); } catch (error) { failCb(error); } return this; } /** * @param {Function} cb * @returns {Sandbox} */ fail(cb) { this._onFail = cb; return this; } /** * @returns {Function} */ static get ON_FAIL_CB() { return (error) => { console.error(error); }; } }
JavaScript
0.000395
@@ -477,24 +477,86 @@ try %7B%0A + process.removeListener('unhandledRejection', failCb);%0A exec
18cac9ece7d835ac7162e3de658081f5efadea44
Clean out some cruft.
simpleJsCopy.js
simpleJsCopy.js
/*! simpleJsCopy.js v0.3.1 by ryanpcmcquen */ // Ryan P.C. McQuen | Everett, WA | [email protected] // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version, with the following exception: // the text of the GPL license may be omitted. // // This program is distributed in the hope that it will be useful, but // without any warranty; without even the implied warranty of // merchantability or fitness for a particular purpose. Compiling, // interpreting, executing or merely reading the text of the program // may result in lapses of consciousness and/or very being, up to and // including the end of all existence and the Universe as we know it. // See the GNU General Public License for more details. // // You may have received a copy of the GNU General Public License along // with this program (most likely, a file named COPYING). If not, see // <https://www.gnu.org/licenses/>. /*global window*/ /*jslint browser:true, white:true*/ (function () { 'use strict'; // A simple copy button: // - Copies on awesome browsers/devices. // - Selects text on underwhelming mobile devices. // - The button instructs the user if necessary. var simpleJsCopy = function () { var copyBtn = document.querySelector('.js-copy-btn'); var setCopyBtnText = function (textToSet) { copyBtn.textContent = textToSet; }; var throwErr = function (err) { throw new Error(err); }; var iPhoneORiPod = false, iPad = false, oldSafari = false; var navAgent = navigator.userAgent; if ( /^((?!chrome).)*safari/i.test(navAgent) // ^ Fancy safari detection thanks to: https://stackoverflow.com/a/23522755 && !/^((?!chrome).)*[0-9][0-9](\.[0-9][0-9]?)?\ssafari/i.test(navAgent) // ^ Even fancier Safari < 10 detection thanks to regex. :^) ) { oldSafari = true; } // We need to test for older Safari and the device, // because of quirky awesomeness. if (navAgent.match(/iPhone|iPod/i)) { iPhoneORiPod = true; } else if (navAgent.match(/iPad/i)) { iPad = true; } if (iPhoneORiPod || iPad) { if (oldSafari) { setCopyBtnText("Select text"); } } if (copyBtn) { copyBtn.addEventListener('click', function () { // Clone the text-to-copy node so that we can // create a hidden textarea, with its text value. // Thanks to @LeaVerou for the idea. var originalCopyItem = document.querySelector('.text-to-copy'); var dollyTheSheep = originalCopyItem.cloneNode(true); var copyItem = document.createElement('textarea'); // If .value is undefined, .textContent will // get assigned to the textarea we made. copyItem.value = dollyTheSheep.value || dollyTheSheep.textContent; copyItem.style.opacity = 0; copyItem.style.position = "absolute"; document.body.appendChild(copyItem); if (copyItem) { // Select the text: copyItem.selectionStart = 0; copyItem.selectionEnd = copyItem.textContent.length; try { // Now that we've selected the text, execute the copy command: document.execCommand('copy'); if (oldSafari) { if (iPhoneORiPod) { setCopyBtnText("Now tap 'Copy'"); } else if (iPad) { // The iPad doesn't have the 'Copy' box pop up, // you have to tap the text first. setCopyBtnText("Now tap the text, then 'Copy'"); } else { // Just old! setCopyBtnText("Press Command + C to copy"); } } else { setCopyBtnText("Copied!"); } } catch (ignore) { setCopyBtnText("Please copy manually"); } originalCopyItem.focus(); if (iPhoneORiPod || iPad) { // This is what selects it on iOS: originalCopyItem.selectionStart = 0; originalCopyItem.selectionEnd = copyItem.textContent.length; } else if (oldSafari) { originalCopyItem.select(); } else { copyItem.focus(); copyItem.select(); } // Disable the button because clicking it again could cause madness. copyBtn.disabled = true; copyItem.remove(); } else { throwErr( "You don't have an element with the class: 'text-to-copy'. Please check the simpleJsCopy README." ); } }); } else { throwErr( "You don't have a <button> with the class: 'js-copy-btn'. Please check the simpleJsCopy README." ); } }; window.addEventListener('DOMContentLoaded', simpleJsCopy); }());
JavaScript
0
@@ -4051,95 +4051,8 @@ ();%0A - if (iPhoneORiPod %7C%7C iPad) %7B%0A // This is what selects it on iOS:%0A @@ -4086,34 +4086,32 @@ ctionStart = 0;%0A - origin @@ -4169,173 +4169,8 @@ th;%0A - %7D else if (oldSafari) %7B%0A originalCopyItem.select();%0A %7D else %7B%0A copyItem.focus();%0A copyItem.select();%0A %7D%0A
19844b14929b3299c3721509c037b6c15090842c
change error message
src/app/execution/txExecution.js
src/app/execution/txExecution.js
'use strict' module.exports = { /** * deploy the given contract * * @param {String} data - data to send with the transaction ( return of txFormat.buildData(...) ). * @param {Object} udap - udapp. * @param {Function} callback - callback. */ createContract: function (data, udapp, callback) { udapp.runTx({data: data, useCall: false}, (error, txResult) => { // see universaldapp.js line 660 => 700 to check possible values of txResult (error case) callback(error, txResult) }) }, /** * call the current given contract * * @param {String} to - address of the contract to call. * @param {String} data - data to send with the transaction ( return of txFormat.buildData(...) ). * @param {Object} funAbi - abi definition of the function to call. * @param {Object} udap - udapp. * @param {Function} callback - callback. */ callFunction: function (to, data, funAbi, udapp, callback) { udapp.runTx({to: to, data: data, useCall: funAbi.constant}, (error, txResult) => { // see universaldapp.js line 660 => 700 to check possible values of txResult (error case) callback(error, txResult) }) }, /** * check if the vm has errored * * @param {Object} txResult - the value returned by the vm * @return {Object} - { error: true/false, message: DOMNode } */ checkVMError: function (txResult) { var errorCode = { OUT_OF_GAS: 'out of gas', STACK_UNDERFLOW: 'stack underflow', STACK_OVERFLOW: 'stack overflow', INVALID_JUMP: 'invalid JUMP', INVALID_OPCODE: 'invalid opcode', REVERT: 'revert', STATIC_STATE_CHANGE: 'static state change' } var ret = { error: false, message: '' } if (!txResult.result.vm.exceptionError) { return ret } var error = `VM error: ${txResult.result.vm.exceptionError}.\n` var msg if (txResult.result.vm.exceptionError === errorCode.INVALID_OPCODE) { msg = `\tThe constructor should be payable if you send value.\n\tThe execution might have thrown.\n` ret.error = true } else if (txResult.result.vm.exceptionError === errorCode.OUT_OF_GAS) { msg = `\tThe transaction ran out of gas. Please increase the Gas Limit.\n` ret.error = true } else if (txResult.result.vm.exceptionError === errorCode.REVERT) { msg = `\tThe transaction has been reverted to the initial state.\n` ret.error = true } else if (txResult.result.vm.exceptionError === errorCode.STATIC_STATE_CHANGE) { msg = `\tState changes is not allowed in Static Call context\n` ret.error = true } ret.message = `${error}${txResult.result.vm.exceptionError}${msg}\tDebug the transaction to get more information.` return ret } }
JavaScript
0.000001
@@ -2024,60 +2024,8 @@ %60%5Ct -The constructor should be payable if you send value. %5Cn%5Ct @@ -2409,16 +2409,74 @@ state.%5Cn +Note: The constructor should be payable if you send value. %60%0A
764e5aa9cf298ba54ed34e3dd79e0e1bdc73ed80
Fix default repeatMode option.
src/draw/handler/Draw.SimpleShape.js
src/draw/handler/Draw.SimpleShape.js
L.SimpleShape = {}; L.Draw.SimpleShape = L.Draw.Feature.extend({ options: { repeatMode: true }, initialize: function (map, options) { L.Draw.Feature.prototype.initialize.call(this, map, options); }, addHooks: function () { L.Draw.Feature.prototype.addHooks.call(this); if (this._map) { this._map.dragging.disable(); //TODO refactor: move cursor to styles this._container.style.cursor = 'crosshair'; this._tooltip.updateContent({ text: this._initialLabelText }); this._map .on('mousedown', this._onMouseDown, this) .on('mousemove', this._onMouseMove, this); } }, removeHooks: function () { L.Draw.Feature.prototype.removeHooks.call(this); if (this._map) { this._map.dragging.enable(); //TODO refactor: move cursor to styles this._container.style.cursor = ''; this._map .off('mousedown', this._onMouseDown, this) .off('mousemove', this._onMouseMove, this); L.DomEvent.off(document, 'mouseup', this._onMouseUp); // If the box element doesn't exist they must not have moved the mouse, so don't need to destroy/return if (this._shape) { this._map.removeLayer(this._shape); delete this._shape; } } this._isDrawing = false; }, _onMouseDown: function (e) { this._isDrawing = true; this._startLatLng = e.latlng; L.DomEvent .on(document, 'mouseup', this._onMouseUp, this) .preventDefault(e.originalEvent); }, _onMouseMove: function (e) { var latlng = e.latlng; this._tooltip.updatePosition(latlng); if (this._isDrawing) { this._tooltip.updateContent({ text: L.drawLocal.draw.handlers.simpleshape.tooltip.end }); this._drawShape(latlng); } }, _onMouseUp: function () { if (this._shape) { this._fireCreatedEvent(); } this.disable(); if (this.options.repeatMode) { this.enable(); } } });
JavaScript
0
@@ -85,19 +85,20 @@ atMode: -tru +fals e%0A%09%7D,%0A%0A%09
9759a929a8d6330f12a952545af630ddf72cb64c
Remove .shifter.json references
grunt/compress.js
grunt/compress.js
/* * Copyright (c) 2013, Liferay Inc. All rights reserved. * Code licensed under the BSD License: * https://github.com/liferay/alloy-ui/blob/master/LICENSE.md * * @author Zeno Rocha <[email protected]> * @author Eduardo Lundgren <[email protected]> */ var TASK = { name: 'compress', description: 'Generate a zip from build, demos and src folders.' }; // -- Dependencies ------------------------------------------------------------- var async = require('async'); var command = require('command'); var fs = require('fs'); var path = require('path'); var walkdir = require('walkdir'); var zipArchiver = require('zip-archiver').Zip; // -- Globals ------------------------------------------------------------------ var ROOT = process.cwd(); // -- Task --------------------------------------------------------------------- module.exports = function(grunt) { grunt.registerTask(TASK.name, TASK.description, function() { var done = this.async(); var baseFileName; var sha; var zipFileName; async.series([ function(mainCallback) { exports._setGruntConfig(mainCallback); }, function(mainCallback) { exports._getCurrentGitHashCommit(function(val) { sha = val; mainCallback(); }); }, function(mainCallback) { baseFileName = grunt.config([TASK.name, 'name']); zipFileName = baseFileName + '.zip'; exports._deleteFiles(mainCallback, zipFileName); }, function(mainCallback) { exports._zip(mainCallback, baseFileName, sha, zipFileName); }], function(err) { if (err) { done(false); } else { done(); } } ); }); exports._setGruntConfig = function(mainCallback) { var options = grunt.option.flags(); options.forEach(function(option) { var key; var value; var valueIndex; // Normalize option option = option.replace(/^--(no-)?/, ''); valueIndex = option.lastIndexOf('='); // String parameter if (valueIndex !== -1) { key = option.substring(0, valueIndex); value = option.substring(valueIndex + 1); } // Boolean parameter else { key = option; value = grunt.option(key); } grunt.config([TASK.name, key], value); }); mainCallback(); }; exports._getCurrentGitHashCommit = function(mainCallback) { command.open(ROOT) .exec('git', ['rev-parse', 'HEAD']) .then(function() { mainCallback(this.lastOutput.stdout); }); }; exports._deleteFiles = function(mainCallback, zipFileName) { var finder = walkdir('.'); var filesToDeleteMap = { '.DS_Store': 1 }; fs.unlink(zipFileName); finder.on('file', function(filename) { var basename = path.basename(filename); if (filesToDeleteMap[basename]) { fs.unlink(filename); } }); finder.on('end', function() { mainCallback(); }); }; exports._zip = function(mainCallback, baseFileName, sha, zipFileName) { var zip = new zipArchiver({ file: zipFileName, root: baseFileName, comment: 'SHA: ' + sha + ' on ' + new Date() }); async.series([ function(zipCallback) { zip.add('build', function() { zipCallback(); }); }, function(zipCallback) { zip.add('demos', function() { zipCallback(); }); }, function(zipCallback) { zip.add('src', function() { zipCallback(); }); }, function(zipCallback) { zip.add('LICENSE.md', function() { zipCallback(); }); }, function(zipCallback) { zip.add('README.md', function() { zipCallback(); }); }, function(zipCallback) { zip.add('.alloy.json', function() { zipCallback(); }); }, function(zipCallback) { zip.add('.shifter.json', function() { zipCallback(); }); }], function() { zip.done(function() { grunt.log.ok('Released ' + zipFileName); mainCallback(); }); } ); }; };
JavaScript
0
@@ -4708,168 +4708,8 @@ %7D);%0A - %7D,%0A function(zipCallback) %7B%0A zip.add('.shifter.json', function() %7B%0A zipCallback();%0A %7D);%0A
54bdcfb2a8d3c3b53008cd446c56cf2b8f1dd56c
add some basic functions
scripts/jq.privateShare.js
scripts/jq.privateShare.js
/** * jquery.privateShare * * A jquery plugin that renders sharebuttons for facebook, google+ and twitter * in accordance with the very restrictive german privacy laws - e.G. without loading any 3rd party API * * @author Sebastian Antosch * @email [email protected] * @copyright 2016 I-SAN.de Webdesign & Hosting GbR * */ (function ($) { "use strict"; // Abort if jQuery is not loaded if (!window.jQuery || !$) { throw new Error('jquery.privateShare needs jQuery Library to be loaded - which is not.') } var /** * Holds some constants */ constants = { FB: { POPUP: { WIDTH: 560, HEIGHT: 630 } }, GP: { POPUP: { WIDTH: 505, HEIGHT: 665 } }, TW: { POPUP: { WIDTH: 695, HEIGHT: 254 } }, POPUPSETTINGS: { directories: 0, fullscreen: 0, location: 0, menubar: 0, status: 0, titlebar: 0, toolbar: 0 } }, /** * Holds the functions to generate the sharelinks * @type {{}} */ getShareLink = { /** * Generates a facebook share link * @param {string} url * @returns {string} */ FB: function (url) { return 'todo'; }, /** * Generates a Google+ Share Link * @param {string} url * @returns {string} */ GP: function (url) { return 'todo'; }, /** * Generates a Twitter tweet link with an optional message * @param {string} url * @param {string} message * @returns {string} */ TW: function (url, message) { return 'todo'; } }, /** * Opens a popup for a share-service with specific dimensions. * Opens a new tab on mobile view instead * @param {string} service - FB (Facebook), GP (Google+), TW (Twitter) * @param {string} link - the link to be called containing all share parameters * @return {Window} - the opened window instance */ openPopup = function (service, link) { var width = constants[service].POPUP.WIDTH, height = constants[service].POPUP.HEIGHT, $win = $(window), wwidth = $win.width(), wheight = $win.height, settings = constants.POPUPSETTINGS, settingsstring = '', win; // Open in a new tab if the popup would exceed the parent windows dimensions if (width > wwidth || height > wheight) { win = window.open(link, '_blank'); win.focus(); return win; } // Otherwise open as a correctly sized and positioned popup settings.width = width; settings.height = height; settings.top = (wheight - height) / 2; settings.left = (wwidth - width) / 2; $.each(function (key, value) { settingsstring += (key + "=" + value + ","); }); win = window.open(link, "privateSharePopup", settingsstring); win.focus(); return win; }, /** * Attaches the sharelink functionality to a supplied link element * @param {jQuery} $link - a jQuery link object * @param {string} service - FB (Facebook), GP (Google+), TW (Twitter) * @param {string} url - the link that shall be shared * @param {string} message - an additional message, only for tweet links * @return {jQuery} */ attachSharelink = function ($link, service, url, message) { // if no url is supplied, use the current one if (!url) { url = window.location.href; } // get the share link var href = getSharelink[service](url, message), alreadyClicked = false; // set the sharelink $link.attr('href', href); $link.on('click touchstart', function (e) { // Only fire once every 500ms preventing ghostclicks, // this allows us to listen for touchstart as well if (!alreadyClicked) { alreadyClicked = true; setTimeout(function () { alreadyClicked = false; }, 500); // Open the sharelink openPopup(service, href); } e.preventDefault(); }); }, // Save all functions in here publicFunctions = { }; /** * Initializes the privateShare functionality * @param {string} action - what to do * @param {Object} options - some options, optional * @returns {jQuery} */ $.fn.privateShare = function (action, options) { if (typeof publicFunctions[action] === "function") { return this.each(function () { publicFunctions[action]($(this), options) }); } throw new Error('jquery.privateShare has no function "' + action + '"!' ); }; }(jQuery));
JavaScript
0.000829
@@ -5124,16 +5124,852 @@ ons = %7B%0A + /**%0A * Attaches a facebook-sharelink%0A * @param %7BjQuery%5D $this%0A * @param %7BObject%7D options%0A */%0A shareFb: function ($this, options) %7B%0A attachSharelink($this, 'FB', options.url);%0A %7D,%0A%0A /**%0A * Attaches a googleplus-sharelink%0A * @param %7BjQuery%5D $this%0A * @param %7BObject%7D options%0A */%0A shareGp: function ($this, options) %7B%0A attachSharelink($this, 'GP', options.url);%0A %7D,%0A%0A /**%0A * Attaches a twitter-tweetlink%0A * param %7BjQuery%5D $this%0A * @param options%0A */%0A shareTw: function ($this, options) %7B%0A attachSharelink($this, 'TW', options.url, options.message);%0A %7D %0A @@ -6377,16 +6377,17 @@ options) +; %0A
e4c6a4d239f72d5f0ecc976b1bf95c6e4cf24f11
Support both SICStus Prolog 4.0 and 3.12.
scripts/make_sicstuslgt.js
scripts/make_sicstuslgt.js
// ================================================================= // Logtalk - Object oriented extension to Prolog // Release 2.28.0 // // Copyright (c) 1998-2006 Paulo Moura. All Rights Reserved. // ================================================================= if (WScript.Arguments.Unnamed.Length > 0) { usage_help(); WScript.Quit(0); } WScript.Echo(''); WScript.Echo('Creating a shortcut named "Logtalk - SICStus Prolog" for running Logtalk with'); WScript.Echo('SICStus Prolog 3.12 (edit the script if you are using other version)...'); WScript.Echo(''); var WshShell = new ActiveXObject("WScript.Shell"); var prolog_path = WshShell.RegRead("HKLM\\Software\\SICS\\SICStus3.12_win32\\SP_PATH") + "\\bin\\spwin.exe"; var FSObject = new ActiveXObject("Scripting.FileSystemObject"); if (!FSObject.FileExists(prolog_path)) { WScript.Echo("Error! Cannot find spwin.exe at the expected place!"); WScript.Echo("Please, edit the script and update the location of the spwin.exe executable."); WScript.Quit(1); } var WshSystemEnv = WshShell.Environment("SYSTEM"); var WshUserEnv = WshShell.Environment("USER"); var logtalk_home; if (WshSystemEnv.Item("LOGTALKHOME")) logtalk_home = WshSystemEnv.Item("LOGTALKHOME"); else if (WshUserEnv.Item("LOGTALKHOME")) logtalk_home = WshUserEnv.Item("LOGTALKHOME") else { WScript.Echo("Error! The environment variable LOGTALKHOME must be defined first!"); usage_help(); WScript.Quit(1); } if (!FSObject.FolderExists(logtalk_home)) { WScript.Echo("The environment variable LOGTALKHOME points to a non-existing directory!"); WScript.Echo("Its current value is: %LOGTALKHOME%"); WScript.Echo("The variable must be set to your Logtalk installation directory!"); WScript.Echo(""); usage_help(); WScript.Quit(1); } logtalk_home = logtalk_home.replace(/\\/g, "\\\\"); if (!FSObject.FolderExists(logtalk_home + "\\bin")) FSObject.CreateFolder(logtalk_home + "\\bin"); var f = FSObject.CreateTextFile(logtalk_home + "\\bin\\logtalk_sicstus.pl", true); f.WriteLine(":- consult('$LOGTALKUSER/configs/sicstus.config')."); f.WriteLine(":- consult('$LOGTALKHOME/compiler/logtalk.pl')."); f.WriteLine(":- consult('$LOGTALKUSER/libpaths/libpaths.pl')."); f.Close(); var ProgramsPath = WshShell.SpecialFolders("AllUsersPrograms"); if (!FSObject.FolderExists(ProgramsPath + "\\Logtalk")) FSObject.CreateFolder(ProgramsPath + "\\Logtalk"); var link = WshShell.CreateShortcut(ProgramsPath + "\\Logtalk\\Logtalk - SICStus Prolog.lnk"); link.Arguments = "-l %LOGTALKHOME%\\bin\\logtalk_sicstus.pl"; link.Description = "Runs Logtalk with SICStus Prolog"; link.IconLocation = "app.exe,1"; link.TargetPath = prolog_path; link.WindowStyle = 1; link.WorkingDirectory = logtalk_home; link.Save(); WScript.Echo('Done. The "Logtalk - SICStus Prolog" shortcut was been added to'); WScript.Echo('the Start Menu Programs. Make sure that the environment variables'); WScript.Echo('LOGTALKHOME and LOGTALKUSER are defined for all users wishing'); WScript.Echo('to use the shortcut.'); WScript.Echo(''); WScript.Echo('Users must run the batch script "cplgtdirs" before using the'); WScript.Echo('"Logtalk - SICStus Prolog" shortcut.'); WScript.Echo(''); WScript.Quit(0); function usage_help() { WScript.Echo(''); WScript.Echo('This script creates a shortcut named "Logtalk - SICStus Prolog" for'); WScript.Echo('running Logtalk with SICStus Prolog. The script must be run by a user'); WScript.Echo('with administrative rights. The LOGTALKHOME environment variable must'); WScript.Echo('be defined before running this script.'); WScript.Echo(''); WScript.Echo('Usage:'); WScript.Echo(' ' + WScript.ScriptName + ' help'); WScript.Echo(' ' + WScript.ScriptName); WScript.Echo(''); }
JavaScript
0.000826
@@ -486,16 +486,23 @@ Prolog +4.0 or 3.12 (ed @@ -639,16 +639,126 @@ log_path +4 = WshShell.RegRead(%22HKLM%5C%5CSoftware%5C%5CSICS%5C%5CSICStus4.0_win32%5C%5CSP_PATH%22) + %22%5C%5Cbin%5C%5Cspwin.exe%22;%0Avar prolog_path3 = WshSh @@ -844,16 +844,34 @@ .exe%22;%0A%0A +var config_file;%0A%0A var FSOb @@ -923,33 +923,143 @@ mObject%22);%0A%0Aif ( -! +FSObject.FileExists(prolog_path4)) %7B%0A%09prolog_path = prolog_path4;%0A%09config_file = %22sicstus4.config%22;%0A%7D%0Aelse if ( FSObject.FileExi @@ -1073,21 +1073,93 @@ log_path +3 )) %7B%0A +%09prolog_path = prolog_path3;%0A%09config_file = %22sicstus.config%22;%0A%7D%0Aelse %7B%0A %09WScript @@ -1215,16 +1215,17 @@ ed place +s !%22);%0A%09WS @@ -2370,30 +2370,35 @@ configs/ -sicstus.config +%22 + config_file + %22 ').%22);%0Af
4c35dba9fa124f18cbaaefdaa9860bad0c652b05
Update LoadData.js
src/js/LoadData.js
src/js/LoadData.js
import axios from 'axios'; export default class LoadData { async dataRes(){ try { const res = await axios(`http://localhost:8080/data.json`); this.data = res.data; } catch(err){ console.log(`LoadData error at LoadData: ${err}`); } }; }
JavaScript
0
@@ -19,16 +19,47 @@ 'axios'; +%0Aimport %7B doms %7D from './base'; %0A%0Aexport @@ -276,54 +276,501 @@ cons -ole.log(%60LoadData error at LoadData: $%7B +t dataError = %60%0A Data isn't loading! %3Cbr /%3E%0A Check data source: the fields should match the template JSON file.%3Cbr /%3E%0A Check path in LoadData - the default is localhost:8080 - %3Cbr /%3E%0A for the test data.json file in /dist - %3Cbr /%3E%0A you need to change it to where your json data is coming from if not here.%60;%0A doms.errorMessage.classList.add('error-show');%0A doms.errorMessage.innerHTML = dataError; %0A console.log( err -%7D%60 ); + %0A @@ -795,10 +795,7 @@ %7D;%0A%7D +; %0A -%0A%0A%0A%09 %0A
6d72099d8c96958c371ea7de09f286678c3fc38d
Update gh-pages doc
app/main.js
app/main.js
var Board = require('./board-canvas'), CycleController = require('./cycle-controller'), Universe = require('./universe'), universe = new Universe({ seed: { type: 'random', pattern: 'random' } }), board = new Board({ container: '#board', universe: universe, cellSize: 4 }); new CycleController({ // board view board: board, // in milliseconds cycle: 60, // handle seed change onChangeSeed: function(pattern) { board.setUniverse(new Universe({ seed: { type: pattern === 'random' ? 'random' : 'pattern', pattern: pattern }, width: universe.width, height: universe.height })); } });
JavaScript
0
@@ -277,9 +277,9 @@ ze: -4 +3 %0A%7D);
09367e66d2da764a9dfd101eb978af803d7e5fcc
Handle Squirrel windows startup events
app/main.js
app/main.js
var app = require('app'); var path = require('path'); var BrowserWindow = require('browser-window'); var Menu = require('menu'); var MenuItem = require('menu-item'); var Shell = require('shell'); var ConfigStore = require('configstore'); var mainWindow = null; const config = new ConfigStore('IRCCloud', { 'width': 1024, 'height': 768 }); function openMainWindow() { mainWindow = new BrowserWindow({'width': config.get('width'), 'height': config.get('height'), 'allowDisplayingInsecureContent': true, 'webPreferences': { 'preload': path.join(__dirname, 'preload.js'), 'nodeIntegration': false }, 'title': 'IRCCloud'}); mainWindow.loadURL('https://www.irccloud.com'); mainWindow.on('closed', function() { mainWindow = null; }); mainWindow.on('resize', function() { size = mainWindow.getSize(); config.set({'width': size[0], 'height': size[1]}); }); mainWindow.on('page-title-updated', function(event) { var title = mainWindow.getTitle(); if (title) { var unread = ""; var matches = title.match(/^\((\d+)\)/); if (matches) { unread = matches[1]; } app.dock.setBadge(unread); } }); mainWindow.webContents.on('new-window', function(event, url, frameName, disposition) { event.preventDefault(); Shell.openExternal(url); }); } app.on('ready', openMainWindow); app.on('activate-with-no-open-windows', openMainWindow); app.on('window-all-closed', function() { if (process.platform != 'darwin') { app.quit(); } }); app.once('ready', function() { var template = [{ label: 'IRCCloud', submenu: [ { label: 'About IRCCloud', click: function() { var win = new BrowserWindow({ width: 915, height: 600, show: false }); win.on('closed', function() { win = null; }); win.webContents.on('will-navigate', function (e, url) { e.preventDefault(); Shell.openExternal(url); }); win.loadURL('https://www.irccloud.com/about'); win.show(); } }, { type: 'separator' }, { label: 'Services', submenu: [] }, { type: 'separator' }, { label: 'Hide IRCCloud', accelerator: 'Command+H', selector: 'hide:' }, { label: 'Hide Others', accelerator: 'Command+Shift+H', selector: 'hideOtherApplications:' }, { label: 'Show All', selector: 'unhideAllApplications:' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: function() { app.quit(); } }, ] }, { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'Command+Z', selector: 'undo:' }, { label: 'Redo', accelerator: 'Shift+Command+Z', selector: 'redo:' }, { type: 'separator' }, { label: 'Cut', accelerator: 'Command+X', selector: 'cut:' }, { label: 'Copy', accelerator: 'Command+C', selector: 'copy:' }, { label: 'Paste', accelerator: 'Command+V', selector: 'paste:' }, { label: 'Select All', accelerator: 'Command+A', selector: 'selectAll:' }, ] }, { label: 'View', submenu: [ { label: 'Reload', accelerator: 'Command+R', click: function() { BrowserWindow.getFocusedWindow().webContents.reloadIgnoringCache(); } }, { label: 'Toggle DevTools', accelerator: 'Alt+Command+I', click: function() { BrowserWindow.getFocusedWindow().toggleDevTools(); } }, ] }, { label: 'Window', submenu: [ { label: 'Minimize', accelerator: 'Command+M', selector: 'performMiniaturize:' }, { label: 'Close', accelerator: 'Command+W', selector: 'performClose:' }, { type: 'separator' }, { label: 'Bring All to Front', selector: 'arrangeInFront:' }, ] }]; menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); });
JavaScript
0
@@ -232,16 +232,505 @@ ore');%0A%0A +var handleStartupEvent = function() %7B%0A // Handle Squirrel startup events, called by the Windows installer.%0A // https://github.com/electronjs/windows-installer#handling-squirrel-events%0A if (process.platform !== 'win32') %7B%0A return false;%0A %7D%0A%0A switch (process.argv%5B1%5D) %7B%0A case '--squirrel-install':%0A case '--squirrel-updated':%0A case '--squirrel-uninstall':%0A case '--squirrel-obsolete':%0A app.quit();%0A return true;%0A %7D%0A%7D;%0A%0Aif (handleStartupEvent()) %7B%0A return;%0A%7D%0A%0A var main
f48b348b64b74adfe2c54a4b98deb1bc89965d8c
refine logic
imports/api/ppls.js
imports/api/ppls.js
import { Meteor } from 'meteor/meteor'; import { Mongo } from 'meteor/mongo'; import { Configs } from '/imports/api/configs'; import { defaultPpls } from '/imports/mock/default-ppls'; export const Ppls = new Mongo.Collection('ppls'); Ppls.const = { DRAW_PPL_COUNT: 350, LOC_ZHUHAI: '珠海', LOC_GUANGZHOU: '广州', LOC_XIANGGANG: '香港' } Meteor.methods({ 'removeAllPpls' : function () { Ppls.remove({}); }, 'resetAllPpls': function() { Ppls.remove({}); Ppls.batchInsert(defaultPpls); } }); if (Meteor.isServer) { const RawPpls = Ppls.rawCollection(); Meteor.methods({ 'drawPpls': function(config) { RawPpls.aggregateSync = Meteor.wrapAsync(RawPpls.aggregate); var candidates = []; if (config.scope == Configs.const.SCOPE_LOCAL) { candidates = RawPpls.aggregateSync([{$match: {laId: '', loc: {$in: [Ppls.const.LOC_ZHUHAI, Ppls.const.LOC_GUANGZHOU, Ppls.const.LOC_XIANGGANG]}}}, {$sample: {size: Ppls.const.DRAW_PPL_COUNT}}]); } else if(config.scope == Configs.const.SCOPE_GLOBAL) { candidates = RawPpls.aggregateSync([{$match: {gaId: ''}}, {$sample: {size: Ppls.const.DRAW_PPL_COUNT}}]); } if (candidates.length) { var luckyGuys = _.sample(candidates, config.ppl); _.each(luckyGuys, function(luckyGuy) { if (config.scope == Configs.const.SCOPE_LOCAL) { luckyGuy.laId = config._id; Ppls.update({_id: luckyGuy._id}, {$set:{laId: config._id}}); } else if(config.scope == Configs.const.SCOPE_GLOBAL) { luckyGuy.gaId = config._id; Ppls.update({_id: luckyGuy._id}, {$set:{gaId: config._id}}); } }); } return candidates; } }); }
JavaScript
0.999999
@@ -179,17 +179,16 @@ -ppls';%0A - %0Aexport @@ -271,76 +271,11 @@ 350 -,%0A LOC_ZHUHAI: '%E7%8F%A0%E6%B5%B7',%0A LOC_GUANGZHOU: '%E5%B9%BF%E5%B7%9E',%0A LOC_XIANGGANG: '%E9%A6%99%E6%B8%AF' %0A%7D +; %0A%0AMe @@ -508,18 +508,16 @@ tion();%0A - %0A Meteo @@ -780,95 +780,19 @@ '', -loc: %7B$in: %5BPpls.const.LOC_ZHUHAI, Ppls.const.LOC_GUANGZHOU, Ppls.const.LOC_XIANGGANG%5D%7D +forLa: true %7D%7D, @@ -963,16 +963,29 @@ gaId: '' +, forGa: true %7D%7D, %7B$sa @@ -1595,8 +1595,9 @@ %0A %7D);%0A%7D +%0A
3b7f710a3793f067821bc9610b7f9edb44c9fb4f
use arrow fn
gulpfile.babel.js
gulpfile.babel.js
import gulp from 'gulp'; import babel from 'babel/register'; import eslint from 'gulp-eslint'; import mocha from 'gulp-mocha'; gulp.task('lint', () => { return gulp.src(['.src/**/*.js', './test/**/*.js']) .pipe(eslint()) .pipe(eslint.format()); }); gulp.task('test', function() { return gulp.src(['test/**/*.js']) .pipe(mocha({ compilers: { js: babel({ jsxPragma: 'jsxr' }) } })); }); gulp.task('default', ['lint', 'test']);
JavaScript
0.000192
@@ -276,18 +276,13 @@ t', -function() +() =%3E %7B%0A
9a4a5571e3dc9d1dad50ee1669ea196ac5d395ce
Remove unused dependency.
gulpfile.babel.js
gulpfile.babel.js
'use strict' /** * Import dependencies * ----------------------------------------------------------------------------- */ import autoprefixer from 'autoprefixer' import babel from 'gulp-babel' import bs from 'browser-sync' import changed from 'gulp-changed' import del from 'del' import eslint from 'gulp-eslint' import gulp from 'gulp' import header from 'gulp-header' import include from 'gulp-include' import jade from 'gulp-jade' import minimist from 'minimist' import nano from 'gulp-cssnano' import pkg from './package.json' import postcss from 'gulp-postcss' import rename from 'gulp-rename' import sass from 'gulp-sass' import sasslint from 'gulp-sass-lint' import sequence from 'run-sequence' import uglify from 'gulp-uglify' /** * Set meta banner * ----------------------------------------------------------------------------- */ const banner = [ '/**', ' * Project: <%= pkg.title %>', ' * Description: <%= pkg.description %>', ' * Version: <%= pkg.version %>', ' * Author: <%= pkg.author.name %> - <%= pkg.author.url %>', ' */', '\n' ].join('\n'); /** * Set paths * ----------------------------------------------------------------------------- */ const path = { build: 'build', src: 'src' } /** * Set build options * ----------------------------------------------------------------------------- */ const options = minimist(process.argv.slice(2), { string: [ 'env' ], default: { env: 'dev' } }) /** * Default task * ----------------------------------------------------------------------------- */ gulp.task('default', (callback) => { return sequence( [ 'build' ], [ 'server' ], callback ) }) /** * Local dev server with live reload * ----------------------------------------------------------------------------- */ gulp.task('server', () => { // Create and initialize local server bs.create() bs.init({ notify: false, server: './build', open: 'local', ui: false }) // Watch for build changes and reload browser bs.watch('build/**/*').on('change', bs.reload) // Watch for source changes and execute associated tasks gulp.watch('./src/data/**/*', [ 'data' ]) gulp.watch('./src/fonts/**/*', [ 'fonts' ]) gulp.watch('./src/images/**/*', [ 'images' ]) gulp.watch('./src/media/**/*', [ 'media' ]) gulp.watch('./src/misc/**/*', [ 'misc' ]) gulp.watch('./src/scripts/**/*.js', [ 'scripts' ]) gulp.watch('./src/styles/**/*.scss', [ 'styles' ]) gulp.watch('./src/vendors/*.js', [ 'vendors' ]) gulp.watch('./src/views/**/*.jade', [ 'views' ]) }) /** * Build static assets * ----------------------------------------------------------------------------- */ gulp.task('build', (callback) => { return sequence( [ 'clean' ], [ 'assets' ], [ 'scripts' ], [ 'styles' ], [ 'vendors' ], [ 'views' ], callback ) }) /** * Remove build directory * ----------------------------------------------------------------------------- */ gulp.task('clean', () => { return del('./build') }) /** * Assets * ----------------------------------------------------------------------------- */ gulp.task('assets', (callback) => { return sequence( [ 'data' ], [ 'fonts' ], [ 'images' ], [ 'media' ], [ 'misc' ], callback ) }) /** * Copy data files * ----------------------------------------------------------------------------- */ gulp.task('data', () => { return gulp // Select files .src(path.src + '/data/**/*') // Check for changes .pipe(changed(path.build + '/data')) // Save files .pipe(gulp.dest(path.build + '/data')) }) /** * Copy font files * ----------------------------------------------------------------------------- */ gulp.task('fonts', () => { return gulp // Select files .src(path.src + '/fonts/**/*') // Check for changes .pipe(changed(path.build + '/fonts')) // Save files .pipe(gulp.dest(path.build + '/fonts')) }) /** * Copy image files * ----------------------------------------------------------------------------- */ gulp.task('images', () => { return gulp // Select files .src(path.src + '/images/**/*') // Check for changes .pipe(changed(path.build + '/images')) // Save files .pipe(gulp.dest(path.build + '/images')) }) /** * Copy media files * ----------------------------------------------------------------------------- */ gulp.task('media', () => { return gulp // Select files .src(path.src + '/media/**/*') // Check for changes .pipe(changed(path.build + '/media')) // Save files .pipe(gulp.dest(path.build + '/media')) }) /** * Copy misc files * ----------------------------------------------------------------------------- */ gulp.task('misc', () => { return gulp // Select files .src([ path.src + '/misc/' + options.env + '/**/*', path.src + '/misc/all/**/*' ], { dot: true }) // Check for changes .pipe(changed(path.build)) // Save files .pipe(gulp.dest(path.build)) }) /** * Build scripts with transpilers * ----------------------------------------------------------------------------- */ gulp.task('scripts', [ 'scripts-lint' ], () => { return gulp // Select files .src(path.src + '/scripts/*.js') // Concatenate includes .pipe(include()) // Transpile .pipe(babel({ presets: [ 'es2015' ] })) // Add meta banner .pipe(header(banner, { pkg: pkg })) // Save unminified file .pipe(gulp.dest(path.build + '/scripts')) // Optimize and minify .pipe(uglify({ preserveComments: 'some' })) // Append suffix .pipe(rename({ suffix: '.min' })) // Save minified file .pipe(gulp.dest(path.build + '/scripts')) }) /** * Lint scripts * ----------------------------------------------------------------------------- */ gulp.task('scripts-lint', () => { return gulp // Select files .src(path.src + '/scripts/**/*.js') // Check for errors .pipe(eslint()) // Format errors .pipe(eslint.format()) // Fail on errors .pipe(eslint.failOnError()) }) /** * Build styles with pre-processors and post-processors * ----------------------------------------------------------------------------- */ gulp.task('styles', () => { return gulp // Select files .src(path.src + '/styles/*.scss') // Compile Sass .pipe(sass({ outputStyle: 'expanded' })) // Add vendor prefixes .pipe(postcss([ require('autoprefixer') ])) // Add meta banner .pipe(header(banner, { pkg: pkg })) // Save unminified file .pipe(gulp.dest(path.build + '/styles')) // Optimize and minify .pipe(nano({ zindex: false, reduceIdents: false, mergeIdents: false })) // Append suffix .pipe(rename({ suffix: '.min' })) // Save minified file .pipe(gulp.dest(path.build + '/styles')) }) /** * Bundle vendors * ----------------------------------------------------------------------------- */ gulp.task('vendors', () => { return gulp // Select files .src(path.src + '/vendors/*.js') // Concatenate includes .pipe(include()) // Save files .pipe(gulp.dest(path.build + '/vendors')) }) /** * Build views with pre-processors * ----------------------------------------------------------------------------- */ gulp.task('views', () => { return gulp // Select files .src(path.src + '/views/site/**/*.jade') // Compile Jade .pipe(jade({ pretty: true, data: { env: options.env } })) // Save files .pipe(gulp.dest(path.build)) })
JavaScript
0
@@ -630,46 +630,8 @@ ss'%0A -import sasslint from 'gulp-sass-lint'%0A impo
bd71384cd69d4a88819df16537323b1529a9e9a1
update help menu
src/keybindings.js
src/keybindings.js
'use strict' const config = require('../config/config.js') const core = require('./core/core.js') const searchAttribute = require('./core/searchAttribute.js') const printChat = require('./helpers/printChat.js') const printChatHTML = require('./helpers/printChatHTML.js') const save = require('./helpers/save.js') const theme = require('./helpers/theme.js') const addDgnEdge = require('./design/addDgnEdge.js') const addDgnStateEdge = require('./design-state/addDgnStateEdge.js') const addImpEdge = require('./implementation/addImpEdge.js') const addImpStateEdge = require('./implementation-state/addImpStateEdge.js') module.exports = function ( cy, selectedNode, selectedEdge, srcNode, trgNode, phase, colorToken ) { // help menu for macOs const helpMenuDarwin = `• focus on console: ⌘L • add Edge: ⌘E • delete element: ⌘⌫ • restore node: ⌘Z • save as: ⇧⌘S • clear sidebar: clear • type 'toggle' to change color theme • type any attribute 'keyword' to search nodes` // help menu for Linux and Windows const helpMenu = `• focus on console: ctrl+L • add Edge: ctrl+E • delete element: ctrl+backspace • restore node: ctrl+Z • save as: shift+ctrl+S • clear sidebar: clear • type 'toggle' to change color theme • type any attribute 'keyword' to search nodes` // adds the url of the github wiki const wikiURLButton = `click to view <button id='url-button' class='startButtons' style='color: ${config.text}; background-color:${config.background}; width: 40px; height: 25px;'>wiki</button>` const consoleId = document.getElementById('console-id') const labelId = document.getElementById('input-label-id') // indicate focus on console consoleId.addEventListener('focus', e => { labelId.style.color = config.blue }) consoleId.addEventListener('blur', () => { labelId.style.color = config.text }) // loses the focus from the console when tapping cy.on('tap', selection => consoleId.blur()) // console commands const commands = () => { const input = document.getElementById('console-id').value document.getElementById('console-id').value = '' switch (input) { case 'help': // checks the platform to display the corrent help menu process.platform === 'darwin' ? printChat(helpMenuDarwin) : printChat(helpMenu) printChatHTML(wikiURLButton) // opens the wiki page with the default browser document.getElementById('url-button').addEventListener('click', () => { require('electron').shell.openExternal(config.wikiUrl) }) break case 'toggle': if (colorToken === false) { theme.setTheme(cy, 'light') colorToken = true } else { theme.setTheme(cy, 'dark') colorToken = false } break case '': break case 'clear': document.getElementById('info-nodes-id').textContent = '' break default: searchAttribute(cy, input) } } // keydown listeners document.addEventListener('keydown', event => { let key = '' // checks the platform to assing the meta key process.platform === 'darwin' ? (key = event.metaKey) : (key = event.ctrlKey) // focus on the consoleId if (key === true && event.code === 'KeyL') { consoleId.focus() } // add edge if (key === true && event.code === 'KeyE') { // checks for undefined selections if (Object.keys(srcNode.out).length !== 0) { if (phase === 'design') { addDgnEdge(cy, srcNode.out, trgNode.out) } else if (phase === 'design-state') { addDgnStateEdge(cy, srcNode.out, trgNode.out) } else if (phase === 'implementation') { addImpEdge(cy, srcNode.out, trgNode.out) } else if (phase === 'implementation-state') { addImpStateEdge(cy, srcNode.out, trgNode.out) } cy.edges().addClass('label-edges') } } // delete elements if (key === true && event.code === 'Backspace') { core.deleteEl(cy, selectedNode.out, selectedEdge.out) } if (key === true && event.code === 'KeyZ') { // restore elements with meta + z core.restoreNode() } if (event.shiftKey === true && key === true && event.code === 'KeyS') { save(cy) } // listens for the ENTER key when focus is on the console if (document.activeElement === consoleId && event.code === 'Enter') { commands() } }) }
JavaScript
0.000001
@@ -897,33 +897,16 @@ clear%0A%E2%80%A2 - type 'toggle' to change @@ -916,35 +916,45 @@ or theme -%0A%E2%80%A2 type any +: toggle%0A%E2%80%A2 search for attribu te 'keyw @@ -949,36 +949,20 @@ ribu -te ' +res: keyword -' to search nodes %60%0A%0A @@ -1171,25 +1171,8 @@ ar%0A%E2%80%A2 - type 'toggle' to cha @@ -1190,27 +1190,37 @@ heme -%0A%E2%80%A2 type any +: toggle%0A%E2%80%A2 search for attribu te ' @@ -1219,36 +1219,20 @@ ribu -te ' +res: keyword -' to search nodes %60%0A%0A
fa4ac94273c12a9911c82afdc08afb69f6ec95b1
add cors for dev and heroku
gulpfile.babel.js
gulpfile.babel.js
'use strict'; import gulp from 'gulp'; import del from 'del'; import gulpLoadPlugins from 'gulp-load-plugins'; import browserSync from 'browser-sync'; import download from 'gulp-download'; import decompress from 'gulp-decompress'; import historyApiFallback from 'connect-history-api-fallback'; const $ = gulpLoadPlugins(); const DEST = 'dist'; const PORT = process.env.PORT || 3000; browserSync.create(); /** * Task jshint * Use js lint */ gulp.task('jshint', () => { return gulp.src([ 'src/js/**/*.js', 'gulfile.js', ]) .pipe($.jshint('.jshintrc')) .pipe($.jshint.reporter('default')) .pipe($.jshint.reporter('fail')); }); /** * Task jscs * Use js cs lint */ gulp.task('jscs', () => { return gulp.src([ 'src/js/**/*.js', 'gulfile.js', ]) .pipe($.jscs('.jscsrc')) .pipe($.jscs.reporter()) .pipe($.jscs.reporter('fail')); }); /** * Task fonts * Move fonts to DEST */ gulp.task('fonts', () => { return gulp.src([ 'src/assets/fonts/*', 'src/lib/font-awesome/fonts/*', ]) .pipe(gulp.dest(DEST + '/fonts')); }); /** * Task images * Apply imagemin and move it to DEST */ gulp.task('images', ['icon'], () => { return gulp.src('src/assets/images/**/*') .pipe($.if($.if.isFile, $.cache($.imagemin({ progressive: true, interlaced: true, svgoPlugins: [{cleanupIDs: false}], })))) .pipe(gulp.dest(DEST + '/images')); }); /** * Task flags * Move country flags to DEST */ gulp.task('flags', () => { return gulp.src('src/lib/flag-css/dist/flags/*') .pipe(gulp.dest(DEST + '/flags')); }); /** * Task styles * Apply scss transformation to css */ gulp.task('styles', ['images', 'flags'], () => { return gulp.src('src/scss/*.scss') .pipe($.sass.sync({ outputStyle: 'expanded', precision: 10, includePaths: ['.'], })) .pipe(gulp.dest('src/css')); }); /** * Task html * Apply uglify, minify to src */ gulp.task('html', ['bower', 'fonts', 'styles', 'lang'], () => { if (process.env.NODE_ENV === 'production') { return gulp.src('src/**/*.html') .pipe($.useref()) .pipe($.if('*.js', $.uglify())) .pipe($.if('*.css', $.minifyCss())) .pipe(gulp.dest(DEST)); } return gulp.src('src/**/*.html') .pipe($.useref()) .pipe(gulp.dest(DEST)); }); /** * Task lang * Download locales files to dest */ gulp.task('lang', () => { return download('https://localise.biz:443/' + 'api/export/archive/json.zip?' + 'key=eMJfQxM9QEEO7im7ZxWZZgMgOQ6lqsKy&' + 'fallback=en&' + 'path=locale-%7B%25lang%7D.json') .pipe(decompress({strip: 1})) .pipe(gulp.dest(DEST + '/locales')); }); /** * Task icon * Move favicon.png file to dest */ gulp.task('icon', () => { return gulp.src([ 'src/assets/favicon.png', ]) .pipe(gulp.dest(DEST)); }); /** * Task bower * Launch bower */ gulp.task('bower', () => { return $.bower(); }); /** * Task clean * Remove dist directory */ gulp.task('clean', () => { return del([ DEST, 'src/lib', 'src/css', ]); }); /** * Task watch-html * Listen to html task and reload the browser */ gulp.task('watch-html', ['jshint', 'jscs', 'html'], () => { return browserSync.reload(); }); /** * Task serve * Launch an instance of the server and listen to * every change reloading the browser */ gulp.task('serve', ['html'], () => { browserSync.init({ server: { baseDir: './' + DEST, middleware: [ historyApiFallback() ], } }); $.watch([ 'src/scss/*.scss', 'src/**/*.html', 'src/js/**/*.js', ], $.batch((events, done) => { gulp.start('watch-html', done); })); }); /** * Task test * Build the project and test for it's consistency */ gulp.task('test', ['jshint', 'jscs']); /** * Task reload * reload the browser after executing default */ gulp.task('reload', ['default'], () => { browserSync.reload(); }); /** * Task serve-prod * build a production server and launch it */ gulp.task('serve-prod', ['default'], () => { $.connect.server({ port: PORT, root: [ './' + DEST ], livereload: false, middleware: (connect, opt) => { return [historyApiFallback()]; }, }); }); /** * Task default * Apply all tasks to build project */ gulp.task('default', ['html']);
JavaScript
0
@@ -397,24 +397,175 @@ .create();%0A%0A +const acceptCors = function() %7B%0A return function(req, res, next) %7B%0A res.setHeader('Access-Control-Allow-Origin', '*');%0A return next();%0A %7D;%0A%7D;%0A%0A /**%0A * Task @@ -3638,17 +3638,30 @@ llback() - +, acceptCors() %5D,%0A %7D @@ -4349,16 +4349,30 @@ llback() +, acceptCors() %5D;%0A %7D
8fdb06c89bed59ce63e9c5a226d39e3c6cb24a38
Add a new question.
questions.js
questions.js
var questions = [ "Worin besteht das Problem?", "Wann tritt das Problem auf?", "Welche Ressourcen habe ich momentan zur Verfügung um das Problem zu lösen?", "Welche Menschen können mir dabei helfen, das Problem zu lösen?", "Wann habe ich das letzte Mal intensiv über dieses Problem nachgedacht?", "Auf welche Ressourcen würden mich andere hinweisen?", "Was würde ich mir raten, wenn ich Berater wär?", "Was müsste ich tun, um eine Lösung des Problems zu verhindern?", "Wer konnte mir bei meinem letzten Problem helfen?", "Welchen Nutzen habe ich von dem Problem?", "Was wäre der nächste Schritt, den ich gehen könnte, um das Problem zu lösen?", "Wie würde es sein, wenn das Problem gelöst wäre?", "Für wen würde sich etwas ändern, wenn das Problem gelöst wäre?", "Wer ist alles von dem Problem betroffen?", "Was würde passieren, wenn ich das Problem nicht angehen würde?", "Wann habe ich mich das letzte Mal bei einem Menschen für etwas bedankt?", "Wann war ich das letzte Mal an der frischen Luft unterwegs?", "Welche Frage stelle ich mir eigentlich gerade?", "Wie schlimm ist mein altuelles Problem?", "Was treibt mich an?", "Warum bin ich auf dieser Seite?", "Unter welchen Bedingungen kann ich am besten über etwas nachdenken?", "Was würde mir ein Kollege jetzt raten?", "Welcher Lösungsansatz hat sich bei dem letzten Problem bewährt?", "In welchem Augenblick ist mein Problem entstanden?", "Wen könnte ich um Rat bitten?", "Warum ist das Problem da?", "Bin ich am richtigen Problem dran oder nur an einem Symptom?" ]
JavaScript
0.999949
@@ -1569,11 +1569,70 @@ ymptom?%22 +,%0A %22Kenne ich das Spielfeld gut, in dem ich mich befinde?%22 %0A%5D%0A
a9dc7e0dd3df97d1df91fb264ad5b124cb30f530
add minWidth to Popup, fix calculation _containerWidth
src/layer/Popup.js
src/layer/Popup.js
L.Popup = L.Class.extend({ includes: L.Mixin.Events, options: { maxWidth: 300, autoPan: true, closeButton: true, offset: new L.Point(0, 2), autoPanPadding: new L.Point(5, 5) }, initialize: function(options) { L.Util.setOptions(this, options); }, onAdd: function(map) { this._map = map; if (!this._container) { this._initLayout(); } this._updateContent(); this._container.style.opacity = '0'; this._map._panes.popupPane.appendChild(this._container); this._map.on('viewreset', this._updatePosition, this); if (this._map.options.closePopupOnClick) { this._map.on('preclick', this._close, this); } this._update(); this._container.style.opacity = '1'; //TODO fix ugly opacity hack this._opened = true; }, onRemove: function(map) { map._panes.popupPane.removeChild(this._container); map.off('viewreset', this._updatePosition, this); map.off('click', this._close, this); this._container.style.opacity = '0'; this._opened = false; }, setLatLng: function(latlng) { this._latlng = latlng; if (this._opened) { this._update(); } return this; }, setContent: function(content) { this._content = content; if (this._opened) { this._update(); } return this; }, _close: function() { if (this._opened) { this._map.removeLayer(this); } }, _initLayout: function() { this._container = L.DomUtil.create('div', 'leaflet-popup'); if (this.options.closeButton) { this._closeButton = L.DomUtil.create('a', 'leaflet-popup-close-button', this._container); this._closeButton.href = '#close'; this._closeButton.onclick = L.Util.bind(this._onCloseButtonClick, this); } this._wrapper = L.DomUtil.create('div', 'leaflet-popup-content-wrapper', this._container); L.DomEvent.disableClickPropagation(this._wrapper); this._contentNode = L.DomUtil.create('div', 'leaflet-popup-content', this._wrapper); this._tipContainer = L.DomUtil.create('div', 'leaflet-popup-tip-container', this._container); this._tip = L.DomUtil.create('div', 'leaflet-popup-tip', this._tipContainer); }, _update: function() { this._container.style.visibility = 'hidden'; this._updateContent(); this._updateLayout(); this._updatePosition(); this._container.style.visibility = ''; this._adjustPan(); }, _updateContent: function() { if (!this._content) return; if (typeof this._content == 'string') { this._contentNode.innerHTML = this._content; } else { this._contentNode.innerHTML = ''; this._contentNode.appendChild(this._content); } }, _updateLayout: function() { this._container.style.width = ''; this._container.style.whiteSpace = 'nowrap'; var width = this._container.offsetWidth; this._container.style.width = (width > this.options.maxWidth ? this.options.maxWidth : width) + 'px'; this._container.style.whiteSpace = ''; this._containerWidth = this._container.offsetWidth; }, _updatePosition: function() { var pos = this._map.latLngToLayerPoint(this._latlng); this._containerBottom = -pos.y - this.options.offset.y; this._containerLeft = pos.x - Math.round(this._containerWidth/2) + this.options.offset.x; this._container.style.bottom = this._containerBottom + 'px'; this._container.style.left = this._containerLeft + 'px'; }, _adjustPan: function() { if (!this.options.autoPan) { return; } var containerHeight = this._container.offsetHeight, layerPos = new L.Point( this._containerLeft, -containerHeight - this._containerBottom), containerPos = this._map.layerPointToContainerPoint(layerPos), adjustOffset = new L.Point(0, 0), padding = this.options.autoPanPadding, size = this._map.getSize(); if (containerPos.x < 0) { adjustOffset.x = containerPos.x - padding.x; } if (containerPos.x + this._containerWidth > size.x) { adjustOffset.x = containerPos.x + this._containerWidth - size.x + padding.x; } if (containerPos.y < 0) { adjustOffset.y = containerPos.y - padding.y; } if (containerPos.y + containerHeight > size.y) { adjustOffset.y = containerPos.y + containerHeight - size.y + padding.y; } if (adjustOffset.x || adjustOffset.y) { this._map.panBy(adjustOffset); } }, _onCloseButtonClick: function(e) { this._close(); L.DomEvent.stop(e); } });
JavaScript
0.000002
@@ -62,24 +62,41 @@ options: %7B%0D%0A +%09%09minWidth: 50,%0D%0A %09%09maxWidth: @@ -2848,32 +2848,25 @@ s._container -.style.w +W idth = (widt @@ -2921,22 +2921,77 @@ h : +( width -) + 'px'; + %3C this.options.minWidth ? this.options.minWidth : width ) );%0D%0A %0D%0A%09%09 @@ -3017,29 +3017,15 @@ le.w -hiteSpace = '';%0D%0A%0D%0A%09%09 +idth = this @@ -3037,26 +3037,35 @@ tainerWidth -= ++ 'px';%0D%0A%09%09 this._contai @@ -3068,27 +3068,37 @@ ntainer. -offsetWidth +style.whiteSpace = '' ;%0D%0A%09%7D,%0D%0A @@ -4504,8 +4504,10 @@ %0A%09%7D%0D%0A%7D); +%0D%0A
6f457cd0a5df2f7a1f2f3cb48e565c54696300e4
increase start window size
app/spec.js
app/spec.js
'use strict'; var app = require('app'); var BrowserWindow = require('browser-window'); var devHelper = require('./vendor/electron_boilerplate/dev_helper'); var windowStateKeeper = require('./vendor/electron_boilerplate/window_state'); var mainWindow; // Preserver of the window size and position between app launches. var mainWindowState = windowStateKeeper('main', { width: 1000, height: 600 }); app.on('ready', function () { mainWindow = new BrowserWindow({ x: mainWindowState.x, y: mainWindowState.y, width: mainWindowState.width, height: mainWindowState.height }); mainWindow.loadUrl('file://' + __dirname + '/spec.html'); devHelper.setDevMenu(); mainWindow.openDevTools(); mainWindow.on('close', function () { mainWindowState.saveState(mainWindow); }); }); app.on('window-all-closed', function () { app.quit(); });
JavaScript
0.000001
@@ -377,18 +377,18 @@ idth: 10 -00 +24 ,%0A he @@ -397,11 +397,11 @@ ht: -600 +768 %0A%7D);