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
76cbfed1ba4e9333144b8fbfd20683a22fcba21a
Make color by orientation false by default
src/JBrowse/View/Track/Alignments2.js
src/JBrowse/View/Track/Alignments2.js
define( [ 'dojo/_base/declare', 'dojo/_base/array', 'dojo/promise/all', 'JBrowse/Util', 'JBrowse/View/Track/CanvasFeatures', 'JBrowse/View/Track/_AlignmentsMixin' ], function( declare, array, all, Util, CanvasFeatureTrack, AlignmentsMixin ) { return declare( [ CanvasFeatureTrack, AlignmentsMixin ], { _defaultConfig: function() { var c = Util.deepUpdate( dojo.clone( this.inherited(arguments) ), { glyph: 'JBrowse/View/FeatureGlyph/Alignment', maxFeatureGlyphExpansion: 0, maxFeatureScreenDensity: 15, colorByOrientation: true, orientationType: 'fr', hideDuplicateReads: true, hideQCFailingReads: true, hideSecondary: true, hideSupplementary: true, hideUnmapped: true, hideUnsplicedReads: false, hideMissingMatepairs: false, hideForwardStrand: false, hideReverseStrand: false, useXS: false, useReverseTemplate: false, useXSOption: true, useReverseTemplateOption: true, viewAsPairs: false, readCloud: false, histograms: { description: 'coverage depth', binsPerBlock: 200 }, style: { showLabels: false } } ); return c; }, _trackMenuOptions: function() { var thisB = this; var displayOptions = []; if(this.config.useReverseTemplateOption) { displayOptions.push({ label: 'Use reversed template', type: 'dijit/CheckedMenuItem', checked: this.config.useReverseTemplate, onClick: function(event) { thisB.config.useReverseTemplate = this.get('checked'); thisB.browser.publish('/jbrowse/v1/v/tracks/replace', [thisB.config]); } }); } if(this.config.useXSOption) { displayOptions.push({ label: 'Use XS', type: 'dijit/CheckedMenuItem', checked: this.config.useXS, onClick: function(event) { thisB.config.useXS = this.get('checked'); thisB.browser.publish('/jbrowse/v1/v/tracks/replace', [thisB.config]); } }); } displayOptions.push({ label: 'View coverage', onClick: function(event) { thisB.config.type = 'JBrowse/View/Track/SNPCoverage' thisB.config._oldAlignmentsHeight = thisB.config.style.height thisB.config.style.height = thisB.config._oldSnpCoverageHeight thisB.browser.publish('/jbrowse/v1/v/tracks/replace', [thisB.config]); } }); displayOptions.push({ label: 'View normal', onClick: function(event) { thisB.config.viewAsPairs = false thisB.config.readCloud = false thisB.config.glyph = 'JBrowse/View/FeatureGlyph/Alignment' thisB.browser.publish('/jbrowse/v1/v/tracks/replace', [thisB.config]); } }); displayOptions.push({ label: 'View as pairs', onClick: function(event) { thisB.config.viewAsPairs = true thisB.config.readCloud = false thisB.config.glyph = 'JBrowse/View/FeatureGlyph/PairedAlignment' thisB.browser.publish('/jbrowse/v1/v/tracks/replace', [thisB.config]); } }); displayOptions.push({ label: 'View paired arcs', onClick: function(event) { thisB.config.viewAsPairs = true thisB.config.readCloud = true thisB.config.glyph = 'JBrowse/View/FeatureGlyph/PairedArc' thisB.browser.publish('/jbrowse/v1/v/tracks/replace', [thisB.config]); } }); displayOptions.push({ label: 'View pairs as read cloud', onClick: function(event) { thisB.config.viewAsPairs = true thisB.config.readCloud = true thisB.config.glyph = 'JBrowse/View/FeatureGlyph/PairedAlignment' thisB.browser.publish('/jbrowse/v1/v/tracks/replace', [thisB.config]); } }); displayOptions.push({ label: 'Color by pair orientation', type: 'dijit/CheckedMenuItem', checked: this.config.colorByOrientation, onClick: function(event) { thisB.config.colorByOrientation = this.get('checked'); thisB.browser.publish('/jbrowse/v1/v/tracks/replace', [thisB.config]); } }); return all([ this.inherited(arguments), this._alignmentsFilterTrackMenuOptions(), displayOptions ]) .then( function( options ) { var o = options.shift(); options.unshift({ type: 'dijit/MenuSeparator' } ); return o.concat.apply( o, options ); }); }, // override getLayout to access addRect method _getLayout: function() { var layout = this.inherited(arguments); if(this.config.readCloud) { layout = declare.safeMixin(layout, { addRect: function() { this.pTotalHeight = this.maxHeight; return 0; } }); } return layout; }, fillBlock: function( args ) { // workaround for the fact that initial load of JBrowse invokes fillBlock on nonsense regions // and then the cache cleanup can be invoked in ways that destroys visible features this.removeFeaturesFromCacheAfterDelay = this.removeFeaturesFromCacheAfterDelay || false if(!this.removeFeaturesFromCacheAfterDelay) { setTimeout(() => { this.removeFeaturesFromCacheAfterDelay = true }, 10000) } if(this.config.viewAsPairs) { let supermethod = this.getInherited(arguments) var reg = this.browser.view.visibleRegion() var len = Math.max(reg.end - reg.start, 4000) const region = { ref: this.refSeq.name, start: Math.max( 0, reg.start ), end: reg.end, viewAsPairs: true } const min = Math.max(0, region.start - len*4) const max = region.end + len*4 this.store.getFeatures({ ref: this.refSeq.name, start: min, end: max, viewAsPairs: true }, () => { /* do nothing */}, () => { var stats = this.store.getStatsForPairCache() this.upperPercentile = stats.upper this.lowerPercentile = stats.lower if(this.removeFeaturesFromCacheAfterDelay) { let f = args.finishCallback args.finishCallback = () => { f() setTimeout(() => { this.store.cleanFeatureCache({ ref: this.refSeq.name, start: min, end: max }) }, 1000) } } supermethod.call(this, args) }, e => { console.error(e) }) } else { this.inherited(arguments); } } }); });
JavaScript
0.000001
@@ -781,27 +781,28 @@ rientation: -tru +fals e,%0A
606ef1ff6432cc20867366a5be3a4ac49de4ed06
fix topicsFilter js styling
lib/topics-filter/topics-filter.js
lib/topics-filter/topics-filter.js
/** * Module dependencies. */ import debug from 'debug'; import merge from 'merge'; import Stateful from '../stateful/stateful.js'; import Storage from '../storage/storage.js'; import topics from '../topics/topics.js'; import user from '../user/user.js'; import sorts from './sorts.js'; let log = debug('democracyos:topics-filter'); let storage = new Storage; class TopicsFilter extends Stateful { constructor () { super(); this.reset = this.reset.bind(this); this.fetch = this.fetch.bind(this); this.refresh = this.refresh.bind(this); this.ontopicsload = this.ontopicsload.bind(this); this.middleware = this.middleware.bind(this); this.state('initializing'); this.initialize(); topics.on('loaded', this.ontopicsload); //TODO: make all this dependent on `bus` when making views reactive in #284 user.on('loaded', this.refresh); user.on('unloaded', this.reset); } /** * Initialize `$_filters`, `$_items`, `$_counts`, and `sorts` * * @api private */ initialize () { this.$_items = []; this.$_counts = []; // TODO: remove this hardcode and use a default sort (maybe by config?) this.$_filters = {}; this.$_filters['sort'] = 'closing-soon'; this.$_filters['status'] = 'open'; this.sorts = sorts; } /** * Re-fetch after `topics.ready` state * * @api private */ refresh () { topics.ready(this.fetch); } /** * Reset filter with defaults * * @api private */ reset () { this.initialize(); this.set( { sort: 'closing-soon', status: 'open', 'hide-voted': false } ); } /** * Re-fetch on `topics.ready` */ ontopicsload () { topics.ready(this.fetch); } /** * When a topic gets voted */ vote (id) { var view = this; topics.get().forEach(function(item) { if (item.id === id && !item.voted) { item.voted = true; item.participants.push(user.id); view.reload(); } }); }; /** * Fetch for filters */ fetch () { if (!user.logged()){ this.reset(); this.state('loaded'); } else { storage.get('topics-filter', (err, data) => { if (err) log('unable to fetch'); this.set(data); this.state('loaded'); }); } } items (v) { if (0 === arguments.length) { return this.$_items; } this.$_items = v; } /** * Get all current `$_filters` or just the * one provided by `key` param * * @param {String} key * @return {Array|String} all `$_filters` or just the one by `key` * @api public */ get (key) { if (0 === arguments.length) { return this.$_filters; }; return this.$_filters[key]; } /** * Set `$_filters` to whatever provided * * @param {String|Object} key to set `value` or `Object` of `key-value` pairs * @param {String} value * @return {TopicsFilter} Instance of `TopicsFilter` * @api public */ set (key, value) { if (2 === arguments.length) { // Create param object and call recursively var obj = {}; return obj[key] = value, this.set(obj); } // key is an object merge(this.$_filters, key); // notify change of filters this.ready(onready.bind(this)); function onready() { this.emit('change', this.get()); } // reload items with updated filters this.reload(); // save current state return this.save(); } /** * Save current filter `$_filters` to * `storage` if possible. * * @return {TopicsFilter} Instance of `TopicsFilter` * @api public */ save () { if (user.logged()) { storage.set('topics-filter', this.get(), onsave.bind(this)); } function onsave(err, ok) { if (err) return log('unable to save'); log('saved'); } return this; } /** * Reload items with current `$_filters` * and emit `reload` after filtering/sorting * * @return {TopicsFilter} Instance of `TopicsFilter` * @api public */ reload () { log('reload items'); var items = topics.get(); if (!items) return; var status = this.get('status'); var sortType = this.get('sort'); var sortFn = sorts[sortType].sort; var hideVoted = this.get('hide-voted'); this.$_counts['open'] = items.filter(i => i.publishedAt && i.status == 'open').length; this.$_counts['closed'] = items.filter(i => i.publishedAt && i.status == 'closed').length; // TODO: remove this once #288 is closed // Always exclude drafts items = items.filter(i => i.publishedAt != null); // Filter by status items = items.filter(i => i.status === status); // Check if logged user's id is in the topic's participants if (hideVoted) { items = items.filter(function(item) { return true !== item.voted; }); } // Sort filtered items = items.sort(sortFn); // save items this.items(items); this.ready(onready.bind(this)); function onready() { this.emit('reload', this.items()); }; return this; } /** * Counts topics under a specific * status, without side-effect * * @param {String} status filter criteria * @return {Number} Count of topics with `status` status */ countFiltered (status) { // (?) Maybe this should be done on demand, and // provide the with the actual open topics count // post filters applied // // Example: // // return (this.items() || []) // .filter(_({ status: status })) // .length; return this.$_counts[status]; } middleware (ctx, next) { this.ready(next); } } /** * Expose a `TopicsFilter` instance */ export default new TopicsFilter;
JavaScript
0.000001
@@ -1206,16 +1206,13 @@ ters -%5B' +. sort -'%5D = ' @@ -1248,18 +1248,15 @@ ters -%5B' +. status -'%5D = ' @@ -2680,25 +2680,24 @@ lters;%0A %7D -; %0A%0A return @@ -3093,23 +3093,16 @@ ;%0A -return obj%5Bkey%5D @@ -3109,17 +3109,30 @@ = value -, +;%0A return this.se @@ -3755,12 +3755,8 @@ (err -, ok ) %7B%0A @@ -4303,16 +4303,13 @@ unts -%5B' +. open -'%5D = i @@ -4391,18 +4391,15 @@ unts -%5B' +. closed -'%5D = i @@ -5054,14 +5054,13 @@ ));%0A + %7D -; %0A%0A
80fe14d830b8e337aeac62cb9c597e654a240e54
remove border-radius from logs button in mimic controls
lib/ui/components/MimicControls.js
lib/ui/components/MimicControls.js
import React from 'react'; import styled from 'styled-components'; const Container = styled.div` display: flex; font-family: Arial, sans-serif; font-size: 12px; background: white; position: fixed; bottom: 0; left: 0; ${(props) => props.fullWidth ? 'width: 100%;' : '' } `; const Control = styled.div` display: flex; align-items: center; padding: 0 8px; height: 25px; border-right: 1px solid #d8d8d8; border-top: 1px solid #d8d8d8; cursor: pointer; ${(props) => props.rounded ? 'border-radius: 0 0 0 5px;' : ''} background-color: ${(props) => props.active ? '#427dd2' : '#f7f7f7' }; ${(props) => props.active ? 'color: #fff;' : ''} &:hover { background-color: #c8dcf4; } `; export const MimicControls = ({ showLogs, showMocks, fullWidth, activeTab, children }) => ( <Container fullWidth={ fullWidth }> <Control rounded onClick={ showLogs } active={ activeTab === 'requests' }> Logs </Control> <Control onClick={ showMocks } active={ activeTab === 'mocks' }> Mocks </Control> { children } </Container> ); export default MimicControls;
JavaScript
0
@@ -477,73 +477,8 @@ er;%0A - $%7B(props) =%3E props.rounded ? 'border-radius: 0 0 0 5px;' : ''%7D%0A ba @@ -799,16 +799,8 @@ rol -rounded onCl
613b74713281038621eb59d3a6b60a71c19ddd43
Update download-build-lib-in-cs.js
scripts/download-build-lib-in-cs.js
scripts/download-build-lib-in-cs.js
var program = require('commander'); var AlfrescoApi = require('alfresco-js-api-node'); var http = require('http'); var fs = require('fs'); var path = require('path'); var archiver = require('archiver'); var AdmZip = require('adm-zip'); var alfrescoJsApi; downloadZip = async (url, outputFolder, pacakge) => { console.log(`Download ${pacakge}`) var file = fs.createWriteStream(`${pacakge}.zip`); return await http.get(`http://${url}`, (response) => { response.pipe(file); file.on('finish', async () => { setTimeout(() => { var zip = new AdmZip(path.join(__dirname, `../${pacakge}.zip`)); console.log(`Unzip ${pacakge}` + path.join(__dirname, `../${pacakge}.zip`)); zip.extractAllToAsync(path.join(__dirname, '../', outputFolder, `@alfresco/`), true, () => { setTimeout(() => { let oldFolder = path.join(__dirname, '../', outputFolder, `@alfresco/${pacakge}`) let newFolder = path.join(__dirname, '../', outputFolder, `@alfresco/adf-${pacakge}`) fs.rename(oldFolder, newFolder, (err) => { console.log('renamed complete'); }); }, 10000); }); }) }); }); } getUrl = async (folder, pacakge) => { let zipDemoNode; try { zipDemoNode = await alfrescoJsApi.nodes.getNode('-my-', { 'relativePath': `Builds/${folder}/${pacakge}.zip` }); } catch (error) { console.log('error: ' + error); } return await alfrescoJsApi.content.getContentUrl(zipDemoNode.entry.id, true); } async function main() { program .version('0.1.0') .option('-p, --password [type]', 'password') .option('-u, --username [type]', 'username') .option('-o, --output [type]', 'oputput folder') .option('--base-href [type]', '') .option('-f, --folder [type]', 'Name of the folder') .option('-host, --host [type]', 'URL of the CS') .parse(process.argv); alfrescoJsApi = new AlfrescoApi({ provider: 'ECM', hostEcm: program.host }); if (!program.output) { program.output = path.join(__dirname, '../node_modules/@alfresco/') } alfrescoJsApi.login(program.username, program.password); let coreUrl = await getUrl(program.folder, 'core'); downloadZip(coreUrl, program.output, 'core'); let contentUrl = await getUrl(program.folder, 'content-services'); downloadZip(contentUrl, program.output, 'content-services'); let processUrl = await getUrl(program.folder, 'process-services'); downloadZip(processUrl, program.output, 'process-services'); let insightUrl = await getUrl(program.folder, 'insights'); downloadZip(insightUrl, program.output, 'insights'); } main();
JavaScript
0.000001
@@ -165,43 +165,8 @@ ');%0A -var archiver = require('archiver'); %0Avar
c70997eea10cc0ef1e4815726659040bca3972bb
Fix jsdoc
scripts/map/MapArticleController.js
scripts/map/MapArticleController.js
/** * MapArticleController * Abstract view controller to display a jointSource. */ let MapArticleController = SingleModelController.createComponent("MapArticleController"); MapArticleController.defineMethod("construct", function construct() { this.jointSourceController = null; Object.defineProperty(this, "jointSource", { get: function () { return this.jointSourceController.jointSource; } }); }); // View (function (MapArticleController) { MapArticleController.defineMethod("initView", function initView() { if (!this.view) return; // Record the router index of before the article is showed this.routerIndex = Router.index - 1; // A new state's already inserted in a successor controllers' initView() // Click event this.view.addEventListener("click", viewOnClick); }); MapArticleController.defineMethod("uninitView", function uninitView() { if (!this.view) return; // Click event this.view.removeEventListener("click", viewOnClick); // Remove the router index delete this.routerIndex; }); // Shared functions function viewOnClick() { Router.jump(this.controller.routerIndex); } })(MapArticleController); MapArticleController.defineMethod("unhideView", function unhideView() { if (!this.view) return; let view = getElementProperty(this.view, "view"); for (let element of this.view.parentNode.querySelectorAll("[data-ica-view]")) { element.hidden = element !== this.view; } for (let element of document.body.querySelectorAll("[data-ica-for-view]")) { let forView = getElementProperty(element, "for-view"); element.classList.toggle("active", view === forView); } });
JavaScript
0.00006
@@ -76,16 +76,32 @@ Source.%0A + * @constructor%0A */%0Alet
e1371be25a083886ba3913d84f8b70e7003044a1
Add credentials on XHRs
app/assets/javascripts/gatemedia/data/index.js
app/assets/javascripts/gatemedia/data/index.js
//= require_self //= require ./implementation/string //= require_tree ./implementation Ember.$.support.cors = true; /* global Data:true */ Data = Ember.Namespace.create({ ajax: function (settings) { return Ember.$.ajax(settings); } });
JavaScript
0
@@ -221,24 +221,103 @@ .$.ajax( -settings +Ember.merge(settings, %7B%0A xhrFields: %7B%0A withCredentials: true%0A %7D%0A %7D) );%0A %7D%0A%7D
3410fd79834581189de94a856d4220dcdf5c9bd6
Remove hook parameter
src/api/server/createExpressServer.js
src/api/server/createExpressServer.js
import express from "express" import shrinkRay from "shrink-ray" import uuid from "uuid" import parameterProtection from "hpp" import helmet from "helmet" import PrettyError from "pretty-error" import favicon from "serve-favicon" import createLocaleMiddleware from "express-locale" import cookieParser from "cookie-parser" import bodyParser from "body-parser" import { ABSOLUTE_CLIENT_OUTPUT_PATH, ABSOLUTE_PUBLIC_PATH } from "./config" const pretty = new PrettyError() // this will skip events.js and http.js and similar core node files pretty.skipNodeFiles() // this will skip all the trace lines about express` core and sub-modules pretty.skipPackage("express") export default function createExpressServer(config, hooks) { // Create our express based server. const server = express() // Create new middleware to serve a favicon from the given path to a favicon file. server.use(favicon(`${ABSOLUTE_PUBLIC_PATH}/favicon.ico`)) // Attach a unique "nonce" to every response. This allows use to declare // inline scripts as being safe for execution against our content security policy. // @see https://helmetjs.github.io/docs/csp/ server.use((request, response, next) => { response.locals.nonce = uuid() // eslint-disable-line no-param-reassign next() }) // and use it for our app's error handler: server.use((error, request, response, next) => { // eslint-disable-line max-params console.log(pretty.render(error)) next() }) // Don't expose any software information to hackers. server.disable("x-powered-by") // Prevent HTTP Parameter pollution. server.use(parameterProtection()) // Content Security Policy (CSP) // // If you are unfamiliar with CSPs then I highly recommend that you do some // reading on the subject: // - https://content-security-policy.com/ // - https://developers.google.com/web/fundamentals/security/csp/ // - https://developer.mozilla.org/en/docs/Web/Security/CSP // - https://helmetjs.github.io/docs/csp/ // // If you are relying on scripts/styles/assets from other servers (internal or // external to your company) then you will need to explicitly configure the // CSP below to allow for this. For example you can see I have had to add // the polyfill.io CDN in order to allow us to use the polyfill script. // It can be a pain to manage these, but it's a really great habit to get in // to. // // You may find CSPs annoying at first, but it is a great habit to build. // The CSP configuration is an optional item for helmet, however you should // not remove it without making a serious consideration that you do not require // the added security. const cspConfig = { directives: { defaultSrc: [ "'self'" ], scriptSrc: [ // Allow scripts hosted from our application. "'self'", // Note: We will execution of any inline scripts that have the following // nonce identifier attached to them. // This is useful for guarding your application whilst allowing an inline // script to do data store rehydration (redux/mobx/apollo) for example. // @see https://helmetjs.github.io/docs/csp/ (request, response) => `'nonce-${response.locals.nonce}'`, // FIXME: Required for eval-source-maps (devtool in webpack) process.env.NODE_ENV === "development" ? "'unsafe-eval'" : "" ].filter((value) => value !== ""), styleSrc: [ "'self'", "'unsafe-inline'", "blob:" ], imgSrc: [ "'self'", "data:" ], fontSrc: [ "'self'", "data:" ], // Note: Setting this to stricter than * breaks the service worker. :( // I can't figure out how to get around this, so if you know of a safer // implementation that is kinder to service workers please let me know. // ["'self'", 'ws:'], connectSrc: [ "*" ], // objectSrc: [ "'none'" ], // mediaSrc: [ "'none'" ], childSrc: [ "'self'" ] } } if (process.env.NODE_ENV === "development") { // When in development mode we need to add our secondary express server that // is used to host our client bundle to our csp config. Object.keys(cspConfig.directives).forEach((directive) => cspConfig.directives[directive].push(`localhost:${process.env.CLIENT_DEVSERVER_PORT}`) ) } server.use(helmet.contentSecurityPolicy(cspConfig)) // The xssFilter middleware sets the X-XSS-Protection header to prevent // reflected XSS attacks. // @see https://helmetjs.github.io/docs/xss-filter/ server.use(helmet.xssFilter()) // Frameguard mitigates clickjacking attacks by setting the X-Frame-Options header. // @see https://helmetjs.github.io/docs/frameguard/ server.use(helmet.frameguard("deny")) // Sets the X-Download-Options to prevent Internet Explorer from executing // downloads in your site’s context. // @see https://helmetjs.github.io/docs/ienoopen/ server.use(helmet.ieNoOpen()) // Don’t Sniff Mimetype middleware, noSniff, helps prevent browsers from trying // to guess (“sniff”) the MIME type, which can have security implications. It // does this by setting the X-Content-Type-Options header to nosniff. // @see https://helmetjs.github.io/docs/dont-sniff-mimetype/ server.use(helmet.noSniff()) if (hooks.onSecuredServerCreated) hooks.onSecuredServerCreated(server) // Parse cookies via standard express tooling server.use(cookieParser()) // Detect client locale and match it with configuration server.use(createLocaleMiddleware({ priority: [ "query", "cookie", "accept-language", "default" ], default: config.DEFAULT_LOCALE.replace(/-/, "_"), allowed: config.ALLOWED_LOCALES.map((entry) => entry.replace(/-/, "_")) })) // Parse application/x-www-form-urlencoded server.use(bodyParser.urlencoded({ extended: false })) // Parse application/json server.use(bodyParser.json()) // Advanced response compression using a async zopfli/brotli combination // https://github.com/aickin/shrink-ray server.use(shrinkRay()) // Configure static serving of our webpack bundled client files. server.use( process.env.CLIENT_BUNDLE_HTTP_PATH, express.static(ABSOLUTE_CLIENT_OUTPUT_PATH, { maxAge: process.env.CLIENT_BUNDLE_CACHE_MAXAGE }) ) // Configure static serving of our "public" root http path static files. server.use(express.static(ABSOLUTE_PUBLIC_PATH)) return server }
JavaScript
0.000001
@@ -721,15 +721,8 @@ nfig -, hooks )%0A%7B%0A
065d0d6f7307f439a3f72eb077125799511d9630
Resolve a merged conflict - app/javascript/mastodon/features/compose/components/search_results.js
app/javascript/mastodon/features/compose/components/search_results.js
app/javascript/mastodon/features/compose/components/search_results.js
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; <<<<<<< HEAD import PropTypes from 'prop-types'; import { injectIntl, FormattedMessage } from 'react-intl'; ======= import { FormattedMessage } from 'react-intl'; >>>>>>> v1.4.7 import AccountContainer from '../../../containers/account_container'; import StatusContainer from '../../../containers/status_container'; import Link from 'react-router-dom/Link'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class SearchResults extends ImmutablePureComponent { static propTypes = { results: ImmutablePropTypes.map.isRequired, isAdmin: PropTypes.bool, searchKeyword: PropTypes.string, }; render () { const { results, searchKeyword, isAdmin } = this.props; let accounts, statuses, hashtags, search_header; let count = 0; if (results.get('accounts') && results.get('accounts').size > 0) { count += results.get('accounts').size; accounts = ( <div className='search-results__section'> {results.get('accounts').map(accountId => <AccountContainer key={accountId} id={accountId} />)} </div> ); } if (results.get('statuses') && results.get('statuses').size > 0) { count += results.get('statuses').size; statuses = ( <div className='search-results__section'> {results.get('statuses').map(statusId => <StatusContainer key={statusId} id={statusId} />)} </div> ); } if (results.get('hashtags') && results.get('hashtags').size > 0) { count += results.get('hashtags').size; hashtags = ( <div className='search-results__section'> {results.get('hashtags').map(hashtag => <Link key={hashtag} className='search-results__hashtag' to={`/timelines/tag/${hashtag}`}> #{hashtag} </Link> )} </div> ); } if (isAdmin && searchKeyword.length > 0) { search_header = ( <Link className='search-results__search-statuses' to={`/statuses/search/${searchKeyword}`}> <i className='fa fa-fw fa-search search-results__search-statuses-icon' /> <FormattedMessage id='search_results.search_toots' defaultMessage='Search toots with "{keyword}"' values={{ keyword: searchKeyword }} /> </Link> ); } else { search_header = ( <div className='search-results__header'> <FormattedMessage id='search_results.total' defaultMessage='{count, number} {count, plural, one {result} other {results}}' values={{ count }} /> </div> ); } return ( <div className='search-results'> {search_header} {accounts} {statuses} {hashtags} </div> ); } }
JavaScript
0.000077
@@ -84,21 +84,8 @@ s';%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0A impo @@ -128,20 +128,8 @@ rt %7B - injectIntl, For @@ -167,78 +167,8 @@ l';%0A -=======%0Aimport %7B FormattedMessage %7D from 'react-intl';%0A%3E%3E%3E%3E%3E%3E%3E v1.4.7%0A impo
4b8b2d5a5cc682e49c969825c25015b79cabdc14
Add tests for selector getters in bookFormReducer.
app/reducers/__tests__/bookFormReducer.spec.js
app/reducers/__tests__/bookFormReducer.spec.js
import expect from 'expect'; import { bookFormReducer } from '../bookFormReducer'; import * as types from '../../constants'; describe('booksReducer', () => { describe('when state is undefined', () => { const state = undefined; it('returns an initial state', () => { expect(bookFormReducer(state)).toEqual({ bookTitle: '', bookAuthor: '', }); }); }); describe('when action type is undefined', () => { const action = { type: undefined }; it('returns state unchanged', () => { const initialState = { bookTitle: 'Book Title', bookAuthor: 'Book Author', }; expect(bookFormReducer(initialState, action)).toEqual(initialState); }); }); describe('when action type is ADD_BOOK', () => { const action = { type: types.ADD_BOOK, title: 'Title', author: 'Author' }; describe('when current state contains characters', () => { const currentState = { bookTitle: 'Title', bookAuthor: 'Author', }; it('returns an object with cleared fields', () => { expect(bookFormReducer(currentState, action)).toEqual({ bookTitle: '', bookAuthor: '', }) }); }); }); describe('when action type is TITLE_CHANGE', () => { const action = { type: types.TITLE_CHANGE, title: 'New title', author: 'New author', }; it('returns a new state with the changed values', () => { const currentState = { bookTitle: 'Current title', bookAuthor: 'Current author', }; expect(bookFormReducer(currentState, action)).toEqual({ bookTitle: action.title, bookAuthor: currentState.bookAuthor, }); }); }); describe('when action type is AUTHOR_CHANGE', () => { const action = { type: types.AUTHOR_CHANGE, title: 'New title', author: 'New author', }; it('returns a new state with the changed values', () => { const currentState = { bookTitle: 'Current title', bookAuthor: 'Current author', }; expect(bookFormReducer(currentState, action)).toEqual({ bookTitle: currentState.bookTitle, bookAuthor: action.author, }); }); }); });
JavaScript
0
@@ -30,16 +30,18 @@ import %7B +%0A bookFor @@ -48,17 +48,51 @@ mReducer - +,%0A getBookTitle,%0A getBookAuthor,%0A %7D from ' @@ -2277,13 +2277,1221 @@ );%0A %7D); +%0A%0A describe('selector getBookTitle', () =%3E %7B%0A describe('when state.bookFormReducer is defined', () =%3E %7B%0A const bookTitle = 'Title';%0A const bookFormReducer = %7B bookTitle %7D;%0A const state = %7B bookFormReducer %7D;%0A%0A it('returns the bookTitle', () =%3E %7B%0A expect(getBookTitle(state)).toBe(bookTitle);%0A %7D);%0A %7D);%0A%0A describe('when state.bookFormReducer is undefined', () =%3E %7B%0A const bookFormReducer = undefined;%0A const state = %7B bookFormReducer %7D;%0A%0A it('returns empty string', () =%3E %7B%0A expect(getBookTitle(state)).toBe('');%0A %7D);%0A %7D);%0A %7D);%0A %0A describe('selector getBookAuthor', () =%3E %7B%0A describe('when state.bookFormReducer is defined', () =%3E %7B%0A const bookAuthor = 'Author';%0A const bookFormReducer = %7B bookAuthor %7D;%0A const state = %7B bookFormReducer %7D;%0A%0A it('returns the bookAuthor', () =%3E %7B%0A expect(getBookAuthor(state)).toBe(bookAuthor);%0A %7D);%0A %7D);%0A%0A describe('when state.bookFormReducer is undefined', () =%3E %7B%0A const bookFormReducer = undefined;%0A const state = %7B bookFormReducer %7D;%0A%0A it('returns empty string', () =%3E %7B%0A expect(getBookAuthor(state)).toBe('');%0A %7D);%0A %7D);%0A %7D); %0A%7D);%0A
0b6015659eaf544d4fc9e810a91a2876d077b8df
Fix generate yail option on value blocks Yail generator returns arrays for value blocks instead of strings, now passing string to setCommentText
appinventor/blocklyeditor/src/blocklyeditor.js
appinventor/blocklyeditor/src/blocklyeditor.js
// Copyright 2012 Massachusetts Institute of Technology. All rights reserved. /** * @fileoverview Visual blocks editor for App Inventor * Initialize the blocks editor workspace. * * @author sharon@google.com (Sharon Perl) */ Blockly.BlocklyEditor = {}; Blockly.BlocklyEditor.startup = function(documentBody, formName) { Blockly.inject(documentBody); Blockly.Drawer.createDom(); Blockly.Drawer.init(); Blockly.BlocklyEditor.formName_ = formName; Blockly.bindEvent_(Blockly.mainWorkspace.getCanvas(), 'blocklyWorkspaceChange', this, function() { window.parent.BlocklyPanel_blocklyWorkspaceChanged(Blockly.BlocklyEditor.formName_); }); }; /** * Add a "Generate Yail" option to the context menu for every block. The generated yail will go in * the block's comment (if it has one) for now. * TODO: eventually create a separate kind of bubble for the generated yail, which can morph into * the bubble for "do it" output once we hook up to the REPL. */ Blockly.Block.prototype.customContextMenu = function(options) { var yailOption = {enabled: true}; yailOption.text = "Generate Yail"; var myBlock = this; yailOption.callback = function() { myBlock.setCommentText(Blockly.Yail.blockToCode1(myBlock)); }; options.push(yailOption); };
JavaScript
0.000004
@@ -1193,65 +1193,369 @@ -myBlock.setCommentText(Blockly.Yail.blockToCode1(myBlock) +var yailText;%0A //Blockly.Yail.blockToCode1 returns a string if the block is a statement%0A //and an array if the block is a value%0A var yailTextOrArray = Blockly.Yail.blockToCode1(myBlock);%0A if(yailTextOrArray instanceof Array)%7B%0A %09yailText = yailTextOrArray%5B0%5D;%0A %7D else %7B%0A %09yailText = yailTextOrArray;%0A %7D%0A myBlock.setCommentText(yailText );%0A
360b60c4ec1ae07d4f2ad2faa7190d3157333cbb
Remove duplicate text from SettingsAdmin.
assets/js/components/settings/SettingsAdmin.js
assets/js/components/settings/SettingsAdmin.js
/** * SettingsOverview component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { useEffect } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { addQueryArgs } from '@wordpress/url'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { CORE_USER } from '../../googlesitekit/datastore/user/constants'; import { CORE_SITE } from '../../googlesitekit/datastore/site/constants'; import { CORE_LOCATION } from '../../googlesitekit/datastore/location/constants'; import Layout from '../layout/Layout'; import { Grid, Cell, Row } from '../../material-components'; import OptIn from '../OptIn'; import VisuallyHidden from '../VisuallyHidden'; import ResetButton from '../ResetButton'; import UserInputPreview from '../user-input/UserInputPreview'; import { USER_INPUT_QUESTIONS_LIST } from '../user-input/util/constants'; import UserInputSettings from '../notifications/UserInputSettings'; import { useFeature } from '../../hooks/useFeature'; import { trackEvent } from '../../util'; import SettingsPlugin from './SettingsPlugin'; const { useSelect, useDispatch } = Data; export default function SettingsAdmin() { const userInputEnabled = useFeature( 'userInput' ); const isUserInputCompleted = useSelect( ( select ) => userInputEnabled && select( CORE_USER ).getUserInputState() === 'completed' ); const userInputURL = useSelect( ( select ) => select( CORE_SITE ).getAdminURL( 'googlesitekit-user-input' ) ); const { navigateTo } = useDispatch( CORE_LOCATION ); const goTo = ( questionIndex = 1 ) => { const questionSlug = USER_INPUT_QUESTIONS_LIST[ questionIndex - 1 ]; if ( questionSlug ) { trackEvent( 'user_input', 'settings_edit', questionSlug ); navigateTo( addQueryArgs( userInputURL, { question: questionSlug, redirect_url: global.location.href, single: 'settings', // Allows the user to edit a single question then return to the settings page. } ) ); } }; useEffect( () => { if ( isUserInputCompleted ) { trackEvent( 'user_input', 'settings_view' ); } }, [ isUserInputCompleted ] ); return ( <Row> { userInputEnabled && ( <Cell size={ 12 }> { isUserInputCompleted && ( <Layout> <div className="googlesitekit-settings-module googlesitekit-settings-module--active googlesitekit-settings-user-input"> <Grid> <Row> <Cell size={ 12 }> <h3 className="googlesitekit-heading-4 googlesitekit-settings-module__title"> { __( 'Your site goals', 'google-site-kit' ) } </h3> <p> { __( 'Based on your responses, Site Kit will show you metrics and suggestions that are specific to your site to help you achieve your goals', 'google-site-kit' ) } </p> </Cell> </Row> <UserInputPreview goTo={ goTo } noFooter /> </Grid> </div> </Layout> ) } { ! isUserInputCompleted && ( <UserInputSettings isDismissable={ false } /> ) } </Cell> ) } <Cell size={ 12 }> <Layout> <div className="googlesitekit-settings-module googlesitekit-settings-module--active"> <Grid> <Row> <Cell size={ 12 }> <h3 className="googlesitekit-heading-4 googlesitekit-settings-module__title"> { __( 'Plugin Status', 'google-site-kit' ) } </h3> </Cell> <Cell size={ 12 }> <div className="googlesitekit-settings-module__meta-items"> <p className="googlesitekit-settings-module__status"> { __( 'Site Kit is connected', 'google-site-kit' ) } <span className="googlesitekit-settings-module__status-icon googlesitekit-settings-module__status-icon--connected"> <VisuallyHidden> { __( 'Connected', 'google-site-kit' ) } </VisuallyHidden> </span> </p> </div> </Cell> </Row> </Grid> <footer className="googlesitekit-settings-module__footer"> <Grid> <Row> <Cell size={ 12 }> <ResetButton /> </Cell> </Row> </Grid> </footer> </div> </Layout> </Cell> <Cell size={ 12 }> <SettingsPlugin /> </Cell> <Cell size={ 12 }> <Layout className="googlesitekit-settings-meta" title={ __( 'Tracking', 'google-site-kit' ) } header fill > <div className="googlesitekit-settings-module googlesitekit-settings-module--active"> <Grid> <Row> <Cell size={ 12 }> <div className="googlesitekit-settings-module__meta-items"> <div className="googlesitekit-settings-module__meta-item googlesitekit-settings-module__meta-item--nomargin"> <OptIn optinAction="analytics_optin_settings_page" /> </div> </div> </Cell> </Row> </Grid> </div> </Layout> </Cell> </Row> ); }
JavaScript
0
@@ -1248,56 +1248,8 @@ n';%0A -import VisuallyHidden from '../VisuallyHidden';%0A impo @@ -4280,140 +4280,10 @@ ted%22 -%3E%0A%09%09%09%09%09%09%09%09%09%09%09%09%3CVisuallyHidden%3E%0A%09%09%09%09%09%09%09%09%09%09%09%09%09%7B __( 'Connected', 'google-site-kit' ) %7D%0A%09%09%09%09%09%09%09%09%09%09%09%09%3C/VisuallyHidden%3E%0A%09%09%09%09%09%09%09%09%09%09%09%3C/span + / %3E%0A%09%09
59d9ede1cf1336a2b8c6c359f0c013a2a602d703
Update doc-block.
assets/js/modules/adsense/datastore/service.js
assets/js/modules/adsense/datastore/service.js
/** * `modules/adsense` data store: service. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { addQueryArgs } from '@wordpress/url'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { STORE_NAME } from './constants'; import { CORE_USER } from '../../../googlesitekit/datastore/user/constants'; import { CORE_SITE } from '../../../googlesitekit/datastore/site/constants'; import { parseDomain } from '../util/url'; const { createRegistrySelector } = Data; export const selectors = { /** * Gets a URL to the service. * * @since 1.14.0 * * @param {Object} state Data store's state. * @param {Object} [args] Object containing optional path and query args. * @param {string} [args.path] A path to append to the base url. * @param {Object} [args.query] Object of query params to be added to the URL. * @return {(string|undefined)} The URL to the service, or `undefined` if not loaded. */ getServiceURL: createRegistrySelector( ( select ) => ( state, { path, query } = {} ) => { const userEmail = select( CORE_USER ).getEmail(); if ( userEmail === undefined ) { return undefined; } const baseURI = 'https://www.google.com/adsense/new/u/0'; const queryParams = query ? { ...query, authuser: userEmail } : { authuser: userEmail }; if ( path ) { const sanitizedPath = `/${ path.replace( /^\//, '' ) }`; return addQueryArgs( `${ baseURI }${ sanitizedPath }`, queryParams ); } return addQueryArgs( baseURI, queryParams ); } ), /** * Returns the service URL for creating a new AdSense account. * * @since 1.14.0 * * @return {(string|undefined)} AdSense URL to create a new account (or `undefined` if not loaded). */ getServiceCreateAccountURL: createRegistrySelector( ( select ) => () => { const siteURL = select( CORE_SITE ).getReferenceSiteURL(); const query = { source: 'site-kit', utm_source: 'site-kit', utm_medium: 'wordpress_signup', }; if ( undefined !== siteURL ) { query.url = siteURL; } return addQueryArgs( 'https://www.google.com/adsense/signup/new', query ); } ), /** * Returns the service URL to an AdSense account's overview page. * * @since 1.14.0 * * @return {(string|undefined)} AdSense account overview URL (or `undefined` if not loaded). */ getServiceAccountURL: createRegistrySelector( ( select ) => () => { const accountID = select( STORE_NAME ).getAccountID(); if ( accountID === undefined ) { return undefined; } const path = `${ accountID }/home`; const query = { source: 'site-kit' }; return select( STORE_NAME ).getServiceURL( { path, query } ); } ), /** * Returns the service URL to an AdSense account's site overview page. * * @since 1.14.0 * * @return {(string|undefined)} AdSense account site overview URL (or `undefined` if not loaded). */ getServiceAccountSiteURL: createRegistrySelector( ( select ) => () => { const accountID = select( STORE_NAME ).getAccountID(); const siteURL = select( CORE_SITE ).getReferenceSiteURL(); if ( accountID === undefined || siteURL === undefined ) { return undefined; } const path = `${ accountID }/home`; const query = { source: 'site-kit', url: parseDomain( siteURL ) || siteURL, }; return select( STORE_NAME ).getServiceURL( { path, query } ); } ), /** * Returns the service URL to an AdSense account's site overview page. * * @since n.e.x.t * * @param {Object} reportArgs URL parameters to be passed to the query. * @return {(string|undefined)} AdSense account site overview URL (or `undefined` if not loaded). */ getServiceReportURL: createRegistrySelector( ( select ) => ( state, reportArgs ) => { const accountID = select( STORE_NAME ).getAccountID(); if ( accountID === undefined ) { return undefined; } const path = `${ accountID }/reporting`; return select( STORE_NAME ).getServiceURL( { path, query: reportArgs } ); } ), /** * Returns the service URL to an AdSense account's site management page. * * @since 1.14.0 * * @return {(string|undefined)} AdSense account site management URL (or `undefined` if not loaded). */ getServiceAccountManageSiteURL: createRegistrySelector( ( select ) => () => { const accountID = select( STORE_NAME ).getAccountID(); const siteURL = select( CORE_SITE ).getReferenceSiteURL(); if ( accountID === undefined || siteURL === undefined ) { return undefined; } const path = `${ accountID }/sites/my-sites`; const query = { source: 'site-kit', url: parseDomain( siteURL ) || siteURL, }; return select( STORE_NAME ).getServiceURL( { path, query } ); } ), /** * Returns the service URL to the AdSense sites list. * * @since 1.14.0 * * @return {(string|undefined)} AdSense account sites list URL (or `undefined` if not loaded). */ getServiceAccountManageSitesURL: createRegistrySelector( ( select ) => ( ) => { const accountID = select( STORE_NAME ).getAccountID(); if ( accountID === undefined ) { return undefined; } const path = `${ accountID }/sites/my-sites`; const query = { source: 'site-kit' }; return select( STORE_NAME ).getServiceURL( { path, query } ); } ), /** * Returns the service URL to an AdSense account's site ads preview page. * * @since 1.14.0 * * @return {(string|undefined)} AdSense account site ads preview URL (or `undefined` if not loaded). */ getServiceAccountSiteAdsPreviewURL: createRegistrySelector( ( select ) => () => { const accountID = select( STORE_NAME ).getAccountID(); const siteURL = select( CORE_SITE ).getReferenceSiteURL(); if ( accountID === undefined || siteURL === undefined ) { return undefined; } const path = `${ accountID }/myads/sites/preview`; const query = { source: 'site-kit', url: parseDomain( siteURL ) || siteURL, }; return select( STORE_NAME ).getServiceURL( { path, query } ); } ), }; const store = { selectors, }; export default store;
JavaScript
0
@@ -3980,37 +3980,23 @@ account -'s site overview page + report .%0A%09 *%0A%09
0ecb0b97fb52779953cc1b1d6034ed7943afa7f1
add colon between key and value
frappe/website/doctype/help_article/help_article.js
frappe/website/doctype/help_article/help_article.js
// Copyright (c) 2016, Frappe Technologies and contributors // For license information, please see license.txt frappe.ui.form.on('Help Article', { refresh: function(frm) { frm.dashboard.clear_headline(); frm.dashboard.set_headline_alert(` <div class="row"> <div class="col-md-6 col-xs-12"> <span class="indicator whitespace-nowrap green"> <span>Helpful ${frm.doc.helpful || 0}</span> </span> </div> <div class="col-md-6 col-xs-12"> <span class="indicator whitespace-nowrap red"> <span>Not Helpful ${frm.doc.not_helpful || 0}</span> </span> </div> </div> `); } });
JavaScript
0
@@ -366,24 +366,25 @@ span%3EHelpful +: $%7Bfrm.doc.h @@ -539,16 +539,17 @@ Helpful +: $%7Bfrm.d
9b8b73e8abb73699ca6ad5767fd5710475fc9c96
fix bug
frontend-modules/angular/ui/searchBox.controller.js
frontend-modules/angular/ui/searchBox.controller.js
app.controller('SearchBoxController', function ($scope, $http, $location, $rootScope, $routeParams) { var isAdvancedSearch = function () { var containsSearchPath = $location.absUrl().includes('/search'); return containsSearchPath; } $scope.showQuickSearchResults = function () { var str = $scope.queryText; var isQueryValid = (!str || /^\s*$/.test(str)) == false; return isQueryValid && !isAdvancedSearch(); }; $scope.hasResults = function () { var r = $scope.result; return r != null && ( r.categories.length > 0 || r.courses.length > 0 || r.videoAnnotations.length > 0 || r.pdfAnnotations.length > 0 || r.contentNodes.length > 0 ); }; $scope.openAdvancedSearch = function () { window.location.href = '/search?term=' + $scope.queryText; }; $scope.$watch('queryText', function (searchTerm) { $rootScope.$broadcast('searchQueryChanged', { state: searchTerm }); // Do not show the search hints // when advanced search page is open if (!searchTerm || searchTerm.length == 0 || isAdvancedSearch()) { $scope.result = null; return; } if (searchTerm === $scope.queryText) { $http.get('/api/search?term=' + searchTerm) .success(function (data) { $scope.result = data; }); } }); var init = function () { try { $scope.queryText = $location.absUrl().split('?')[1].split('=')[1]; } catch (e) { //ignore } }; init(); });
JavaScript
0.000001
@@ -1528,24 +1528,448 @@ %7D%0A %7D);%0A%0A + var getParameterByName = function (name, url) %7B%0A if (!url) %7B%0A url = window.location.href;%0A %7D%0A name = name.replace(/%5B%5C%5B%5C%5D%5D/g, %22%5C%5C$&%22);%0A var regex = new RegExp(%22%5B?&%5D%22 + name + %22(=(%5B%5E&#%5D*)%7C&%7C#%7C$)%22),%0A results = regex.exec(url);%0A if (!results) return null;%0A if (!results%5B2%5D) return '';%0A return decodeURIComponent(results%5B2%5D.replace(/%5C+/g, %22 %22));%0A %7D;%0A%0A var init @@ -1999,16 +1999,17 @@ try %7B%0A +%0A @@ -2035,54 +2035,54 @@ t = -$location.absUrl().split('?')%5B1%5D.split('=')%5B1%5D +getParameterByName('term', $location.absUrl()) ;%0A
952865e4b1eb0d626221695ea7e1d04de0189ed8
fix config
generators/app/templates/config/default/exporter.js
generators/app/templates/config/default/exporter.js
'use strict'; /** * Nitro Exporter Config * https://github.com/namics/nitro-exporter */ const config = { exporter: { dest: 'dist', i18n: [], publics: true, renames: [ { src: 'dist/assets/**', base: 'dist/assets', dest: 'dist/', }, ], replacements: [ { glob: ['dist/*.html', 'dist/css/*.css'], replace: [ { from: '/assets/', to: '', }, ], }, { glob: ['dist/js/*.js'], replace: [ { from: '/api', to: 'api', }, ], }, { glob: ['dist/*.html'], replace: [ { from: '([a-z]+)\\.(css|js)', to: '$1.min.$2', }, ], }, ], views: true, zip: false, }, }; module.exports = config.exporter;
JavaScript
0.000003
@@ -527,141 +527,8 @@ %09%7D,%0A -%09%09%09%7B%0A%09%09%09%09glob: %5B'dist/*.html'%5D,%0A%09%09%09%09replace: %5B%0A%09%09%09%09%09%7B%0A%09%09%09%09%09%09from: '(%5Ba-z%5D+)%5C%5C.(css%7Cjs)',%0A%09%09%09%09%09%09to: '$1.min.$2',%0A%09%09%09%09%09%7D,%0A%09%09%09%09%5D,%0A%09%09%09%7D,%0A %09%09%5D,
bbaac928494e7dbfc83c917c516a417eb4ad1954
add minu dust forecast index
server/models/modelMinuDustFrcst.js
server/models/modelMinuDustFrcst.js
/** * informData+informCode가 기준임. * 새로 받은 데이터는 기존ㅇ informData에 업데이트 함. * inmage는 5, 23시에만 큰이미지, 23시에 오늘로 들어오는 이미지는 내일 예측모델임, 23시 당일 내용인지 확실치 않으나, 일단 그렇다고 봄. * Created by aleckim on 2016. 4. 1.. */ var mongoose = require('mongoose'); var mdfSchema = new mongoose.Schema({ informCode: String, //PM10, PM25, O3 informData: String, //2016-04-03 dataTime: String, //2016-03-20 5시 발표, 11시, 17시 23시 informCause: String, informOverall: String, informGrade: [ { region: String, //서울, 제주, 세종 분류는 있으나, 예보 없음. grade: String, //예보없음, 좋음, 보통, 나쁨, 매우나쁨 } ], imageUrl: [String] }); mdfSchema.index({dataTime:1}); module.exports = mongoose.model('MinuDustFrcst', mdfSchema);
JavaScript
0
@@ -672,16 +672,49 @@ ime:1%7D); +%0AmdfSchema.index(%7BinformData:1%7D); %0A%0Amodule
9b5f763a795b0166d4789802a868a7192ee72a87
update iChatClient.js
server/public/lib/js/iChatClient.js
server/public/lib/js/iChatClient.js
// <script type="text/javascript"> // var client = new Faye.Client('http://at35.com:4567/faye', { // timeout : 120, // retry : 5 // }); // // var subscription = client.subscribe('/foo', function(message) { // // handle message // alert(message.text); // console.log(message); // }); // // setTimeout(function(){ // var publication = client.publish('/foo', {text: 'Hi there, foo test'}); // // publication.then(function() { // alert('Message received by server!'); // }, function(error) { // alert('There was a problem: ' + error.message); // }); // // },2000); // </script> // function __extend(des, src) { if (!des) { des = {}; } if (src) { for (var i in src) { des[i] = src[i]; } } return des; } window.iChatClient = iChatClient = function(option){ this.subs = []; this.sifter = new Sifter([]); this.debug = true; var opt = __extend({ url: 'http://127.0.0.1:4567/faye', timeout : 120, retry : 5 },option); this.client = new Faye.Client(opt.url, opt); Faye.logger = console.log; this.client.addExtension({ outgoing: function(message, callback) { if (message.channel === '/meta/subscribe') { message.ext = message.ext || {}; message.ext.username = 'username'; } callback(message); } }); Logger = { incoming: function(message, callback) { console.log('incoming', message); callback(message); }, outgoing: function(message, callback) { console.log('outgoing', message); callback(message); } }; this.client.addExtension(Logger); this.client.disable('autodisconnect'); this.client.on('transport:down', function() { // the client is offline console.log("the client is offline"); }); this.client.on('transport:up', function() { // the client is online console.log("the client is online"); }); return this; } iChatClient.prototype.log = function(t) { if (this.debug) { console.log('[iChat LOG] ' + t); } } iChatClient.prototype.add = function(item) { if(this.is_exist(item.chat_id) == true){ this.log('chat_id以及存在了'); return; } this.subs.push(item); this.sifter = new Sifter(this.subs); } /** * client.join('a_chat_id',function(message) { // handle message alert(message.text); console.log(message); }); * */ iChatClient.prototype.join = function(chat_id,cb){ var topic = '/' + chat_id; this.cancel_with_caht_id(chat_id,function(){ console.log("iChatClient.cancel_with_caht_id() finished."); }); var subscription = this.client.subscribe(topic, cb); var _instance = this; _instance.add({ 'chat_id' : chat_id, 'subscription' : subscription }); return subscription; } iChatClient.prototype.is_exist = function(chat_id){ this.log(' chat_id = ' + chat_id); var result = this.search(chat_id, 1); return (result.items.length > 0) ? true : false; } iChatClient.prototype.cancel_with_caht_id = function(chat_id, cb){ this.log(' chat_id = ' + chat_id); var result = this.search(chat_id, 1); if(result.items.length > 0 && cb) { var obj = this.subs[result.items[0].id]; var sub = obj.subscription; sub.then(function() { // 只有与服务器建立连接的topic才有效。 sub.cancel(); // subscription.unsubscribe('/foo'); }); console.log('当前'+ chat_id +'订阅,已取消'); cb(); }else { console.log('当前'+ chat_id +'没有订阅,无需离开'); } } iChatClient.prototype.fetch = function(chat_id, cb){ this.log(' chat_id = ' + chat_id); var result = this.search(chat_id, 1); if(result.items.length > 0 && cb) { var obj = this.subs[result.items[0].id]; cb(obj); }else { console.log('当前'+ chat_id +'没有订阅,无需离开'); } } iChatClient.prototype.search = function(chat_id, limit){ this.log(' chat_id = ' + chat_id); var result = this.sifter.search('' + chat_id, { fields: ['chat_id'], sort: [{field: 'chat_id', direction: 'asc'}], limit: limit }); return result; } iChatClient.prototype.leave = function(chat_id, cb){ this.log(' chat_id = ' + chat_id); if(this.is_exist(chat_id) != true){ return; } this.fetch(chat_id, function(obj){ var sub = obj.subscription; sub.cancel(); if(cb){ cb(); } }); } iChatClient.prototype.leave_all = function( cb){ for(var i in this.subs){ var obj = this.subs[i]; var chat_id = obj.chat_id var sub = obj.subscription; sub.cancel(); if(cb){ cb(); } } this.subs = []; } iChatClient.prototype.send = function(topic, message, cb_received_by_server, cb_error){ var publication = this.client.publish('/' + topic, message); publication.then(function() { // alert('Message received by server!'); if(cb_received_by_server) cb_received_by_server(); }, function(error) { // alert('There was a problem: ' + error.message); if(cb_error) cb_error(error); }); } iChatClient.prototype.disable_autodisconnect = function(){ this.client.disable('autodisconnect'); } iChatClient.prototype.disable_websocket = function(){ this.client.disable('websocket'); } iChatClient.prototype.disconnect = function(){ this.client.disconnect(); } iChatClient.prototype.reconnect = function(){ // 实际上是重新subscribe就可以了 // this.client.connect(callback, context); } // module.exports = iChatClient;
JavaScript
0
@@ -1044,16 +1044,19 @@ opt);%0A%09 +// Faye.log
eeaf88b6a62d8da7ee292ded184acf6dd5a2e3b8
Add 'is' in the words to wordsToIgnore list
server/utils/customTextAnalytics.js
server/utils/customTextAnalytics.js
import $ from 'jquery'; import { wordsAPIKey } from '../../API_KEYS'; /** * Helper functions for custom text analytics */ // get each word's word count function countEachWord(textInput) { // split up input string into arrays by spaces and newline chars const whiteSpaceChars = /\s/; const allWords = textInput.split(whiteSpaceChars); const wordCountObject = {}; allWords.forEach((currentWord) => { // get rid of punctuation and make word lowercase const editedWord = currentWord.replace(/\W/g, '').toLowerCase(); // account for empty strings (aka trailed whitespace) if (editedWord.length) { if (!wordCountObject[editedWord]) { wordCountObject[editedWord] = 1; } else { wordCountObject[editedWord] += 1; } } }); return wordCountObject; } // find the top three most-used words, excluding 'the', 'a', 'an', and 'and' function topThreeWords(wordCountObject) { const wordsToIgnore = /the\b|a\b|an\b|and\b/; // avoid modifying original wordCountObject const copiedObj = JSON.parse(JSON.stringify(wordCountObject)); const mostCommonWords = {}; const wordKeys = Object.keys(copiedObj); let i = 0; wordKeys.forEach((word) => { if (word.match(wordsToIgnore)) { delete copiedObj[word]; } }); function findCurrentMostFrequent(wordObj) { let largest = 0; let mostUsed = ''; const currentKeys = Object.keys(wordObj); currentKeys.forEach((key) => { if (wordObj[key] > largest) { largest = wordObj[key]; mostUsed = key; } }); mostCommonWords[mostUsed] = largest; delete copiedObj[mostUsed]; } while (i < 3) { if (Object.keys(copiedObj).length) { findCurrentMostFrequent(copiedObj); } i++; } return mostCommonWords; } // checks to see if any 'avoid' words (words the user wants to avoid) were used function checkWordsToAvoid(wordsToAvoidArr, allWordsUsedObj) { const wordsUsed = {}; wordsToAvoidArr.forEach((word) => { if (allWordsUsedObj[word]) { wordsUsed[word] = allWordsUsedObj[word]; } }); if (Object.keys(wordsUsed).length) { return wordsUsed; } return 'Congrats! You didn\'t use any of the words you were avoiding!'; } // make call to Words API export function getDefsAndSyns(word) { const datamuseAPI = `https://api.datamuse.com/words?max=5&rel_syn=${word}`; const wordsAPI = `https://wordsapiv1.p.mashape.com/words/${word}`; const response = {}; // get definitions and part of speech $.ajax({ url: wordsAPI, type: 'GET', async: false, success: (data) => { response.pos = data.results[0].partOfSpeech; response.def = data.results[0].definition; }, error: (err) => { throw new Error('There was an error making the GET request to the words API!', err); }, beforeSend: (xhr) => { xhr.setRequestHeader('X-Mashape-Key', wordsAPIKey); xhr.setRequestHeader('Accept', 'application/json'); }, }); // get synonyms $.ajax({ type: 'GET', url: datamuseAPI, async: false, dataType: 'JSON', success: (data) => { response.syns = data; }, error: (err) => { throw new Error('Error - ', err); }, }); return response; } // call helper functions to get analytics export function analyzeText(userTextInput, wordsToAvoid) { const analytics = {}; // word totals const totalOfEachWord = countEachWord(userTextInput); analytics.allTotals = totalOfEachWord; // words to avoid if (wordsToAvoid) { analytics.wordsNotAvoided = checkWordsToAvoid(wordsToAvoid, totalOfEachWord); } else { analytics.wordsNotAvoided = 'No words to avoid'; } // top used words const threeMostUsed = topThreeWords(totalOfEachWord); analytics.topThree = threeMostUsed; return analytics; }
JavaScript
0.999924
@@ -969,16 +969,21 @@ %5Cb%7Cand%5Cb +%7Cis%5Cb /;%0A%0A //
8214ee8fad439848f60ac2fcfa1cc7909285ef5b
fix blinking when toggling advanced
skins/base/views/templates/Login.js
skins/base/views/templates/Login.js
/* Copyright 2015 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require('react'); var ComponentBroker = require("../../../../src/ComponentBroker"); var MatrixClientPeg = require("../../../../src/MatrixClientPeg"); var ProgressBar = ComponentBroker.get("molecules/ProgressBar"); var Loader = require("react-loader"); var LoginController = require("../../../../src/controllers/templates/Login"); var ServerConfig = ComponentBroker.get("molecules/ServerConfig"); module.exports = React.createClass({ DEFAULT_HS_URL: 'https://matrix.org', DEFAULT_IS_URL: 'https://vector.im', displayName: 'Login', mixins: [LoginController], getInitialState: function() { return { serverConfigVisible: false }; }, componentWillMount: function() { this.onHSChosen(); this.customHsUrl = this.DEFAULT_HS_URL; this.customIsUrl = this.DEFAULT_IS_URL; }, getHsUrl: function() { if (this.state.serverConfigVisible) { return this.customHsUrl; } else { return this.DEFAULT_HS_URL; } }, getIsUrl: function() { if (this.state.serverConfigVisible) { return this.customIsUrl; } else { return this.DEFAULT_IS_URL; } }, onServerConfigVisibleChange: function(ev) { this.setState({ serverConfigVisible: ev.target.checked }, this.onHsUrlChanged); }, /** * Gets the form field values for the current login stage */ getFormVals: function() { return { 'username': this.refs.user.getDOMNode().value.trim(), 'password': this.refs.pass.getDOMNode().value.trim() }; }, onHsUrlChanged: function() { this.customHsUrl = this.refs.serverConfig.getHsUrl().trim(); this.customIsUrl = this.refs.serverConfig.getIsUrl().trim(); MatrixClientPeg.replaceUsingUrls( this.getHsUrl(), this.getIsUrl() ); this.setState({ hs_url: this.getHsUrl(), is_url: this.getIsUrl() }); // XXX: HSes do not have to offer password auth, so we // need to update and maybe show a different component // when a new HS is entered. if (this.updateHsTimeout) { clearTimeout(this.updateHsTimeout); } var self = this; this.updateHsTimeout = setTimeout(function() { self.onHSChosen(); }, 500); }, componentForStep: function(step) { switch (step) { case 'choose_hs': case 'fetch_stages': var serverConfigStyle = {}; serverConfigStyle.display = this.state.serverConfigVisible ? 'block' : 'none'; return ( <div> <input className="mx_Login_checkbox" id="advanced" type="checkbox" checked={this.state.serverConfigVisible} onChange={this.onServerConfigVisibleChange} /> <label className="mx_Login_label" htmlFor="advanced">Use custom server options (advanced)</label> <div style={serverConfigStyle}> <ServerConfig ref="serverConfig" defaultHsUrl={this.customHsUrl} defaultIsUrl={this.customIsUrl} onHsUrlChanged={this.onHsUrlChanged} /> </div> </div> ); // XXX: clearly these should be separate organisms case 'stage_m.login.password': return ( <div> <form onSubmit={this.onUserPassEntered}> <input className="mx_Login_field" ref="user" type="text" value={this.state.username} onChange={this.onUsernameChanged} placeholder="Email or user name" /><br /> <input className="mx_Login_field" ref="pass" type="password" value={this.state.password} onChange={this.onPasswordChanged} placeholder="Password" /><br /> { this.componentForStep('choose_hs') } <input className="mx_Login_submit" type="submit" value="Log in" /> </form> </div> ); } }, onUsernameChanged: function(ev) { this.setState({username: ev.target.value}); }, onPasswordChanged: function(ev) { this.setState({password: ev.target.value}); }, loginContent: function() { var loader = this.state.busy ? <div className="mx_Login_loader"><Loader /></div> : null; return ( <div> <h2>Sign in</h2> {this.componentForStep(this.state.step)} <div className="mx_Login_error"> { loader } {this.state.errorText} </div> <a className="mx_Login_create" onClick={this.showRegister} href="#">Create a new account</a> </div> ); }, render: function() { return ( <div className="mx_Login"> <div className="mx_Login_box"> <div className="mx_Login_logo"> <img src="img/logo.png" width="249" height="78" alt="vector"/> </div> {this.loginContent()} </div> </div> ); } });
JavaScript
0
@@ -2285,35 +2285,31 @@ ) %7B%0A -this.custom +var new HsUrl = this @@ -2350,35 +2350,31 @@ ();%0A -this.custom +var new IsUrl = this @@ -2403,32 +2403,267 @@ IsUrl().trim();%0A +%0A if (newHsUrl == this.customHsUrl &&%0A newIsUrl == this.customIsUrl)%0A %7B%0A return;%0A %7D%0A else %7B%0A this.customHsUrl = newHsUrl;%0A this.customIsUrl = newIsUrl;%0A %7D%0A%0A MatrixCl
5bb1dffd6cfca727cce6ec7cedc0258a175ea046
make it even possible to uncheck an option ...
source/assets/js/srf-form-fields.js
source/assets/js/srf-form-fields.js
export function init() { $(".radio-button, .checkbox").on("keypress", function (e) { // enable checking radios by tabbing in + <enter> if (e.keyCode === 13) { $(this).prop('checked', true); return false; } }); }
JavaScript
0
@@ -184,16 +184,32 @@ + var isChecked = $(this) @@ -227,14 +227,71 @@ ked' -, true +) ? false : true;%0A $(this).prop('checked', isChecked );%0A
8d208aa193f42b4edb6befd24403e707387da448
Update news-container.js
source/views/news/news-container.js
source/views/news/news-container.js
// @flow import React from 'react' import delay from 'delay' import type {StoryType} from './types' import LoadingView from '../components/loading' import {NoticeView} from '../components/notice' import type {TopLevelViewPropsType} from '../types' import {reportNetworkProblem} from '../../lib/report-network-problem' import {NewsList} from './news-list' import {fetchRssFeed, fetchWpJson} from './fetch-feed' export default class NewsContainer extends React.Component { props: TopLevelViewPropsType & { name: string, url: string, query?: Object, embedFeaturedImage?: boolean, mode: 'rss' | 'wp-json', thumbnail: number, } state: { entries: StoryType[], loading: boolean, refreshing: boolean, error: ?Error, } = { entries: [], loading: true, error: null, refreshing: false, } componentWillMount() { this.loadInitialData() } loadInitialData = async () => { await this.fetchData() this.setState(() => ({loading: false})) } fetchData = async () => { try { let entries: StoryType[] = [] if (this.props.mode === 'rss') { entries = await fetchRssFeed(this.props.url, this.props.query) } else if (this.props.mode === 'wp-json') { entries = await fetchWpJson(this.props.url, this.props.query) } else { throw new Error(`unknown mode ${this.props.mode}`) } this.setState(() => ({entries})) } catch (error) { if (error.message.startsWith('Unexpected token <')) { tracker.trackEvent('news', 'St. Olaf WPDefender strikes again') this.setState(() => ({ error: new Error( "Oops. Looks like we've triggered a St. Olaf website defense mechanism. Try again in 5 minutes.", ), })) } else { reportNetworkProblem(error) this.setState(() => ({error})) } } } refresh = async () => { let start = Date.now() this.setState(() => ({refreshing: true})) await this.fetchData() // wait 0.5 seconds – if we let it go at normal speed, it feels broken. let elapsed = Date.now() - start if (elapsed < 500) { await delay(500 - elapsed) } this.setState(() => ({refreshing: false})) } render() { if (this.state.error) { return <NoticeView text={`Error: ${this.state.error.message}`} /> } if (this.state.loading) { return <LoadingView /> } return ( <NewsList entries={this.state.entries} onRefresh={this.refresh} loading={this.state.refreshing} navigation={this.props.navigation} name={this.props.name} mode={this.props.mode} embedFeaturedImage={this.props.embedFeaturedImage} thumbnail={this.props.thumbnail} /> ) } }
JavaScript
0.000002
@@ -237,24 +237,64 @@ '../types'%0A +import %7Btracker%7D from '../../analytics'%0A import %7Brepo @@ -938,34 +938,8 @@ %7D%0A - %0A l
3051fa0f0967db9f29aa3bfb34296c2fb85fd46c
Add a test for getTopicListScreenParams
src/__tests__/baseSelectors-test.js
src/__tests__/baseSelectors-test.js
import deepFreeze from 'deep-freeze'; import { getCurrentRoute, getCurrentRouteParams, getTopMostNarrow } from '../baseSelectors'; import { streamNarrow } from '../utils/narrow'; describe('getCurrentRoute', () => { test('return name of the current route', () => { const state = deepFreeze({ nav: { index: 1, routes: [ { routeName: 'first', params: { email: 'a@a.com' } }, { routeName: 'second', params: { email: 'b@a.com' } }, ], }, }); const expectedResult = 'second'; const actualResult = getCurrentRoute(state); expect(actualResult).toEqual(expectedResult); }); }); describe('getCurrentRouteParams', () => { test('return "undefined" even when there is no data', () => { const state = deepFreeze({ nav: {}, }); const actualResult = getCurrentRouteParams(state); expect(actualResult).toBe(undefined); }); test('return params of the current route', () => { const state = deepFreeze({ nav: { index: 1, routes: [ { routeName: 'first', params: { email: 'a@a.com' } }, { routeName: 'second', params: { email: 'b@a.com' } }, ], }, }); const expectedResult = { email: 'b@a.com' }; const actualResult = getCurrentRouteParams(state); expect(actualResult).toEqual(expectedResult); }); }); describe('getTopMostNarrow', () => { test('return undefined if no chat screen are in stack', () => { const state = deepFreeze({ nav: { index: 0, routes: [{ routeName: 'main' }], }, }); expect(getTopMostNarrow(state)).toBe(undefined); }); test('return narrow of first chat screen from top', () => { const narrow = streamNarrow('all'); const state = deepFreeze({ nav: { index: 1, routes: [{ routeName: 'main' }, { routeName: 'chat', params: { narrow } }], }, }); expect(getTopMostNarrow(state)).toEqual(narrow); }); test('iterate over stack to get first chat screen', () => { const narrow = streamNarrow('all'); const state = deepFreeze({ nav: { index: 2, routes: [ { routeName: 'main' }, { routeName: 'chat', params: { narrow } }, { routeName: 'account' }, ], }, }); expect(getTopMostNarrow(state)).toEqual(narrow); }); });
JavaScript
0
@@ -40,16 +40,18 @@ import %7B +%0A getCurr @@ -59,16 +59,18 @@ ntRoute, +%0A getCurr @@ -84,16 +84,46 @@ eParams, +%0A getTopicListScreenParams,%0A getTopM @@ -127,25 +127,26 @@ opMostNarrow - +,%0A %7D from '../b @@ -1397,32 +1397,385 @@ lt);%0A %7D);%0A%7D);%0A%0A +describe('getTopicListScreenParams', () =%3E %7B%0A test('even when no params are passed do not return %22undefined%22', () =%3E %7B%0A const state = deepFreeze(%7B%0A nav: %7B%0A index: 0,%0A routes: %5B%7B routeName: 'topics' %7D%5D,%0A %7D,%0A %7D);%0A%0A const actualResult = getTopicListScreenParams(state);%0A%0A expect(actualResult).toBeDefined();%0A %7D);%0A%7D);%0A%0A describe('getTop
fe6b7c0ea2b3ad518d3bbd6f14dbec2c0a31103b
Improve _addMatrixClientListener docs
src/actions/MatrixActionCreators.js
src/actions/MatrixActionCreators.js
/* Copyright 2017 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import dis from '../dispatcher'; // TODO: migrate from sync_state to MatrixActions.sync so that more js-sdk events // become dispatches in the same place. /** * Create a MatrixActions.sync action that represents a MatrixClient `sync` event, * each parameter mapping to a key-value in the action. * * @param {MatrixClient} matrixClient the matrix client * @param {string} state the current sync state. * @param {string} prevState the previous sync state. * @returns {Object} an action of type MatrixActions.sync. */ function createSyncAction(matrixClient, state, prevState) { return { action: 'MatrixActions.sync', state, prevState, matrixClient, }; } /** * @typedef AccountDataAction * @type {Object} * @property {string} action 'MatrixActions.accountData'. * @property {MatrixEvent} event the MatrixEvent that triggered the dispatch. * @property {string} event_type the type of the MatrixEvent, e.g. "m.direct". * @property {Object} event_content the content of the MatrixEvent. */ /** * Create a MatrixActions.accountData action that represents a MatrixClient `accountData` * matrix event. * * @param {MatrixClient} matrixClient the matrix client. * @param {MatrixEvent} accountDataEvent the account data event. * @returns {AccountDataAction} an action of type MatrixActions.accountData. */ function createAccountDataAction(matrixClient, accountDataEvent) { return { action: 'MatrixActions.accountData', event: accountDataEvent, event_type: accountDataEvent.getType(), event_content: accountDataEvent.getContent(), }; } /** * This object is responsible for dispatching actions when certain events are emitted by * the given MatrixClient. */ export default { // A list of callbacks to call to unregister all listeners added _matrixClientListenersStop: [], /** * Start listening to certain events from the MatrixClient and dispatch actions when * they are emitted. * @param {MatrixClient} matrixClient the MatrixClient to listen to events from */ start(matrixClient) { this._addMatrixClientListener(matrixClient, 'sync', createSyncAction); this._addMatrixClientListener(matrixClient, 'accountData', createAccountDataAction); }, /** * Start listening to events emitted by matrixClient, dispatch an action created by the * actionCreator function. * @param {MatrixClient} matrixClient a MatrixClient to register a listener with. * @param {string} eventName the event to listen to on MatrixClient. * @param {function} actionCreator a function that should return an action to dispatch * when given the arguments emitted in the MatrixClient * event. */ _addMatrixClientListener(matrixClient, eventName, actionCreator) { const listener = (...args) => { dis.dispatch(actionCreator(matrixClient, ...args)); }; matrixClient.on(eventName, listener); this._matrixClientListenersStop.push(() => { matrixClient.removeListener(eventName, listener); }); }, /** * Stop listening to events. */ stop() { this._matrixClientListenersStop.forEach((stopListener) => stopListener()); }, };
JavaScript
0.000001
@@ -2901,32 +2901,75 @@ nts -emitted by matrixClient, +of type eventName on matrixClient and when they are emitted,%0A * dis @@ -2998,23 +2998,16 @@ d by the -%0A * actionC
1d5817e06c64f454f6dac1b7132c37f3d3ed52ab
set types in api
src/api/client-event-manager-api.js
src/api/client-event-manager-api.js
/** * Copyright 2019 The Subscribe with Google Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { AnalyticsEvent as AnalyticsEventDef, EventOriginator as EventOriginatorDef, } from '../proto/api_messages'; /** @enum {number} */ export const FilterResult = { /** The event is allowed to proceed to the listeners. */ PROCESS_EVENT: 0, /** The event is canceled and the listeners are not informed about it. */ CANCEL_EVENT: 1, }; /** * Defines a client event in SwG * Properties: * - eventType: Required. The AnalyticsEvent type that occurred. * - eventOriginator: Required. The codebase that initiated the event. * - isFromUserAction: Optional. True if the user took an action to generate * the event. * - additionalParameters: Optional. A JSON object to store generic data. * * @typedef {{ * eventType: ?AnalyticsEventDef, * eventOriginator: !EventOriginatorDef, * isFromUserAction: ?boolean, * additionalParameters: ?Object, * }} */ export let ClientEvent; /* eslint-disable no-unused-vars */ /** * @interface */ export class ClientEventManagerApi { /** * Call this function to log an event. The registered listeners will be * invoked unless the event is filtered. * @param {!function(!ClientEvent, ?ClientEventParams)} listener */ registerEventListener(listener) {} /** * Register a filterer for events if you need to potentially prevent the * listeners from hearing about it. A filterer should return * FilterResult.CANCEL_EVENT to prevent listeners from hearing about the * event. * @param {!function(!ClientEvent):FilterResult} filterer */ registerEventFilterer(filterer) {} /** * Call this function to log an event. It will immediately throw an error if * the event is invalid. It will then asynchronously call the filterers and * stop the event if a filterer cancels it. After that, it will call each * listener asynchronously. * @param {!ClientEvent} event * @param {Object} eventParams */ logEvent(event, eventParams) {} } /* eslint-enable no-unused-vars */ /** * Event Properties to handle for a specific event. For example, GA Event * properties to skip SwG logging but still be handled via callback. * @typedef {{ * googleAnalyticsParameters: ({ * eventCategory: string, * surveyQuestion: string, * surveyAnswerCategory: string, * eventLabel: string, * }|undefined) * }} */ export let ClientEventParams;
JavaScript
0
@@ -1807,17 +1807,17 @@ tEvent, -? +! ClientEv @@ -1825,16 +1825,17 @@ ntParams += )%7D liste @@ -2536,22 +2536,35 @@ @param %7B -Object +!ClientEventParams= %7D eventP
5b24945148c01fc5dcb579bb917a83c589a78e70
update gh-pages from README
bin/copyToGhPages.js
bin/copyToGhPages.js
var exec = require('child_process').exec; queue([checkoutPage, getBack, commit, checkoutMaster]); function queue (fns) { // Execute and remove the first function. var fn = fns.shift(); fn(function (err) { if (!err) { if (fns.length) { // If we still have functions // we continue queue(fns); } else { // We exist if we've finished process.exit(0); } } else { // We log if we have an error. console.error(fn.name + ': ', err); process.exit(1); } }); } function checkoutPage (next) { console.log(' - checkout gh-pages.'); exec('git checkout gh-pages', next); } function getBack (next) { console.log(' - checkout built file from master and move it.'); exec('git checkout master ./dist/nipplejs.js && ' + 'git reset ./dist/nipplejs.js && ' + 'mv ./dist/nipplejs.js ./javascripts/', next); } function commit (next) { console.log(' - commit latest build to gh-pages.'); exec('git add ./javascripts/nipplejs.js && ' + 'git commit -m "chore: new build" && ' + 'git push origin gh-pages', next); } function checkoutMaster (next) { console.log(' - checkout master.'); exec('git checkout master', next); }
JavaScript
0.000002
@@ -34,16 +34,40 @@ ').exec; +%0Avar fs = require('fs'); %0A%0Aqueue( @@ -89,16 +89,28 @@ getBack, + modifyFile, commit, @@ -851,18 +851,14 @@ out -built file +README fro @@ -874,16 +874,29 @@ and -move it. +rename it to index.md ');%0A @@ -925,34 +925,28 @@ master -./dist/nipplejs.js +-- README.md && ' +%0A @@ -964,34 +964,25 @@ t reset -./dist/nipplejs.js +README.md && ' +%0A @@ -997,56 +997,466 @@ 'mv -./dist/nipplejs.js ./javascripts/',%0A next +README.md index.md',%0A next);%0A%7D%0A%0Afunction modifyFile (next) %7B%0A console.log(' - reading the new index.md');%0A fs.readFile('index.md', function (err, data) %7B%0A if (err) %7B%0A next(err);%0A return;%0A %7D%0A console.log(' - writing the new content for Jekyll');%0A var body = data.split('%5Cn');%0A body.splice(0, 3, '---', 'layout: index', '---');%0A fs.writeFile('index.md', body.join('%5Cn'), next);%0A %7D );%0A%7D @@ -1516,21 +1516,19 @@ latest -build +doc to gh-p @@ -1523,33 +1523,32 @@ doc to gh-pages -. ');%0A exec('gi @@ -1557,33 +1557,16 @@ add -./javascripts/nipplejs.js +index.md && @@ -1597,24 +1597,30 @@ -m %22 -chore: new build +docs: sync from master %22 &&
26a9878c49801f1d049cd7b229ebae6eaaf0acd2
add customer role fixture
bin/load-fixtures.js
bin/load-fixtures.js
#!/usr/bin/env babel-node import { syncDB } from '../src/model-helpers'; import { loadFixtures } from '../test/helpers'; const fixtures = [ 'systems.json', 'customers.json' ]; syncDB() .then(() => loadFixtures(fixtures)) .then(() => { console.log('Loaded fixtures!'); process.exit(0); }) .catch(err => { console.log(err); process.exit(1); });
JavaScript
0
@@ -155,16 +155,43 @@ .json',%0A + 'customer-roles.json',%0A 'cus
a9e10209eddc194b4b4ccc37bd610d69761b03ec
Update config in monitor bin
bin/storj-monitor.js
bin/storj-monitor.js
#!/usr/bin/env node 'use strict'; const program = require('commander'); const Config = require('../lib/config'); const Monitor = require('../lib/monitor'); program.version(require('../package').version); program.option('-c, --config <path_to_config_file>', 'path to the config file'); program.parse(process.argv); var config = new Config(process.env.NODE_ENV || 'develop', program.config, program.datadir); var monitor = new Monitor(config); monitor.start(function(err) { if (err) { console.log(err); } }); module.exports = monitor;
JavaScript
0.000001
@@ -98,16 +98,24 @@ '../lib/ +monitor/ config') @@ -350,71 +350,19 @@ (pro -cess.env.NODE_ENV %7C%7C 'develop', program.config, program.datadir +gram.config );%0Av
939581e4dfa76924a54caa537353846587e05668
Fix attempt
api/models/Dimmer.js
api/models/Dimmer.js
var _ = require('lodash') var Device = require('./Device') module.exports = _.merge(_.cloneDeep(Device), { attributes: { getStatus: function () { return new Promise((resolve, reject) => { this.insteonClient().level() .then((result) => { if (result !== undefined && result !== null && result !== '') { var level = parseInt(result) var status = (level === 0 ? 'off' : 'on') console.log(`[${this.insteonId}] Dimmer is at ${level}%`) resolve({ status: status, level: level }) } else { reject(new Error(`Unable to get status for dimmer ${this.insteonId}`)) } }, reason => { reject(reason) }) }) }, refresh: function () { this.insteonClient().level() .then((result) => { if (result !== undefined && result !== null && result !== '') { var level = parseInt(result) var status = (level === 0 ? 'off' : 'on') console.log(`[${this.insteonId}] Dimmer is at ${level}%`) this.sendSmartThingsUpdate({ command: 'refresh', status: status, level: level }) } else { console.log(`Unable to get status for dimmer ${this.insteonId}`) } }, reason => { console.log(`Error getting status for dimmer ${this.insteonId}`) }) }, turnOn: function () { this.insteonClient().turnOn() .then((result) => { if (result.response) { console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`) this.sendSmartThingsUpdate({ command: 'turn_on', status: 'on', level: '100' }) } else { console.log(`Unable to turn on dimmer ${this.insteonId}`) } }, reason => { console.log(`Error turning on dimmer ${this.insteonId}`) }) }, turnOff: function () { this.insteonClient().turnOff() .then((result) => { if (result.response) { console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`) this.sendSmartThingsUpdate({ command: 'turn_off', status: 'off', level: 0 }) } else { console.log(`Unable to turn off dimmer ${this.insteonId}`) } }, reason => { console.log(`Error turning off dimmer ${this.insteonId}`) }) }, setLevel: function (level) { this.insteonClient().level(level) .then((result) => { if (result.response) { console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`) var status = level === 0 ? 'off' : 'on' this.sendSmartThingsUpdate({ command: 'set_level', status: status, level: level }) } else { console.log(`Unable to set level for dimmer ${this.insteonId}`) } }, reason => { console.log(`Error setting level for dimmer ${this.insteonId}`) }) }, brighten: function () { this.insteonClient().brighten() .then((result) => { if (result.response) { console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`) this.sendSmartThingsUpdate({ command: 'brighten' }) } else { console.log(`Unable to brighten dimmer ${this.insteonId}`) } }, reason => { console.log(`Error brightening dimmer ${this.insteonId}`) }) }, dim: function () { this.insteonClient().dim() .then((result) => { if (result.response) { console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`) } else { console.log(`Unable to lower dimmer ${this.insteonId}`) this.sendSmartThingsUpdate({ command: 'dim' }) } }, reason => { console.log(`Error lowering dimmer ${this.insteonId}`) }) }, subscribeEvents: function () { console.log(`[${this.insteonId}] Subscribing to dimmer events...`) var light = this.insteonClient() light.on('turnOn', (group, level) => { console.log(`[${this.insteonId}] Dimmer turned ON`) if (level === null) { this.getStatus() .then((result) => { this.sendSmartThingsUpdate({ event: 'turn_on', status: result['status'], level: result['level'] }) }, reason => { this.sendSmartThingsUpdate({ event: 'turn_on', status: 'on' }) }) } else { this.sendSmartThingsUpdate({ event: 'turn_on', status: 'on', level: level }) } }) light.on('turnOnFast', (group) => { console.log(`[${this.insteonId}] Dimmer turned ON FAST`) this.sendSmartThingsUpdate({ event: 'turn_on_fast', status: 'on', level: 100 }) }) light.on('turnOff', (group) => { console.log(`[${this.insteonId}] Dimmer turned OFF`) this.sendSmartThingsUpdate({ event: 'turn_off', status: 'off', level: 0 }) }) light.on('turnOffFast', (group) => { console.log(`[${this.insteonId}] Dimmer turned OFF FAST`) this.sendSmartThingsUpdate({ event: 'turn_off_fast', status: 'off', level: 0 }) }) light.on('brightening', (group) => { console.log(`[${this.insteonId}] Dimmer brightening`) this.sendSmartThingsUpdate({ event: 'brightening' }) }) light.on('brightened', (group) => { console.log(`[${this.insteonId}] Dimmer brightened`) this.getStatus() .then((result) => { this.sendSmartThingsUpdate({ event: 'brightened', status: result['status'], level: result['level'] }) }, reason => { this.sendSmartThingsUpdate({ event: 'brightened' }) }) }) light.on('dimming', (group) => { console.log(`[${this.insteonId}] Dimmer dimming`) this.sendSmartThingsUpdate({ event: 'dimming' }) }) light.on('dimmed', (group) => { console.log(`[${this.insteonId}] Dimmer dimmed`) this.sendSmartThingsUpdate({ event: 'dimmed' }) this.getStatus() .then((result) => { this.sendSmartThingsUpdate({ event: 'dimmed', status: result['status'], level: result['level'] }) }, reason => { this.sendSmartThingsUpdate({ event: 'dimmed' }) }) }) console.log(`[${this.insteonId}] Subscribed to dimmer events`) }, startPolling: function () { this.refresh() setInterval(() => { this.refresh() }, this.refreshSeconds * 1000) } }, beforeValidate: function (attrs, cb) { attrs.type = 'dimmer' cb() } })
JavaScript
0.000014
@@ -2627,16 +2627,17 @@ tatus = +( level == @@ -2654,16 +2654,17 @@ ' : 'on' +) %0A
0290789e839c7b8274045c8a738c8e427ee53993
define model
api/models/Module.js
api/models/Module.js
/** * Module.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/#!documentation/models */ module.exports = { attributes: { } };
JavaScript
0.000007
@@ -221,16 +221,510 @@ tes: %7B%0A%0A + title: %7B%0A type: 'string',%0A required: true%0A %7D,%0A%0A services: %7B%0A type: 'array',%0A required: true,%0A enum: %5B%0A 'alert',%0A 'automation',%0A 'geolocation',%0A 'mail',%0A 'multimedia',%0A 'news',%0A 'update',%0A 'weather'%0A %5D%0A %7D,%0A%0A protocol: %7B%0A type: 'string',%0A required: true,%0A enum: %5B%0A 'rest',%0A 'zwave'%0A %5D%0A %7D %0A%0A active: %7B%0A type: 'boolean',%0A defaultsTo: true%0A %7D%0A%0A %7D%0A%7D;%0A%0A
77b63d0177862139f250b9803c0c625f70b5558b
Fix missing TTA times crashing departures route (api)
api/providers/tta.js
api/providers/tta.js
const got = require('got'); const time = require('../utils/time.js'); const cache = require('../utils/cache.js'); const log = require('../utils/log.js'); /* Stops */ async function updateCache(id) { try { const body = (await got('https://transport.tallinn.ee/siri-stop-departures.php?stopid=' + id, { timeout: 1000, retry: 1 })).body; if (body.indexOf('ERROR') > -1) throw new Error('Invalid response'); return body.split('\n').map((line) => line.split(',')).slice(2, -1).map((departure) => ({ name: departure[1], type: departure[0], time: Number(departure[3]), countdown: Number(departure[2] - 5) })); } catch (ex) { log.warn`Failed to fetch TTA departures.${ex}`; return null; } } // Get trips for stop. async function getStopDepartures(id, mntDepartures) { const ttaDepartures = await cache.use('tta', id, updateCache.bind(this, id)); const departures = []; // Asynchronously fetch future TTA departures. cache.use('tta', id, updateCache.bind(this, id)); // Merge MNT departures with TTA departures if available. for (const mntDeparture of mntDepartures) { // Add coach departure. if (mntDeparture.type.startsWith('coach')) { departures.push(mntDeparture); continue; } // Try to match departures. const ttaDeparture = ttaDepartures.find((departure) => departure.name === mntDeparture.name && departure.type === mntDeparture.type && Math.abs(departure.time - mntDeparture.time) < 60); // Add (matched) departure. if (ttaDeparture) departures.push({ ...mntDeparture, time: ttaDeparture.time, countdown: ttaDeparture.countdown - time.getSeconds(), live: ttaDeparture.time !== ttaDeparture.countdown + 5, provider: 'tta' }); else departures.push(mntDeparture); } return departures.filter((departure) => departure.countdown > 0).sort((prevDeparture, nextDeparture) => prevDeparture.countdown - nextDeparture.countdown); } module.exports = { getStopDepartures };
JavaScript
0.000203
@@ -371,44 +371,91 @@ -1) -throw new Error('Invalid response'); +%7B%0A%09%09%09log.warn%60Failed to fetch TTA departures.$%7Bnew Error(body)%7D%60;%0A%09%09%09return %5B%5D;%0A%09%09%7D %0A%09%09%0A @@ -748,12 +748,10 @@ urn -null +%5B%5D ;%0A%09%7D
4c28169bdb165d820c267967db7dee3d32f2b88e
Remove leftover TTA code (api)
api/providers/tta.js
api/providers/tta.js
const got = require('got'); const time = require('../utils/time.js'); const debug = require('../utils/debug.js'); // Get trips for stop. async function getStopDepartures(id, mntDepartures) { let ttaDepartures = []; let departures = []; try { ttaDepartures = (await got('https://transport.tallinn.ee/siri-stop-departures.php?stopid=' + id, { timeout: 600, retry: 1 })).body.split('\n').map((line) => line.split(',')).slice(2).map((departure) => ({ name: departure[1], type: departure[0], time: Number(departure[3]), countdown: Number(departure[2]) })); } catch (ex) { debug.warn('Failed to fetch TTA data.', ex); } // Merge MNT trips with TTA trips if available. if (ttaDepartures.length) for (const mntDeparture of mntDepartures) { // Add coach trip. if (mntDeparture.type.startsWith('coach') && mntDeparture.countdown > 0) { departures.push(mntDeparture); continue; } // Add matched trip. const ttaTime = ttaDepartures.find((departure, i) => { if (departure.name !== mntDeparture.name || departure.type !== mntDeparture.type || Math.abs(departure.time - mntDeparture.time) > 60) return false; // ttaDepartures.splice(i, 1); return true; }); if (!ttaTime) continue; departures.push({ ...mntDeparture, time: ttaTime.time, countdown: ttaTime.countdown - time.getSeconds(), live: ttaTime.time !== ttaTime.countdown, provider: 'tta' }); } else departures = mntDepartures.filter((trip) => trip.countdown > 0); // Sort merged trips by countdown. return departures.sort((prevDeparture, nextDeparture) => prevDeparture.countdown - nextDeparture.countdown); } module.exports = { getStopDepartures };
JavaScript
0
@@ -982,25 +982,13 @@ ture -, i ) =%3E -%7B%0A%09%09%09if ( depa @@ -998,19 +998,19 @@ re.name -! == += mntDepa @@ -1020,18 +1020,18 @@ re.name -%7C%7C +&& departu @@ -1038,17 +1038,17 @@ re.type -! += == mntDe @@ -1064,10 +1064,10 @@ ype -%7C%7C +&& Mat @@ -1112,90 +1112,14 @@ me) -%3E +%3C 60) - return false;%0A%09%09%09%0A%09%09%09// ttaDepartures.splice(i, 1);%0A%09%09%09return true;%0A%09%09%7D);%0A%09%09 +; %0A%09%09i
e06d72d3ede08b786e06c734f2ecd8ff592e60b5
Refactor to inline value search
lib/node_modules/@stdlib/types/ndarray/base/assert/is-order/lib/main.js
lib/node_modules/@stdlib/types/ndarray/base/assert/is-order/lib/main.js
'use strict'; // MODULES // var indexOf = require( '@stdlib/utils/index-of' ); var orders = require( '@stdlib/types/ndarray/base/orders' ); // VARIABLES // var ORDERS = orders(); // MAIN // /** * Tests whether an input value is an ndarray order. * * @param {*} v - value to test * @returns {boolean} boolean indicating whether an input value is an ndarray order * * @example * var bool = isOrder( 'row-major' ); * // returns true * * bool = isOrder( 'column-major' ); * // returns true * * bool = isOrder( 'foo' ); * // returns false */ function isOrder( v ) { return ( indexOf( ORDERS, v ) !== -1 ); } // end FUNCTION isOrder() // EXPORTS // module.exports = isOrder;
JavaScript
0
@@ -27,59 +27,8 @@ //%0A%0A -var indexOf = require( '@stdlib/utils/index-of' );%0A var @@ -126,16 +126,41 @@ ders();%0A +var len = ORDERS.length;%0A %0A%0A// MAI @@ -541,46 +541,111 @@ %7B%0A%09 -return ( indexOf( ORDERS, v ) !== -1 ) +var i;%0A%09for ( i = 0; i %3C len; i++ ) %7B%0A%09%09if ( v === ORDERS%5B i %5D ) %7B%0A%09%09%09return true;%0A%09%09%7D%0A%09%7D%0A%09return false ;%0A%7D
d68e34a30f326aa411f69ef5e51b387e47d2c1d3
Update videos.js
api/v3.0.0/videos.js
api/v3.0.0/videos.js
/** * Copyright 2013 Ionică Bizău * * A Node.JS module, which provides an object oriented wrapper for the Youtube v3 API. * Author: Ionică Bizău <bizauionica@gmail.com> * **/ var Util = require("../../util"); var querystring = require("querystring"); function getRating (options, callback) { var self = this; var url = Util.createUrl.apply(self, ["videos/getRating", options]); var reqOptions = { url: url }; self.Client.request(reqOptions, callback); } function list (options, callback) { var self = this; var url = Util.createUrl.apply(self, ["videos", options]); var reqOptions = { url: url }; self.Client.request(reqOptions, callback); } function comments (options, callback) { var self = this; var url = 'https://gdata.youtube.com/feeds/api/videos/'; var reqOptions = { url: url + options.videoId + '/comments?' + querystring.stringify(options) }; self.Client.request(reqOptions, callback); } function insert (options, callback) { callback(null, {"error": "Not yet implemented"}); } function update (options, callback) { callback(null, {"error": "Not yet implemented"}); } function deleteItem (options, callback) { callback(null, {"error": "Not yet implemented"}); } function rate (options, callback) { callback(null, {"error": "Not yet implemented"}); } module.exports = { getRating: getRating, list: list, comments: comments, insert: insert, update: update, delete: deleteItem, rate: rate };
JavaScript
0
@@ -767,186 +767,135 @@ var -self%09= this;%0A%09var url%09%09= 'https://gdata.youtube.com/feeds/api/videos/';%0A%0A var reqOptions = %7B%0A url: url + options.videoId + '/comments?' + querystring.stringify(options) +action = 'commentThreads';%0A var url = Util.createUrl.apply(this, %5Baction, options%5D);%0A var reqOptions = %7B%0A url: url %0A @@ -895,36 +895,36 @@ url%0A %7D;%0A%0A -self +this .Client.request(
224a1584e445c038a11dd761698fccf2c649f564
Remove react-tap-event-plugin
src/components/App.js
src/components/App.js
require('styles/normalize.css') require('styles/_colors.scss') require('styles/_utils.scss') require('styles/_layout.scss') require('styles/App.scss') import React from 'react' import injectTapEventPlugin from 'react-tap-event-plugin' import TopMenu from 'components/organisms/top_menu/TopMenu' import Sidebar from 'components/organisms/sidebar/Sidebar' import Main from 'components/organisms/main/Main' injectTapEventPlugin() class AppComponent extends React.Component { render() { return ( <div id='app' className='app'> <TopMenu /> <div className='row full-height'> <Main /> <Sidebar /> </div> </div> ) } } AppComponent.defaultProps = { } export default AppComponent
JavaScript
0.000005
@@ -175,66 +175,8 @@ ct'%0A -import injectTapEventPlugin from 'react-tap-event-plugin'%0A impo @@ -345,32 +345,8 @@ n'%0A%0A -injectTapEventPlugin()%0A%0A clas
8eea7c5ea9eb904fb836dbda907fa01ff7de1698
move import to top
app/pubsub-listener.js
app/pubsub-listener.js
import Promise from 'bluebird' import { createClient as redis } from 'redis' import _ from 'lodash' import IoSever from 'socket.io' import models from './models' import config_loader from '../config/config' export default class PubsubListener { constructor(server, app) { "use strict"; var io = IoSever(server) var config = config_loader.load() var adapter = require('socket.io-redis') , redisPub = redis(config.redis.port, config.redis.host, config.redis.options) , redisSub = redis(config.redis.port, config.redis.host, _.extend(config.redis.options, { detect_buffers: true })) redisPub.on('error', function(err) { console.log(err) }) redisSub.on('error', function(err) { console.log(err) }) io.adapter(adapter({ pubClient: redisPub, subClient: redisSub })) io.sockets.on('connection', function(socket) { socket.on('subscribe', function(data) { for(var channel in data) { if (data[channel]) { data[channel].forEach(function(id) { if (id) { app.logger.info('User has subscribed to ' + id + ' ' + channel) socket.join(channel + ':' + id) } }) } } }) socket.on('unsubscribe', function(data) { for(var channel in data) { if (data[channel]) { data[channel].forEach(function(id) { if (id) { app.logger.info('User has disconnected from ' + id + ' ' + channel) socket.leave(channel + ':' + id) } }) } } }) }) var channels = redis(config.redis.port, config.redis.host, {}) channels.on('error', function(err) { console.log(err) }) channels.subscribe('post:new', 'post:destroy', 'post:update', 'comment:new', 'comment:destroy', 'comment:update', 'like:new', 'like:remove', 'post:hide', 'post:unhide' ) // TODO: extract to separate functions channels.on('message', function(channel, msg) { switch(channel) { case 'post:destroy': var data = JSON.parse(msg) var event = { meta: { postId: data.postId } } io.sockets.in('timeline:' + data.timelineId).emit('post:destroy', event) io.sockets.in('post:' + data.postId).emit('post:destroy', event) break case 'post:new': var data = JSON.parse(msg) models.Post.findById(data.postId) .then(function(post) { new models.PostSerializer(post).toJSON(function(err, json) { io.sockets.in('timeline:' + data.timelineId).emit('post:new', json) }) }) break case 'post:update': var data = JSON.parse(msg) models.Post.findById(data.postId) .then(function(post) { new models.PostSerializer(post).toJSON(function(err, json) { io.sockets.in('timeline:' + data.timelineId).emit('post:update', json) io.sockets.in('post:' + data.postId).emit('post:update', json) }) }) break case 'comment:new': var data = JSON.parse(msg) models.Comment.findById(data.commentId) .then(function(comment) { new models.PubsubCommentSerializer(comment).toJSON(function(err, json) { if (data.timelineId) { io.sockets.in('timeline:' + data.timelineId).emit('comment:new', json) } else { io.sockets.in('post:' + data.postId).emit('comment:new', json) } }) }) break case 'comment:update': var data = JSON.parse(msg) models.Comment.findById(data.commentId) .then(function(comment) { new models.PubsubCommentSerializer(comment).toJSON(function(err, json) { if (data.timelineId) { io.sockets.in('timeline:' + data.timelineId).emit('comment:update', json) } else { io.sockets.in('post:' + data.postId).emit('comment:update', json) } }) }) break case 'comment:destroy': var data = JSON.parse(msg) var event = { postId: data.postId, commentId: data.commentId } io.sockets.in('post:' + data.postId).emit('comment:destroy', event) models.Post.findById(data.postId) .then(function(post) { return post.getTimelineIds() }) .then(function(timelineIds) { return Promise.map(timelineIds, function(timelineId) { return io.sockets.in('timeline:' + timelineId).emit('comment:destroy', event) }) }) break case 'like:new': var data = JSON.parse(msg) models.User.findById(data.userId) .then(function(user) { new models.LikeSerializer(user).toJSON(function(err, json) { var event = json event.meta = { postId: data.postId } if (data.timelineId) { io.sockets.in('timeline:' + data.timelineId).emit('like:new', event) } else { io.sockets.in('post:' + data.postId).emit('like:new', event) } }) }) break case 'like:remove': var data = JSON.parse(msg) var event = { meta: { userId: data.userId, postId: data.postId } } if (data.timelineId) io.sockets.in('timeline:' + data.timelineId).emit('like:remove', event) else io.sockets.in('post:' + data.postId).emit('like:remove', event) break case 'post:hide': // NOTE: posts are hidden only on RiverOfNews timeline so this // event won't leak any personal information var data = JSON.parse(msg) var event = { meta: { postId: data.postId } } io.sockets.in('timeline:' + data.timelineId).emit('post:hide', event) break case 'post:unhide': // NOTE: posts are hidden only on RiverOfNews timeline so this // event won't leak any personal information var data = JSON.parse(msg) var event = { meta: { postId: data.postId } } io.sockets.in('timeline:' + data.timelineId).emit('post:unhide', event) break } }) } }
JavaScript
0
@@ -124,16 +124,54 @@ cket.io' +%0Aimport adapter from 'socket.io-redis' %0A%0Aimport @@ -404,53 +404,8 @@ var - adapter = require('socket.io-redis')%0A , red
faec926aa46f4e0a74e42c5e08b080ba657db1b0
Save credentials as base64
src/components/App.js
src/components/App.js
import {h, Component} from 'preact' import * as outline from '../outline' import {parse, stringify} from '../doclist' import GitHub, {extractGistInfo} from '../github' import History from '../history' import {ToolbarButton} from './Toolbar' import MenuPanel from './MenuPanel' import DocumentView from './DocumentView' import BusyScreen from './BusyScreen' export default class App extends Component { history = new History() state = { busy: [], changed: false, user: null, showMenu: true, currentIndex: 0, docs: [], selectedIds: [] } constructor() { super() this.recordHistory() } componentDidMount() { // Auto login let credentials = JSON.parse(localStorage.getItem('acinoprst_credentials')) if (credentials != null) this.login(credentials) } pull = () => { return this.client.getGist(this.gistId).then(gist => { let filename = Object.keys(gist.files)[0] return this.client.getGistFileContent(gist, filename).then(content => { return {gist, filename, content} }) }) .then(({gist, filename, content}) => { this.gistFilename = filename this.setState({ user: { avatar: gist.owner.avatar_url, name: gist.owner.login } }) this.updateDocs({docs: parse(content)}) this.setState({changed: false}) }) } push = () => { return this.client.editGist(this.gistId, { files: { [this.gistFilename]: { content: stringify(this.state.docs) } } }).then(() => { this.setState({changed: false}) }) } login = ({gistUrl, accessToken}) => { this.startBusy() localStorage.setItem('acinoprst_credentials', JSON.stringify({gistUrl, accessToken})) return Promise.resolve().then(() => { let {id, user, host} = extractGistInfo(gistUrl) this.client = new GitHub({host, user, pass: accessToken}) this.gistId = id }).then(() => { return this.pull() }).then(() => { this.updateCurrentIndex({currentIndex: 0}) this.history.clear() this.recordHistory() }).catch(err => { alert(`Login failed.\n\n${err}`) this.logout() }) .then(() => this.endBusy()) } logout = () => { localStorage.removeItem('acinoprst_credentials') this.client = null this.setState({user: null, docs: []}) } pullClick = () => { this.startBusy('pull') return this.pull().catch(err => { alert(`Loading of gist failed.\n\n${err}`) }) .then(() => this.endBusy()) } pushClick = () => { this.startBusy('push') return this.push().catch(err => { alert(`Updating gist failed.\n\n${err}`) }).then(() => { this.endBusy() }) } startBusy = type => { this.setState(s => ({busy: (s.busy.push(type), s.busy)})) } endBusy = () => { this.setState(s => ({busy: (s.busy.pop(), s.busy)})) } getCurrentDoc = () => { let {docs, currentIndex} = this.state return docs[currentIndex] } recordHistory = () => { this.history.push({...this.state}) } stepInHistory = step => { let entry = this.history.step(step) if (entry == null) return let {currentIndex, docs, selectedIds} = entry this.setState({currentIndex, docs, selectedIds}) } undo = () => this.stepInHistory(-1) redo = () => this.stepInHistory(1) showMenu = () => { this.setState({showMenu: true}) } hideMenu = () => { this.setState({showMenu: false}) } updateDocs = ({docs}) => { if (docs === this.state.docs) return this.setState({docs, changed: true}) this.recordHistory() } updateCurrentIndex = ({currentIndex}) => { if (currentIndex === this.state.currentIndex) return let currentDoc = this.state.docs[currentIndex] this.setState({ currentIndex, selectedIds: currentDoc == null ? [] : currentDoc.list.slice(0, 1).map(item => item.id) }) this.recordHistory() } updateSelectedIds = ({selectedIds}) => { this.setState({selectedIds}) } updateDoc = ({doc}) => { let {docs, currentIndex} = this.state this.updateDocs({docs: docs.map((x, i) => i === currentIndex ? doc : x)}) } removeDoc = () => { let {docs, currentIndex} = this.state let result = confirm('Do you really want to remove this document?') if (!result) return this.updateDocs({docs: docs.filter((_, i) => i !== currentIndex)}) this.updateCurrentIndex({currentIndex: Math.max(0, currentIndex - 1)}) } handleDocumentClick = ({index}) => { this.updateCurrentIndex({currentIndex: index}) this.hideMenu() } render() { let doc = this.getCurrentDoc() return <section id="app"> <MenuPanel user={this.state.user} show={this.state.showMenu} docs={this.state.docs} currentIndex={this.state.currentIndex} onDocumentClick={this.handleDocumentClick} onDocumentsChange={this.updateDocs} onLogin={this.login} onLogout={this.logout} /> <DocumentView disabled={doc == null || this.state.user == null} doc={doc || {title: '', list: []}} selectedIds={this.state.selectedIds} undoable={this.history.isUndoable()} redoable={this.history.isRedoable()} headerButtons={[ <ToolbarButton key="pull" type={this.state.busy.includes('pull') && 'sync'} icon={`./img/${this.state.busy.includes('pull') ? 'sync' : 'down'}.svg`} text="Pull" onClick={this.pullClick} />, this.state.changed && <ToolbarButton key="push" type={this.state.busy.includes('push') && 'sync'} icon={`./img/${this.state.busy.includes('push') ? 'sync' : 'up'}.svg`} text="Push" onClick={this.pushClick} />, <ToolbarButton key="remove" icon="./img/trash.svg" text="Remove" onClick={this.removeDoc} /> ]} onMenuButtonClick={this.showMenu} onChange={this.updateDoc} onSelectionChange={this.updateSelectedIds} onUndo={this.undo} onRedo={this.redo} /> <BusyScreen show={this.state.busy.length > 0}/> </section> } }
JavaScript
0.000002
@@ -752,19 +752,8 @@ s = -JSON.parse( loca @@ -793,17 +793,16 @@ ntials') -) %0A @@ -838,16 +838,32 @@ s.login( +JSON.parse(atob( credenti @@ -866,16 +866,18 @@ entials) +)) %0A %7D%0A%0A @@ -1981,16 +1981,21 @@ tials', +btoa( JSON.str @@ -2025,16 +2025,17 @@ Token%7D)) +) %0A%0A
a2233ee2f02b6ae3e67682503bbe688b0338859d
Add ability to sign in with Google
src/components/App.js
src/components/App.js
import firebase from 'firebase'; import React from 'react'; import styled from 'styled-components'; import ChallengeImportForm from './ChallengeImportForm'; import ChallengeList from './ChallengeList'; import Header from './Header'; import request from '../utils/request'; const Content = styled.main` margin: 0 auto; max-width: 45rem; padding-top: 2rem; `; export default class App extends React.Component { state = { challenges: [], url: '', }; componentDidMount() { this.challengesRef = firebase.database().ref('challenges'); this.challengesRef.on('value', (snapshot) => { const challenges = snapshot.val() || {}; this.setState({ challenges: Object.values(challenges), }); }); } componentWillUnmount() { this.challengesRef.off(); } handleSubmit = async (event) => { event.preventDefault(); try { const [, slug] = this.state.url.match(/codewars.com\/kata\/([^/]+)/i); const data = await request(`/codewars/code-challenges/${slug}`); if (!this.state.challenges.find(challenge => challenge.id === data.id)) { const { description, id, name, rank, tags, url } = data; const challenge = { createdAt: firebase.database.ServerValue.TIMESTAMP, description, id, name, points: rank.name, tags, url, }; this.challengesRef.push(challenge); this.setState({ url: '', }); } } catch (error) { console.log(error.message); } } handleChange = (event) => { this.setState({ [event.target.name]: event.target.value, }); } render() { return ( <div> <Header /> <Content> <ChallengeImportForm handleChange={this.handleChange} handleSubmit={this.handleSubmit} url={this.state.url} /> <ChallengeList challenges={this.state.challenges} /> </Content> </div> ); } }
JavaScript
0
@@ -462,416 +462,1132 @@ ,%0A -%7D;%0A%0A componentDidMount() %7B%0A this.challengesRef = firebase.database().ref('challenges');%0A this.challengesRef.on('value', (snapshot) =%3E %7B%0A const challenges = snapshot.val() %7C%7C %7B%7D;%0A this.setState(%7B%0A challenges: Object.values(challenges),%0A %7D);%0A %7D);%0A %7D%0A%0A componentWillUnmount() %7B%0A this.challengesRef.off();%0A %7D%0A%0A handleSubmit = async (event) =%3E %7B%0A event.preventDefault();%0A + user: null,%0A %7D;%0A%0A setUser(user) %7B // eslint-disable-line react/sort-comp%0A if (/umich%5C.edu$/i.test(user.email)) %7B%0A const %7B displayName, email, photoURL, uid %7D = user;%0A this.setState(%7B%0A user: %7B displayName, email, photoURL, uid %7D,%0A %7D);%0A %7D else %7B%0A console.log('You must be part of the %22umich.edu%22 domain to use this app.');%0A %7D%0A %7D%0A%0A componentDidMount() %7B%0A this.challengesRef = firebase.database().ref('challenges');%0A this.challengesRef.on('value', (snapshot) =%3E %7B%0A const challenges = snapshot.val() %7C%7C %7B%7D;%0A this.setState(%7B%0A challenges: Object.values(challenges),%0A %7D);%0A %7D);%0A%0A this.auth = firebase.auth();%0A this.auth.onAuthStateChanged((user) =%3E %7B%0A if (user) %7B%0A this.setUser(user);%0A %7D%0A %7D);%0A %7D%0A%0A componentWillUnmount() %7B%0A this.challengesRef.off();%0A %7D%0A%0A async signIn() %7B%0A try %7B%0A const google = new firebase.auth.GoogleAuthProvider();%0A const %7B user %7D = await this.auth.signInWithPopup(google);%0A this.setUser(user);%0A %7D catch (error) %7B%0A console.log(error.message);%0A %7D%0A %7D%0A%0A async importChallenge() %7B %0A @@ -2274,16 +2274,258 @@ %7D%0A %7D%0A%0A + handleSubmit = async (event) =%3E %7B%0A event.preventDefault();%0A%0A if (this.state.user) %7B%0A this.importChallenge();%0A %7D else %7B%0A await this.signIn();%0A if (this.state.user) %7B%0A this.importChallenge();%0A %7D%0A %7D%0A %7D%0A%0A handle
255ffc44f70f9cf74a4bd4dbd37afb3bda811a0c
case 426
mobile-site/components/OptionButton.js
mobile-site/components/OptionButton.js
import React from 'react'; export default React.createClass({ getInitialState() { return { scrollTop: 0 }; }, componentDidMount() { window.addEventListener('scroll', this.scroll); }, scroll() { this.setState({ scrollTop: $('body').scrollTop() }); }, goTop() { $('body').animate({ scrollTop: 0 }, 500); }, render() { const scrollTop = this.state.scrollTop; return ( <a className={`go-top ${scrollTop ? 'active' : ''}`} onClick={this.goTop}></a> ); }, });
JavaScript
0.999398
@@ -193,16 +193,103 @@ );%0A %7D,%0A + componentWillUnmount() %7B%0A window.removeEventListener('scroll', this.scroll);%0A %7D,%0A scroll
29f6c7e774d4f6bcfadd9f8eabefde7014beaf3d
Fix comment to reflect the new (non-deprecated) way of accessing a class type.
src/classic/element/ReactElement.js
src/classic/element/ReactElement.js
/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ 'use strict'; var ReactContext = require('ReactContext'); var ReactCurrentOwner = require('ReactCurrentOwner'); var assign = require('Object.assign'); var warning = require('warning'); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { warning( false, 'Don\'t set the %s property of the React element. Instead, ' + 'specify the correct value when initially creating the element.', key ); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if (__DEV__) { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = {props: props, originalProps: assign({}, props)}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if (__DEV__) { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if (__DEV__) { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement;
JavaScript
0
@@ -5284,16 +5284,17 @@ s. E.g. +%60 %3CFoo /%3E. @@ -5305,21 +5305,17 @@ === Foo -.type +%60 .%0A // T
4a3173c9ea1d90aa74a0253cd98990c0da0a084a
add missing jsdoc
app/scripts/sidebar.js
app/scripts/sidebar.js
export default class Sidebar { /** * Constructs the Sidebar * @param {GoogleMap} map The map * @param {String} itemSelector The sidebar item selector * @param {Object} hotspotsData The hotspot data */ constructor(map, itemSelector, hotspotsData) { this.map = map; this.hotspotsData = hotspotsData; this.currentFilter = []; this.$itemsContainer = document.querySelector('.sidebar__keys__items'); this.$items = document.querySelectorAll(itemSelector); this.$sidebarHeader = document.querySelector('.sidebar__keys__header'); this.sidebarHeaderTextShow = this.$sidebarHeader.dataset.show; this.sidebarHeaderTextHide = this.$sidebarHeader.dataset.hide; this.initEvents(); } /** * Add click listener to sidebar items */ initEvents() { /* eslint-disable id-length */ for (let i = 0; i < this.$items.length; i++) { let type = this.$items[i].dataset.filter; this.$items[i].addEventListener('click', () => this.filterMarker(this.hotspotsData, this.$items[i], type)); } /* eslint-enable id-length */ this.$sidebarHeader.addEventListener('click', () => this.toggleSidebar()); } /** * Filter the hotspot data * @param {Object} hotspotsData The hotspot data * @param {DOMNode} item The sidebar item * @param {String} type The type of the filter */ filterMarker(hotspotsData, item, type) { let filteredData = []; item.classList.toggle('sidebar__keys__items__item--active'); this.updateCurrentFilter(type); this.currentFilter.forEach(filter => { hotspotsData.forEach(hotspot => { if (hotspot.type === filter) { filteredData.push(hotspot); } }); }); if (filteredData.length > 0) { this.map.addHotspots(filteredData); } else { this.map.addHotspots(hotspotsData); } } /** * Update the current filter selection * @param {String} type The hotspot data */ updateCurrentFilter(type) { let index = this.currentFilter.indexOf(type); if (index === -1) { this.currentFilter.push(type); } else { this.currentFilter.splice(index, 1); } } toggleSidebar() { this.$itemsContainer.classList.toggle('sidebar__keys__items--hidden'); if (this.$sidebarHeader.textContent === this.sidebarHeaderTextHide) { this.$sidebarHeader.textContent = this.sidebarHeaderTextShow; } else { this.$sidebarHeader.textContent = this.sidebarHeaderTextHide; } } }
JavaScript
0.000006
@@ -2170,16 +2170,63 @@ %7D%0A %7D%0A%0A + /**%0A * Toggle the sidebar visibility%0A */%0A toggle
ef9bc4d074099919a51bb8e7825d3457704ec4aa
update openfin config urls to match server [ARTP-877]
src/client/lib/downloadInstaller.js
src/client/lib/downloadInstaller.js
const https = require('https') const getJSON = require('get-json') const fs = require('fs') const getInstallerGeneratorUrl = async (fileName, appJSONUrl, os) => { const installerGeneratorUrl = `https://install.openfin.co/download/?config=${appJSONUrl}&fileName=${fileName}&os=${os}`; if (os === 'osx') { const appJSON = await getJSON(appJSONUrl) const appName = appJSON.startup_app.name const iconFile = appJSON.startup_app.applicationIcon return `${installerGeneratorUrl}&internal=true&appName=${appName}&iconFile=${iconFile}` } return `${installerGeneratorUrl}&unzipped=true` } const createInstaller = async (type, env, os = 'win') => { // maintain previous filenames for installers TODO: is this a requirement? const isLauncher = type === 'launcher' const fileName = `ReactiveTraderCloud${isLauncher ? '-launcher' : ''}-${env}` const appJSONUrl = `https://web-dev.adaptivecluster.com/openfin/${type}/${env}.json` const installerGeneratorUrl = await getInstallerGeneratorUrl(fileName, appJSONUrl, os) const extension = os === 'win' ? 'exe' : 'dmg' console.log(` - Generating installer: \x1b[36m${fileName}.${extension}\x1b[0m`) return new Promise(resolve => { https.get(installerGeneratorUrl, response => { const file = fs.createWriteStream(`install/${fileName}.${extension}`) response.pipe(file) resolve() }) }) } const createInstallers = installersData => { console.log(`Generating installers`) console.log( '\x1b[33m%s\x1b[0m', // Yellow ` NOTE: The installers contain just the URL to the manifest, not a copy of the manifest itself. Make sure the files are available on their respective locations when distributing the installer. `, ) const installerDownloads = installersData.map(({ type, env, os })=> { return createInstaller(type, env, os) }); return Promise.all(installerDownloads) } const INSTALLERS_TO_CREATE = [ { type: 'app', env: 'dev', os: 'win' }, { type: 'app', env: 'dev', os: 'osx' }, { type: 'app', env: 'uat', os: 'win' }, { type: 'app', env: 'uat', os: 'osx' }, { type: 'app', env: 'demo', os: 'win' }, { type: 'app', env: 'demo', os: 'osx' }, { type: 'launcher', env: 'dev', os: 'win' }, { type: 'launcher', env: 'dev', os: 'osx' }, { type: 'launcher', env: 'uat', os: 'win' }, { type: 'launcher', env: 'uat', os: 'osx' }, { type: 'launcher', env: 'demo', os: 'win' }, { type: 'launcher', env: 'demo', os: 'osx' } ] createInstallers(INSTALLERS_TO_CREATE)
JavaScript
0
@@ -893,19 +893,22 @@ s://web- -dev +$%7Benv%7D .adaptiv @@ -939,15 +939,8 @@ ype%7D -/$%7Benv%7D .jso
8c1a8a62a9f9c7d641776f97b81518fdaaa1f96e
Update main.js
public/assets/main.js
public/assets/main.js
var map = L.map('map').setView([40, -95], 4); L.tileLayer( 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw', { maxZoom: 18, attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' + '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="http://mapbox.com">Mapbox</a>' + ' | <a id="mapcredits" href="#">Map Credits</a>', id: 'mapbox.light' }).addTo(map); var win = L.control.window(map,{title:'Credits',content:'<a href="" target="_blank">Writeup</a><br /><br /><b>Data:</b><br />James Fee <a href="https://github.com/cageyjames/GeoJSON-Ballparks" target="_blank">GeoJSON Ballparks</a><br />Me: <a href="" target="_blank" >MLB Schedule Data</a><br /><br /><b>Plugins</b><br /><a href="https://github.com/mapshakers/leaflet-control-window" target="_blank" >Leaflet Control Window</a> (this)', modal: true}) document.getElementById('mapcredits').addEventListener('click', function(){win.show();}) var xhr = new XMLHttpRequest(); xhr.open('GET', '/games'); xhr.send(null); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { var game_day_data = JSON.parse(xhr.responseText); pictureArray(game_day_data); } else { console.log('Error: ' + xhr.status); } } }; function addMarkers(game_day_data, values) { var markers = []; game_day_data.forEach(function(d, i) { var newIcon = L.icon({ iconUrl: values[i], iconSize: [30, 40], iconAnchor: [15, 40], popupAnchor: [0, -15] }); markers[i] = L.marker([d.coordinates[1], d.coordinates[0]], { icon: newIcon }).addTo(map); markers[i].bindPopup("<b>" + d["SUBJECT"] + "</b><br />"+ ((d["START TIME"]) ? (d["START TIME"]).replace(/^[0]+/g,'') : "") + " (local)<br />" + d["START TIME ET"].replace(/^[0]+/g,'') + " (ET)<br />" + d["LOCATION"]); }); } function pictureArray(game_day_data) { var length = game_day_data.length; var c = []; //canvas elements var a = []; //promises for (var i = 0; i < length; i++) { c[i] = document.createElement('canvas'); c[i].width = 30; c[i].height = 40; c[i].setAttribute("style", "display: none;"); var teams = (game_day_data[i].SUBJECT).replace(" - Time TBD",""); teams = teams.split(' at '); c[i].dataset.home = teamAbbrevLookup(teams[1]); c[i].dataset.away = teamAbbrevLookup(teams[0]); } //Technique adapted from: http://stackoverflow.com/a/15620872/4805025 c.forEach(function(elem, idx) { var home = elem.dataset.home; var away = elem.dataset.away; a[idx] = new Promise(function(resolve, reject) { var ctx = elem.getContext("2d"); var imageObj1 = new Image(); var imageObj2 = new Image(); var imageObj3 = new Image(); imageObj1.src = "markers/frame.png"; imageObj1.onload = function() { ctx.drawImage(imageObj1, 0, 0); imageObj2.src = "markers/" + away + ".png"; imageObj2.onload = function() { ctx.drawImage(imageObj2, 1, 1); imageObj3.src = "markers/" + home + ".png"; imageObj3.onload = function() { ctx.drawImage(imageObj3, 1, 16); var img = elem.toDataURL("image/png"); resolve(img); } } } }); }); Promise.all(a).then(function(values) { addMarkers(game_day_data, values); }, function(reason) { console.log('error:', reason); return 'error'; }); } //end pictureArray
JavaScript
0
@@ -1924,16 +1924,17 @@ r /%3E%22+ ( + (d%5B%22STAR @@ -1988,16 +1988,17 @@ '') : %22%22 + ) + %22 (l @@ -2007,24 +2007,49 @@ al)%3Cbr /%3E%22 + + ( (d%5B%22START TIME ET%22%5D) ? d%5B%22START TI @@ -2076,16 +2076,23 @@ %5D+/g,'') + : %22%22 ) + %22 (ET
de9cd297158fccb4603a346ea3074715f0f549da
Update on master - Removed unnecessary server logging in ./server/serverData.js
server/serverData.js
server/serverData.js
// Note: comments done with // http://patorjk.com/software/taag/#p=display&f=Doom&t=Logger // ______ _ // | _ \ | | // ___ ___ _ ____ _____ _ __| | | |__ _| |_ __ _ // / __|/ _ \ '__\ \ / / _ \ '__| | | / _` | __/ _` | // \__ \ __/ | \ V / __/ | | |/ / (_| | || (_| | // |___/\___|_| \_/ \___|_| |___/ \__,_|\__\__,_| // Server data master object var serverData = {}; // Server data initialize serverData.initialize = function () { // Initialize rooms serverData.rooms = {}; // Set roomNames this.roomNames = [ 'Alpha', 'Beta', 'Delta', 'Omega' ]; // Add one room this.addRoom(); }; // _ __ ___ ___ _ __ ___ ___ // | '__/ _ \ / _ \| '_ ` _ \/ __| // | | | (_) | (_) | | | | | \__ \ // |_| \___/ \___/|_| |_| |_|___/ // Server data add room serverData.addRoom = function () { // Get room count var roomCount = Object.keys(this.rooms).length; // Get rooms object var rooms = this.rooms; // Get room names array var roomNames = this.roomNames; // Initialize empty room rooms[roomNames[roomCount]] = {}; }; // Server data add player to room serverData.addPlayerToRoom = function (data) { // Set player room this.updateSocketInfo({ socketID: data.socketID, roomName: data.roomName }); console.log('setting room data'); // Update player in room this.updatePlayerInRoom(data); // Return success return { roomJoined: true, roomName: data.roomName }; }; // Server data update player in room serverData.updatePlayerInRoom = function (data) { // Get username var username = data.username; // Get playerData var playerData = data.playerData; // Get roomName var roomName = this.sockets[data.socketID].roomName; // Get rooms var rooms = this.rooms; // Set key value pair in room rooms[roomName][username] = playerData; }; // _ _ ___ ___ _ __ ___ // | | | / __|/ _ \ '__/ __| // | |_| \__ \ __/ | \__ \ // \__,_|___/\___|_| |___/ // Master object for all connected sockets serverData.sockets = {}; // Server data initialize socket info serverData.initializeSocketInfo = function (data) { // Get socketID var socketID = data.socketID; // Initialize to empty object this.sockets[socketID] = {}; var tmpSocket = this.sockets[socketID]; // Set username tmpSocket.username = null; // Set roomName tmpSocket.roomName = null; }; // Server data update socket info serverData.updateSocketInfo = function (data) { // Get socketID var socketID = data.socketID; // Get username var username = data.username || null; // If username, set username if (username) { this.sockets[socketID].username = username; } // Get roomName var roomName = data.roomName || null; // If username, set username if (roomName) { this.sockets[socketID].roomName = roomName; } }; // _ _ _ _ _ _ // (_) (_) | (_) | (_) // _ _ __ _| |_ _ __ _| |_ _______ // | | '_ \| | __| |/ _` | | |_ / _ \ // | | | | | | |_| | (_| | | |/ / __/ // |_|_| |_|_|\__|_|\__,_|_|_/___\___| // Initialize server data serverData.initialize(); // Add serverData to exports module.exports = serverData;
JavaScript
0
@@ -1335,44 +1335,8 @@ %7D);%0A - console.log('setting room data');%0A //
4958d2c65a0595259100685946cdaa8629e50a8a
Fix typo
src/components/App.js
src/components/App.js
import {Component} from 'react' import {HotKeys} from 'react-hotkeys' import {observer} from 'mobx-react' import DevTools from 'mobx-react-devtools' import r from 'r-dom' import {appState, chartStore} from '../stores' import ChartBench from './ChartBench' import NoteSelect from './NoteSelect' @observer export default class App extends Component { handleBenchKeyChange = (key) => { appState.benchKey = key } render () { const keyMap = { commit: 'ctrl+enter', left: ['left', 'h'], redo: 'ctrl+shift+z', right: ['right', 'l'], undo: 'ctrl+z' } const {gitHubCommitUrl, lastUpdatedOn, packageVersion} = this.props return r(HotKeys, {keyMap}, [ r(DevTools, null), r('h1', 'OpenChordCharts sample data'), r('p', [ 'This page shows renderings of OpenChordCharts ', r('a', { href: 'https://github.com/openchordcharts/sample-data' }, 'sample JSON files'), '.' ]), r('p', [ `zVersion ${packageVersion}, last updated on `, r('a', { href: gitHubCommitUrl }, lastUpdatedOn), '.' ]), r('p', [ 'Current key: ', r(NoteSelect, { onChange: this.handleBenchKeyChange, value: appState.benchKey }) ]), r('section', chartStore.charts.map(chart => r(ChartBench, {key: chart.slug, chart, width: 800}))) ]) } }
JavaScript
0.999999
@@ -979,17 +979,16 @@ %60 -z Version
d5b6574e3bc68136c67063c5307048dd03060436
fix clibuild error
app/services/logger.js
app/services/logger.js
import Ember from "ember"; import config from "../config/environment"; export default Ember.Service.extend({ session: Ember.inject.service(), rollbar: Ember.inject.service(), getReason(reason) { return reason instanceof Error || typeof reason !== "object" ? reason : JSON.stringify(reason); }, error: function(reason) { if (reason.status === 0) { return; } console.info(reason); if (config.environment === "production" || config.staging) { var currentUser = this.get("session.currentUser"); var userName = currentUser.get("fullName"); var userId = currentUser.get("id"); var error = this.getReason(reason); var environment = config.staging ? "staging" : config.environment; var version = `${config.APP.SHA} (shared ${config.APP.SHARED_SHA})`; var airbrake = new airbrakeJs.Client({ projectId: config.APP.AIRBRAKE_PROJECT_ID, projectKey: config.APP.AIRBRAKE_PROJECT_KEY }); airbrake.setHost(config.APP.AIRBRAKE_HOST); airbrake.notify({ error, context: { userId, userName, environment, version } }); this.set('rollbar.currentUser', currentUser); this.get('rollbar').error(error, data = { id: userId, username: userName, environment: environment}); } } });
JavaScript
0.000001
@@ -478,24 +478,40 @@ .staging) %7B%0A + var data;%0A var cu
af43be6bc14ec48cccf632c999efdb6ac617436e
Remove ident
src/components/Vue.js
src/components/Vue.js
let { VueLoaderPlugin } = require('vue-loader'); let ExtractTextPlugin = require('extract-text-webpack-plugin'); class Vue { /** * Required dependencies for the component. */ dependencies() { if (Config.extractVueStyles && Config.globalVueStyles) { return ['sass-resources-loader']; // Required for importing global styles into every component. } } /** * Override the generated webpack configuration. * * @param {Object} webpackConfig */ webpackConfig(webpackConfig) { webpackConfig.module.rules.push({ test: /\.vue$/, loader: 'vue-loader' }); webpackConfig.plugins.push(new VueLoaderPlugin()); this.updateCssLoaders(webpackConfig); } /** * Update all preprocessor loaders to support CSS extraction. */ updateCssLoaders(webpackConfig) { // Basic CSS and PostCSS this.updateCssLoader( 'css', [ { loader: 'css-loader', options: { importLoaders: 1 } }, { loader: 'postcss-loader', options: this.postCssOptions() } ], webpackConfig ); // LESS this.updateCssLoader( 'less', ['css-loader', 'less-loader'], webpackConfig ); // SASS this.updateCssLoader( 'sass', [ 'css-loader', { loader: 'sass-loader', options: Config.globalVueStyles ? { resources: Mix.paths.root(Config.globalVueStyles), indentedSyntax: true } : { indentedSyntax: true } } ], webpackConfig ); // SCSS this.updateCssLoader( 'scss', [ 'css-loader', { loader: 'sass-loader', options: Config.globalVueStyles ? { resources: Mix.paths.root(Config.globalVueStyles) } : {} } ], webpackConfig ); // STYLUS this.addStylusLoader(webpackConfig); } /** * Update a single CSS loader. */ updateCssLoader(loader, loaders, webpackConfig) { let rule = webpackConfig.module.rules.find(rule => { return rule.test instanceof RegExp && rule.test.test('.' + loader); }); if (Config.extractVueStyles) { let extractPlugin = this.extractPlugin(); rule.loaders = extractPlugin.extract({ fallback: 'style-loader', use: loaders }); this.addExtractPluginToConfig(extractPlugin, webpackConfig); } else { loaders.unshift('style-loader'); rule.loaders = loaders; } } /** * Add Stylus loader support. */ addStylusLoader(webpackConfig) { let extractPlugin = this.extractPlugin(); webpackConfig.module.rules.push({ test: /\.styl(us)?$/, loaders: Config.extractVueStyles ? extractPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'stylus-loader'] }) : ['style-loader', 'css-loader', 'stylus-loader'] }); if (Config.extractVueStyles) { this.addExtractPluginToConfig(extractPlugin, webpackConfig); } } /** * Fetch the appropriate postcss plugins for the compile. */ postCssOptions() { let postCssOptions = { ident: 'postcss' }; // 1. If there's a mix.postCss() call in webpack.mix.js, we'll use the plugins from that call. // 2. If the user has a postcss.config.js file, postcss-loader will automatically read from that. // 3. Otherwise, we'll set plugins to an empty array to avoid the compile breaking. if (Mix.components.get('postCss')) { postCssOptions.plugins = Mix.components.get( 'postCss' ).details[0].postCssPlugins; } else if (!File.exists(Mix.paths.root('postcss.config.js'))) { postCssOptions.plugins = []; } return postCssOptions; } /** * Add an extract text plugin to the webpack config plugins array. */ addExtractPluginToConfig(extractPlugin, webpackConfig) { if (extractPlugin.isNew) { webpackConfig.plugins.push(extractPlugin); } } /** * Fetch the appropriate extract plugin. */ extractPlugin() { // If the user set extractVueStyles: true, we'll try // to append the Vue styles to an existing CSS chunk. if (typeof Config.extractVueStyles === 'boolean') { let preprocessorName = Object.keys(Mix.components.all()) .reverse() .find(componentName => { return ['sass', 'less', 'stylus', 'postCss'].includes( componentName ); }); if (preprocessorName) { return Mix.components .get(preprocessorName) .extractPlugins.slice(-1)[0]; } } // Otherwise, we'll need to whip up a fresh extract text instance. return tap( new ExtractTextPlugin(this.extractFileName()), extractPlugin => { extractPlugin.isNew = true; } ); } /** * Determine the extract file name. */ extractFileName() { let fileName = typeof Config.extractVueStyles === 'string' ? Config.extractVueStyles : '/css/vue-styles.css'; return fileName.replace(Config.publicPath, '').replace(/^\//, ''); } } module.exports = Vue;
JavaScript
0
@@ -3908,26 +3908,8 @@ = %7B - ident: 'postcss' %7D;%0A%0A
a543f86dc1219162002855fbda2f0e79c1c0f310
add check for logged out
roundcube/src/main/php/js/routes.js
roundcube/src/main/php/js/routes.js
// declare namespace var Roundcube = Roundcube || {}; Roundcube.routes = function() { if (Roundcube.refreshInterval) { if (OC.Router) { OC.Router.registerLoadedCallback(function() { var url = OC.Router.generate('roundcube_refresh'); setInterval(function() { $.post(url); }, Roundcube.refreshInterval * 1000); }); // starting with OC7 OC.Router was removed } else { var url = OC.generateUrl('apps/roundcube/' + 'refresh'); setInterval(function() { $.post(url); }, Roundcube.refreshInterval * 1000); } } } $(document).ready(function() { Roundcube.routes(); });
JavaScript
0
@@ -49,16 +49,55 @@ %7C%7C %7B%7D;%0A%0A +/**%0A * Set client side refresh job%0A */%0A Roundcub @@ -120,16 +120,42 @@ ion() %7B%0A + if (OC.currentUser) %7B%0A if (Ro @@ -181,24 +181,26 @@ rval) %7B%0A + if (OC.Route @@ -204,22 +204,17 @@ uter) %7B%0A - +%09 OC.Route @@ -252,16 +252,18 @@ on() %7B%0A%09 + var url @@ -306,16 +306,38 @@ esh');%0A%09 + Roundcube.refresh = setInter @@ -356,16 +356,18 @@ () %7B%0A%09 + $.post(u @@ -372,16 +372,18 @@ (url);%0A%09 + %7D, Round @@ -416,24 +416,30 @@ 0);%0A +%09 - %7D);%0A +return true;%0A%09%7D);%0A%09 // s @@ -481,16 +481,18 @@ ved%0A + %7D else %7B @@ -492,22 +492,17 @@ else %7B%0A - +%09 var url @@ -550,21 +550,36 @@ resh');%0A - +%09Roundcube.refresh = setInte @@ -597,16 +597,45 @@ on() %7B%0A%09 + if (OC.currentUser) %7B%0A%09 $.post(u @@ -643,57 +643,298 @@ l);%0A +%09 - %7D, Roundcube.refreshInterval * 1000);%0A %7D +%7D else %7B%0A%09 // if user is null end up refresh (logged out)%0A%09 clearTimeout(Roundcube.refresh);%0A%09 %7D%0A%09%7D, Roundcube.refreshInterval * 1000);%0A%09return true;%0A %7D%0A %7D%0A %7D else %7B%0A // if user is null end up refresh (logged out)%0A clearTimeout(Roundcube.refresh);%0A return false; %0A %7D
f4bfb3ca744bf0290d1dff82c936a9d2c6ed2969
update color blue
app/settings/config.js
app/settings/config.js
// configuration values of the app const config = {} // graph color values config.setColors = color => { // Atom's dark color theme if (color === 'dark') { config.text = '#abb2bf' config.background = '#282c34' config.darkBackground = '#21252b' config.black = '#3b4251' config.gray = '#abb2bf' config.blue = '#61afef' config.red = '#be5046' config.orange = '#cf8772' config.green = '#98c379' config.yellow = '#d19a66' config.magenta = '#c678dd' config.cyan = '#56b6c2' // Atom's light color theme } else if (color === 'light') { config.text = '#383a42' config.background = '#fafafa' config.darkBackground = '#eaeaeb' config.black = '#a0a1a7' config.gray = '#abb2bf' config.blue = '#3399cd' config.red = '#e45649' config.orange = '#cf8772' config.green = '#50a14f' config.yellow = '#986901' config.magenta = '#a381ff' config.cyan = '#0184bc' } } // default color theme config.colorTheme = 'dark' // first theme paint config.setColors(config.colorTheme) // urls // url for the ASTo wiki config.wikiUrl = 'https://or3stis.github.io/apparatus/wiki' // url for searching vulnerabilities config.cveSearchUrl = 'http://cve.circl.lu/api/search/' module.exports = config
JavaScript
0.000004
@@ -760,14 +760,14 @@ = '# -3399cd +4078f2 '%0A
b2a4b8c94cdc230bb5a458bc49a72326cc038344
add button to move "list" screen
src/components/app.js
src/components/app.js
// @flow import React from 'react' import { StyleSheet, View, } from 'react-native' import {COLOR} from '../constants' // Import Reader from './reader' import Button from './button' import StatusBar from './status-bar' const styles = StyleSheet.create({ container: { flex: 1, }, logo: { flex: 5, }, button: { backgroundColor: COLOR.SOFT_BLUE, flex: 1, }, title: { color: COLOR.WHITE, fontSize: 32, fontWeight: 'bold', fontFamily: 'avenir', }, }) export default function App() { return ( <View style={styles.container}> <StatusBar /> <View style={styles.logo} /> <Button onPress={() => { console.log('Scan is tapped') }} title="Scan" buttonStyle={styles.button} titleStyle={styles.title} /> </View> ) }
JavaScript
0
@@ -317,17 +317,94 @@ %0A %7D,%0A -b +listButton: %7B%0A backgroundColor: COLOR.BRIGHT_RED,%0A flex: 1,%0A %7D,%0A scanB utton: %7B @@ -745,16 +745,210 @@ () =%3E %7B%0A + console.log('List is tapped')%0A %7D%7D%0A title=%22List%22%0A buttonStyle=%7Bstyles.listButton%7D%0A titleStyle=%7Bstyles.title%7D%0A /%3E%0A %3CButton%0A onPress=%7B() =%3E %7B%0A @@ -1039,17 +1039,21 @@ %7Bstyles. -b +scanB utton%7D%0A
5757aa6de0fc71a3bd33225ace63465b2f9ce7a6
Add per-category points display to the scoreboard
static/assets/js/hc_scoreboard.js
static/assets/js/hc_scoreboard.js
const SCOREBOARD_CATEGORIES = ["Service", "CTF"]; function build_hc_series(scores, categories = SCOREBOARD_CATEGORIES) { return categories.map(cat => ({ id: cat, name: cat, data: scores.filter(doc => doc.type === cat).map(doc => doc.points), })); } $(function () { // Get initial chart data, set up columns for teams $.getJSON( '/team/scores/split' ) .done(function(scores) { const teams = [...new Set(scores.map(doc => doc.teamname))]; const hc_scoreboard_series = build_hc_series(scores); Highcharts.chart('hc_scoreboard', { chart: { type: 'column' }, title: { text: 'Team Scores' }, subtitle: { text: '(Updates automatically)' }, xAxis: { type: 'category', categories: teams, labels: { align: 'center', style: { fontSize: '14pt', fontWeight: 'bold', textOutline: '1px contrast' } }, tickWidth: 0, crosshair: false, }, yAxis: { min: 0, title: { text: 'Points' }, stackLabels: { enabled: true, // Fixes scores above columns from disappearing allowOverlap: true, // Fixes the 'bad spacing' of scores over 1000 (otherwise rendered as '1 000') formatter: function() { return this.total; }, style: { color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'white', fontSize: '3.5vw', } }, }, // Legend is a floating box on the top-right of the chart legend: { floating: true, verticalAlign: 'top', y: 25, align: 'right', x: -30, backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'gray', borderColor: '#CCC', borderWidth: 1, shadow: true, }, // Tooltip is the box that appears when hovering over a specific column tooltip: { shared: true, useHTML: true, headerFormat: '<span>{point.key}</span><table style="background-color:initial">', pointFormat: '<tr>' + '<td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y:.0f}</b></td>' + '</tr>', footerFormat: '</table>', hideDelay: 100, style: { fontSize: '22pt', }, }, plotOptions: { column: { stacking: 'normal', pointPadding: 0, groupPadding: 0.1, // borderWidth: 0, // colorByPoint: true, shadow: true } }, series: hc_scoreboard_series, }); }); });
JavaScript
0.000001
@@ -3347,16 +3347,286 @@ ow: true +,%0A dataLabels: %7B%0A enabled: true,%0A formatter: function() %7B return this.y; %7D,%0A style: %7B%0A fontSize: '2.2em',%0A %7D,%0A %7D, %0A
a1558755bbdfbf485bcdfd13923006dab460dd58
Change how password creation when using social network is handled
server/services/user.service.js
server/services/user.service.js
'use strict'; /** * Users service */ var User = require('mongoose').model('User'); var encrypt = require('../utils/encryption'); var mailer = require('../utils/mailer'); var validator = require('validator'); var Promise = require('bluebird'); /** * Module interface */ module.exports = { getUsers: getUsers, getUserById: getUserById, getUserByUsername: getUserByUsername, getUserByEmail: getUserByEmail, getUsersByAnsweredQuestion: getUsersByAnsweredQuestion, createUser: createUser, updateUser: updateUser, deleteUser: deleteUser, getUserWithStats: getUserWithStats, requestNewPassword: requestNewPassword, resetPassword: resetPassword }; /** * Return array of all users */ function getUsers() { return User.find({}); } /** * Return the user with the given id */ function getUserById(userId) { return User.findOne({_id: userId}) .then(function(user) { if (!user) { throw new Error('USER_DOES_NOT_EXIST'); } return user; }) .then(user => user.populateUser()); } /** * Return the user with the given username address */ function getUserByUsername(username) { return User.findOne({username: username}) .then(function(user) { if (!user) { throw new Error('USER_DOES_NOT_EXIST'); } return user; }) .then(user => user.populateUser()); } /** * Return the user with the given email address */ function getUserByEmail(email) { return User.findOne({email: email}) .then(function(user) { if (!user) { throw new Error('USER_DOES_NOT_EXIST'); } return user; }) .then(user => user.populateUser()); } /** * Return the list of users who answered a question */ function getUsersByAnsweredQuestion(questionId) { return User.find({'answers.question': questionId}); } /** * Create a new user */ function createUser(userData, facebookId, twitterId, googleId) { // Encrypt password userData.salt = encrypt.createSalt(); if (facebookId || twitterId || googleId) { // If registration from social network userData.password = encrypt.createToken(); } if (userData.password) { userData.hashedPassword = encrypt.hashPassword(userData.salt, userData.password); } if (facebookId) { userData.facebookId = facebookId; } if (twitterId) { userData.twitterId = twitterId; } if (googleId) { userData.googleId = googleId; } // Create user return User.validate(userData) .then(userData => User.create(userData)) .catch(function(err) { var reason = err.message; if (reason.indexOf('E11000') > -1) { if (reason.indexOf('username') > -1) { reason = 'USERNAME_ALREADY_EXISTS'; } else if (reason.indexOf('email') > -1) { reason = 'EMAIL_ALREADY_EXISTS'; } } throw new Error(reason); }); } /** * Update a user */ function updateUser(updatedUser, userId) { return User.validate(updatedUser) .then(() => User.findOne({_id: userId})) .then(function(user) { if (!user) { throw new Error('USER_DOES_NOT_EXIST'); } user.username = updatedUser.username; user.email = updatedUser.email; // If needed, generate new hashed password if (updatedUser.password && updatedUser.password.length > 0) { user.salt = encrypt.createSalt(); user.hashedPassword = encrypt.hashPassword(user.salt, updatedUser.password); } return user.save(); }) .then(user => user.populateUser()) .catch(function(err) { var reason = err.message; // If the error is E11000, the reason is a duplicate username or email if (reason.indexOf('E11000') > -1) { if (reason.indexOf('username') > -1) { reason = 'USERNAME_ALREADY_EXISTS'; } if (reason.indexOf('email') > -1) { reason = 'EMAIL_ALREADY_EXISTS'; } } throw new Error(reason); }); } /** * Delete a user */ function deleteUser(userId) { return User.remove({_id: userId}); } /** * Return user with his stats */ function getUserWithStats(userId) { return User.findOne({_id: userId}) .then(user => user.populateUser()) .then(user => user.toJSON({virtuals: true})); } /** * Send a mail to the user with a link to set a new password */ function requestNewPassword(username, language) { // Try to find the concerned user var criteria = validator.isEmail(username) ? {email: username} : {username: username}; // Create the token var token = encrypt.createToken(); return User.findOne(criteria) .then(function(user) { if (!user) { throw new Error('USER_DOES_NOT_EXIST'); } user.resetPasswordToken = token; user.resetPasswordExpire = Date.now() + (1000 * 60 * 60 * 2); // 2 hours in the future return user.save(); }) .then(function(user) { return mailer.sendRequestNewPasswordMail(language, user.email, token); }); } /** * Reset the password of the user if he provides the right token */ function resetPassword(newPassword, token) { if (token === undefined || token.length === 0 || !validator.isHexadecimal(token)) { return Promise.reject(new Error('INVALID_TOKEN')); } return User.findOne({resetPasswordToken: token}) .then(function(user) { if (!user || Date.now() >= user.resetPasswordExpire) { throw new Error('INVALID_TOKEN'); } user.salt = encrypt.createSalt(); user.hashedPassword = encrypt.hashPassword(user.salt, newPassword); user.resetPasswordToken = undefined; user.resetPasswordExpire = undefined; return user; }) .then(user => User.validate(user)) .then(user => user.save()) .then(user => user.populateUser()); }
JavaScript
0.000004
@@ -1976,42 +1976,25 @@ if ( -facebookId %7C%7C twitterId %7C%7C googleI +!userData.passwor d) %7B @@ -2032,16 +2032,33 @@ network +, random password %0A use @@ -2105,37 +2105,8 @@ %7D%0A - if (userData.password) %7B%0A us @@ -2185,20 +2185,16 @@ sword);%0A - %7D%0A if (fa
f1b22e87f1422e0f5017abc73bff59d4fa19fd91
version mobile configs disk caching
Libraries/BatchedBridge/BatchedBridgedModules/__mocks__/NativeModules.js
Libraries/BatchedBridge/BatchedBridgedModules/__mocks__/NativeModules.js
/** * Copyright 2004-present Facebook. All Rights Reserved. */ 'use strict'; var NativeModules = { I18n: { translationsDictionary: JSON.stringify({ 'Good bye, {name}!|Bye message': '¡Adiós {name}!', }), }, Timing: { createTimer: jest.genMockFunction(), deleteTimer: jest.genMockFunction(), }, GraphPhotoUpload: { upload: jest.genMockFunction(), }, FacebookSDK: { login: jest.genMockFunction(), logout: jest.genMockFunction(), queryGraphPath: jest.genMockFunction().mockImpl( (path, method, params, callback) => callback() ), }, DataManager: { queryData: jest.genMockFunction(), }, UIManager: { customBubblingEventTypes: {}, customDirectEventTypes: {}, Dimensions: {}, }, AsyncLocalStorage: { getItem: jest.genMockFunction(), setItem: jest.genMockFunction(), removeItem: jest.genMockFunction(), clear: jest.genMockFunction(), }, SourceCode: { scriptURL: null, }, }; module.exports = NativeModules;
JavaScript
0
@@ -974,16 +974,80 @@ l,%0A %7D,%0A + BuildInfo: %7B%0A appVersion: '0',%0A buildVersion: '0',%0A %7D,%0A %7D;%0A%0Amodu
e7aea7c181a5a7619d0756e4e02f7694446c9289
Remove not needed functions and move from other files
src/helpers/util.js
src/helpers/util.js
import _ from 'lodash'; /** * Returns copy of an object with mapped values. Works really similar to * lodash's mapValues, with difference that also EVERY nested object is * also mapped with passed function. * * @param {Object} obj - object to map values of * @param {Function} fn - function to map values with * * @returns {Object} * @private */ export const deepMapValues = (obj, fn) => _.mapValues(obj, (value) => { if (_.isPlainObject(value)) return deepMapValues(value, fn); return fn(value); }); export const isFunction = (obj) => typeof obj === 'function';
JavaScript
0
@@ -527,52 +527,274 @@ nst -isFunction = (obj) =%3E typeof obj === 'function'; +extendWithBind = (...args) =%3E%0A _.extendWith(...args, (objectValue, sourceValue, key, object, source) =%3E %7B%0A if (!_.isUndefined(objectValue)) %7B return objectValue; %7D%0A if (_.isFunction(sourceValue)) %7B return sourceValue.bind(source); %7D%0A return sourceValue;%0A %7D);%0A
7c8973fd77c539ad22a4c1383285344b9f81286e
Fix benchRoundtrip benchmark
server/tests/serialize_bench.js
server/tests/serialize_bench.js
/** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Benchmarks for JavaScript interpreter. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const fs = require('fs'); const path = require('path'); const util = require('util'); const Interpreter = require('../interpreter'); const {getInterpreter, startupFiles} = require('./interpreter_common'); const Serializer = require('../serialize'); /** * Run a benchmark of the interpreter being serialized/deserialized. * @param {!B} b The benchmark runner object. * @param {string} name The name of the test. * @param {string} src The code to be evaled before roundtripping. * @param {function(!Interpreter)=} initFunc Optional function to be * called after creating new interpreter instance but before * running src. Can be used to insert extra native functions into * the interpreter. initFunc is called with the interpreter * instance to be configured as its parameter. */ function runSerializationBench(b, name, src, initFunc) { for (let i = 0; i < 4; i++) { const intrp1 = new Interpreter(); const intrp2 = new Interpreter(); if (initFunc) { initFunc(intrp1); initFunc(intrp2); } const err = undefined; try { intrp1.createThreadForSrc(src); intrp1.run(); intrp1.stop(); b.start(name, i); let json = Serializer.serialize(intrp1); b.end(name + ' serialize', i); let str = JSON.stringify(json); let len = str.length; b.end(name + ' stringify (' + Math.ceil(len / 1024) + 'kiB)', i); json = JSON.parse(str); b.end(name + ' parse', i); Serializer.deserialize(json, intrp2); b.end(name + ' deserialize', i); } catch (err) { b.crash(name, util.format('%s\n%s', src, err.stack)); } } }; /** * Run a benchmark of the interpreter being serialized/deserialized. * @param {!B} b The benchmark runner object. * @param {string} name The name of the test. * @param {string} src The code to be evaled before roundtripping. * @param {function(!Interpreter)=} initFunc Optional function to be * called after creating new interpreter instance but before * running src. Can be used to insert extra native functions into * the interpreter. initFunc is called with the interpreter * instance to be configured as its parameter. */ function runDeserializationBench(b, name, src, initFunc) { for (var i = 0; i < 4; i++) { const intrp1 = new Interpreter(); const intrp2 = new Interpreter(); if (initFunc) { initFunc(intrp1); initFunc(intrp2); } const err = undefined; try { intrp1.createThreadForSrc(src); intrp1.run(); intrp1.stop(); b.start(name, i); const json = Serializer.serialize(intrp1); var len = JSON.stringify(json).length; Serializer.deserialize(json, intrp2); b.end(name + ' (' + Math.ceil(len / 1024) + 'kiB)', i); } catch (err) { b.crash(name, util.format('%s\n%s', src, err.stack)); } } }; /** * Run a benchmark of the interpreter after being * serialized/deserialized. * @param {!B} b The benchmark runner object. * @param {string} name The name of the test. * @param {string} src The code to be evaled. */ function runInterpreterBench(b, name, src) { for (let i = 0; i < 4; i++) { const intrp1 = getInterpreter(); const intrp2 = new Interpreter(); try { intrp1.createThreadForSrc(src); intrp1.stop(); const json = Serializer.serialize(intrp1); Serializer.deserialize(json, intrp2); // Deserialized interpreter was stopped, but we want to be able to // step/run it, so wake it up to PAUSED. intrp2.pause(); b.start(name, i); intrp2.run(); b.end(name, i); } catch (err) { b.crash(name, util.format('%s\n%s', src, err.stack)); } finally { intrp2.stop(); } } }; /** * Run benchmarks roundtripping the interpreter. * @param {!B} b The test runner object. */ exports.benchRoundtrip = function(b) { let name = 'Roundtrip demo'; const demoDir = path.join(__dirname, '../../demo'); const filenames = fs.readdirSync(demoDir); filenames.sort(); let src = ''; for (const filename of filenames) { if (!(filename.match(/.js$/))) continue; src += fs.readFileSync(String(path.join(demoDir, filename))); } const fakeBuiltins = function(intrp) { // Hack to install stubs for builtins found in codecity.js. const builtins = [ 'CC.log', 'CC.checkpoint', 'CC.shutdown', 'CC.hash', 'CC.acorn.parse', 'CC.acorn.parseExpressionAt', ]; for (const bi of builtins) { new intrp.NativeFunction({id: bi, length: 0,}); } }; runSerializationBench(b, name, src, fakeBuiltins); }; /** * Run the fibbonacci10k benchmark. * @param {!B} b The test runner object. */ exports.benchResurrectedFibbonacci10k = function(b) { let name = 'ressurrectedFibonacci10k'; let src = ` var fibonacci = function(n, output) { var a = 1, b = 1, sum; for (var i = 0; i < n; i++) { output.push(a); sum = a + b; a = b; b = sum; } } for(var i = 0; i < 10000; i++) { var result = []; fibonacci(78, result); } result; `; runInterpreterBench(b, name, src); };
JavaScript
0
@@ -4701,20 +4701,20 @@ '../../ -demo +core ');%0A co
297b844aa873bdb9856ae24589d9d00ece04662c
Implement fix from #5129 for main branch.
assets/js/components/surveys/SurveyViewTrigger.js
assets/js/components/surveys/SurveyViewTrigger.js
/** * SurveyViewTrigger component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; /** * WordPress dependencies */ import { useEffect } from '@wordpress/element'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { CORE_SITE } from '../../googlesitekit/datastore/site/constants'; import { CORE_USER } from '../../googlesitekit/datastore/user/constants'; const { useSelect, useDispatch } = Data; export default function SurveyViewTrigger( { triggerID, ttl = 0 } ) { const usingProxy = useSelect( ( select ) => select( CORE_SITE ).isUsingProxy() ); const isTimedOut = useSelect( ( select ) => select( CORE_USER ).isSurveyTimedOut( triggerID ) ); const isTimingOut = useSelect( ( select ) => select( CORE_USER ).isTimingOutSurvey( triggerID ) ); const { triggerSurvey } = useDispatch( CORE_USER ); const shouldTriggerSurvey = isTimedOut === false && isTimingOut === false; useEffect( () => { if ( shouldTriggerSurvey && usingProxy ) { triggerSurvey( triggerID, { ttl } ); } }, [ shouldTriggerSurvey, usingProxy, triggerSurvey, triggerID, ttl ] ); return null; } SurveyViewTrigger.propTypes = { triggerID: PropTypes.string.isRequired, ttl: PropTypes.number, };
JavaScript
0
@@ -717,43 +717,8 @@ es'; -%0A%0A/**%0A * WordPress dependencies%0A */ %0Aimp @@ -726,21 +726,20 @@ rt %7B use -Effec +Moun t %7D from @@ -744,26 +744,17 @@ om ' -@wordpress/element +react-use ';%0A%0A @@ -1183,516 +1183,142 @@ nst -isTimedOut = useSelect( ( select ) =%3E%0A%09%09select( CORE_USER ).isSurveyTimedOut( triggerID )%0A%09);%0A%09const isTimingOut = useSelect( ( select ) =%3E%0A%09%09select( CORE_USER ).isTimingOutSurvey( triggerID )%0A%09);%0A%0A%09const %7B triggerSurvey %7D = useDispatch( CORE_USER );%0A%0A%09const shouldTriggerSurvey = isTimedOut === false && isTimingOut === false;%0A%0A%09useEffect( () =%3E %7B%0A%09%09if ( shouldTriggerSurvey && usingProxy ) %7B%0A%09%09%09triggerSurvey( triggerID, %7B ttl %7D );%0A%09%09%7D%0A%09%7D, %5B shouldTriggerSurvey, usingProxy, triggerSurvey, triggerID, ttl %5D +%7B triggerSurvey %7D = useDispatch( CORE_USER );%0A%0A%09useMount( () =%3E %7B%0A%09%09if ( usingProxy ) %7B%0A%09%09%09triggerSurvey( triggerID, %7B ttl %7D );%0A%09%09%7D%0A%09%7D );%0A
c5c36f6549df807c71f81bfbe01e39facb255ae5
Update searchListings API call to pass information via query parameters
app/actions/index.js
app/actions/index.js
import axios from 'axios'; const ROOT_URL = (process.env.NODE_ENV === 'production') ? 'https://antfinder-api.herokuapp.com' : 'http://localhost:3000'; // const ROOT_URL = 'https://antfinder-api.herokuapp.com'; // const ROOL_URL = 'http://localhost:3000'; // For local testing const config = { withCredentials: true }; export const ADD_LISTING = 'ADD_LISTING'; export const CREATE_USER = 'CREATE_USER'; export const GET_USER_INFO = 'GET_USER_INFO'; export const LOGIN_USER = 'LOGIN_USER'; export const LOGOUT_USER = 'LOGOUT_USER'; export const AUTHENTICATE_USER = 'AUTHENTICATE_USER'; export const CHANGE_USER_PASSWORD = 'CHANGE_USER_PASSWORD'; export const SEARCH_LISTINGS = 'SEARCH_LISTINGS'; export const GET_LISTING = 'GET_LISTING'; export const GET_CURRENT_USER_LISTINGS = 'GET_CURRENT_USER_LISTINGS'; export const DELETE_LISTING = 'DELETE_LISTING'; export const createUser = props => { const { firstName: first_name, lastName: last_name, email, username, password } = props; const newUser = { first_name, last_name, email, username, password }; const request = axios.post(`${ ROOT_URL }/users`, newUser, config); return { type: CREATE_USER, payload: request }; }; export const loginUser = props => { const { username, password } = props; const user = { username, password }; const request = axios.post(`${ ROOT_URL }/login`, user, config); return { type: LOGIN_USER, payload: request }; }; export const logoutUser = () => { const request = axios.get(`${ ROOT_URL }/logout`, config); return { type: LOGOUT_USER, payload: request } } export const authenticateUser = () => { const request = axios.get(`${ ROOT_URL }/authenticate`, config); return { type: AUTHENTICATE_USER, payload: request }; }; export const getUserInfo = () => { const request = axios.get(`${ ROOT_URL }/user`, config); return { type: GET_USER_INFO, payload: request }; }; export const changeUserPassword = (oldPassword, password) => { const request = axios.put(`${ ROOT_URL }/users`, { oldPassword, password }, config); return { type: CHANGE_USER_PASSWORD, payload: request }; }; export const addListing = newListing => { const request = axios.post(`${ ROOT_URL }/listings`, newListing, config); return { type: ADD_LISTING, payload: request }; }; export const searchListings = (listing_type, query) => { const request = axios.get(`${ ROOT_URL }/listings`, { listing_type, query }, config); return { type: SEARCH_LISTINGS, payload: request }; }; export const getListing = listingID => { const request = axios.get(`${ ROOT_URL }/listings/${ listingID }`, config); return { type: GET_LISTING, payload: request }; }; export const getMyListings = () => { const request = axios.get(`${ ROOT_URL }/listings/current_user`, config); return { type: GET_CURRENT_USER_LISTINGS, payload: request }; }; export const deleteListing = listingID => { const request = axios.delete(`${ ROOT_URL }/listings/${ listingID }`, config); return { type: DELETE_LISTING, payload: request }; };
JavaScript
0
@@ -2558,19 +2558,31 @@ listings -%60, +?listing_type=$ %7B listin @@ -2591,17 +2591,27 @@ type -, + %7D&query=$%7B query %7D , co @@ -2606,16 +2606,17 @@ query %7D +%60 , config
284f33c5784ddf56813eb75fbce8e17568f7c870
Check if text content has been changed
app/tests/scrambler.js
app/tests/scrambler.js
describe('scrambler tests', function(){ beforeEach(function() { fixture.setBase('fixtures') }); beforeEach(function(){ this.sample = fixture.load('sample.html'); runSpy = spyOn(scrambler._scrambler, "run").and.callThrough(); jasmine.clock().install(); }); afterEach(function() { fixture.cleanup(); jasmine.clock().uninstall(); }); it('plays with the html fixture', function() { scrambler.scramble(this.sample[0], false); expect(runSpy.calls.count()).toEqual(1); jasmine.clock().tick(501); expect(runSpy.calls.count()).toEqual(3); // TODO: check if the text has been scrambled }); it('defaults on body when calling the go function', function() { var scramblerSpy = spyOn(scrambler, "scramble"); scrambler.go('en'); expect(scramblerSpy.calls.count()).toEqual(1); expect(scramblerSpy).toHaveBeenCalledWith(document.querySelector('body'), true); }); it('the go function accepts a custom element', function() { var scramblerSpy = spyOn(scrambler, "scramble"); scrambler.go('en', this.sample[0]); expect(scramblerSpy.calls.count()).toEqual(1); expect(scramblerSpy).toHaveBeenCalledWith(this.sample[0], true); }); });
JavaScript
0.000014
@@ -1,8 +1,86 @@ +function removeWhitespace(string) %7B%0A return string.replace(/%5Cs+/g, '');%0A%7D%0A%0A describe @@ -521,32 +521,109 @@ ', function() %7B%0A + var originalContent = removeWhitespace(this.sample%5B0%5D.textContent);%0A%0A scramble @@ -804,53 +804,89 @@ -// TODO: check if the text has been scrambled +expect(originalContent).not.toEqual(removeWhitespace(this.sample%5B0%5D.textContent)) %0A
51a19a8ace41d9c9feccdcf6e2008d9070f957b2
Update [gemrank] regex to match "1st" (#2743)
services/gem/gem-rank.tester.js
services/gem/gem-rank.tester.js
'use strict' const Joi = require('joi') const isOrdinalNumber = Joi.string().regex(/^[1-9][0-9]+(ᵗʰ|ˢᵗ|ⁿᵈ|ʳᵈ)$/) const isOrdinalNumberDaily = Joi.string().regex( /^[1-9][0-9]+(ᵗʰ|ˢᵗ|ⁿᵈ|ʳᵈ) daily$/ ) const t = (module.exports = require('../create-service-tester')()) t.create('total rank (valid)') .get('/rt/rspec-puppet-facts.json') .expectJSONTypes( Joi.object().keys({ name: 'rank', value: isOrdinalNumber, }) ) t.create('daily rank (valid)') .get('/rd/rails.json') .expectJSONTypes( Joi.object().keys({ name: 'rank', value: isOrdinalNumberDaily, }) ) t.create('rank (not found)') .get('/rt/not-a-package.json') .expectJSON({ name: 'rank', value: 'not found' }) t.create('rank is null') .get('/rd/rails.json') .intercept(nock => nock('http://bestgems.org') .get('/api/v1/gems/rails/daily_ranking.json') .reply(200, [ { date: '2019-01-06', daily_ranking: null, }, ]) ) .expectJSON({ name: 'rank', value: 'invalid rank' })
JavaScript
0.000001
@@ -163,33 +163,33 @@ (%0A /%5E%5B1-9%5D%5B0-9%5D -+ +* (%E1%B5%97%CA%B0%7C%CB%A2%E1%B5%97%7C%E2%81%BF%E1%B5%88%7C%CA%B3%E1%B5%88) da
d3887cee9624f8cdefd243649d3280ad2231aff8
Use babel helper modules on es2015 sources
babel-es2015.config.js
babel-es2015.config.js
module.exports = { plugins: ['@babel/plugin-proposal-async-generator-functions'], env: { es: { plugins: ['./babel-plugin-pure-curry'] }, cjs: { plugins: [ 'add-module-exports', '@babel/plugin-transform-modules-commonjs' ] } } };
JavaScript
0
@@ -24,16 +24,97 @@ ugins: %5B +%0A %5B'@babel/plugin-transform-runtime', %7B useESModules: true, corejs: 2 %7D%5D,%0A '@babel/ @@ -155,16 +155,19 @@ nctions' +%0A %5D,%0A env @@ -166,24 +166,111 @@ %5D,%0A env: %7B%0A + test: %7B%0A plugins: %5B%5B'@babel/plugin-transform-runtime', %7B corejs: 2 %7D%5D%5D%0A %7D,%0A es: %7B%0A @@ -427,16 +427,76 @@ ommonjs' +,%0A %5B'@babel/plugin-transform-runtime', %7B corejs: 2 %7D%5D %0A %5D
57a0299a0dd3a59431d6ebc9db1c1c69daf24fa7
Fix Merge Problem
app/client/router.js
app/client/router.js
// This is where iron:router should go lili = function () { return 2; }
JavaScript
0.000002
@@ -69,8 +69,45 @@ rn 2;%0A%7D%0A +test = function() %7B%0A return 1;%0A%7D;%0A
05f3260318ec736ebeff9f9ac42933f9e04e0653
add check body
modules/haproxy/controllers/setting.js
modules/haproxy/controllers/setting.js
'use strict'; const mongoose = require('mongoose'); const express = require('express'); const path = require('path'); const db = require('../../../lib/db'); const checkIdOnRequest = require('../../common').checkIdOnRequest; const moduleDB = require('../db'); const app = express(); const router = express.Router(); const core = require('../../../src/core'); const prefix = '/haproxy/settings'; module.exports = (parent) => { app.disable('x-powered-by'); app.set('trust proxy', parent.get('trust proxy')); app.set('views', path.join(__dirname, '..', 'views')); core.logger.verbose('Init:'); core.logger.verbose(`\t\tGET -> ${prefix}`); router.get('/', (req, res, next) => { moduleDB.HAProxySettingModel.find().exec((err, list) => { if (err) { next(err); } else { const content = parent.wordsList['haproxy'][res.locals.lang]['settings']; content.data = list; res.render('settings', content); } }); }); core.logger.verbose(`\t\tPOST -> ${prefix}`); router.post('/', (req, res, next) => { let name = req.body.name; let desc = req.body.desc; var model = new moduleDB.HAProxySettingModel({ token_name: name, description: desc }); model.save((err) => { if (err) { next(err); } else { res.json({ok: true}); } }); }); router.param('id', checkIdOnRequest({ model: moduleDB.HAProxySettingModel, current: 'currentModel' })); core.logger.verbose(`\t\tPUT -> ${prefix}`); router.put('/:id', (req, res, next) => { let name = req.body.name; let desc = req.body.desc; req.currentModel.token_name = name; req.currentModel.description = desc; req.currentModel.save((err) => { if (err) { next(err); } else { res.json({ok: true}); } }); }); core.logger.verbose(`\t\tDELETE -> ${prefix}`); router.delete('/:id', (req, res, next) => { req.currentModel.remove((err) => { if (err) { next(err); } else { const msg = parent.wordsList['haproxy'][res.locals.lang]['ajax'].delete.ok; res.json({ok: true, msg: req.currentModel.token_name + msg}); } }); }); app.use(prefix, parent.authorize, router); parent.use(app); };
JavaScript
0
@@ -153,16 +153,52 @@ ib/db'); +%0A%0Aconst _ = require('../../common'); %0Aconst c @@ -1237,32 +1237,280 @@ req.body.desc;%0A%0A + if (!_.isStringParam(req.body, 'name')) %7B%0A return next(new Error('Missing %22name%22 property'));%0A %7D%0A%0A if (!_.isStringParam(req.body, 'desc')) %7B%0A return next(new Error('Missing %22desc%22 property'));%0A %7D%0A%0A var mode @@ -2044,32 +2044,32 @@ req.body.name;%0A - let desc @@ -2079,32 +2079,280 @@ req.body.desc;%0A%0A + if (!_.isStringParam(req.body, 'name')) %7B%0A return next(new Error('Missing %22name%22 property'));%0A %7D%0A%0A if (!_.isStringParam(req.body, 'desc')) %7B%0A return next(new Error('Missing %22desc%22 property'));%0A %7D%0A%0A req.curr
fd03712e2bbd10356373dcaf8e3b7cc993711d6e
add click log
templates/js-template-runtime/src/app.js
templates/js-template-runtime/src/app.js
var HelloWorldLayer = cc.Layer.extend({ isMouseDown:false, helloImg:null, helloLabel:null, circle:null, sprite:null, ctor:function () { ////////////////////////////// // 1. super init first this._super(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // ask director the window size var size = cc.director.getWinSize(); // add a "close" icon to exit the progress. it's an autorelease object var closeItem = cc.MenuItemImage.create( res.CloseNormal_png, res.CloseSelected_png, function () { history.go(-1); },this); closeItem.attr({ x: size.width - 20, y: 20, anchorX: 0.5, anchorY: 0.5 }); var menu = cc.Menu.create(closeItem); menu.x = 0; menu.y = 0; this.addChild(menu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label this.helloLabel = cc.LabelTTF.create("Hello World", "Arial", 38); // position the label on the center of the screen this.helloLabel.x = size.width / 2; this.helloLabel.y = 0; // add the label as a child to this layer this.addChild(this.helloLabel, 5); var lazyLayer = cc.Layer.create(); this.addChild(lazyLayer); // add "HelloWorld" splash screen" this.sprite = cc.Sprite.create(res.HelloWorld_png); this.sprite.attr({ x: size.width / 2, y: size.height / 2, scale: 0.5, rotation: 180 }); lazyLayer.addChild(this.sprite, 0); var rotateToA = cc.RotateTo.create(2, 0); var scaleToA = cc.ScaleTo.create(2, 1, 1); this.sprite.runAction(cc.Sequence.create(rotateToA, scaleToA)); this.helloLabel.runAction(cc.Spawn.create(cc.MoveBy.create(2.5, cc.p(0, size.height - 40)),cc.TintTo.create(2.5,255,125,0))); return true; } }); var HelloWorldScene = cc.Scene.extend({ onEnter:function () { this._super(); var layer = new HelloWorldLayer(); this.addChild(layer); } });
JavaScript
0.000002
@@ -731,21 +731,33 @@ -history.go(-1 +cc.log(%22Menu is clicked!%22 );%0A
56996d204bb1401bde293433185b68866c8eb8a4
fix minor mistake
src/main/js/ephox/snooker/model/TableGrid.js
src/main/js/ephox/snooker/model/TableGrid.js
define( 'ephox.snooker.model.TableGrid', [ 'ephox.compass.Arr', 'ephox.peanut.Fun', 'ephox.snooker.model.GridRow' ], function (Arr, Fun, GridRow) { var getColumn = function (grid, index) { return Arr.map(grid, function (row) { return GridRow.getCell(grid, index); }); }; var getRow = function (grid, index) { return grid[index]; }; var findDiff = function (xs, comp) { if (xs.length === 0) return 0; var first = xs[0]; var index = Arr.findIndex(xs, function (x) { return !comp(first, x); }); return index === -1 ? xs.length : index; }; /* * grid is the grid * row is the row index into the grid * column in the column index into the grid * * Return * colspan: column span of the cell at (row, column) * rowspan: row span of the cell at (row, column) */ var subgrid = function (grid, row, column, comparator) { var restOfRow = getRow(grid, row).cells().slice(column); var endColIndex = findDiff(restOfRow, comparator); var restOfColumn = getColumn(grid, column).slice(row); var endRowIndex = findDiff(restOfColumn, comparator); return { colspan: Fun.constant(endColIndex), rowspan: Fun.constant(endRowIndex) }; }; return { subgrid: subgrid }; } );
JavaScript
0.99764
@@ -283,20 +283,19 @@ getCell( -grid +row , index)
9d84f5128fa28cac19ae3682b578714efc354b5a
change ambient light color
components/famous-demos/torus/torus.js
components/famous-demos/torus/torus.js
BEST.component('famous-demos:torus', { tree: 'torus.html', behaviors: { '.my-mesh-container': { 'origin': [0.5, 0.5], 'mount-point': [0.5, 0.5], 'size': function(canvasSize) { return canvasSize; }, 'position': function(position) { return [position[0], position[1]]; }, 'rotation': function($time) { return [$time / 1000, $time / 1000, $time / 1000]; }, }, '.my-point-light': { 'color': function(pointLightColor) { return pointLightColor; }, 'position': function(pointLightPos) { return [0, 0, 0] } }, '.my-ambient-light': { 'color': function(ambientLightColor) { return ambientLightColor; } }, '.my-webgl-mesh': { 'geometry': function(geometry) { return geometry; }, 'color': function(color) { return color; }, } }, states: { color: '#3cf', geometry: 'Icosahedron', position: [window.innerWidth * 0.5, window.innerHeight * 0.5], pointLightColor: 'white', ambientLightColor: 'blue', canvasSize: [200, 200, 200], } });
JavaScript
0.000001
@@ -1332,16 +1332,20 @@ Color: ' +dark blue',%0A
c6cb9ce2a525f5ac35fc896ef6a30c4e2fe29b5c
Fix calendar colors
public/js/calendar.js
public/js/calendar.js
// (function() { // Launch calendar var calendar = $('#calendar'); calendar.fullCalendar({ header: { left: 'title prev,next today', right: 'month,agendaWeek,agendaDay' }, editable: true, selectable: true, unselectCancel: '.popover', firstDay: 1, timeFormat: 'H:mm', eventClick: editor.open, select: editor.select, unselect: editor.close }); // Adaptive view based on window width var addSources = function(sources) { org.cals = sources; $.each(sources, function(index, source) { source.color = 'hsl(' + (index % 6) * 60 + ', 100%, 30%)'; calendar.fullCalendar('addEventSource', source); }) editor.init(); calnav.render(sources) }; //api.get('api/1/orgs/''/calendars', addSources); addSources(calendars); // Adaptive view based on window width var adaptView = function() { var h = $('main').height(); if ($(window).width() < 850) { calendar.fullCalendar('changeView', 'agendaDay'); calendar.fullCalendar('option', 'height', 5000); } else if ($(window).width() > 850 && $(window).width() < 1080) { calendar.fullCalendar('changeView', 'agendaWeek'); calendar.fullCalendar('option', 'height', h); } else { calendar.fullCalendar('changeView', 'month'); calendar.fullCalendar('option', 'height', h); }; }; // When resizing the window, get the correct view. $(window).resize(adaptView); adaptView(); })();
JavaScript
0.000011
@@ -552,73 +552,8 @@ ) %7B%0A - source.color = 'hsl(' + (index %25 6) * 60 + ', 100%25, 30%25)';%0A
1d7830812f4e1177319bbc8e25d9519e1ee7d7bd
Remove d3.chart sourceMappingURL comment, causes FF warning.
velo/static/javascripts/d3.chart.min.js
velo/static/javascripts/d3.chart.min.js
(function(t){"use strict";function e(t){var e,r,n,i;if(!t)return t;for(r=arguments.length,e=1;r>e;e++)if(n=arguments[e])for(i in n)t[i]=n[i];return t}var r=t.d3,n=Object.hasOwnProperty,i=function(t,e){if(!t)throw Error("[d3.chart] "+e)};i(r,"d3.js is required"),i("string"==typeof r.version&&r.version.match(/^3/),"d3.js version 3 is required");var a=/^(enter|update|merge|exit)(:transition)?$/,s=function(t){i(t,"Layers must be initialized with a base."),this._base=t,this._handlers={}};s.prototype.dataBind=function(){i(!1,"Layers must specify a `dataBind` method.")},s.prototype.insert=function(){i(!1,"Layers must specify an `insert` method.")},s.prototype.on=function(t,e,r){return r=r||{},i(a.test(t),"Unrecognized lifecycle event name specified to `Layer#on`: '"+t+"'."),t in this._handlers||(this._handlers[t]=[]),this._handlers[t].push({callback:e,chart:r.chart||null}),this._base},s.prototype.off=function(t,e){var r,n=this._handlers[t];if(i(a.test(t),"Unrecognized lifecycle event name specified to `Layer#off`: '"+t+"'."),!n)return this._base;if(1===arguments.length)return n.length=0,this._base;for(r=n.length-1;r>-1;--r)n[r].callback===e&&n.splice(r,1);return this._base},s.prototype.draw=function(t){var e,n,a,s,o,h,c,l;e=this.dataBind.call(this._base,t),i(e&&e.call===r.selection.prototype.call,"Invalid selection defined by `Layer#dataBind` method."),i(e.enter,"Layer selection not properly bound."),n=e.enter(),n._chart=this._base._chart,a=[{name:"update",selection:e},{name:"enter",selection:this.insert.bind(n)},{name:"merge",selection:e},{name:"exit",selection:e.exit.bind(e)}];for(var u=0,p=a.length;p>u;++u)if(h=a[u].name,s=a[u].selection,"function"==typeof s&&(s=s()),!s.empty()){if(i(s&&s.call===r.selection.prototype.call,"Invalid selection defined for '"+h+"' lifecycle event."),o=this._handlers[h])for(c=0,l=o.length;l>c;++c)s._chart=o[c].chart||this._base._chart,s.call(o[c].callback);if(o=this._handlers[h+":transition"],o&&o.length)for(s=s.transition(),c=0,l=o.length;l>c;++c)s._chart=o[c].chart||this._base._chart,s.call(o[c].callback)}},r.selection.prototype.layer=function(t){var e,r=new s(this);if(r.dataBind=t.dataBind,r.insert=t.insert,"events"in t)for(e in t.events)r.on(e,t.events[e]);return this.on=function(){return r.on.apply(r,arguments)},this.off=function(){return r.off.apply(r,arguments)},this.draw=function(){return r.draw.apply(r,arguments)},this};var o=function(t,e){var r=this.constructor,i=r.__super__;i&&o.call(i,t,e),n.call(r.prototype,"initialize")&&this.initialize.apply(t,e)},h=function(t,e){var r=this.constructor,i=r.__super__;return this===t&&n.call(this,"transform")&&(e=this.transform(e)),n.call(r.prototype,"transform")&&(e=r.prototype.transform.call(t,e)),i&&(e=h.call(i,t,e)),e},c=function(t,e){this.base=t,this._layers={},this._attached={},this._events={},e&&e.transform&&(this.transform=e.transform),o.call(this,this,[e])};c.prototype.initialize=function(){},c.prototype.unlayer=function(t){var e=this.layer(t);return delete this._layers[t],delete e._chart,e},c.prototype.layer=function(t,e,r){var n;if(1===arguments.length)return this._layers[t];if(2===arguments.length){if("function"==typeof e.draw)return e._chart=this,this._layers[t]=e,this._layers[t];i(!1,"When reattaching a layer, the second argument must be a d3.chart layer")}return n=e.layer(r),this._layers[t]=n,e._chart=this,n},c.prototype.attach=function(t,e){return 1===arguments.length?this._attached[t]:(this._attached[t]=e,e)},c.prototype.draw=function(t){var e,r,n;t=h.call(this,this,t);for(e in this._layers)this._layers[e].draw(t);for(r in this._attached)n=this.demux?this.demux(r,t):t,this._attached[r].draw(n)},c.prototype.on=function(t,e,r){var n=this._events[t]||(this._events[t]=[]);return n.push({callback:e,context:r||this,_chart:this}),this},c.prototype.once=function(t,e,r){var n=this,i=function(){n.off(t,i),e.apply(this,arguments)};return this.on(t,i,r)},c.prototype.off=function(t,e,r){var n,i,a,s,o,h;if(0===arguments.length){for(t in this._events)this._events[t].length=0;return this}if(1===arguments.length)return a=this._events[t],a&&(a.length=0),this;for(n=t?[t]:Object.keys(this._events),o=0;n.length>o;o++)for(i=n[o],a=this._events[i],h=a.length;h--;)s=a[h],(e&&e===s.callback||r&&r===s.context)&&a.splice(h,1);return this},c.prototype.trigger=function(t){var e,r,n=Array.prototype.slice.call(arguments,1),i=this._events[t];if(void 0!==i)for(e=0;i.length>e;e++)r=i[e],r.callback.apply(r.context,n);return this},c.extend=function(t,r,i){var a,s=this;a=r&&n.call(r,"constructor")?r.constructor:function(){return s.apply(this,arguments)},e(a,s,i);var o=function(){this.constructor=a};return o.prototype=s.prototype,a.prototype=new o,r&&e(a.prototype,r),a.__super__=s.prototype,c[t]=a,a},r.chart=function(t){return 0===arguments.length?c:1===arguments.length?c[t]:c.extend.apply(c,arguments)},r.selection.prototype.chart=function(t,e){if(0===arguments.length)return this._chart;var r=c[t];return i(r,"No chart registered with name '"+t+"'"),new r(this,e)},r.selection.enter.prototype.chart=function(){return this._chart},r.transition.prototype.chart=r.selection.enter.prototype.chart})(this); //@ sourceMappingURL=d3.chart.min.map
JavaScript
0
@@ -5141,42 +5141,4 @@ s);%0A -//@ sourceMappingURL=d3.chart.min.map%0A
f2c9ad2387836eb693ddc1777720de9dad3ef232
Store the data-tumblelog attribute in a variable
contentscript.js
contentscript.js
var openBlockList = function () { $('document').ready( function () { $("#blocked_blogs > .accordion_trigger_wrapper > .accordion_trigger").click(); }); } var block = function (blog) { $("#blocked_blogs > .accordion_content > .block-input > .text > #block").val(blog); setTimeout(function () { $("#blocked_blogs > .accordion_content > .block-input > .block-button").click(); }, 500); } var activate = function () { console.log ("activate"); var usersToBeBlockedStr = window.prompt("Please input comma separated list of users to be blocked",""); var usersToBeBlocked = usersToBeBlockedStr.split(","); openBlockList(); // we will be watching the blockListContainer for changes var blockListContainer = $('#blocked_blogs > div.accordion_content'); // i don't know if i need all this to do what i need to do // TODO: determine what to keep and what to trim var mutationObserverConfig = { attributes: true, childList: true, subtree: true }; var mutationObserverCallback = function (mutationsList, observer) { for (var mutation of mutationsList) { if (mutation.type == 'childList') { if (mutation.target.classList[0] == "error_tag") { console.log("Error"); } else if (mutation.addedNodes.length > 0) { if ((mutation.addedNodes[0]).getAttribute('data-tumblelog') !== null) { console.log("Added to blocklist: " + (mutation.addedNodes[0]).getAttribute('data-tumblelog')); } } else if (mutation.removedNodes.length > 0) { if ((mutation.removedNodes[0]).getAttribute('data-tumblelog') !== null) { console.log("Removed from blocklist: " + (mutation.removedNodes[0]).getAttribute('data-tumblelog')); } } } } }; var observer = new MutationObserver(mutationObserverCallback); // in the console you don't need [0], but in the extension you do... a frustrating adventure in troubleshooting observer.observe(blockListContainer[0], mutationObserverConfig); var i = 0; var inter = setInterval (function () { console.log (i + " -- " + usersToBeBlocked[i]); block(usersToBeBlocked[i++]); if (i >= usersToBeBlocked.length) { clearInterval(inter); console.log ("exit"); } }, 1100); // observer.disconnect() // this is disabled because it triggers before any of the blocking happens } activate ();
JavaScript
0.000027
@@ -1274,36 +1274,48 @@ gth %3E 0) %7B%0A%09%09%09%09%09 -if ( +var tumblelog = (mutation.addedN @@ -1345,32 +1345,52 @@ data-tumblelog') +;%0A%09%09%09%09%09if (tumblelog !== null) %7B%0A%09%09%09 @@ -1433,52 +1433,8 @@ %22 + -(mutation.addedNodes%5B0%5D).getAttribute('data- tumb @@ -1430,34 +1430,32 @@ t: %22 + tumblelog -') );%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D%0A
cffa5d85b09b20b5a7a17c50c0bb183435350c8a
check for binding value first before the expression closes #995
src/core/generator.js
src/core/generator.js
import Config from '../config'; import { getScope, getDataAttribute, isObject, toArray, find, getPath, hasPath, isNullOrUndefined, isCallable, deepParseInt, } from './utils'; /** * Generates the options required to construct a field. */ export default class Generator { static generate (el, binding, vnode) { const model = Generator.resolveModel(binding, vnode); const options = Config.resolve(vnode.context); return { name: Generator.resolveName(el, vnode), el: el, listen: !binding.modifiers.disable, scope: Generator.resolveScope(el, binding, vnode), vm: Generator.makeVM(vnode.context), expression: binding.value, component: vnode.child, classes: options.classes, classNames: options.classNames, getter: Generator.resolveGetter(el, vnode, model), events: Generator.resolveEvents(el, vnode) || options.events, model, delay: Generator.resolveDelay(el, vnode, options), rules: Generator.resolveRules(el, binding), initial: !!binding.modifiers.initial, validity: options.validity, aria: options.aria, initialValue: Generator.resolveInitialValue(vnode) }; } static getCtorConfig (vnode) { if (!vnode.child) return null; const config = getPath('child.$options.$_veeValidate', vnode); return config; } /** * * @param {*} el * @param {*} binding */ static resolveRules (el, binding) { if (!binding || !binding.expression) { return getDataAttribute(el, 'rules'); } if (typeof binding.value === 'string') { return binding.value; } if (~['string', 'object'].indexOf(typeof binding.value.rules)) { return binding.value.rules; } return binding.value; } /** * @param {*} vnode */ static resolveInitialValue (vnode) { const model = vnode.data.model || find(vnode.data.directives, d => d.name === 'model'); return model && model.value; } /** * Creates a non-circular partial VM instance from a Vue instance. * @param {*} vm */ static makeVM (vm) { return { get $el () { return vm.$el; }, get $refs () { return vm.$refs; }, $watch: vm.$watch ? vm.$watch.bind(vm) : () => {}, $validator: vm.$validator ? { errors: vm.$validator.errors, validate: vm.$validator.validate.bind(vm.$validator), update: vm.$validator.update.bind(vm.$validator) } : null }; } /** * Resolves the delay value. * @param {*} el * @param {*} vnode * @param {Object} options */ static resolveDelay (el, vnode, options) { let delay = getDataAttribute(el, 'delay'); let globalDelay = (options && 'delay' in options) ? options.delay : 0; if (!delay && vnode.child && vnode.child.$attrs) { delay = vnode.child.$attrs['data-vv-delay']; } return (delay) ? { local: { input: parseInt(delay) }, global: deepParseInt(globalDelay) } : { global: deepParseInt(globalDelay) }; } /** * Resolves the events to validate in response to. * @param {*} el * @param {*} vnode */ static resolveEvents (el, vnode) { let events = getDataAttribute(el, 'validate-on'); if (!events && vnode.child && vnode.child.$attrs) { events = vnode.child.$attrs['data-vv-validate-on']; } if (!events && vnode.child) { const config = Generator.getCtorConfig(vnode); events = config && config.events; } return events; } /** * Resolves the scope for the field. * @param {*} el * @param {*} binding */ static resolveScope (el, binding, vnode = {}) { let scope = null; if (isObject(binding.value)) { scope = binding.value.scope; } if (vnode.child && isNullOrUndefined(scope)) { scope = vnode.child.$attrs && vnode.child.$attrs['data-vv-scope']; } return !isNullOrUndefined(scope) ? scope : getScope(el); } /** * Checks if the node directives contains a v-model or a specified arg. * Args take priority over models. * * @return {Object} */ static resolveModel (binding, vnode) { if (binding.arg) { return binding.arg; } if (isObject(binding.value) && binding.value.arg) { return binding.value.arg; } const model = vnode.data.model || find(vnode.data.directives, d => d.name === 'model'); if (!model) { return null; } const watchable = /^[a-z_]+[0-9]*(\w*\.[a-z_]\w*)*$/i.test(model.expression) && hasPath(model.expression, vnode.context); if (!watchable) { return null; } return model.expression; } /** * Resolves the field name to trigger validations. * @return {String} The field name. */ static resolveName (el, vnode) { let name = getDataAttribute(el, 'name'); if (!name && !vnode.child) { return el.name; } if (!name && vnode.child && vnode.child.$attrs) { name = vnode.child.$attrs['data-vv-name'] || vnode.child.$attrs['name']; } if (!name && vnode.child) { const config = Generator.getCtorConfig(vnode); if (config && isCallable(config.name)) { const boundGetter = config.name.bind(vnode.child); return boundGetter(); } return vnode.child.name; } return name; } /** * Returns a value getter input type. */ static resolveGetter (el, vnode, model) { if (model) { return () => { return getPath(model, vnode.context); }; } if (vnode.child) { const path = getDataAttribute(el, 'value-path') || (vnode.child.$attrs && vnode.child.$attrs['data-vv-value-path']); if (path) { return () => { return getPath(path, vnode.child); }; } const config = Generator.getCtorConfig(vnode); if (config && isCallable(config.value)) { const boundGetter = config.value.bind(vnode.child); return () => { return boundGetter(); }; } return () => { return vnode.child.value; }; } switch (el.type) { case 'checkbox': return () => { let els = document.querySelectorAll(`input[name="${el.name}"]`); els = toArray(els).filter(el => el.checked); if (!els.length) return undefined; return els.map(checkbox => checkbox.value); }; case 'radio': return () => { const els = document.querySelectorAll(`input[name="${el.name}"]`); const elm = find(els, el => el.checked); return elm && elm.value; }; case 'file': return (context) => { return toArray(el.files); }; case 'select-multiple': return () => { return toArray(el.options).filter(opt => opt.selected).map(opt => opt.value); }; default: return () => { return el && el.value; }; } } }
JavaScript
0
@@ -1378,51 +1378,50 @@ * -%0A * @param %7B*%7D el%0A * @param %7B*%7D binding + Resolves the rules defined on an element. %0A @@ -1467,16 +1467,35 @@ %7B%0A if + (!binding.value && (!bindi @@ -1520,16 +1520,17 @@ ression) +) %7B%0A
c83e73127beddee5cb7685d9037d715c3339bb27
set node name by replacing into GraphNode object
src/inputAdapter.js
src/inputAdapter.js
var Class = require('class-wrapper').Class; var GraphNode = require('./src/GraphNode'); /** * Input adapter * * It converts the raw objects into GraphNodes and prepares node of interest for futher processing * * @param {Object} [properties] - Adapter properties. Any of already defined properties can be redefined and new one can be added. Only property names which are already defined for methods or if the value is undefined, then such properties will be skipped and warnong message will be displayed in the console. */ var InputAdapter = Class(function(properties) { if (properties) { Object.keys(properties).forEarch(property => { if (typeof this[property] === 'function') { console.warn(`InputAdapter(): property ${property} is skipped because this name is already reserved for a method`); return; } var value = properties[property]; if (typeof value === 'undefined') { console.warn(`InputAdapter(): property ${property} is skipped because it's value is undefined`); return; } this[property] = properties[property]; }); } }, /** @lends InputAdapter.prototype */{ /** * Node of interest * * @type {GraphNode} */ noi: null, /** * Map of node name to their's raw data * * @type {Object} */ map: null, /** * Set [node map]{@link GraphNode#map} * * @param {Object} map - Map of nodes * * @throws {TypeError} "map" argument is expected to be an instance of Object class */ setNodeMap: function(map) { if (!(map instanceof Object)) { throw new TypeError('"map" argument is expected to be an instance of Object class'); } this.map = map; }, /** * Prepare raw NOI data for the further processing * * It also collects and sets the parent stack for NOI * * @param {String} noiName - NOI name * @returns {GrapchNode} - NOI * * @throws {TypeError} "noi" argument is expected to be a string * @throws {Error} Node data for "${noiName}" does not exist in the provided node map */ prepareNOI: function(noiName) { this.noi = null; if (typeof noiName !== 'string') { throw new TypeError('"noi" argument is expected to be a string'); } var noiData = this.map[noiName]; if (!noiData) { throw new Error(`Node data for "${noiName}" does not exist in the provided node map`); } this.noi = new GraphNode(noiData, { parentStack: noiData.parent ? this.prepareParentNodes(noiData.parent) : undefined }); return this.noi; }, /** * Prepare parent node * * It also sets the correct type of the node. * * @param {String} nodeName - Parent node name * @returns {GraphNode[]} - Ordered stack of parent nodes */ prepareParentNodes: function(nodeName) { var data = this.map[nodeName]; var stack = [new GraphNode(data, { type: data ? 'parent' : 'no-ref' })]; if (data && data.parent) { stack = stack.concat(this.prepareParentNodes(data.parent)); } return stack; }, /** * Prepare children and mixin nodes * * It also sets the correct type of the node. */ prepareOtherNodes: function() { [ 'children', 'mixin' ].forEach(groupName => { var set = this.noi[groupName]; if (!set) { return; } set.forEach((nodeName, index) => { var data = this.map[nodeName]; set[index] = new GraphNode(data, { type: data ? groupName : 'no-ref' }); }); }); } }); module.exports = InputAdapter;
JavaScript
0.000003
@@ -68,12 +68,8 @@ ('./ -src/ Grap @@ -2329,16 +2329,34 @@ Data, %7B%0A +%09%09%09name: noiName,%0A %09%09%09paren @@ -2492,24 +2492,154 @@ nt node%0A%09 *%0A +%09 * The first node in stack is the actual parent node of the NOI. The last parent node is the root node of the inheritance chain.%0A %09 * It also @@ -2659,32 +2659,39 @@ ect type of the +parent node.%0A%09 *%0A%09 * @p @@ -2909,16 +2909,35 @@ data, %7B%0A +%09%09%09name: nodeName,%0A %09%09%09type: @@ -3420,16 +3420,56 @@ Name%5D;%0A%0A +%09%09%09%09// Replace node name with GraphNode%0A %09%09%09%09set%5B @@ -3499,16 +3499,37 @@ data, %7B%0A +%09%09%09%09%09name: nodeName,%0A %09%09%09%09%09typ
625101fde0df3b6325d222657d9df81570bc6bd7
Put focus on input field after language switch.
assets/js/app.js
assets/js/app.js
/** * Copyright Ben Stones, 2016. All rights reserved. * * @author Ben Stones (ben@b3ns.com) * * Do not use in your own projects without prior permission. */ $(document).ready(function() { var alphabet = { a: { english: 'Alpha', deutsch: 'Anton', animals: 'Anaconda' }, b: { english: 'Bravo', deutsch: 'Berta', animals: 'Bluebird' }, c: { english: 'Charlie', deutsch: 'Cäsar', animals: 'Chameleon' }, d: { english: 'Delta', deutsch: 'Dora', animals: 'Dog' }, e: { english: 'Echo', deutsch: 'Emil', animals: 'Elephant' }, f: { english: 'Foxtrot', deutsch: 'Friedrich', animals: 'Ferret' }, g: { english: 'Golf', deutsch: 'Gustav', animals: 'Gnu' }, h: { english: 'Hotel', deutsch: 'Heinrich', animals: 'Hamster' }, i: { english: 'Indigo', deutsch: 'Ida', animals: 'Ibex' }, j: { english: 'Juliet', deutsch: 'Julius', animals: 'Kangaroo' }, k: { english: 'Kilo', deutsch: 'Kaufmann', animals: 'Koala' }, l: { english: 'Lima', deutsch: 'Ludwig', animals: 'Ladybug' }, m: { english: 'Mike', deutsch: 'Martha', animals: 'Mouse' }, n: { english: 'November', deutsch: 'Nordpol', animals: 'Nautilus' }, o: { english: 'Oscar', deutsch: 'Otto', animals: 'Orca' }, p: { english: 'Papa', deutsch: 'Paula', animals: 'Pigeon' }, q: { english: 'Quebec', deutsch: 'Quelle', animals: 'Quetzal' }, r: { english: 'Romeo', deutsch: 'Richard', animals: 'Rabbit' }, s: { english: 'Sierra', deutsch: 'Siegfried', animals: 'Squirrel' }, t: { english: 'Tango', deutsch: 'Theodor', animals: 'Tuna' }, u: { english: 'Uniform', deutsch: 'Ulrich', animals: 'Urchin' }, v: { english: 'Victor', deutsch: 'Viktor', animals: 'Viper' }, w: { english: 'Whiskey', deutsch: 'Wilhelm', animals: 'Wasp' }, x: { english: 'X-Ray', deutsch: 'Xanthippe', animals: 'Xerus' }, y: { english: 'Yankee', deutsch: 'Ypsilon', animals: 'Yak' }, z: { english: 'Zulu', deutsch: 'Zeppelin', animals: 'Zebra' }, 0: { english: 'Zero', deutsch: 'Null', animals: 'Zero' }, 1: { english: 'One', deutsch: 'Eins', animals: 'One' }, 2: { english: 'Two', deutsch: 'Zwei', animals: 'Two' }, 3: { english: 'Three', deutsch: 'Drei', animals: 'Three' }, 4: { english: 'Four', deutsch: 'Vier', animals: 'Four' }, 5: { english: 'Five', deutsch: 'Fünf', animals: 'Five' }, 6: { english: 'Six', deutsch: 'Sechs', animals: 'Six' }, 7: { english: 'Seven', deutsch: 'Sieben', animals: 'Seven' }, 8: { english: 'Eight', deutsch: 'Acht', animals: 'Eight' }, 9: { english: 'Nine', deutsch: 'Neun', animals: 'Nine' } }; var defaultLanguage = 'english'; var formInput = $('form input'); var resultBox = $('div#result'); $('form').submit(function(e) { e.preventDefault(); }); $('div#options > ul > li > a').click(function() { // Get parent element of selected option var selection = $(this).parent(); // Set the selected option active selection.addClass('active').siblings().removeClass('active'); // Change the default language defaultLanguage = selection.attr('data-language'); // Switch text on labels to use the new default language $('.language-specific').text( $('.language-specific').attr('data-' + defaultLanguage) ); // Trigger generation with new language generate(formInput); }); formInput.keyup(function(e) { if (e.keyCode != 16) { generate($(this)); } }); function generate(object) { var characters = object.val().toLowerCase().split(''); var phonetic = ''; for (i = 0; i < characters.length; i++) { if (typeof alphabet[characters[i]][defaultLanguage] !== 'undefined' && alphabet[characters[i]][defaultLanguage]) { phonetic += alphabet[characters[i]][defaultLanguage] + ', '; } } if (characters.length) { resultBox.html('<p>' + phonetic.substring(0, phonetic.length - 2) + '</p>').slideDown('medium'); } else { resultBox.slideUp('fast'); } } });
JavaScript
0
@@ -5163,16 +5163,80 @@ mInput); +%0A%0A // Put focus on input field%0A formInput.focus(); %0A %7D);
0ec2200d9d2bbee1521f9adf7c79d7318513f32a
Fix `log` in modulr.js to avoid undefined variable errors
assets/modulr.js
assets/modulr.js
var modulr = (function() { var _modules = {}, _aliases = {}, _cache = {}, PREFIX = '__module__'; // Prefix identifiers to avoid issues in IE. function log(str) { if (console && console.log) { console.log(str); } } function require(identifier) { var m, key = PREFIX + identifier; log('Required module "' + identifier + '".'); if (_aliases[key]) { key = _aliases[key]; log('Found module "' + identifier + '" as alias of module "' + key.replace('__module__', '') + '".'); } if (!_cache[key]) { m = _modules[key]; if (!m) { throw 'Can\'t find module "' + identifier + '".'; } _cache[key] = m(require, {}); } return _cache[key]; } function cache(identifier, fn) { var key = PREFIX + identifier; log('Cached module "' + identifier + '".'); if (_modules[key]) { throw 'Can\'t ovewrite module "' + identifier + '".'; } _modules[key] = fn; } function alias(alias, identifier) { log('Linked "' + alias + '" to module "' + identifier + '".'); _aliases[PREFIX + alias] = PREFIX + identifier; } return { require: require, cache: cache, alias: alias }; })();
JavaScript
0.000001
@@ -16,16 +16,22 @@ unction( +global ) %7B%0A va @@ -194,16 +194,23 @@ if ( +global. console @@ -1232,11 +1232,15 @@ %7D;%0A%7D)( +this );%0A
01c682f34e36d3d275639dd8df73350ba80f4685
Fix regression in sibling navigation
webapp/public/javascripts/events_nav.js
webapp/public/javascripts/events_nav.js
$j(function() { $j('.events_nav').change(function(event) { var selector = $j(this); var cancelled = true; var dialogButtons = function() { var buttons = {}; buttons[i18n.t('save_and_exit')] = function() { cancelled = false; $j('#events_nav_spinner').show(); $j(formWatcher.form).append(redirectTo( build_url_with_tab_index( selector.val()))); post_and_exit(formWatcher.form); $j(this).dialog('close'); }; buttons[i18n.t('leave_without_saving')] = function() { cancelled = false; $j('#events_nav_spinner').show(); formWatcher.submitted = true; send_url_with_tab_index(selector.val()); $j(this).dialog('close'); }; return buttons; }; var redirectTo = function(path) { return '<input id="events_nav_redirect" type="hidden" name="redirect_to" value="' + path + '"/>'; }; var formIsDirty = function() { if (window.formWatcher === undefined) { return false; } else { return formWatcher.isDirty(); } }; if ($j(this).val()) { if (formIsDirty()) { $j('#events_nav_dialog').dialog({ title: i18n.t('unsaved_changes'), height: 300, width: 600, buttons: dialogButtons(), beforeClose: function(event, ui) { if (cancelled) { selector.val(''); } } }); } else { $j('#events_nav_spinner').show(); send_url_with_tab_index(selector.val()); } } }); });
JavaScript
0.000014
@@ -504,16 +504,19 @@ her.form +.id );%0A
359e7e48b9f92321b3614305a08b976e2b43ea8d
fix The Y axis label does not work on IE browser
webapp/src/chart/renderer/axis-label.js
webapp/src/chart/renderer/axis-label.js
// import d3 from 'd3' /* function wrap (text, width) { text.each(function () { let text = d3.select(this) let words = text.text().split('').reverse() let word let line = [] let sumLineNumber = words.length let lineNumber = 1 let lineHeight = 1.1 let tspan = text.text(null).append('tspan') while (words.length > 0) { word = words.pop() line.push(word) tspan.text(line.join(' ')) if (tspan.node().getComputedTextLength() > width) { line.pop() tspan.text(line.join(' ')) line = [word] var currentLineHeight = words.length === sumLineNumber - 1 ? -Math.ceil(sumLineNumber / 2, -1) : 1 tspan = text.append('tspan') .attr({ 'x': 0, 'dy': (currentLineHeight * lineNumber * lineHeight) + 'rem' }) .text(word) } } }) } */ function axisLabel () { var _width = 1 var _height = 1 var _fontSize = 14 var _xLabel, _yLabel // var _textLength = 5 var _margin = {top: 0, right: 0, bottom: 30, left: 10} function chart (selection) { if (_xLabel) { var xAxisLabel = selection.select('.x.axis').selectAll('.label').data(_xLabel) .enter().append('g') .attr({ 'class': 'label', 'transform': 'translate(' + (_width / 2) + ', ' + _margin.bottom + ')' }) .style({ 'font-size': _fontSize }) xAxisLabel.append('text').text(d => { return d }) } if (_yLabel) { var yAxisLabel = selection.select('.y.axis').selectAll('.label').data(_yLabel) .enter().append('g') .attr({ 'class': 'label', 'transform': 'translate(' + (-_margin.left) + ', ' + (_height / 2) + ')' }) .style({ 'font-size': _fontSize }) yAxisLabel.append('text').text(d => { return d }) .style( 'transform', 'rotate(-90deg)' ) .attr({ 'dx': 0, 'dy': 10 }) // .call(wrap, _textLength, 0, 0) } } chart.fontSize = function (value) { if (!arguments.length) { return _fontSize } _fontSize = value return chart } chart.width = function (value) { if (!arguments.length) { return _width } _width = value return chart } chart.height = function (value) { if (!arguments.length) { return _height } _height = value return chart } chart.fontSize = function (value) { if (!arguments.length) { return _fontSize } _fontSize = value return chart } chart.data = function (xValue, yValue) { if (!arguments.length) { return _xLabel } _xLabel = xValue ? [xValue] : null _yLabel = yValue ? [yValue] : null return chart } chart.margin = function (value) { if (!arguments.length) { return _margin } _margin = value return chart } return chart } export default axisLabel
JavaScript
0.000002
@@ -876,16 +876,54 @@ %7D)%0A%7D%0A*/ +%0A// import browser from 'util/browser' %0A%0Afuncti @@ -1929,17 +1929,15 @@ . -style(%0A +attr(%7B%0A @@ -1957,68 +1957,28 @@ orm' -,%0A 'rotate(-90deg)'%0A )%0A .attr(%7B +: 'rotate(-90 0 0)', %0A
ed51f6a038e1b7ae203574a31f68539d26040f3f
add change event to datepicker
webroot/js/app/components/DatePicker.js
webroot/js/app/components/DatePicker.js
App.Components.DatePickerComponent = Frontend.Component.extend({ setup: function($elements) { $elements.each(function(i, element) { var $container = $(element); if ($container.data('datePickerApplied')) { return; } var $selectContainer = $container.find('select:first').parent(); $container.find('select').hide(); var pickerMarkup = '<div class="input-group date"><input type="text" class="form-control"/><span class="input-group-addon"><i class="fa fa-calendar-o"></i></span></div>'; $selectContainer.append(pickerMarkup); var type = $container.hasClass('dateTime') ? 'dateTime' : 'date'; var format = 'DD.MM.YYYY'; if(type === 'dateTime') { format = 'DD.MM.YYYY HH:mm'; } $selectContainer.find('input[type=text]').blur(function (e) { // if only day and month were entered, make sure the current year is used. if (e.currentTarget.value.substring(6) == '0000') { e.currentTarget.value = e.currentTarget.value.substring(0, 6) + moment().year(); $(e.currentTarget).trigger('change'); } }); var $picker = $selectContainer.find('.input-group.date'); $picker.datetimepicker({ format: format, focusOnShow: !this.Controller.getVar('isMobile'), sideBySide: true, locale: this.Controller.getVar('locale') || 'en', date: this._getDateFromSelects($container), icons: { time: 'fa fa-clock', date: 'fa fa-calendar', up: 'fa fa-chevron-up', down: 'fa fa-chevron-down', previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', today: 'fa fa-calendar-o', clear: 'fa fa-trash' } }); // Update the selects to the correct values after a datepicker change $picker.on('dp.change', function(e) { var $container = $(e.currentTarget).parents('.form-group'); this._updateSelects($container, e.date, $(e.currentTarget)); }.bind(this)); $container.data('datePickerApplied', true); }.bind(this)); }, _updateSelects: function($selectContainer, date, input) { if (input.find('input').val().length == 0) { $selectContainer.find('select option[selected="selected"]').each(function(i, el) { $(el).removeAttr("selected"); }); return null; } $selectContainer.find('select').each(function(i, el) { var $select = $(el); if($select.attr('name').indexOf('[year]') > -1) { $select.val(date.year()); } if($select.attr('name').indexOf('[month]') > -1) { $select.val(date.format('MM')); } if($select.attr('name').indexOf('[day]') > -1) { $select.val(date.format('DD')); } if($select.attr('name').indexOf('[hour]') > -1) { $select.val(date.format('HH')); } if($select.attr('name').indexOf('[minute]') > -1) { $select.val(date.format('mm')); } }); }, _getDateFromSelects: function($selectContainer) { var date = moment(); $selectContainer.find('select').each(function(i, el) { var $select = $(el); var val = parseInt($select.val(), 10); if($select.attr('name').indexOf('[year]') > -1) { date.year(val); } if($select.attr('name').indexOf('[month]') > -1) { date.month(val - 1); } if($select.attr('name').indexOf('[day]') > -1) { date.date(val); } if($select.attr('name').indexOf('[hour]') > -1) { date.hour(val); } if($select.attr('name').indexOf('[minute]') > -1) { date.minute(val); } }); return date; } });
JavaScript
0.000001
@@ -2861,32 +2861,79 @@ select = $(el);%0A + var previousValue = $select.val();%0A if($ @@ -3524,32 +3524,130 @@ ;%0A %7D%0A + if (previousValue != $select.val()) %7B%0A $select.change();%0A %7D%0A %7D);%0A
83c4d0ca903f905f332179a86461fbd8c220bc4b
Comment deep-db autoscaling until scale down ready
src/deep-db/lib/DB.js
src/deep-db/lib/DB.js
/** * Created by AlexanderC on 6/15/15. */ 'use strict'; import Kernel from 'deep-kernel'; import Vogels from 'vogels'; import {ExtendModel} from './Vogels/ExtendModel'; import {ModelNotFoundException} from './Exception/ModelNotFoundException'; import Validation from 'deep-validation'; import Utils from 'util'; import {FailedToCreateTableException} from './Exception/FailedToCreateTableException'; import {FailedToCreateTablesException} from './Exception/FailedToCreateTablesException'; import {AbstractDriver} from './Local/Driver/AbstractDriver'; import {AutoScaleDynamoDB} from './DynamoDB/AutoScaleDynamoDB'; /** * Vogels wrapper */ export class DB extends Kernel.ContainerAware { /** * @param {Array} models * @param {Object} tablesNames */ constructor(models = [], tablesNames = {}) { super(); this._tablesNames = tablesNames; this._validation = new Validation(models); this._models = this._rawModelsToVogels(models); } /** * @returns {Validation} */ get validation() { return this._validation; } /** * @returns {Vogels[]} */ get models() { return this._models; } /** * @param {String} modelName * @returns {Boolean} */ has(modelName) { return typeof this._models[modelName] !== 'undefined'; } /** * @param {String} modelName * @returns {Vogels} */ get(modelName) { if (!this.has(modelName)) { throw new ModelNotFoundException(modelName); } let model = this._models[modelName]; if (this.kernel && this.kernel.isRumEnabled) { // inject logService into extended model to log RUM events model.logService = this.kernel.get('log'); } return model; } /** * @param {String} modelName * @param {Function} callback * @param {Object} options * @returns {DB} */ assureTable(modelName, callback, options = {}) { if (!this.has(modelName)) { throw new ModelNotFoundException(modelName); } options = Utils._extend(DB.DEFAULT_TABLE_OPTIONS, options); options[modelName] = options; Vogels.createTables(options, (error) => { if (error) { throw new FailedToCreateTableException(modelName); } callback(); }); return this; } /** * @param {Function} callback * @param {Object} options * @returns {DB} */ assureTables(callback, options = {}) { let allModelsOptions = {}; let allModelNames = []; for (let modelName in this._models) { if (!this._models.hasOwnProperty(modelName)) { continue; } allModelsOptions[modelName] = Utils._extend(DB.DEFAULT_TABLE_OPTIONS, options); allModelNames.push(modelName); } Vogels.createTables(allModelsOptions, (error) => { if (error) { throw new FailedToCreateTablesException(allModelNames, error); } callback(); }); return this; } /** * Booting a certain service * * @param {Kernel} kernel * @param {Function} callback */ boot(kernel, callback) { this._validation.boot(kernel, () => { this._tablesNames = kernel.config.tablesNames; this._models = this._rawModelsToVogels(kernel.config.models); if (this._localBackend) { this._enableLocalDB(callback); } else { this._initVogelsAutoscale(); callback(); } }); } /** * @private */ _initVogelsAutoscale() { Vogels.AWS.config.maxRetries = 3; Vogels.documentClient( new AutoScaleDynamoDB( Vogels.dynamoDriver(), Vogels.documentClient() ).extend() ); } /** * @param {Object} driver * @returns {DB} * @private */ _setVogelsDriver(driver) { Vogels.dynamoDriver(driver); return this; } /** * @param {Function} callback * @param {String} driver * @param {Number} tts * @returns {AbstractDriver} */ static startLocalDynamoDBServer(callback, driver = 'LocalDynamo', tts = AbstractDriver.DEFAULT_TTS) { let LocalDBServer = require('./Local/DBServer').DBServer; let server = LocalDBServer.create(driver); server.start(callback, tts); return server; } /** * @returns {AWS.DynamoDB|VogelsMock.AWS.DynamoDB|*} * @private */ get _localDynamoDb() { return new Vogels.AWS.DynamoDB({ endpoint: new Vogels.AWS.Endpoint(`http://localhost:${DB.LOCAL_DB_PORT}`), accessKeyId: 'fake', secretAccessKey: 'fake', region: 'us-east-1', }); } /** * @param {Function} callback * @private */ _enableLocalDB(callback) { this._setVogelsDriver(this._localDynamoDb); this.assureTables(callback); } /** * @returns {Object} */ static get DEFAULT_TABLE_OPTIONS() { return { readCapacity: 1, writeCapacity: 1, }; } /** * @param {Array} rawModels * @returns {Object} */ _rawModelsToVogels(rawModels) { let models = {}; for (let modelKey in rawModels) { if (!rawModels.hasOwnProperty(modelKey)) { continue; } let backendModels = rawModels[modelKey]; for (let modelName in backendModels) { if (!backendModels.hasOwnProperty(modelName)) { continue; } models[modelName] = new ExtendModel(Vogels.define( modelName, this._wrapModelSchema(modelName) )).inject(); } } return models; } /** * @param {String} name * @returns {Object} * @private */ _wrapModelSchema(name) { return { hashKey: 'Id', timestamps: true, tableName: this._tablesNames[name], schema: this._validation.getSchema(name), }; } /** * @returns {Number} */ static get LOCAL_DB_PORT() { return AbstractDriver.DEFAULT_PORT; } }
JavaScript
0
@@ -3279,24 +3279,25 @@ else %7B%0A +%0A this._in @@ -3284,24 +3284,90 @@ %7B%0A%0A +// @todo: uncomment when scale down functionality ready%0A // this._initVo
8e4a34108c7367b0b528b944994c75c7cf3b60cc
disable stack and merge options "by color" when color is not a property #2207 (#2289)
src/components/dialogs/stack/stack.js
src/components/dialogs/stack/stack.js
import * as utils from 'base/utils'; import Component from 'base/component'; import Dialog from 'components/dialogs/_dialog'; import draggablelist from 'components/draggablelist/draggablelist'; /* * stack dialog */ var Stack = Dialog.extend({ /** * Initializes the dialog component * @param config component configuration * @param context component context (parent) */ init: function(config, parent) { this.name = 'stack'; var _this = this; // in dialog, this.model_expects = ["state", "ui", "locale"]; this.components = [{ component: draggablelist, placeholder: '.vzb-dialog-draggablelist', model: ["state.marker.group", "state.marker.color", "locale", "ui.chart"], groupID: "manualSorting", isEnabled: "manualSortingEnabled", dataArrFn: _this.manualSorting.bind(_this), lang: '' }]; this.model_binds = { 'change:state.marker.group': function(evt) { //console.log("group change " + evt); if(!_this._ready) return; _this.updateView(); } }; this._super(config, parent); }, readyOnce: function() { this._super(); var _this = this; this.group = this.model.state.marker.group; this.stack = this.model.state.marker.stack; this.howToStackEl = this.element.select('.vzb-howtostack').selectAll("input") .on("change", function() { _this.setModel("stack", d3.select(this).node().value); }) this.howToMergeEl = this.element.select('.vzb-howtomerge').selectAll("input") .on("change", function() { _this.setModel("merge", d3.select(this).node().value); }) this.updateView(); }, ready: function() { this._super(); this.updateView(); }, updateView: function() { var _this = this; this.howToStackEl .property('checked', function() { if(d3.select(this).node().value === "none") return _this.stack.which==="none"; if(d3.select(this).node().value === "bycolor") return _this.stack.which===_this.model.state.marker.color.which; if(d3.select(this).node().value === "all") return _this.stack.which==="all"; }); _this.model.ui.chart.manualSortingEnabled = _this.stack.which == "all"; this.howToMergeEl .property('checked', function() { if(d3.select(this).node().value === "none") return !_this.group.merge && !_this.stack.merge; if(d3.select(this).node().value === "grouped") return _this.group.merge; if(d3.select(this).node().value === "stacked") return _this.stack.merge; }) .attr('disabled', function(){ if(d3.select(this).node().value === "none") return null; // always enabled if(d3.select(this).node().value === "grouped") return _this.stack.which === "none" ? true : null; if(d3.select(this).node().value === "stacked") return _this.stack.which === "all" ? null : true; }); }, manualSorting: function(value) { if(arguments.length === 0) return this.model.state.marker.group.manualSorting; this.model.state.marker.group.manualSorting = value; }, setModel: function(what, value) { var obj = {stack: {}, group: {}}; if(what === "merge") { switch (value){ case "none": obj.group.merge = false; obj.stack.merge = false; break; case "grouped": obj.group.merge = true; obj.stack.merge = false; break; case "stacked": obj.group.merge = false; obj.stack.merge = true; break; } } if(what === "stack") { switch (value){ case "all": obj.stack.use = "constant"; obj.stack.which = "all"; break; case "none": obj.stack.use = "constant"; obj.stack.which = "none"; break; case "bycolor": obj.stack.use = "property"; obj.stack.which = this.model.state.marker.color.which; break; } //validate possible merge values in group and stack hooks if(value === "none" && this.group.merge) obj.group.merge = false; if(value !== "all" && this.stack.merge) obj.stack.merge = false; } this.model.state.marker.set(obj); } }); export default Stack;
JavaScript
0
@@ -1874,24 +1874,314 @@ s._super();%0A + if(this.model.state.marker.color.use !== %22property%22) %7B%0A if(this.stack.use == %22property%22) %7B %0A this.setModel(%22stack%22, %22none%22);%0A return;%0A %7D %0A else if(this.group.merge) %7B%0A this.setModel(%22merge%22, %22none%22);%0A return;%0A %7D%0A %7D%0A this.u @@ -2189,24 +2189,24 @@ dateView();%0A - %7D,%0A%0A @@ -2380,33 +2380,32 @@ alue === %22none%22) - return _this.st @@ -2641,24 +2641,397 @@ ch===%22all%22;%0A + %7D)%0A .attr('disabled', function()%7B%0A if(d3.select(this).node().value === %22none%22) return null; // always enabled%0A if(d3.select(this).node().value === %22all%22) return null; // always enabled%0A if(d3.select(this).node().value === %22bycolor%22) return _this.model.state.marker.color.use !== %22property%22 ? true : null;%0A @@ -3255,33 +3255,32 @@ alue === %22none%22) - return !_this.g @@ -3607,17 +3607,16 @@ %22none%22) - return @@ -3737,16 +3737,69 @@ = %22none%22 + %7C%7C _this.model.state.marker.color.use !== %22property%22 ? true
95301ee2209048f10ebd723ecf8bd93d95d359b5
Fix tv4 language loading
src/components/formula/formulaDemo.js
src/components/formula/formulaDemo.js
'use strict'; require('../../'); require('formula'); let angular = require('angular'); angular .module('formulaDemo', ['npdcCommon', 'formula']) .controller('FormulaCtrl', ($mdDialog, $scope, $timeout, formula, formulaAutoCompleteService, fileFunnelService, chronopicService, npdcAppConfig, NpolarApiResource) => { $scope.formula = formula.getInstance({ schema: "./demo/schema.json", form: "./demo/form.json", templates: npdcAppConfig.formula.templates.concat([ { match: "people_item", template: '<npdc:formula-person></npdc:formula-person>' }, { match: "gcmd", template: '<npdc:formula-gcmd></npdc:formula-gcmd>' }, { match: "sciencekeywords_item", template: '<npdc:formula-gcmd-keyword></npdc:formula-gcmd-keyword>' }, { match: "placenames_item", template: '<npdc:formula-placename></npdc:formula-placename>' }, { match: "array_object2", template: '<npdc:formula-tabdata></npdc:formula-tabdata>' }, { match: "file_ref", template: '<npdc:formula-file-object></npdc:formula-file-object>' } ]), languages: [{ map: require('formula/i18n/no.json'), code: 'no_NB', aliases: ['no', 'nb'] }] }); let updateModel = function() { $scope.formula.setModel({ _id: 'foobarID', string: 'timeoutfoobar', string_date: '2012-05-17', boolean: true, array_object: Array(100).fill({ string_default: 'foo', number: 1 }), array_string_enum: ['foo', 'qux'], array_string: ['foobar', 'bazquz'], ref_object: { name: 'test', email: 'foo', dn: 'no' }, nested_array: [ [1, 2], [1, 2] ], array_hierarchy: [{ sub_array_one: [{ sub_sub_array_one: [{ obj_1_1_1: 'foo', obj_1_1_2: 4 }] }] }] }); console.log("timeout"); }; $timeout(updateModel); let acSource = ["Dalene", "Allan", "Lecia", "Leta", "Matthew", "Marlen", "Collette", "Alfredo", "Francina", "Dorene", "Ali", "Anette", "Courtney", "Arlena", "Spring", "Suzanna", "Roseanne", "Evita", "Gaynell", "Ellena", "Lucinda", "Delisa", "Lamont", "Eloy", "Luanna", "Cyndi", "Lynn", "Clare", "Stacey", "Tameka", "Cheryll", "Jong", "Hoyt", "Marhta", "Roselia", "Gala", "Chun", "Weston", "Zola", "Luana", "Arnette", "Delorse", "Libbie", "Nenita", "Lorina", "Carolyn", "Burma", "Russell", "Beatris", "Macie"]; let acSourceFn = function (q) { return acSource.filter(item => item.toLowerCase().indexOf(q.toLowerCase()) === 0); }; let acSource2 = [{a: "Anders", b: "http://tjosho.com"}, {a: "Remi", b: "http://lololo.no"}]; let acSource2Fn = function (q) { return acSource2.filter(item => item.a.toLowerCase().indexOf(q.toLowerCase()) === 0); }; let Dataset = NpolarApiResource.resource({'path': '/dataset', 'resource': 'Dataset' }); formulaAutoCompleteService.optionsFromFacets(['organisations.gcmd_short_name', 'links.type'], Dataset, $scope.formula); formulaAutoCompleteService.defineOptions({ match: "autocomplete", querySource: acSourceFn, //label: 'key', //value: 'key', //onSelect, minLength: 1 //(default 0) }, $scope.formula); formulaAutoCompleteService.defineOptions({ match: "autocomplete2", querySource: acSource2Fn, label: 'a', value: 'b', onSelect(item) { alert('Select: ' + item.a + ': ' + item.b); } }, $scope.formula); formulaAutoCompleteService.defineOptions({ match: "autocomplete3", querySource: "//api.npolar.no/person/?fields=first_name,last_name,organisation,email&format=json&variant=array", label: "first_name", value: "first_name" }, $scope.formula); fileFunnelService.defineOptions({match: '#/string_file', multiple: true}, $scope.formula); chronopicService.defineOptions({match: '#/string_date', locale: 'ja', format: "{YYYY} {YY} {YYYY} {MMM} {DD} {MMMM}"}); chronopicService.defineOptions({match: '#/string_datetime', locale: 'en'}); });
JavaScript
0.000025
@@ -1383,12 +1383,12 @@ : 'n -o_NB +b_NO ',%0A
cac9754dd8bdbb8cd771ee2b87dd57830b9b3e07
reset the run prop
browser/ui/editor.js
browser/ui/editor.js
var ever = require('ever') var deepEqual = require('deep-equal') module.exports = Editor function Editor(world) { var display = Display(world) var code = Code(world) } var helpText = require('../../help.json').join('\n') function Code(world) { var ta = document.createElement('textarea') ta.className = 'code' ta.value = helpText document.body.appendChild(ta) var tj = document.createElement('textarea') tj.className = 'json' document.body.appendChild(tj) var spellbook = document.createElement('div') spellbook.className = 'spellbook' spellbook.textContent = helpText document.body.appendChild(spellbook) var tabs = document.createElement('div') tabs.className = 'tabs' tabs.appendChild(createTab('codex', function () { tj.style.display = 'none' ta.style.display = 'block' spellbook.style.display = 'none' })) tabs.appendChild(createTab('tome', function () { ta.style.display = 'none' tj.style.display = 'block' spellbook.style.display = 'none' })) tabs.querySelector('.tab').className = 'tab active' tabs.appendChild(createTab('spellbook', function () { ta.style.display = 'none' tj.style.display = 'none' spellbook.style.display = 'block' })) function createTab (txt, cb) { var div = document.createElement('div') div.className = 'tab' div.textContent = txt div.addEventListener('click', function (ev) { var o = tabs.querySelector('.active') if (o) o.className = 'tab' div.className = 'tab active' cb.call(div, ev) ever({ codex : ta, tome : tj }[txt]).emit('change') }) return div } tabs.appendChild((function () { var div = document.createElement('div') div.className = 'cast tab' div.textContent = 'cast' div.addEventListener('click', function () { var name = document.querySelector('.tab.active').textContent console.log('cast ' + name) if (name === 'codex') { current.set('source', ta.value) } else if (name === 'tome') { try { next = JSON.parse(tj.value) } catch (err) { tj.className = 'json error'; return } tj.className = 'json' var ch = Object.keys(current.state).concat(Object.keys(next)) .reduce(function (acc, key) { if (!deepEqual(current.state[key], next[key])) { acc[key] = next[key] } return acc }, {}) ; current.set(ch) } }) var current world.on('examine', function (row) { current = row }) function onchange () { if (!current) return var name = document.querySelector('.tab.active').textContent if (name === 'codex') { try { Function(ta.value) } catch (err) { ta.className = 'code error' div.className = 'cast tab disable' return } ta.className = 'code' div.className = 'cast tab' } else if (name === 'tome') { try { JSON.parse(tj.value) } catch (err) { tj.className = 'json error' div.className = 'cast tab disable' return } tj.className = 'json' div.className = 'cast tab' } } tj.addEventListener('change', onchange) tj.addEventListener('keydown', onchange) ta.addEventListener('change', onchange) ta.addEventListener('keydown', onchange) return div })()) document.body.appendChild(tabs) world.on("examine", function (row) { world.emit('log', 'examine: '+ (row.id || row)) if(!row.get || !row.get('source')) return _row = row ta.value = row.get("source") tj.value = JSON.stringify(row.state, null, 2) }) } function Display(world) { var log = document.createElement('pre') log.className = 'display' document.body.appendChild(log) world.on('log', function (s) { log.appendChild(document.createTextNode(s+'\n')) if(log.childNodes.length > 5) log.removeChild(log.firstChild) }) }
JavaScript
0.000001
@@ -2168,17 +2168,18 @@ set( -' +%7B source -', + : ta. @@ -2175,32 +2175,46 @@ ource : ta.value +, run : true %7D )%0A %7D%0A
df76149931d79d4d7367adfc28cf49d3d071bb9a
Fix test
packages/strapi-plugin-upload/admin/src/components/VideoPreview/tests/VideoPreview.test.js
packages/strapi-plugin-upload/admin/src/components/VideoPreview/tests/VideoPreview.test.js
import React from 'react'; import { screen, render, fireEvent } from '@testing-library/react'; import { ThemeProvider } from 'styled-components'; import VideoPreview from '..'; import themes from '../../../../../../strapi-admin/admin/src/themes'; jest.mock('react-intl', () => ({ // eslint-disable-next-line react/prop-types FormattedMessage: ({ id }) => <div>{id}</div>, useIntl: () => ({ formatMessage: ({ id }) => id, }), })); describe('VideoPreview', () => { it('shows its initial state with no props', () => { const { container } = render( <ThemeProvider theme={themes}> <VideoPreview /> </ThemeProvider> ); expect(container).toMatchSnapshot(); }); it('shows a loading state when resolving the asset', () => { render( <ThemeProvider theme={themes}> <VideoPreview hasIcon previewUrl="https://some-preview-url/img.jpg" src="https://something-good/video.mp4" /> </ThemeProvider> ); expect(screen.getByLabelText('upload.list.assets.loading-asset')).toBeVisible(); }); it('shows the thumbnail but not the video when previewURL is passed', () => { const { container } = render( <ThemeProvider theme={themes}> <VideoPreview hasIcon previewUrl="https://some-preview-url/img.jpg" src="https://something-good/video.mp4" /> </ThemeProvider> ); expect(screen.getByAltText('upload.list.assets.preview-asset')).toBeVisible(); expect(container.querySelector('video')).toBeFalsy(); }); it('shows the video when the previewURL is not passed', () => { const { container } = render( <ThemeProvider theme={themes}> <VideoPreview hasIcon src="https://something-good/video.mp4" /> </ThemeProvider> ); expect(container.querySelector('video')).toBeVisible(); }); it('shows a fallback message when the video is in error', () => { const { container } = render( <ThemeProvider theme={themes}> <VideoPreview hasIcon src="https://something-good/video.wvf" /> </ThemeProvider> ); fireEvent(container.querySelector('video'), new Event('error')); expect(screen.getByText('upload.list.assets.not-supported-content')).toBeVisible(); }); });
JavaScript
0.000004
@@ -1858,39 +1858,45 @@ r('video')).toBe -Visible +InTheDocument ();%0A %7D);%0A%0A it(
197e7f82bfba70a3ace8b908267a09e3da0c2d5f
fix to handle empty string properly
src/ecma-debugger/view-commandline.js
src/ecma-debugger/view-commandline.js
(function() { View = function(id, name, container_class) { /* a quick hack */ var self = this; var __frame_index = -1; var __console_output = null; var __console_input = null; var __prefix = null; var handleEval = function(xml, runtime_id) { var value_type = xml.getNodeData('data-type'); var status = xml.getNodeData('status'); if( status == 'completed' ) { var return_value = xml.getElementsByTagName('string')[0]; if(return_value) { __console_output.render(['pre', return_value.firstChild.nodeValue]); var container = __console_output.parentNode.parentNode; container.scrollTop = container.scrollHeight; } else if (return_value = xml.getElementsByTagName('object-id')[0]) { var object_id = return_value.textContent; var object_ref_name = "$" + object_id; var tag = tagManager.setCB(null, handleEval, [runtime_id] ); var script_string = "return " + object_ref_name + ".toString()"; services['ecmascript-debugger'].eval( tag, runtime_id, '', '', "<![CDATA["+script_string+"]]>", [object_ref_name, object_id]); } } else { var error_id = xml.getNodeData('object-id'); if( error_id ) { var tag = tagManager.setCB(null, handleError); services['ecmascript-debugger'].examineObjects(tag, runtime_id, error_id); } } } var handleError = function(xml) { var return_value = xml.getElementsByTagName('string')[0]; if(return_value) { __console_output.render(['pre', return_value.firstChild.nodeValue]); var container = __console_output.parentNode.parentNode; container.scrollTop = container.scrollHeight; } } var markup = "\ <div class='padding'>\ <div class='console-output'></div>\ <div class='console-input' handler='console-focus-input'>\ <span class='commandline-prefix'>&gt;&gt;&gt; </span>\ <div><textarea handler='commandline' rows='1' title='hold shift to add a new line'></textarea></div>\ </div>\ </div>"; var templates = {}; templates.consoleInput = function(entry) { var lines_count = entry.msg.split(/\r?\n/).length; var line_head = '>>>'; while( --lines_count > 1 ) { line_head += '\n...'; } return [['div', line_head], ['pre', entry.msg]]; } eventHandlers.click['console-focus-input'] = function(event, ele) { ele.getElementsByTagName('textarea')[0].focus(); } var submit = function(input) { var rt_id = runtimes.getSelectedRuntimeId(), frame_id = '', thread_id = ''; if(rt_id) { if( __frame_index > -1 ) { frame_id = __frame_index; thread_id = stop_at.getThreadId(); } var tag = tagManager.setCB(null, handleEval, [rt_id] ); var script_string = submit_buffer.join(''); services['ecmascript-debugger'].eval(tag, rt_id, thread_id, frame_id, "<![CDATA["+script_string+"]]>"); submit_buffer = []; } else { alert('select a runtime'); } } var submit_buffer = []; var line_buffer = []; var line_buffer_cursor = 0; var line_buffer_push = function(line) { line_buffer[line_buffer.length] = line.replace(/\r\n/g, ""); if( line_buffer.length > 100 ) { line_buffer = line_buffer.slice(line_buffer.length - 100); } line_buffer_cursor = line_buffer.length; } eventHandlers.keyup['commandline'] = function(event) { if(event.keyCode == 38 || event.keyCode == 40) { line_buffer_cursor += event.keyCode == 38 ? -1 : 1; line_buffer_cursor = line_buffer_cursor < 0 ? line_buffer.length-1 : line_buffer_cursor > line_buffer.length-1 ? 0 : line_buffer_cursor; event.target.value = (line_buffer.length ? line_buffer[line_buffer_cursor] : '').replace(/\r\n/g, ''); event.preventDefault(); return; } const CRLF = "\r\n"; var value = event.target.value; var lastCRLFIndex = value.lastIndexOf(CRLF); if(lastCRLFIndex != -1) { if ( value.length -2 != lastCRLFIndex ) { value = value.slice(0, lastCRLFIndex) + value.slice(lastCRLFIndex + 2) + CRLF; } __console_output.render( ['div', ( submit_buffer.length ? "... " : ">>> " ) + value, 'class', 'log-entry']); line_buffer_push( submit_buffer[submit_buffer.length] = value ); if(!event.shiftKey) { submit(); } __prefix.textContent = submit_buffer.length ? "... " : ">>> "; event.target.value = ''; } } this.createView = function(container) { container.innerHTML = markup; container.scrollTop = container.scrollHeight; __console_output = container.getElementsByTagName('div')[1]; __console_input = container.getElementsByTagName('div')[2]; __prefix = __console_input.getElementsByTagName('span')[0]; } this.ondestroy = function() { __console_output = null; __console_input = null; __prefix = null; } var onFrameSelected = function(msg) { __frame_index = msg.frame_index; } messages.addListener('frame-selected', onFrameSelected); this.init(id, name, container_class); } View.prototype = ViewBase; new View('command_line', ui_strings.VIEW_LABEL_COMMAND_LINE, 'scroll'); })()
JavaScript
0.000021
@@ -551,32 +551,59 @@ t.render(%5B'pre', + return_value.firstChild && return_value.fi @@ -612,32 +612,38 @@ tChild.nodeValue + %7C%7C '' %5D);%0A va
fe3040fffe7f34c8f8b8e1cb849f09138debbfab
simplify generator test (#2756)
src/execution/__tests__/lists-test.js
src/execution/__tests__/lists-test.js
import { expect } from 'chai'; import { describe, it } from 'mocha'; import { parse } from '../../language/parser'; import { buildSchema } from '../../utilities/buildASTSchema'; import { execute, executeSync } from '../execute'; describe('Execute: Accepts any iterable as list value', () => { function complete(rootValue: mixed) { return executeSync({ schema: buildSchema('type Query { listField: [String] }'), document: parse('{ listField }'), rootValue, }); } it('Accepts a Set as a List value', () => { const listField = new Set(['apple', 'banana', 'apple', 'coconut']); expect(complete({ listField })).to.deep.equal({ data: { listField: ['apple', 'banana', 'coconut'] }, }); }); it('Accepts an Generator function as a List value', () => { function* yieldItems() { yield 'one'; yield 2; yield true; } const listField = yieldItems(); expect(complete({ listField })).to.deep.equal({ data: { listField: ['one', '2', 'true'] }, }); }); it('Accepts function arguments as a List value', () => { function getArgs(...args: Array<string>) { return args; } const listField = getArgs('one', 'two'); expect(complete({ listField })).to.deep.equal({ data: { listField: ['one', 'two'] }, }); }); it('Does not accept (Iterable) String-literal as a List value', () => { const listField = 'Singular'; expect(complete({ listField })).to.deep.equal({ data: { listField: null }, errors: [ { message: 'Expected Iterable, but did not find one for field "Query.listField".', locations: [{ line: 1, column: 3 }], path: ['listField'], }, ], }); }); }); describe('Execute: Handles list nullability', () => { async function complete({ listField, as }) { const schema = buildSchema(`type Query { listField: ${as} }`); const document = parse('{ listField }'); const result = await executeQuery(listField); // Promise<Array<T>> === Array<T> expect(await executeQuery(promisify(listField))).to.deep.equal(result); if (Array.isArray(listField)) { const listOfPromises = listField.map(promisify); // Array<Promise<T>> === Array<T> expect(await executeQuery(listOfPromises)).to.deep.equal(result); // Promise<Array<Promise<T>>> === Array<T> expect(await executeQuery(promisify(listOfPromises))).to.deep.equal( result, ); } return result; function executeQuery(listValue) { return execute({ schema, document, rootValue: { listField: listValue } }); } function promisify(value: mixed): Promise<mixed> { return value instanceof Error ? Promise.reject(value) : Promise.resolve(value); } } it('Contains values', async () => { const listField = [1, 2]; expect(await complete({ listField, as: '[Int]' })).to.deep.equal({ data: { listField: [1, 2] }, }); expect(await complete({ listField, as: '[Int]!' })).to.deep.equal({ data: { listField: [1, 2] }, }); expect(await complete({ listField, as: '[Int!]' })).to.deep.equal({ data: { listField: [1, 2] }, }); expect(await complete({ listField, as: '[Int!]!' })).to.deep.equal({ data: { listField: [1, 2] }, }); }); it('Contains null', async () => { const listField = [1, null, 2]; const errors = [ { message: 'Cannot return null for non-nullable field Query.listField.', locations: [{ line: 1, column: 3 }], path: ['listField', 1], }, ]; expect(await complete({ listField, as: '[Int]' })).to.deep.equal({ data: { listField: [1, null, 2] }, }); expect(await complete({ listField, as: '[Int]!' })).to.deep.equal({ data: { listField: [1, null, 2] }, }); expect(await complete({ listField, as: '[Int!]' })).to.deep.equal({ data: { listField: null }, errors, }); expect(await complete({ listField, as: '[Int!]!' })).to.deep.equal({ data: null, errors, }); }); it('Returns null', async () => { const listField = null; const errors = [ { message: 'Cannot return null for non-nullable field Query.listField.', locations: [{ line: 1, column: 3 }], path: ['listField'], }, ]; expect(await complete({ listField, as: '[Int]' })).to.deep.equal({ data: { listField: null }, }); expect(await complete({ listField, as: '[Int]!' })).to.deep.equal({ data: null, errors, }); expect(await complete({ listField, as: '[Int!]' })).to.deep.equal({ data: { listField: null }, }); expect(await complete({ listField, as: '[Int!]!' })).to.deep.equal({ data: null, errors, }); }); it('Contains error', async () => { const listField = [1, new Error('bad'), 2]; const errors = [ { message: 'bad', locations: [{ line: 1, column: 3 }], path: ['listField', 1], }, ]; expect(await complete({ listField, as: '[Int]' })).to.deep.equal({ data: { listField: [1, null, 2] }, errors, }); expect(await complete({ listField, as: '[Int]!' })).to.deep.equal({ data: { listField: [1, null, 2] }, errors, }); expect(await complete({ listField, as: '[Int!]' })).to.deep.equal({ data: { listField: null }, errors, }); expect(await complete({ listField, as: '[Int!]!' })).to.deep.equal({ data: null, errors, }); }); it('Results in error', async () => { const listField = new Error('bad'); const errors = [ { message: 'bad', locations: [{ line: 1, column: 3 }], path: ['listField'], }, ]; expect(await complete({ listField, as: '[Int]' })).to.deep.equal({ data: { listField: null }, errors, }); expect(await complete({ listField, as: '[Int]!' })).to.deep.equal({ data: null, errors, }); expect(await complete({ listField, as: '[Int!]' })).to.deep.equal({ data: { listField: null }, errors, }); expect(await complete({ listField, as: '[Int!]!' })).to.deep.equal({ data: null, errors, }); }); });
JavaScript
0
@@ -811,26 +811,25 @@ nction* -yieldItems +listField () %7B%0A @@ -886,44 +886,8 @@ %7D -%0A const listField = yieldItems(); %0A%0A
a112333c40467f6f3d8b652602db228455206a8e
remove :visible (popup) check from UIOutLogSystem
src/game/systems/ui/UIOutLogSystem.js
src/game/systems/ui/UIOutLogSystem.js
define([ 'ash', 'game/GlobalSignals', 'game/nodes/LogNode', 'game/constants/UIConstants', ], function (Ash, GlobalSignals, LogNode, UIConstants) { var UIOutLogSystem = Ash.System.extend({ logNodes: null, lastUpdateTimeStamp: 0, updateFrequency: 1000 * 15, constructor: function () { }, addToEngine: function (engine) { var logSystem = this; this.logNodes = engine.getNodeList(LogNode); this.onPlayerMoved = function(playerPosition) { logSystem.checkPendingMessages(playerPosition); }; GlobalSignals.playerMovedSignal.add(this.onPlayerMoved); this.update(); }, removeFromEngine: function (engine) { this.logNodes = null; GlobalSignals.playerMovedSignal.remove(this.onPlayerMoved); }, update: function (time) { if ($(".popup:visible").length > 0) return; var timeStamp = new Date().getTime(); var isTime = timeStamp - this.lastUpdateTimeStamp > this.updateFrequency; var hasNewMessages = false; var messages = []; for (var node = this.logNodes.head; node; node = node.next) { messages = messages.concat(node.logMessages.messages); hasNewMessages = hasNewMessages || node.logMessages.hasNewMessages; node.logMessages.hasNewMessages = false; } if (!hasNewMessages && !isTime && time) return; this.pruneMessages(); this.refreshMessages(messages); this.lastUpdateTimeStamp = timeStamp; }, checkPendingMessages: function (playerPosition) { var validLevel; var validSector; var validInCamp; for (var node = this.logNodes.head; node; node = node.next) { var pendingMessages = node.logMessages.messagesPendingMovement; for (var i in pendingMessages) { var msg = node.logMessages.messagesPendingMovement[i]; validLevel = !msg.pendingLevel || msg.pendingLevel == playerPosition.level; validSector = !msg.pendingSector || msg.pendingSector == playerPosition.sectorId(); validInCamp = (typeof msg.pendingInCamp === "undefined") || msg.pendingInCamp === playerPosition.inCamp; if (validLevel && validSector && validInCamp) { node.logMessages.showPendingMessage(msg); } } } }, refreshMessages: function (messages) { var animateFromIndex = messages.length - (messages.length - $("#log ul li").length); $("#log ul").empty(); var msg; var liMsg; for (var index = 0; index < messages.length; index++) { msg = messages[index]; var li = '<li'; if (msg.loadedFromSave) li += ' class="log-loaded"'; li += '><span class="time">' + UIConstants.getTimeSinceText(msg.time) + " ago" + '</span> '; if (msg.campLevel) li += '<span class="msg-camp-level"> (level ' + msg.campLevel + ')</span>'; li += '<span class="msg">' + msg.text; if (msg.combined > 0) li += '<span class="msg-count"> (x' + (msg.combined + 1) + ')</span>'; li += '</span></li>'; liMsg = $(li); $("#log ul").prepend(liMsg); var animate = index >= animateFromIndex; if (animate) { liMsg.toggle(false); liMsg.fadeIn(500); } } }, pruneMessages: function () { var maxMessages = 30; var messagesToPrune = 10; var nodeMessages; for (var node = this.logNodes.head; node; node = node.next) { nodeMessages = node.logMessages.messages; if (nodeMessages.length > maxMessages) { nodeMessages.splice(0, nodeMessages.length - maxMessages + messagesToPrune); } } }, }); return UIOutLogSystem; });
JavaScript
0
@@ -847,38 +847,31 @@ if ( -$(%22.popup:visible%22).length %3E 0 +this.gameState.isPaused ) re
9877a28b9f02639c37e6bd88ea91e820b0a218f9
fix typo
src/platforms/web/api-setup.js
src/platforms/web/api-setup.js
import { Lbry } from 'lbry-redux'; import apiPublishCallViaWeb from './publish'; import { X_LBRY_AUTH_TOKEN } from 'constants/token'; export const SDK_API_URL = `${process.env.SDK_API_URL}/api/v1/proxy` || 'https://api.lbry.tv/api/v1/proxy'; Lbry.setDaemonConnectionString(SDK_API_URL); Lbry.setOverride( 'publish', params => new Promise((resolve, reject) => { apiPublishCallViaWeb( SDK_API_URL, Lbry.getApiRequestHeaders() && Object.keys(Lbry.getApiRequestHeaders()).includes(X_LBRY_AUTH_TOKEN) ? Lbry.getApiRequestHeaders()[X_LBRY_AUTH_TOKEN] : '', 'publish', params, resolve, reject ); }) );
JavaScript
0.999991
@@ -159,11 +159,8 @@ L = -%60$%7B proc @@ -182,23 +182,8 @@ _URL -%7D/api/v1/proxy%60 %7C%7C
3496d0db7cc7250f90be44e7a095c70ed3c30f0d
fix link scroll handling
components/link/index.js
components/link/index.js
import style from './style' import { withRouter } from 'next/router' const Link = ({ button, children, handleClick, handleFocus, handleRefresh, href, nav, primary, router, secondary, subnav }) => { const defaultHandleClick = e => { if (href.indexOf('http') === -1) { e.preventDefault() const isHash = href.indexOf('#') === 0 const url = isHash ? `${router.pathname}${href}` : href if (router.pathname === href && typeof handleRefresh === 'function') { handleRefresh() } router.push(url).then(() => { if (!isLocal) { window.scrollTo(0, 0) } }) } } const click = typeof handleClick === 'function' ? handleClick : defaultHandleClick return ( <a className={[ button ? 'button' : '', primary ? 'primary' : '', secondary ? 'secondary' : '', nav ? 'nav' : '', subnav ? 'subnav' : '', router.pathname === href ? 'selected' : '' ].filter(v => v).join(' ')} href={ href } onClick={ click } onFocus={ handleFocus } > { children } <style jsx>{ style }</style> </a> ) } export default withRouter(Link)
JavaScript
0
@@ -605,13 +605,12 @@ (!is -Local +Hash ) %7B%0A
cd335d2108e177034b7748482e54d35c5da7c8ed
simplify factory using ES6
src/popart/FX/EffectFactory.js
src/popart/FX/EffectFactory.js
import { RuttEtraCore, RuttEtraDisplay } from './RuttEtra/RuttEtra'; import RuttEtraController from './RuttEtra/RuttEtraController'; import { SynthesizerCore, SynthesizerDisplay } from './Synthesizer/Synthesizer'; import SynthesizerController from './Synthesizer/SynthesizerController'; import { MosaicCore, MosaicDisplay } from './Mosaic/Mosaic'; import MosaicController from './Mosaic/MosaicController'; import { LEDCore, LEDDisplay } from './LED/LED'; import LEDController from './LED/LEDController'; import { BlurCore, BlurDisplay } from './Blur/Blur'; import BlurController from './Blur/BlurController'; import { RGBSplitCore, RGBSplitDisplay } from './RGBSplit/RGBSplit'; import RGBSplitController from './RGBSplit/RGBSplitController'; import { PhotoStyleCore, PhotoStyleDisplay } from './PhotoStyle/PhotoStyle'; import PhotoStyleController from './PhotoStyle/PhotoStyleController'; import { FeedbackCore, FeedbackDisplay } from './Feedback/Feedback'; import FeedbackController from './Feedback/FeedbackController'; import { TrailsCore, TrailsDisplay } from './Trails/Trails'; import TrailsController from './Trails/TrailsController'; import LFO from '../Modulators/LFO'; import LFOController from '../Modulators/LFOController'; import Sequencer from '../Modulators/Sequencer'; import SequencerController from '../Modulators/SequencerController'; var effectFactory = { lookupComponentByName: function(name) { let lookup = { 'SynthesizerDisplay': SynthesizerDisplay, 'SynthesizerController': SynthesizerController, 'SynthesizerCore': SynthesizerCore, 'RuttEtraDisplay': RuttEtraDisplay, 'RuttEtraController': RuttEtraController, 'RuttEtraCore': RuttEtraCore, 'MosaicDisplay': MosaicDisplay, 'MosaicController': MosaicController, 'MosaicCore': MosaicCore, 'LEDDisplay': LEDDisplay, 'LEDController': LEDController, 'LEDCore': LEDCore, 'BlurDisplay': BlurDisplay, 'BlurController': BlurController, 'BlurCore': BlurCore, 'RGBSplitDisplay': RGBSplitDisplay, 'RGBSplitController': RGBSplitController, 'RGBSplitCore': RGBSplitCore, 'PhotoStyleDisplay': PhotoStyleDisplay, 'PhotoStyleController': PhotoStyleController, 'PhotoStyleCore': PhotoStyleCore, 'FeedbackDisplay': FeedbackDisplay, 'FeedbackController': FeedbackController, 'FeedbackCore': FeedbackCore, 'TrailsDisplay': TrailsDisplay, 'TrailsController': TrailsController, 'TrailsCore': TrailsCore, 'LFO': LFO, 'LFOController': LFOController, 'Sequencer': Sequencer, 'SequencerController': SequencerController, }; return lookup[name]; } }; export default effectFactory;
JavaScript
0.000001
@@ -1753,1659 +1753,598 @@ ';%0A%0A -var effectFactory = %7B%0A lookupComponentByName: function(name) %7B%0A let lookup = %7B%0A 'SynthesizerDisplay': SynthesizerDisplay,%0A 'SynthesizerController': SynthesizerController,%0A 'SynthesizerCore': SynthesizerCore,%0A 'RuttEtraDisplay': RuttEtraDisplay,%0A 'RuttEtraController': RuttEtraController,%0A 'RuttEtraCore': RuttEtraCore,%0A 'MosaicDisplay': MosaicDisplay,%0A 'MosaicController': MosaicController,%0A 'MosaicCore': MosaicCore,%0A 'LEDDisplay': LEDDisplay,%0A 'LEDController': LEDController,%0A 'LEDCore': LEDCore,%0A 'BlurDisplay': BlurDisplay,%0A 'BlurController': BlurController,%0A 'BlurCore': BlurCore,%0A 'RGBSplitDisplay': RGBSplitDisplay,%0A 'RGBSplitController': RGBSplitController,%0A 'RGBSplitCore': RGBSplitCore,%0A 'PhotoStyleDisplay': PhotoStyleDisplay,%0A 'PhotoStyleController': PhotoStyleController,%0A 'PhotoStyleCore': PhotoStyleCore,%0A 'FeedbackDisplay': FeedbackDisplay,%0A 'FeedbackController': FeedbackController,%0A 'FeedbackCore': FeedbackCore,%0A 'TrailsDisplay': TrailsDisplay,%0A 'TrailsController': TrailsController,%0A 'TrailsCore': TrailsCore,%0A%0A 'LFO': LFO,%0A 'LFOController': LFOController,%0A 'Sequencer': +const classes = %7B%0A SynthesizerDisplay,%0A SynthesizerController,%0A SynthesizerCore,%0A RuttEtraDisplay,%0A RuttEtraController,%0A RuttEtraCore,%0A MosaicDisplay,%0A MosaicController,%0A MosaicCore,%0A LEDDisplay,%0A LEDController,%0A LEDCore,%0A BlurDisplay,%0A BlurController,%0A BlurCore,%0A RGBSplitDisplay,%0A RGBSplitController,%0A RGBSplitCore,%0A PhotoStyleDisplay,%0A PhotoStyleController,%0A PhotoStyleCore,%0A FeedbackDisplay,%0A FeedbackController,%0A FeedbackCore,%0A TrailsDisplay,%0A TrailsController,%0A TrailsCore,%0A%0A LFO,%0A LFOController,%0A @@ -2362,17 +2362,8 @@ - ' Sequ @@ -2381,45 +2381,79 @@ ller -': SequencerController,%0A %7D;%0A +,%0A%7D;%0A%0Avar effectFactory = %7B%0A lookupComponentByName: function(name) %7B %0A @@ -2464,22 +2464,23 @@ return -lookup +classes %5Bname%5D;%0A
1c20633039a600ef584495f56bde493914f211e6
Use the term Graph (not dataset) to description SPARQL RDF Datasets
components/rdf-update.js
components/rdf-update.js
// rdf-update.js var _ = require('underscore'); var Promise = require('promise'); var Handlebars = require('handlebars'); var rdfstore = require('rdfstore'); var basenode = require('./base-node'); var promiseComponent = require('./promise-component'); exports.getComponent = promiseComponent({ description: "Executes the given SPARQL update on the provided RDF graph and returns it", icon: 'cogs', inPorts: { parameters: { description: "A map of template parameters", datatype: 'object', ondata: basenode.assign('parameters') }, update: { description: "SPARQL update template string in handlebars syntax", datatype: 'string', required: true, ondata: basenode.assign('update', Handlebars.compile) }, "default": { description: "Graph URI for the default dataset", datatype: 'string', ondata: basenode.assign('defaultURIs', basenode.push) }, namespace: { description: "Graph URI for the named dataset", datatype: 'string', ondata: basenode.assign('namespaceURIs', basenode.push) }, 'in': { description: "RDF JS Interface Graph object", datatype: 'object', required: true, ondata: execute } } }); function execute(graph) { var update = this.update(this.parameters); var graphURI = graph.graphURI; var defaultURIs = _.compact([graphURI].concat(this.defaultURIs)); var args = (this.defaultURIs || this.namespaceURIs || graphURI) ? [update, defaultURIs, this.namespaceURIs || []] : [update]; return asRdfStore(graph).then(function(store){ return Promise.denodeify(store.execute).apply(store, args).then(function(){ if (graphURI) { return denodeify(store, 'graph', graphURI); } else { return denodeify(store, 'graph'); } }).then(function(graph){ graph.rdfstore = store; graph.graphURI = graphURI; return graph; }); }); } function asRdfStore(graph) { if (graph.rdfstore) return Promise.resolve(graph.rdfstore); else return denodeify(rdfstore, 'create', {}).then(function(store){ return Promise.resolve(graph).then(function(graph){ if (!graph.graphURI) return denodeify(store, 'insert', graph); else return denodeify(store, 'insert', graph, graph.graphURI); }).then(_.constant(store)); }); } function denodeify(object, functionName /* arguments */) { var args = _.toArray(arguments).slice(2); return Promise.denodeify(object[functionName]).apply(object, args); }
JavaScript
0.00052
@@ -892,23 +892,21 @@ the -d +D efault -dataset +Graph %22,%0A @@ -1078,25 +1078,21 @@ for -the named dataset +a Named Graph %22,%0A
8aaf43416f77e622b749f4362489ee84a3d0bd8c
put the svg defs nodes into the header/footer of the compile script
concat-svg/concat-svg.js
concat-svg/concat-svg.js
#!/usr/bin/env node var fs = require('fs'); var cheerio = require('cheerio'); var path = require('path'); var cheerioOptions = {xmlMode: true}; var files = process.argv.slice(2); function read(file) { var content = fs.readFileSync(file, 'utf8'); return cheerio.load(content, cheerioOptions); } function transmogrify($, name) { // output with cleaned up icon name var node = $('#Icon').attr('id', name); // print icon svg console.log($.xml(node)); } function path2IconName(file) { parts = path.basename(file).split('_'); // remove ic_ parts.shift(); // remove _24px.svg parts.pop(); return parts.join('-'); } console.log('<svg><defs>'); files.forEach(function(file) { var name = path2IconName(file); var $ = read(file); transmogrify($, name); }); console.log('</defs></svg>');
JavaScript
0
@@ -635,36 +635,8 @@ %0A%7D%0A%0A -console.log('%3Csvg%3E%3Cdefs%3E');%0A file @@ -751,34 +751,4 @@ %7D);%0A -console.log('%3C/defs%3E%3C/svg%3E');%0A
1c580c053afd8dc5c3a7a31f315a990efa1c8545
change the way to display Instance on call tree
src/js/call-tree.js
src/js/call-tree.js
__$__.CallTree = {}; __$__.CallTree.Initialize = function() { __$__.CallTree.rootNode = new __$__.CallTree.Main('main', []); }; /** * @type {__$__.CallTree.Node} */ __$__.CallTree.Node = class Node { /** * @param {String} label * @param {Array of __$__.CallTree.Node} callPath */ constructor (label, callPath) { this.label = label; this.callPath = callPath.concat(this); this.children = []; this.shape = 'box'; if (callPath.length >= 1) { let parent = callPath[callPath.length - 1]; parent.children.push(this); } } /** * @return {String} the context-sensitive ID of this */ getContextSensitiveID() { if (this.contextSensitiveID === undefined) { this.contextSensitiveID = this.callPath.map(node => { return node.getLabelForContextSensitiveID(); }).join('-'); } return this.contextSensitiveID; } /** * @return {String|*} */ getLabelForContextSensitiveID() { return this.label; } getDisplayedLabel() { return this.label; } }; __$__.CallTree.Main = class Main extends __$__.CallTree.Node { constructor (label, callPath) { super(label, callPath); } }; __$__.CallTree.FunctionCall = class FunctionCall extends __$__.CallTree.Node { constructor (label, callPath) { super(label, callPath); } }; __$__.CallTree.Function = class Function extends __$__.CallTree.Node { constructor (label, callPath, simplifiedLabel, functionName) { super(label, callPath); this.simplifiedLabel = simplifiedLabel; this.functionName = (functionName) ? functionName : 'anonymous'; } getDisplayedLabel() { let parent = this.callPath[this.callPath.length - 2]; if (parent && parent.constructor.name === 'Instance') { return parent.getDisplayedLabel(); } else { return this.functionName; } } }; __$__.CallTree.Loop = class Loop extends __$__.CallTree.Node { constructor (label, callPath, simplifiedLabel, count) { super(label, callPath); this.simplifiedLabel = simplifiedLabel; this.count = count; } getLabelForContextSensitiveID() { return super.getLabelForContextSensitiveID() + '-' + this.count; } getDisplayedLabel() { return this.simplifiedLabel; } }; __$__.CallTree.Instance = class Instance extends __$__.CallTree.Node { constructor (label, callPath, callee) { super(label, callPath); this.callee = callee; } getDisplayedLabel() { return 'new ' + this.callee; } };
JavaScript
0.000001
@@ -2693,17 +2693,18 @@ urn 'new - +%5Cn ' + this
97fab7ee403a81d9786351c31320991b38f9b8f1
enable type checking for `test/integration/instance-lookup-test.js`
test/integration/instance-lookup-test.js
test/integration/instance-lookup-test.js
const fs = require('fs'); const InstanceLookup = require('../../src/instance-lookup').InstanceLookup; const homedir = require('os').homedir(); const assert = require('chai').assert; const AbortController = require('node-abort-controller'); var RESERVED_IP_ADDRESS = '192.0.2.0'; // Can never be used, so guaranteed to fail. function getConfig() { return { server: JSON.parse( fs.readFileSync( homedir + '/.tedious/test-connection.json', 'utf8' ) ).config.server, instanceName: JSON.parse( fs.readFileSync( homedir + '/.tedious/test-connection.json', 'utf8' ) ).instanceName }; } describe('Instance Lookup Test', function() { it('should test good instance', function(done) { var config = getConfig(); if (!config.instanceName) { // Config says don't do this test (probably because SQL Server Browser is not available). return this.skip(); } const controller = new AbortController(); new InstanceLookup().instanceLookup({ server: config.server, instanceName: config.instanceName, signal: controller.signal }, function(err, port) { if (err) { return done(err); } assert.ok(port); done(); }); }); it('should test bad Instance', function(done) { var config = getConfig(); const controller = new AbortController(); new InstanceLookup().instanceLookup({ server: config.server, instanceName: 'badInstanceName', timeout: 100, retries: 1, signal: controller.signal }, function(err, port) { assert.ok(err); assert.ok(!port); done(); }); }); it('should test bad Server', function(done) { const controller = new AbortController(); new InstanceLookup().instanceLookup({ server: RESERVED_IP_ADDRESS, instanceName: 'badInstanceName', timeout: 100, retries: 1, signal: controller.signal }, function(err, port) { assert.ok(err); assert.ok(!port); done(); }); }); });
JavaScript
0
@@ -1,12 +1,26 @@ +// @ts-check%0A%0A const fs = r @@ -37,84 +37,8 @@ ');%0A -const InstanceLookup = require('../../src/instance-lookup').InstanceLookup;%0A cons @@ -113,20 +113,21 @@ assert;%0A -cons +impor t AbortC @@ -136,26 +136,21 @@ troller -= require( +from 'node-ab @@ -164,17 +164,93 @@ troller' -) +;%0A%0Aconst InstanceLookup = require('../../src/instance-lookup').InstanceLookup ;%0A%0Avar R
e005348fba63ff1331c4cfdd084ddde9039a7219
remove toggle function
www/js/controllers/payCtrlController.js
www/js/controllers/payCtrlController.js
angular.module('app.controllers') .controller('payCtrl', function($scope, DishesService, SharesService, BillService, OptionsService, BillService, HistoryService, ionicToast) { var $expenseData = DishesService.all(); var $people = SharesService.all(); var $bill = BillService.getBill(); var $totalValue = 0; var $totalDetail = []; $scope.people = getSummaryData(); $scope.totalValue = $totalValue; $scope.totalDetail = $totalDetail; $scope.bill = $bill; $scope.history = {}; $scope.history.name = ''; $scope.view = function($event, team) { viewDetail($event, team); } $scope.clear = function($event, team) { BillService.resetBill(); SharesService.clear(); DishesService.clear(); } $scope.saveHistory = function(history){ var getDate = function(){ var date = new Date(); return (date.getMonth()+1).toString() + '/' + date.getDate().toString() + '/' + date.getFullYear().toString() + ' ' + date.toLocaleTimeString(); }; var histObj = { name: angular.copy($scope.history.name), date: getDate(), grandTotal: angular.copy($scope.totalValue), bill: angular.copy(BillService.getBill()), dishes: angular.copy(DishesService.all()), people: angular.copy(SharesService.all()) }; HistoryService.addHistory(histObj); $scope.history.name = ""; ionicToast.show('Record saved.', 'top', false, 2500); }; function getSummaryData() { var people = createPeople(); var index = 0; var result = []; calculateBill(people); for(i in people) { $totalValue += people[i].getPrice(); result.push(people[i].getSummary()); index++; } return result; } function createPeople() { var people = {}; var name; for( index in $people) { name = $people[index].name; people[name] = new plopleBill(name); } return people; } function calculateBill(people) { var currentList; var price; var oriPrice; var name; var vat = ($bill.vat == 0)? 1 : (1+($bill.vat/100)); var serviceCharge = ($bill.serviceCharge == 0)? 1: (1+($bill.serviceCharge/100)); if (OptionsService.get() == "E") { price = $bill.grandTotal/$people.length; oriPrice = $bill.totalAmount/$people.length; for(i in people) { people[i].addDish("All Menu", price, oriPrice); } } else { for(index in $expenseData) { currentList = $expenseData[index]; price = currentList.price/currentList.people.length; for(i in currentList.people) { name = currentList.people[i].name; people[name].addDish(currentList.name, (price*vat*serviceCharge),price); } } } } function viewDetail($event, team) { angular.element(document.getElementsByClassName("detailPanel")).addClass("hidden"); angular.element($event.currentTarget).next().toggleClass("hidden"); } }); var plopleBill = function(name) { var name = name; var dish = []; var total = 0; return { getPrice: function() { return total; }, getSummary: function() { if( dish.length == 0 ) return {name: name, payAmount: total, detail: [{name: "No record...", price: ""}]}; else return {name: name, payAmount: total, detail: dish}; }, addDish: function(name, price, oriPrice) { dish.push({ name:name, price: price, oriPrice: oriPrice}); total += price; } }; }
JavaScript
0.000002
@@ -579,17 +579,16 @@ m);%0A%09%7D%0A%0A -%09 %0A%09$scope @@ -2596,16 +2596,18 @@ team) %7B%0A +// %09%09angula @@ -2684,16 +2684,18 @@ dden%22);%0A +// %09%09angula
4dc84947b544847a0ea361f38db0655e6eaf7f9e
fix dependency to scenes managing class #core (cherry picked from commit d59a7c7)
www/js/mygame/scenes/installMyScenes.js
www/js/mygame/scenes/installMyScenes.js
G.installMyScenes = (function (SceneManager, Width, Height) { "use strict"; function installMyScenes(sceneServices) { // create your scenes and add them to the scene manager var sceneManager = new SceneManager(); sceneManager.add(function (next) { var stage = sceneServices.stage; stage.createText('Hello World :)').setPosition(Width.HALF, Height.HALF); }); return sceneManager; } return installMyScenes; })(H5.SceneManager, H5.Width, H5.Height);
JavaScript
0
@@ -29,23 +29,17 @@ n (Scene -Manager +s , Width, @@ -196,23 +196,17 @@ ar scene -Manager +s = new S @@ -209,23 +209,17 @@ ew Scene -Manager +s ();%0A%0A @@ -228,23 +228,17 @@ scene -Manager +s .add(fun @@ -415,23 +415,17 @@ rn scene -Manager +s ;%0A %7D%0A @@ -468,15 +468,9 @@ cene -Manager +s , H5
16a1a1cd26430b212f2241aae220b7c8d63d43e3
Remove useless function
src/js/utilities.js
src/js/utilities.js
function isNumber(n) { return typeof n === 'number' && !isNaN(n); } function isUndefined(n) { return typeof n === 'undefined'; } function toArray(obj, offset) { var args = []; // This is necessary for IE8 if (isNumber(offset)) { args.push(offset); } return args.slice.apply(obj, args); } // Custom proxy to avoid jQuery's guid function proxy(fn, context) { var args = toArray(arguments, 2); return function () { return fn.apply(context, args.concat(toArray(arguments))); }; } function isCrossOriginURL(url) { var parts = url.match(/^(https?:)\/\/([^\:\/\?#]+):?(\d*)/i); return parts && ( parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port ); } function addTimestamp(url) { var timestamp = 'timestamp=' + (new Date()).getTime(); return (url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp); } function getImageData(image) { var naturalWidth = image.naturalWidth; var naturalHeight = image.naturalHeight; var newImage; // IE8 if (!naturalWidth) { newImage = new Image(); newImage.src = image.src; naturalWidth = newImage.width; naturalHeight = newImage.height; } return { naturalWidth: naturalWidth, naturalHeight: naturalHeight, aspectRatio: naturalWidth / naturalHeight }; } function getTransform(options) { var transforms = []; var rotate = options.rotate; var scaleX = options.scaleX; var scaleY = options.scaleY; if (isNumber(rotate)) { transforms.push('rotate(' + rotate + 'deg)'); } if (isNumber(scaleX) && isNumber(scaleY)) { transforms.push('scale(' + scaleX + ',' + scaleY + ')'); } return transforms.length ? transforms.join(' ') : 'none'; } function getRotatedSizes(data, reverse) { var deg = abs(data.degree) % 180; var arc = (deg > 90 ? (180 - deg) : deg) * Math.PI / 180; var sinArc = sin(arc); var cosArc = cos(arc); var width = data.width; var height = data.height; var aspectRatio = data.aspectRatio; var newWidth; var newHeight; if (!reverse) { newWidth = width * cosArc + height * sinArc; newHeight = width * sinArc + height * cosArc; } else { newWidth = width / (cosArc + sinArc / aspectRatio); newHeight = newWidth / aspectRatio; } return { width: newWidth, height: newHeight }; } function getSourceCanvas(image, data) { var canvas = $('<canvas>')[0]; var context = canvas.getContext('2d'); var x = 0; var y = 0; var width = data.naturalWidth; var height = data.naturalHeight; var rotate = data.rotate; var scaleX = data.scaleX; var scaleY = data.scaleY; var scalable = isNumber(scaleX) && isNumber(scaleY) && (scaleX !== 1 || scaleY !== 1); var rotatable = isNumber(rotate) && rotate !== 0; var advanced = rotatable || scalable; var canvasWidth = width; var canvasHeight = height; var translateX; var translateY; var rotated; if (scalable) { translateX = width / 2; translateY = height / 2; } if (rotatable) { rotated = getRotatedSizes({ width: width, height: height, degree: rotate }); canvasWidth = rotated.width; canvasHeight = rotated.height; translateX = rotated.width / 2; translateY = rotated.height / 2; } canvas.width = canvasWidth; canvas.height = canvasHeight; if (advanced) { x = -width / 2; y = -height / 2; context.save(); context.translate(translateX, translateY); } if (rotatable) { context.rotate(rotate * Math.PI / 180); } // Should call `scale` after rotated if (scalable) { context.scale(scaleX, scaleY); } context.drawImage(image, x, y, width, height); if (advanced) { context.restore(); } return canvas; } function toString(o) { var items =[]; $.each(o, function (i, n) { items.push([i, n].join(': ')) }); return items.join(', '); }
JavaScript
0.000904
@@ -4023,160 +4023,4 @@ %7D%0A -%0A function toString(o) %7B%0A var items =%5B%5D;%0A%0A $.each(o, function (i, n) %7B%0A items.push(%5Bi, n%5D.join(': '))%0A %7D);%0A%0A return items.join(', ');%0A %7D%0A
587724875b27ef9f80c722790188cc1f4d949581
add bg to loader
app/js/src/Loader.js
app/js/src/Loader.js
export default class Loader extends createjs.LoadQueue { constructor() { super(); createjs.Sound.alternateExtensions = ['mp3']; this.installPlugin(createjs.Sound); this.loadManifest([ { id: 'char', src: 'img/monster-sprite.png' }, { id: 'spike', src: 'img/spike.png' }, { id: 'back', src: 'sound/background.ogg' }, { id: 'flap', src: 'sound/flap.ogg' }, { id: 'loose', src: 'sound/loose.ogg' }, ]); } }
JavaScript
0.000001
@@ -285,32 +285,180 @@ g/spike.png' %7D,%0A + %7B id: 'sky', src: 'img/bg/sky.png' %7D,%0A %7B id: 'mountain', src: 'img/bg/mountain.png' %7D,%0A %7B id: 'ground', src: 'img/bg/ground.png' %7D,%0A %7B id: 'bac
ff9fed688b2e0c4e32f657a18f4cb7be432d91be
Update backend.js
api/backend.js
api/backend.js
var pubnub = PUBNUB.init({ publish_key: 'pub-c-f1c1301a-f5c5-4038-8f35-a4ec81044399', subscribe_key: 'sub-c-2ed8a5ea-014a-11e4-b97b-02ee2ddab7fe' }); pubnub.subscribe({ channel: 'hasreon_chat', message: function (m) { interpret(m); } }); var msgArray; function interpret(recv) { msgArray = recv.split("~"); //Separate the Username from the incoming command if(recv.charAt(0) == "/") { //if the recieved data is a command, then do the below, else ignore. //Note that commands will not support additional parameters if(msgArray[0] == "/n" || "/north" || "/N" || "/North" || "/NORTH") { } } }
JavaScript
0.000001
@@ -524,16 +524,145 @@ ameters%0A +%09%09if(msgArray%5B0%5D == %22/init%22) %7B%0A%09%09%09pubnub.publish(%7B%0A%09%09%09%09channel: %22hasreon_chat%22,%0A%09%09%09%09message: %22:get('fairfalcongate')%22%0A%09%09%09%7D);%0A%09%09%7D%0A %09%09%0A%09%09if(
189a7cb8bc146b0482512c4a4589671725f0e5fd
fix float number
slackbot/commands.js
slackbot/commands.js
'use strict' const get = require('../src/request') const { auth, url, goal } = require('../src/configs') const parser = require('../src/parser') const { countIssuesByType, countIssuesByDifficulty, sumPontuation, sumTime, scoredIssues } = require('../src/filters') const loadIssues = ( user ) => { const startDate = '2017-07-01' const endDate = '2017-07-31' const filterUrl = url( startDate, endDate, user ) const headers = { 'Authorization': `Basic ${auth()}` } const options = { headers } return get(filterUrl, options) .then( response => parser(response.data) ) .catch( response => `Error: ${response.message}` ) } const score = ( user ) => { return loadIssues( user ) .then( issues => { const objective = goal(user) const pontuation = sumPontuation( issues ) const percentage = ( (pontuation * 100) / objective ).toFixed(2); const moreThanHalf = 'Tu ta o bichão memo, em?!' const lessThanHalf = 'Anda logo com isso ae!' const lessThanOneThird = 'Trabalha não?! É bom começar.' const response = [ `Você tem *${pontuation}* pontos e completou *${percentage}%* da meta *${objective}* !`, `Faltam *${objective - pontuation}* pontos, *${100 - percentage}%* para bater a meta!`, `\n${percentage < 33 ? lessThanOneThird : percentage < 50 ? lessThanHalf : moreThanHalf}` ] return response.join('\n') }) .catch( response => `Error: ${response.message}` ) } const issues = ( user ) => { return loadIssues( user ) .then( issues => { const nc = countIssuesByDifficulty( issues, 'Não classificado') const s = countIssuesByDifficulty( issues, 'Simples') const vs = countIssuesByDifficulty( issues, 'Muito simples') const m = countIssuesByDifficulty( issues, 'Média') const h = countIssuesByDifficulty( issues, 'Difícil') const vh = countIssuesByDifficulty( issues, 'Muito difícil') const cs = countIssuesByType( issues, 'Atendimento') const cst = sumTime( issues, 'Atendimento' ) const tasks = countIssuesByType( issues, 'Tarefa') const taskstime = sumTime( issues, 'Tarefa' ) const scored = scoredIssues( issues ) const response = [ `Issues Não Classificadas: *${nc}*`, `Issues Muito simples: *${vs}*`, `Issues Simples: *${s}*`, `Issues Médias: *${m}*`, `Issues Difíceis: *${h}*`, `Issues Muito díficeis: *${vh}*`, `\nIssues de Atendimento: *${cs}*`, `Total de tempo em issues de Atendimento: *${cst} minutos*`, `\nIssues de Tarefas: *${tasks}*`, `Total de tempo em issues de Tarefas: *${taskstime} minutos*`, `\nTotal de issues: *${issues.length}*`, `Total de issues pontuadas: *${scored.length}*` ] return response.join('\n') }) .catch( response => `Error: ${response.message}` ) } module.exports = { score, issues }
JavaScript
0.000021
@@ -1335,16 +1335,17 @@ tos, *$%7B +( 100 - pe @@ -1348,24 +1348,36 @@ - percentage +).toFixed(2) %7D%25* para bat
4ad08cf52f4b106dcceec16d43d3d26dd48c81b4
Add thousand seperator (superior version with dots)
src/resources/js/statistics.js
src/resources/js/statistics.js
$(document).ready(() => { const formatNumber = number => number.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1.'); let chart; const updateStatistics = statistics => { $('#alltime').html(`All-time clicks: ${formatNumber(statistics.alltime)}`); $('#daily').html(`Today's clicks: ${formatNumber(statistics.daily)}`); $('#weekly').html(`This week's clicks: ${formatNumber(statistics.weekly)}`); $('#monthly').html(`This month's clicks: ${formatNumber(statistics.monthly)}`); $('#yearly').html(`This year's clicks: ${formatNumber(statistics.yearly)}`); $('#average').html(`Average clicks a day (in this month): ~${formatNumber(statistics.average)}`); $.get('/api/chartData').done(data => { const months = data.map(entry => entry = entry.month); const clicks = data.map(entry => entry = entry.clicks); const ctx = $('#monthly-chart'); if (!chart) { chart = new Chart(ctx, { type: 'line', data: { labels: months, datasets: [{ data: clicks, label: 'Clicks' }] } }); } else { chart.data.labels = months; chart.data.datasets[0].data = clicks; chart.update(); } }); }; $.get('/conInfo').done(con => { const domainOrIP = document.URL.split('/')[2].split(':')[0]; const host = con.ssl ? `wss://${domainOrIP}` : `ws://${domainOrIP}:${con.port}`; const ws = new WebSocket(host); ws.addEventListener('open', event => { ws.addEventListener('message', message => { let data; try { data = JSON.parse(message.data); } catch (e) { data = {}; } if (!['counterUpdate', 'notification'].includes(data.type)) return; if (data.statistics) updateStatistics(data.statistics); // only numbers ever get updated here, no need to differentiate the events else if (data.type === 'notification' && data.notification) { $('#notification').text(data.notification.text); $('#notification-wrapper').fadeIn().fadeOut(data.notification.duration * 1000); } }); }); }); $.get('/counter?statistics').done(statistics => updateStatistics(statistics)); });
JavaScript
0
@@ -1027,16 +1027,331 @@ %09%09%09%09%09%7D%5D%0A +%09%09%09%09%09%7D,%0A%09%09%09%09%09options: %7B%0A%09%09%09%09%09%09scales: %7B%0A%09%09%09%09%09%09%09yAxes: %5B%7B%0A%09%09%09%09%09%09%09%09ticks: %7B%0A%09%09%09%09%09%09%09%09%09callback: value =%3E value.toLocaleString('de-DE'),%0A%09%09%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09%09%7D%5D%0A%09%09%09%09%09%09%7D,%0A%09%09%09%09%09%09tooltips: %7B%0A%09%09%09%09%09%09%09callbacks: %7B%0A%09%09%09%09%09%09%09%09label: (tItems, data) =%3E %60$%7Bdata.datasets%5B0%5D.data%5BtItems.index%5D.toLocaleString('de-DE')%7D%60%0A%09%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09%7D%0A %09%09%09%09%09%7D%0A%09
6d0f9547cfacc64f54acc31ba42ac2399048ce0c
remove debugger statements
platform/nativescript/compiler/directives/model.js
platform/nativescript/compiler/directives/model.js
import { genComponentModel, genAssignmentCode } from 'compiler/directives/model' import { isKnownView, getViewMeta } from '../../element-registry' export default function model(el, dir) { if (el.type === 1 && isKnownView(el.tag)) { genViewComponentModel(el, dir.value, dir.modifiers) } else { genComponentModel(el, dir.value, dir.modifiers) } } function genViewComponentModel(el, value, modifiers) { debugger const { number, trim } = modifiers || {} const { prop } = getViewMeta(el.tag).model const baseValueExpression = '$event' let valueExpression = `${baseValueExpression}.object[${JSON.stringify(prop)}]` if (trim) { valueExpression = `(typeof ${valueExpression} === 'string'` + `? ${valueExpression}.trim()` + `: ${valueExpression})` } if (number) { valueExpression = `_n(${valueExpression})` } const assignment = genAssignmentCode(value, valueExpression) el.model = { value: `(${value})`, expression: JSON.stringify(value), callback: `function (${baseValueExpression}) {debugger;${assignment}}` } }
JavaScript
0.000261
@@ -413,19 +413,8 @@ ) %7B%0A - debugger%0A co @@ -1040,17 +1040,8 @@ %7D) %7B -debugger; $%7Bas
21170be839a7ace82dcd5cb59b10071e3df95672
Add the auth path for onboarding
src/routes/onboarding/index.js
src/routes/onboarding/index.js
function getRoute(path, subComponentName) { return { path: path, subComponentName: subComponentName, getComponents(location, cb) { require.ensure([], (require) => { cb(null, require('../../components/views/OnboardingView')) }) }, } } export default { path: 'onboarding', onEnter() { require('../../networking/auth') }, getChildRoutes(location, cb) { require.ensure([], () => { cb(null, [ getRoute('communities', 'CommunityPicker'), getRoute('awesome-people', 'PeoplePicker'), getRoute('profile-header', 'CoverPicker'), getRoute('profile-avatar', 'AvatarPicker'), getRoute('profile-bio', 'InfoPicker'), ]) }) }, }
JavaScript
0.000002
@@ -104,16 +104,78 @@ ntName,%0A + onEnter() %7B%0A require('../../networking/auth')%0A %7D,%0A getC
542edd9ace1d5998569c89106c14aa80969c4ccb
Make invert colour-aware
src/filters/invert.js
src/filters/invert.js
// @flow import { BOOL } from "constants/controlTypes"; import { cloneCanvas, fillBufferPixel, getBufferIndex } from "utils"; export const optionTypes = { invertAlpha: { type: BOOL, default: false } }; export const defaults = { invertAlpha: optionTypes.invertAlpha.default }; const invert = ( input: HTMLCanvasElement, options: { invertAlpha: boolean } = defaults ): HTMLCanvasElement => { const output = cloneCanvas(input, false); const inputCtx = input.getContext("2d"); const outputCtx = output.getContext("2d"); if (!inputCtx || !outputCtx) return input; const buf = inputCtx.getImageData(0, 0, input.width, input.height).data; for (let x = 0; x < input.width; x += 1) { for (let y = 0; y < input.height; y += 1) { const i = getBufferIndex(x, y, input.width); const r = 255 - buf[i]; const g = 255 - buf[i + 1]; const b = 255 - buf[i + 2]; const a = options.invertAlpha ? 255 - buf[i + 3] : buf[i + 3]; fillBufferPixel(buf, i, r, g, b, a); } } outputCtx.putImageData(new ImageData(buf, output.width, output.height), 0, 0); return output; }; export default { name: "Invert", func: invert, options: defaults, optionTypes, defaults };
JavaScript
0.002296
@@ -162,114 +162,348 @@ vert -Alpha: %7B type: BOOL, default: false %7D%0A%7D;%0A%0Aexport const defaults = %7B%0A invertAlpha: optionTypes.invertAlpha +R: %7B type: BOOL, default: true %7D,%0A invertG: %7B type: BOOL, default: true %7D,%0A invertB: %7B type: BOOL, default: true %7D,%0A invertA: %7B type: BOOL, default: false %7D%0A%7D;%0A%0Aexport const defaults = %7B%0A invertR: optionTypes.invertR.default,%0A invertG: optionTypes.invertG.default,%0A invertB: optionTypes.invertB.default,%0A invertA: optionTypes.invertA .def @@ -572,29 +572,97 @@ s: %7B +%0A invert -Alpha: boolean +R: boolean,%0A invertG: boolean,%0A invertB: boolean,%0A invertA: boolean%0A %7D = @@ -1111,22 +1111,49 @@ onst r = + options.invertR ? 255 - + buf%5Bi%5D : buf%5Bi%5D; @@ -1168,16 +1168,34 @@ onst g = + options.invertG ? 255 - b @@ -1200,16 +1200,29 @@ buf%5Bi + + 1%5D : buf%5Bi + 1%5D;%0A @@ -1234,21 +1234,52 @@ nst b = -255 - +options.invertB ? 255 - buf%5Bi + 2%5D : buf%5Bi + @@ -1318,12 +1318,8 @@ ertA -lpha ? 2
36058544a52e54e2ba55214b18b90a8dfd1547c3
Make Mouse a singleton object.
src/flash/ui/Mouse.js
src/flash/ui/Mouse.js
function Mouse() { } Object.defineProperties(Mouse, { cursor: describeAccessor( function () { return 'auto'; // TODO }, function (val) { notImplemented(); } ), supportsCursor: describeAccessor(function () { return true; // TODO }), supportsNativeCursor: describeAccessor(function () { return true; // TODO }), hide: describeMethod(function () { notImplemented(); }), registerCursor: describeMethod(function (name, cursor) { notImplemented(); }), show: describeMethod(function () { notImplemented(); }), unregisterCursor: describeMethod(function (name) { notImplemented(); }) });
JavaScript
0
@@ -1,55 +1,34 @@ -function Mouse() %7B%0A%7D%0A%0AObject.defineProperties(Mouse +var Mouse = Object.create(null , %7B%0A