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
4f716ddbcc65c9aaf89db18ee8caa07899ebe43c
Add facility to not save responses when certain conditions hold true (needsRetryMatcher)
src/recorder.js
src/recorder.js
const passThrough = require('./pass_through'); module.exports = function recorded(settings) { const { catalog } = settings; const capture = passThrough(true); return function(request, callback) { let host = request.url.hostname; if (request.url.port && request.url.port !== '80') host = `${host}:${request.url.port}`; // Look for a matching response and replay it. try { const matchers = catalog.find(host); if (matchers) for (let matcher of matchers) { let response = matcher(request); if (response) { callback(null, response); return; } } } catch (error) { error.code = 'CORRUPT FIXTURE'; error.syscall = 'connect'; callback(error); return; } // Do not record this host. if (settings.isDropped(request.url.hostname)) { const refused = new Error('Error: connect ECONNREFUSED'); refused.code = refused.errno = 'ECONNREFUSED'; refused.syscall = 'connect'; callback(refused); return; } // In recording mode capture the response and store it. if (settings.mode === 'record') { capture(request, function(error, response) { if (error) callback(error); else catalog.save(host, request, response, function(saveError) { callback(saveError, response); }); }); return; } // Not in recording mode, pass control to the next proxy. callback(); }; };
JavaScript
0
@@ -1279,16 +1279,425 @@ else%0A + if (settings.needsRetryMatchers && settings.needsRetryMatchers%5Bhost%5D) %7B%0A if (settings.needsRetryMatchers%5Bhost%5D(request, response)) %7B%0A // if responseNeedsRetryMatchers matches, just return response,%0A // and do not record it. This weeds out responses that need to be retried.%0A callback(null, response);%0A return;%0A %7D%0A %7D%0A
8657461040aedb17cbadffa43162c6d86a0dc780
add checkout router.
src/router-config.js
src/router-config.js
import VueRouter from 'vue-router' import Bus from './bus'; import PassportLayout from './components/Passport.vue'; import Signin from './views/passport/Signin.vue'; import Signup from './views/passport/Signup.vue'; import Home from './views/Home.vue' import Video from './views/pr/Video.vue' import Comments from './views/pr/Comments.vue' import WallPaper from './views/pr/WallPaper.vue' import News from './views/pr/News.vue' import Contact from './views/support/Contact.vue' import SupportLayout from './views/support/Layout.vue' import AccountLayout from './views/account/Layout.vue' import NotFound from './views/NotFound.vue' let router = new VueRouter({ // mode: 'history', routes: [ { path: '/', component: Home }, { name: 'passport', path: '/signin', component: PassportLayout }, { name: 'passport', path: '/signup', component: PassportLayout }, { path: '/pr', redirect: '/pr/video', }, { path: '/pr/video', component: Video }, { path: '/pr/comment', component: Comments }, { path: '/pr/wallpaper', component: WallPaper }, { path: '/pr/news', component: News }, { name: 'support-order', path: '/order/:name', component: SupportLayout }, { name: 'support-service', path: '/service/:name', component: SupportLayout }, { name: 'support-copyright', path: '/copyright/:name', component: SupportLayout }, { path: '/contact', component: Contact }, { name: 'account', path: '/account/order', component: AccountLayout }, { name: 'account', path: '/account/order/:id', component: AccountLayout }, { name: 'account', path: '/account/address', component: AccountLayout }, { name: 'account', path: '/account/information', component: AccountLayout }, { path: '*', component: NotFound } ], scrollBehavior(to, from, savedPosition) { return {x: 0, y: 0}; } }); router.beforeEach((to, from, next)=> { if(to.name != 'passport') { Bus.$emit('changeLayout', true); } next(); }); export default router;
JavaScript
0
@@ -579,24 +579,76 @@ Layout.vue'%0A +import Checkout from './views/payment/Checkout.vue'%0A import NotFo @@ -680,16 +680,17 @@ d.vue'%0A%0A +%0A let rout @@ -2463,32 +2463,121 @@ %7D,%0A %7B %0A + path: '/checkout/:id',%0A component: Checkout%0A %7D,%0A %7B %0A path
9301d75faeaf7545133bf7cf6bfb5d29bbd4bd63
add payment router path.
src/router-config.js
src/router-config.js
import VueRouter from 'vue-router' import Bus from './bus'; import PassportLayout from './components/Passport.vue'; import Signin from './views/passport/Signin.vue'; import Signup from './views/passport/Signup.vue'; import Home from './views/Home.vue' import Video from './views/pr/Video.vue' import Comments from './views/pr/Comments.vue' import WallPaper from './views/pr/WallPaper.vue' import News from './views/pr/News.vue' import Contact from './views/support/Contact.vue' import SupportLayout from './views/support/Layout.vue' import AccountLayout from './views/account/Layout.vue' import Checkout from './views/payment/Checkout.vue' import NotFound from './views/NotFound.vue' let router = new VueRouter({ // mode: 'history', routes: [ { path: '/', component: Home }, { name: 'passport', path: '/signin', component: PassportLayout }, { name: 'passport', path: '/signup', component: PassportLayout }, { path: '/pr', redirect: '/pr/video', }, { path: '/pr/video', component: Video }, { path: '/pr/comment', component: Comments }, { path: '/pr/wallpaper', component: WallPaper }, { path: '/pr/news', component: News }, { name: 'support-order', path: '/order/:name', component: SupportLayout }, { name: 'support-service', path: '/service/:name', component: SupportLayout }, { name: 'support-copyright', path: '/copyright/:name', component: SupportLayout }, { path: '/contact', component: Contact }, { name: 'account', path: '/account/order', component: AccountLayout }, { name: 'account', path: '/account/order/:id', component: AccountLayout }, { name: 'account', path: '/account/address', component: AccountLayout }, { name: 'account', path: '/account/information', component: AccountLayout }, { path: '/checkout/:id', component: Checkout }, { path: '*', component: NotFound } ], scrollBehavior(to, from, savedPosition) { return {x: 0, y: 0}; } }); router.beforeEach((to, from, next)=> { if(to.name != 'passport') { Bus.$emit('changeLayout', true); } next(); }); export default router;
JavaScript
0
@@ -631,24 +631,74 @@ eckout.vue'%0A +import Payment from './views/payment/Payment.vue'%0A import NotFo @@ -2602,32 +2602,119 @@ %7D,%0A %7B %0A + path: '/payment/:id',%0A component: Payment%0A %7D,%0A %7B %0A path
cc96b2734c845d4b17c8bacd26a3a40708b24acb
fix bug with presets selection after updating (#376)
src/webcomponents/commons/filters/consequence-type-select-filter.js
src/webcomponents/commons/filters/consequence-type-select-filter.js
/** * Copyright 2015-2019 OpenCB * * 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 {LitElement, html} from "lit"; import LitUtils from "../utils/lit-utils.js"; import UtilsNew from "../../../core/utilsNew.js"; import "../forms/select-field-filter.js"; export default class ConsequenceTypeSelectFilter extends LitElement { constructor() { super(); // Set status and init private properties this._init(); } createRenderRoot() { return this; } static get properties() { return { ct: { type: String }, config: { type: Object } }; } _init() { this._prefix = UtilsNew.randomString(8); this._ct = []; // this.ct is a comma separated list, this._ct is an array of the same data this.presetSelected = new Map(); // this.isChecked = {}; this.options = []; } connectedCallback() { super.connectedCallback(); this._config = {...this.getDefaultConfig(), ...this.config}; this.options = this._config.categories.map(item => item.title ? { id: item.title.toUpperCase(), fields: item.terms.map(term => this.mapTerm(term)) } : this.mapTerm(item) ); } // eslint-disable-next-line no-unused-vars firstUpdated(changedProperties) { // Display SO terms in the badgers UtilsNew.initTooltip(this); } update(changedProperties) { if (changedProperties.has("ct")) { if (this.ct) { this._ct = this.ct.split(","); this.presetSelected = new Map(); // Reset active presets // Add active presets (this._config.alias || []).forEach(alias => { const allTermsSelected = alias.terms.every(term => this._ct.includes(term)); if (allTermsSelected) { this.presetSelected.set(alias.name, alias); } }); } else { this._ct = []; // this.isChecked = {}; } } super.update(changedProperties); } mapTerm(term) { // TODO think about this badge: // <span class='badge badge-light' style="color: ${CONSEQUENCE_TYPES.style[term.impact]}">${term.impact}</span> return { id: term.name, name: `${term.name} <span class="badge badge-light">${term.id}</span>` }; } onPresetSelect(preset, e) { if (preset && this._config.alias) { const aliasSelect = this._config.alias.find(alias => alias.name === preset); if (aliasSelect) { // 1. Add/delete selected presets if (e.currentTarget.checked) { // Just keep track of the selected preset this.presetSelected.set(aliasSelect.name, aliasSelect); } else { // Remove preset selection and all its terms this.presetSelected.delete(aliasSelect.name); this._ct = this._ct.filter(ct => !aliasSelect.terms.includes(ct)); } // 2. Add all terms from the still selected presets, just in case some shared terms were deleted const ctSet = new Set(this._ct); for (const key of this.presetSelected.keys()) { for (const term of this.presetSelected.get(key).terms) { ctSet.add(term); } } this._ct = [...ctSet]; // 3. Update display this.requestUpdate(); // 4. Notify changes this.filterChange(); } else { console.error("Consequence type preset not found: ", preset); } } } onFilterChange(e) { // 1. Set selected values const ctSet = new Set(e.detail.value?.split(",") || []); this._ct = [...ctSet]; // 2. Remove any preset election, this is not compatible with manual selection for (const key of this.presetSelected.keys()) { const allTermsSelected = this.presetSelected.get(key).terms.every(ct => this._ct.indexOf(ct) > -1); if (!allTermsSelected) { this.presetSelected.delete(key); } } // 3. Update disaply this.requestUpdate(); // 4. Notfify changes this.filterChange(); } filterChange() { LitUtils.dispatchCustomEvent(this, "filterChange", this._ct.join(",")); } /* Updates the state of all checkboxes in case of item selected from the dropdown and in case of click on a checkbox, including indeterminate state (which is visual only, the real state is still true/false). */ // updateCheckboxes() { // for (const alias of this._config.alias) { // this.isChecked[alias.name] = alias.terms.every(v => this._ct.indexOf(v) > -1); // $(`.${this._prefix}_ctCheckbox`).prop("indeterminate", false); // // if (!this.isChecked[alias.name]) { // const id = `${this._prefix}${alias.name.replace(/ |[()]|/g, "")}`; // $(`#${id}`).prop("indeterminate", alias.terms.some(v => this._ct.indexOf(v) > -1)); // } // } // this.isChecked = {...this.isChecked}; // this.requestUpdate(); // } getDefaultConfig() { return CONSEQUENCE_TYPES; } render() { return html` <!-- Render the different aliases configured --> <div class="form-group"> ${this._config.alias && this._config.alias.length > 0 ? html` <div style="margin: 5px 0px"> <span>Add terms from a preset configuration:</span> </div> ${this._config.alias.map(alias => { const id = `${this._prefix}${alias.name.replace(/ |[()]|/g, "")}`; return html` <div style="margin: 5px 0px"> <label class="text" for="${id}" style="font-weight: normal; cursor: pointer"> <input type="checkbox" class="${this._prefix}_ctCheckbox" id="${id}" name="layout" value="${alias.name}" .checked="${this.presetSelected.has(alias.name)}" @click="${e => this.onPresetSelect(alias.name, e)}"> <span style="margin: 0px 5px">${alias.name} </span> </label> <span tooltip-title="Terms" tooltip-text="${alias.terms.join("<br>")}" class="badge badge-secondary"> ${alias.terms?.length} terms </span> </div> `; })} ` : null} </div> <div class="form-group"> <div style="margin: 10px 0px"> <span>Or select terms manually:</span> </div> <select-field-filter multiple ?liveSearch="${true}" .data="${this.options}" .value=${this._ct} @filterChange="${this.onFilterChange}"> </select-field-filter> </div> `; } } customElements.define("consequence-type-select-filter", ConsequenceTypeSelectFilter);
JavaScript
0
@@ -2288,32 +2288,56 @@ d active presets + using selected CT terms %0A @@ -2372,21 +2372,22 @@ forEach( -alias +preset =%3E %7B%0A @@ -2429,21 +2429,22 @@ ected = -alias +preset .terms.e @@ -2578,25 +2578,27 @@ set( -alias +preset .name, -alias +preset );%0A
02da01fd19fb9c1c576690dd9edcc491f9ff4158
update routes.js
src/router/routes.js
src/router/routes.js
// Routes import Landing from '@/components/Landing' import Welcome from '@/components/Welcome' import Login from '@/components/auth/Login' import UpdateProfile from '@/components/auth/UpdateProfile' import App from '@/components/App' import NotFound from '@/components/errors/404' const routes = [{ path: '/', component: Landing, children: [{ path: '/', component: Welcome, name: 'Welcome' }, { path: '/login', component: Login, name: 'login' }, { path: '/update-profile', component: UpdateProfile, name: 'Profile Update', meta: { auth: true } }, { path: '/app', component: App, name: 'Main app', meta: { auth: true } } ] }, { path: '*', components: NotFound } ] export default routes;
JavaScript
0.000002
@@ -276,16 +276,39 @@ s/404'%0A%0A +import Vue from 'vue'%0A%0A const ro
4eac51d2f3610f576232cd085b8dee7c07fbab08
Remove default wildcard route pointed to home
src/router/routes.js
src/router/routes.js
// import app pages import Home from '@/app/pages/Home' // import admin page components import Admin from '@/admin/pages/Admin' import Login from '@/admin/pages/Login' import Settings from '@/admin/pages/settings/Settings' import Routing from '@/admin/pages/Routing' import Media from '@/admin/pages/Media' import Database from '@/admin/pages/Database' import ContentType from '@/admin/pages/content/content-type/ContentType' import FieldNew from '@/admin/pages/content/fields/FieldNew' import FieldEdit from '@/admin/pages/content/fields/FieldEdit' import Contents from '@/admin/pages/content/contents/Contents' import ContentsNew from '@/admin/pages/content/contents/ContentsNew' import ContentsEdit from '@/admin/pages/content/contents/ContentsEdit' const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/login', name: 'Login', component: Login }, { path: '/admin', name: 'Admin', component: Admin, children: [ { path: 'settings', component: Settings }, { path: 'routing', component: Routing }, { path: 'media', component: Media }, { path: 'database', component: Database }, { path: 'content', component: ContentType, children: [ { path: 'fieldNew', component: FieldNew }, { path: 'fieldEdit/:key', component: FieldEdit } ] }, { path: 'content/:key', component: Contents, children: [ { path: 'new', component: ContentsNew }, { path: 'edit/:contentKey', component: ContentsEdit } ] } ] }, { path: '*', name: 'default', component: Home } ] export default routes
JavaScript
0
@@ -1835,73 +1835,8 @@ %5D%0A - %7D,%0A %7B%0A path: '*',%0A name: 'default',%0A component: Home%0A %7D%0A
4a5fb9470bdd08365d90a320beec89dd31b91f6a
Update src/router/routes.js
src/router/routes.js
src/router/routes.js
// Routes import Layout from '@/components/Layout' import Welcome from '@/components/Welcome' import Login from '@/components/auth/Login' import UpdateProfile from '@/components/auth/UpdateProfile' import App from '@/components/App' import NotFound from '@/components/errors/404' import Firestore from '@/components/Firestore' import Vue from 'vue' const routes = [{ path: '/', component: Layout, children: [{ path: '/', component: Welcome, name: 'Welcome' }, { path: '/login', component: Login, name: 'login' }, { path: '/update-profile', component: UpdateProfile, name: 'Profile Update', meta: { auth: true } }, { path: '/realtime-database', component: App, name: 'Realtime Database', meta: { auth: true } }, { path: '/firestore', component: Firestore, name: 'Cloud Firestore', meta: { auth: true } }, { path: '*', component: NotFound } ] }] export default routes;
JavaScript
0.000002
@@ -1,14 +1,4 @@ -// Routes%0A impo @@ -1258,17 +1258,16 @@ %5D%0A%7D%5D%0A%0A -%0A export d
0194f21b9c916a284f62b1fb9a376c3370ae3e73
fix logger for pattern init
src/registry.js
src/registry.js
/* * changes to previous patterns.register/scan mechanism * - if you want initialised class, do it in init * - init returns set of elements actually initialised * - handle once within init * - no turnstile anymore * - set pattern.jquery_plugin if you want it */ define([ "jquery", "./logging", "./utils", // below here modules that are only loaded "./compat" ], function($, logging, utils) { var log = logging.getLogger('registry'), jquery_plugin = utils.jquery_plugin; var _ = { patterns: {}, scan: function(content) { var $content = $(content), pattern, $match, plog, $initialised; for (var name in _.patterns) { pattern = _.patterns[name]; plog = logging.getLogger(name); // construct set of matching elements $match = $content.filter(pattern.trigger); $match = $match.add($content.find(pattern.trigger)); $match = $match.filter(':not(.cant-touch-this)'); // call pattern init in case of matching elements, the // pattern returns the set of actually initialised // elements if ($match.length > 0) { plog.debug('Initialising:', $match); try { pattern.init($match); plog.debug('Initialised:', $initialised); } catch (e) { plog.critical("Error initialising pattern", e); } } } }, register: function(pattern) { if (_.patterns[pattern.name]) { log.error("Already have a pattern called: " + pattern.name); return null; } // register pattern to be used for scanning new content _.patterns[pattern.name] = pattern; // register pattern as jquery plugin if (pattern.jquery_plugin) { // XXX: here the pattern used to be jquery_plugin wrapped $.fn[pattern.name] = jquery_plugin(pattern); } log.info('Registered pattern:', pattern.name, pattern); return pattern; } }; return _; }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab
JavaScript
0
@@ -1503,16 +1503,13 @@ log. -critical +error (%22Er
9476834c445cfa21207e5be3dc61e98b8c14e7f7
Fix typo
src/routes/tokens.js
src/routes/tokens.js
'use strict' const { send, json, createError } = require('micro') const tokens = require('../database/tokens') const response = (entry) => ({ type: 'token', data: { id: entry.id, created: entry.created, updated: entry.updated } }) const add = async (req, res) => { const { username, password } = await json(req) if (username == null) throw createError(400, 'Username missing') if (password == null) throw createError(400, 'Password missing') if (process.env.USERNAME == null) throw createError(500, 'Ackee username missing in enviroment') if (process.env.PASSWORD == null) throw createError(500, 'Ackee password missing in enviroment') if (username !== process.env.USERNAME) throw createError(400, 'Username or password incorrect') if (password !== process.env.PASSWORD) throw createError(400, 'Username or password incorrect') const entry = await tokens.add() return send(res, 201, response(entry)) } const del = async (req, res) => { const { tokenId } = req.params await tokens.del(tokenId) send(res, 204) } module.exports = { add, del }
JavaScript
0.999999
@@ -541,24 +541,25 @@ ng in enviro +n ment')%0A%09if ( @@ -644,16 +644,17 @@ n enviro +n ment')%0A%0A
d48f837105182f88df63ffa466f30973a4ff6668
Use right encoding
GulpFlow.js
GulpFlow.js
/** * GulpFlow provides a [gulp](https://gulpjs.com) plugin for [Flow](http://flowtype.org). * * @module GulpFlow * @main GulpFlow */ var _ = require("underscore"); var Class = require("yajscf"); var through = require("through2"); var gutil = require("gulp-util"); var PluginError = gutil.PluginError; var execFile = require("child_process").execFileSync; var flow = require("flow-bin"); module.exports = Class.extend( { /** * GulpFlow is a Gulp plugin for type-checking code with `flow`. * * @class GulpFlow * @constructor */ init: function() { /** * Options to pass to the `flow` binary. * * @property options * @type string[] * @private */ this.options = [ "--json" ]; /** * Name of this plugin. * * @property PLUGIN_NAME * @type string */ this.PLUGIN_NAME = "gulp-flowcheck"; }, /** * Check for type errors and store them in `this.results`. * Only compatible with buffers at the moment. * * @method check * @return {Object} A gulp-compatible stream. */ check: function() { var me = this; this.results = {}; return through.obj(function(file, encoding, callback) { if(file.isNull()) { callback(); return; } if(file.isStream()) { this.emit("error", new PluginError(me.PLUGIN_NAME, "streams are not supported (yet?)")); } var output; try { output = execFile(flow, _.union(["check-contents"], me.options), { input: file.contents.toString("utf-8") }); } catch(e) { // flow normally exits with a non-zero status if errors are found output = e.stdout; } file.contents = output; callback(null, file); }); }, /** * Dump the results of the type check to the command line. * * @method reporter * @return {Object} A gulp-compatible stream. */ reporter: function() { return through.obj(function(file, encoding, callback) { var contents = file.contents.toString(encoding); //console.dir(contents); var errors = JSON.parse(contents).errors; _.forEach(errors, gutil.log); callback(null, file); }); } });
JavaScript
0.000018
@@ -1803,15 +1803,16 @@ ing( -%22utf-8%22 +encoding )%0A
661a58a0a23c9a20b9b1b27b865f5e1580628c6d
Fix init exceptions.
src/registry.js
src/registry.js
/** * Patterns registry - Central registry and scan logic for patterns * * Copyright 2012-2013 Simplon B.V. * Copyright 2012-2013 Florian Friesdorf * Copyright 2013 Marko Durkovic * Copyright 2013 Rok Garbas */ /* * changes to previous patterns.register/scan mechanism * - if you want initialised class, do it in init * - init returns set of elements actually initialised * - handle once within init * - no turnstile anymore * - set pattern.jquery_plugin if you want it */ define([ "jquery", "./core/logger", "./utils", // below here modules that are only loaded "./compat", "./jquery-ext" ], function($, logger, utils) { var log = logger.getLogger("registry"), jquery_plugin = utils.jquery_plugin; var disable_re = /patterns-disable=([^&]+)/g, dont_catch_re = /patterns-dont-catch/g, dont_catch = false, disabled = {}, match; while ((match=disable_re.exec(window.location.search)) !== null) { disabled[match[1]] = true; log.info('Pattern disabled via url config:', match[1]); } while ((match=dont_catch_re.exec(window.location.search)) !== null) { dont_catch = true; log.info('I will not catch init exceptions'); } var registry = { patterns: {}, // as long as the registry is not initialized, pattern // registration just registers a pattern. Once init is called, // the DOM is scanned. After that registering a new pattern // results in rescanning the DOM only for this pattern. initialized: false, init: function() { $(document).ready(function() { log.info('loaded: ' + Object.keys(registry.patterns).sort().join(', ')); registry.scan(document.body); registry.initialized = true; log.info('finished initial scan.'); }); }, scan: function(content, do_not_catch_init_exception, patterns) { var $content = $(content), all = [], allsel, pattern, $match, plog; // If no list of patterns was specified, we scan for all // patterns patterns = patterns || Object.keys(registry.patterns); // selector for all patterns patterns.forEach(function(name) { if (disabled[name]) { log.debug('Skipping disabled pattern:', name); return; } pattern = registry.patterns[name]; if (pattern.transform) { if (do_not_catch_init_exception || dont_catch) { pattern.transform($content); } else { try { pattern.transform($content); } catch (e) { log.error("Transform error for pattern" + name, e); } } } if (pattern.trigger) { all.push(pattern.trigger); } }); allsel = all.join(","); // Find all elements that belong to any pattern. $match = $content.findInclusive(allsel); $match = $match.filter(function() { return $(this).parents('pre').length === 0; }); $match = $match.filter(":not(.cant-touch-this)"); // walk list backwards and initialize patterns inside-out. // // XXX: If patterns would only trigger via classes, we // could iterate over an element classes and trigger // patterns in order. // // Advantages: Order of pattern initialization controled // via order of pat-classes and more efficient. $match.toArray().reduceRight(function(acc, el) { var $el = $(el); for (var name in registry.patterns) { pattern = registry.patterns[name]; plog = logger.getLogger("pat." + name); if ($el.is(pattern.trigger)) { plog.debug("Initialising:", $el); if (do_not_catch_init_exception || dont_catch) { try { pattern.init($el); plog.debug("done."); } catch (e) { plog.error("Caught error:", e); } } else { pattern.init($el); plog.debug("done."); } } } }, null); }, // XXX: differentiate between internal and custom patterns // _register vs register register: function(pattern) { if (!pattern.name) { log.error("Pattern lacks name:", pattern); return false; } if (registry.patterns[pattern.name]) { log.error("Already have a pattern called: " + pattern.name); return false; } // register pattern to be used for scanning new content registry.patterns[pattern.name] = pattern; // register pattern as jquery plugin if (pattern.jquery_plugin) { var pluginName = ("pat-" + pattern.name) .replace(/-([a-zA-Z])/g, function(match, p1) { return p1.toUpperCase(); }); $.fn[pluginName] = jquery_plugin(pattern); // BBB 2012-12-10 $.fn[pluginName.replace(/^pat/, "pattern")] = jquery_plugin(pattern); } log.debug("Registered pattern:", pattern.name, pattern); if (registry.initialized) { registry.scan(document.body, false, [pattern.name]); } return true; } }; $(document) .on("patterns-injected.patterns", function(ev) { registry.scan(ev.target); $(ev.target).trigger("patterns-injected-scanned"); }); return registry; }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab
JavaScript
0.000015
@@ -4271,32 +4271,161 @@ %7C dont_catch) %7B%0A + pattern.init($el);%0A plog.debug(%22done.%22);%0A %7D else %7B%0A @@ -4686,137 +4686,8 @@ %7D%0A - %7D else %7B%0A pattern.init($el);%0A plog.debug(%22done.%22);%0A
fefd045f7a7cf752bd554317f72c3458bcb5eeee
Remove unnecessary gulp task dependency
Gulpfile.js
Gulpfile.js
'use strict'; var fork = require('child_process').fork, gulp = require('gulp'), eslint = require('gulp-eslint'), mocha = require('gulp-mocha'), install = require('gulp-install'), benchmark = require('gulp-benchmark'), rename = require('gulp-rename'), download = require('gulp-download'), through = require('through2'), concat = require('gulp-concat'), jsdoc = require('gulp-jsdoc-to-markdown'), insert = require('gulp-insert'); gulp.task('generate-trie', function () { function createTrie(entitiesData) { return Object.keys(entitiesData).reduce(function (trie, entity) { var resultCp = entitiesData[entity].codepoints; entity = entity.replace(/^&/, ''); var entityLength = entity.length, last = entityLength - 1, leaf = trie; for (var i = 0; i < entityLength; i++) { var key = entity.charCodeAt(i); if (!leaf[key]) leaf[key] = {}; if (i === last) leaf[key].c = resultCp; else { if (!leaf[key].l) leaf[key].l = {}; leaf = leaf[key].l; } } return trie; }, {}); } function trieCodeGen(file, encoding, callback) { var entitiesData = JSON.parse(file.contents.toString()), trie = createTrie(entitiesData), out = '\'use strict\';\n\n' + '//NOTE: this file contains auto-generated trie structure that is used for named entity references consumption\n' + '//(see: http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#tokenizing-character-references and\n' + '//http://www.whatwg.org/specs/web-apps/current-work/multipage/named-character-references.html#named-character-references)\n' + 'module.exports = ' + JSON.stringify(trie).replace(/"/g, '') + ';\n'; file.contents = new Buffer(out); callback(null, file); } return download('https://html.spec.whatwg.org/multipage/entities.json') .pipe(through.obj(trieCodeGen)) .pipe(rename('named_entity_trie.js')) .pipe(gulp.dest('lib/tokenizer')); }); gulp.task('generate-api-reference', function () { return gulp .src('lib/**/*.js') .pipe(concat('05_api_reference.md')) .pipe(jsdoc()) .pipe(insert.prepend('# API Reference\n')) .pipe(gulp.dest('docs')); }); gulp.task('docs', ['generate-api-reference'], function () { return gulp .src('docs/*.md') .pipe(concat('index.md')) .pipe(gulp.dest('docs/build')); }); gulp.task('install-upstream-parse5', function () { return gulp .src('test/benchmark/package.json') .pipe(install()); }); gulp.task('benchmark', ['install-upstream-parse5'], function () { return gulp .src('test/benchmark/*.js', {read: false}) .pipe(benchmark({ failOnError: true, reporters: benchmark.reporters.etalon('Upstream') })); }); gulp.task('install-memory-benchmark-dependencies', function () { return gulp .src('test/memory_benchmark/package.json') .pipe(install()); }); gulp.task('sax-parser-memory-benchmark', ['install-memory-benchmark-dependencies'], function (done) { fork('./test/memory_benchmark/sax_parser').once('close', done); }); gulp.task('named-entity-data-memory-benchmark', ['install-memory-benchmark-dependencies'], function (done) { fork('./test/memory_benchmark/named_entity_data').once('close', done); }); gulp.task('lint', function () { return gulp .src([ 'lib/**/*.js', 'test/**/*.js', 'Gulpfile.js' ]) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('update-feedback-tests', function () { var Parser = require('./lib/Parser'); var Tokenizer = require('./lib/tokenizer'); var defaultTreeAdapter = require('./lib/tree_adapters/default'); var testUtils = require('./test/test_utils'); function appendToken(dest, token) { switch (token.type) { case Tokenizer.EOF_TOKEN: return false; case Tokenizer.NULL_CHARACTER_TOKEN: case Tokenizer.WHITESPACE_CHARACTER_TOKEN: token.type = Tokenizer.CHARACTER_TOKEN; /* falls through */ case Tokenizer.CHARACTER_TOKEN: if (dest.length > 0 && dest[dest.length - 1].type === Tokenizer.CHARACTER_TOKEN) { dest[dest.length - 1].chars += token.chars; return true; } break; } dest.push(token); return true; } function collectParserTokens(html) { var tokens = []; var parser = new Parser(); parser._processInputToken = function (token) { Parser.prototype._processInputToken.call(this, token); // Needed to split attributes of duplicate <html> and <body> // which are otherwise merged as per tree constructor spec if (token.type === Tokenizer.START_TAG_TOKEN) token.attrs = token.attrs.slice(); appendToken(tokens, token); }; parser.parse(html); return tokens.map(testUtils.convertTokenToHtml5Lib); } return gulp .src(['test/data/tree_construction/*.dat', 'test/data/tree_construction_regression/*.dat']) .pipe(through.obj(function (file, encoding, callback) { var tests = testUtils.parseTreeConstructionTestData( file.contents.toString(), defaultTreeAdapter ); var out = { tests: tests.filter(function (test) { return !test.fragmentContext; // TODO }).map(function (test) { var input = test.input; return { description: testUtils.addSlashes(input), input: input, output: collectParserTokens(input) }; }) }; file.contents = new Buffer(JSON.stringify(out, null, 4)); callback(null, file); })) .pipe(rename({extname: '.test'})) .pipe(gulp.dest('test/data/parser_feedback')); }); gulp.task('test', ['lint'], function () { return gulp .src('test/fixtures/*_test.js') .pipe(mocha({ ui: 'exports', reporter: 'progress', timeout: typeof v8debug === 'undefined' ? 20000 : Infinity // NOTE: disable timeouts in debug })); });
JavaScript
0.00005
@@ -3566,51 +3566,8 @@ rk', - %5B'install-memory-benchmark-dependencies'%5D, fun
1754a498ce71ba072d7c28fb485908df29eecb7a
Add Tumblr AJAX calls
src/scripts/theme.js
src/scripts/theme.js
(function () { })();
JavaScript
0.000001
@@ -12,14 +12,690 @@ ) %7B%0A +/**%0A * @desc This will be triggered when a new page of Notes is loaded and ready to be inserted.%0A * @param %7BElement%7D html - The HTML node that the AJAX notes loading function returns.%0A * @returns %7BBoolean%7D - If this function returns false, it will block the Notes from being inserted.%0A */%0A var onNotesLoaded = function (html) %7B%0A return true;%0A %7D;%0A%0A /**%0A * @desc This will be triggered after a new page of Notes has been inserted into the DOM.%0A */%0A var onNotesInserted = function () %7B%0A%0A %7D;%0A%0A // Expose the note insertion functions%0A window.tumblrNotesLoaded = onNotesLoaded;%0A window.tumblrNotesInserted = onNotesInserted; %0A%7D)();
a022b5ca37bd9a2ffd806b912e7998c29653a6b0
Use fetchJsonp
src/sdk/instagram.js
src/sdk/instagram.js
import { getHashValue, getQueryStringValue, rslError } from '../utils' const INSTAGRAM_API = 'https://api.instagram.com/v1' let instagramAuth = 'https://api.instagram.com/oauth/authorize/?response_type=token' let instagramAppId let instagramRedirect let instagramAccessToken // Load fetch polyfill for browsers not supporting fetch API if (!window.fetch) { require('whatwg-fetch') } /** * Fake Instagram SDK loading (needed to trick RSL into thinking its loaded). */ const load = (appId, redirect) => new Promise((resolve, reject) => { instagramAppId = appId instagramRedirect = redirect instagramAuth = `https://api.instagram.com/oauth/authorize/?client_id=${instagramAppId}&redirect_uri=${instagramRedirect}%3FrslCallback%3Dinstagram&response_type=token` if (getQueryStringValue('rslCallback') === 'instagram') { if (getQueryStringValue('error')) { return reject(rslError({ provider: 'instagram', type: 'auth', description: 'Authentication failed', error: { error_reason: getQueryStringValue('error_reason'), error_description: getQueryStringValue('error_description') } })) } else { instagramAccessToken = getHashValue('access_token') } } return resolve(instagramAccessToken) }) /** * Checks if user is logged in to app through Instagram. * @see https://www.instagram.com/developer/endpoints/users/#get_users_self */ const checkLogin = (autoLogin = false) => { if (autoLogin) { return login() } if (!instagramAccessToken) { return Promise.reject(rslError({ provider: 'instagram', type: 'access_token', description: 'No access token available', error: null })) } return new Promise((resolve, reject) => { window.fetch(`${INSTAGRAM_API}/users/self/?access_token=${instagramAccessToken}`) .then((response) => response.json()) .then((json) => { if (json.meta.code !== 200) { return reject(rslError({ provider: 'instagram', type: 'check_login', description: 'Failed to fetch user data', error: json.meta })) } return resolve({ data: json.data, accessToken: instagramAccessToken }) }).catch(() => reject({ fetchErr: true, err: rslError({ provider: 'instagram', type: 'check_login', description: 'Failed to fetch user data due to CORS issue', error: null }) })) }) } /** * Trigger Instagram login process. * This code only triggers login request, response is handled by a callback handled on SDK load. * @see https://www.instagram.com/developer/authentication/ */ const login = () => new Promise((resolve, reject) => { checkLogin() .then((response) => resolve(response)) .catch((err) => { if (!err.fetchErr) { window.open(instagramAuth, '_self') } else { return reject(err.err) } }) }) /** * Helper to generate user account data. * @param {Object} data */ const generateUser = (data) => ({ profile: { id: data.data.id, name: data.data.full_name, firstName: data.data.full_name, lastName: data.data.full_name, email: undefined, // Instagram API doesn’t provide email (see https://www.instagram.com/developer/endpoints/users/#get_users_self) profilePicURL: data.data.profile_picture }, token: { accessToken: data.accessToken, expiresAt: Infinity } }) export default { checkLogin, generateUser, load, login }
JavaScript
0.000003
@@ -1,8 +1,46 @@ +import fetchJsonp from 'fetch-jsonp'%0A%0A import %7B @@ -178,75 +178,8 @@ Auth - = 'https://api.instagram.com/oauth/authorize/?response_type=token' %0Alet @@ -1739,28 +1739,26 @@ %3E %7B%0A -window. fetch +Jsonp (%60$%7BINST @@ -2222,16 +2222,23 @@ %7D) +%0A .catch((
7bfb29c45f76ed7e81c5e5c79341a7e84f3ff771
Change bar drinks sorts
src/selectors/bar.js
src/selectors/bar.js
export const getDrinkById = state => drinkId => { const filteredDrinks = state.bar.drinks.filter(drink => drinkId === drink.id) return filteredDrinks[0] } export const getNameDrinkById = state => drinkId => { const drink = getDrinkById(state)(drinkId) || {} return drink.name || '' } export const sortDrinkByCategory = (drinks, categoryName) => { return drinks .filter(drink => drink.category === categoryName) .sort((a, b) => { if (a.name > b.name) { return 1 } if (a.name < b.name) { return -1 } // a должно быть равным b return 0 }) }
JavaScript
0.000001
@@ -365,21 +365,16 @@ n drinks -%0A .filter( @@ -414,21 +414,16 @@ oryName) -%0A .sort((a @@ -425,24 +425,273 @@ rt((a, b) =%3E + %7B%0A // a %D0%B4%D0%BE%D0%BB%D0%B6%D0%BD%D0%BE %D0%B1%D1%8B%D1%82%D1%8C %D1%80%D0%B0%D0%B2%D0%BD%D1%8B%D0%BC b%0A const aEnable = a.status !== 'DISABLED'%0A const bEnable = b.status !== 'DISABLED'%0A // return aEnable === bEnable ? 0 : aEnable ? -1 : 1%0A if (aEnable !== bEnable) %7B%0A return aEnable ? -1 : 1%0A %7D else %7B%0A if @@ -794,40 +794,8 @@ %7D%0A - // a %D0%B4%D0%BE%D0%BB%D0%B6%D0%BD%D0%BE %D0%B1%D1%8B%D1%82%D1%8C %D1%80%D0%B0%D0%B2%D0%BD%D1%8B%D0%BC b%0A @@ -805,17 +805,21 @@ eturn 0%0A - + %7D%0A %7D)%0A%7D%0A
b4cae9c80ba937e722cb61467685eabd2431c051
Update isEdge docs to note it detects Legacy Edge (#8287)
modules/tinymce/tools/docs/tinymce.Env.js
modules/tinymce/tools/docs/tinymce.Env.js
/** * Returns the current browser name. * * @property browser.current * @type String */ /** * Returns the current browser major and minor version. * * @property browser.version * @type Object */ /** * Returns <code>true</code> if the user's browser is Microsoft Edge. * * @method browser.isEdge * @return {Boolean} Returns <code>true</code> if the user's browser is Microsoft Edge. */ /** * Returns <code>true</code> if the user's browser is Chromium based, such as Google Chrome or newer versions of Microsoft Edge. * * @method browser.isChromium * @return {Boolean} Returns <code>true</code> if the user's browser is Chromium based. */ /** * Returns <code>true</code> if the user's browser is Microsoft Internet Explorer. * * @method browser.isIE * @return {Boolean} Returns <code>true</code> if the user's browser is Microsoft Internet Explorer. */ /** * Returns <code>true</code> if the user's browser is Opera. * * @method browser.isOpera * @return {Boolean} Returns <code>true</code> if the user's browser is Opera. */ /** * Returns <code>true</code> if the user's browser is Firefox. * * @method browser.isFirefox * @return {Boolean} Returns <code>true</code> if the user's browser is Firefox. */ /** * Returns <code>true</code> if the user's browser is Safari. * * @method browser.isSafari * @return {Boolean} Returns <code>true</code> if the user's browser is Safari. */ /** * Returns the current operating system name. * * @property os.current * @type String */ /** * Returns the current operating system major and minor version. * * @property os.version * @type Object */ /** * Returns <code>true</code> if the user's operating system is Microsoft Windows. * * @method os.isWindows * @return {Boolean} Returns <code>true</code> if the user's operating system is Microsoft Windows. */ /** * Returns <code>true</code> if the user's operating system is iOS. * * @method os.isiOS * @return {Boolean} Returns <code>true</code> if the user's operating system is iOS. */ /** * Returns <code>true</code> if the user's operating system is Android. * * @method os.isAndroid * @return {Boolean} Returns <code>true</code> if the user's operating system is Android. */ /** * Returns <code>true</code> if the user's operating system is macOS. * * @method os.isMacOS * @return {Boolean} Returns <code>true</code> if the user's operating system is macOS. */ /** * Returns <code>true</code> if the user's operating system is Linux. * * @method os.isLinux * @return {Boolean} Returns <code>true</code> if the user's operating system is Linux. */ /** * Returns <code>true</code> if the user's operating system is Solaris. * * @method os.isSolaris * @return {Boolean} Returns <code>true</code> if the user's operating system is Solaris. */ /** * Returns <code>true</code> if the user's operating system is FreeBSD. * * @method os.isFreeBSD * @return {Boolean} Returns <code>true</code> if the user's operating system is FreeBSD. */ /** * Returns <code>true</code> if the user's operating system is ChromeOS. * * @method os.isChromeOS * @return {Boolean} Returns <code>true</code> if the user's operating system is ChromeOS. */ /** * Returns <code>true</code> if the user's device is a desktop device. * * @method deviceType.isDesktop * @return {Boolean} Returns <code>true</code> if the user's device is a desktop device. */ /** * Returns <code>true</code> if the user's device is an iPad. * * @method deviceType.isiPad * @return {Boolean} Returns <code>true</code> if the user's device is an iPad. */ /** * Returns <code>true</code> if the user's device is an iPhone. * * @method deviceType.isiPhone * @return {Boolean} Returns <code>true</code> if the user's device is an iPhone. */ /** * Returns <code>true</code> if the user's device is a phone. * * @method deviceType.isPhone * @return {Boolean} Returns <code>true</code> if the user's device is a phone. */ /** * Returns <code>true</code> if the user's device is a tablet. * * @method deviceType.isTablet * @return {Boolean} Returns <code>true</code> if the user's device is a tablet. */ /** * Returns <code>true</code> if the user's device is a touch device. * * @method deviceType.isTouch * @return {Boolean} Returns <code>true</code> if the user's device is a touch device. */ /** * Returns <code>true</code> if the user's device is a WebView device. * * @method deviceType.isWebView * @return {Boolean} Returns <code>true</code> if the user's device is a WebView device. */
JavaScript
0
@@ -260,32 +260,105 @@ er is Microsoft +Edge Legacy. Does not return true for the newer Chromium-based Microsoft Edge.%0A *%0A * @met @@ -458,24 +458,31 @@ crosoft Edge + Legacy .%0A */%0A%0A/**%0A
adce94747e95d35985d550a19a06af76a9bea2da
fix wrong routing in the presence of bundle.js
src/server/server.js
src/server/server.js
'use strict'; const app = require('koa')(); const compress = require('koa-compress'); const cors = require('kcors'); const fs = require('fs'); const http = require('http'); const passport = require('koa-passport'); const path = require('path'); const responseTime = require('koa-response-time'); const serve = require('koa-serve'); const session = require('koa-session'); const api = require('./routes/api'); const auth = require('./routes/auth'); const config = require('../config/config').globalConfig; const debug = require('../util/debug')('server'); const nunjucks = require('./nunjucks'); let _started; app.use(function *(next) { debug.trace(`Method: ${this.method}; Path: ${this.path}`); yield next; }); app.use(compress()); app.use(responseTime()); // trust X-Forwarded- headers app.proxy = config.proxy; // support proxyPrefix in this.redirect() let proxyPrefix = config.proxyPrefix; if (!proxyPrefix.startsWith('/')) { proxyPrefix = '/' + proxyPrefix; } if (!proxyPrefix.endsWith('/')) { proxyPrefix = proxyPrefix + '/'; } debug(`proxy prefix: ${proxyPrefix}`); if (proxyPrefix !== '/') { const _redirect = app.context.redirect; app.context.redirect = function (url, alt) { if (typeof url === 'string' && url.startsWith('/')) { url = proxyPrefix + url.substring(1); } return _redirect.call(this, url, alt); }; } nunjucks(app, { root: path.join(__dirname, '../../views'), ext: 'html' }); app.use(serve('assets', path.join(__dirname, '../../public'))); const bundlePath = path.join(__dirname, '../../public/bundle.js'); if (fs.existsSync(bundlePath)) { // always render index.html unless it's an API route let indexHtml = fs.readFileSync(path.join(__dirname, '../../public/index.html'), 'utf8'); indexHtml = indexHtml.replace(/assets\//g, proxyPrefix + 'assets/'); const bundleJs = fs.readFileSync(bundlePath, 'utf8'); app.use(function*(next) { if (this.path.startsWith(`${proxyPrefix}db`) || this.path.startsWith(`${proxyPrefix}auth`)) { yield next; } else if (this.path.endsWith('/bundle.js')) { this.body = bundleJs; } else { this.body = indexHtml; } }); } const allowedOrigins = config.allowedOrigins; debug(`allowed cors origins: ${allowedOrigins}`); app.use(cors({ origin: ctx => { const origin = ctx.get('Origin'); for (var i = 0; i < allowedOrigins.length; i++) { if (allowedOrigins[i] === origin) { return origin; } } return '*'; }, credentials: true })); app.keys = config.keys; app.use(session({ key: 'roc:sess', maxAge: config.sessionMaxAge, path: '/', domain: config.sessionDomain, secure: config.sessionSecure, httpOnly: true, signed: true }, app)); app.use(passport.initialize()); app.use(passport.session()); app.use(function*(next) { yield next; // Force a session change to renew the cookie this.session.time = Date.now(); }); app.use(function*(next) { this.state.pathPrefix = proxyPrefix; this.state.urlPrefix = this.origin + proxyPrefix; yield next; }); app.on('error', printError); //Unhandled errors if (config.debugrest) { // In debug mode, show unhandled errors to the user app.use(function *(next) { try { yield next; } catch (err) { this.status = err.status || 500; this.body = err.message + '\n' + err.stack; printError(err); } }); } // Authentication app.use(auth.routes()); // ROC API app.use(api.routes()); module.exports.start = function () { if (_started) return _started; _started = new Promise(function (resolve) { http.createServer(app.callback()).listen(config.port, function () { debug.warn('running on localhost:' + config.port); resolve(app); }); }); return _started; }; module.exports.app = app; function printError(err) { debug.error('unexpected error: ' + (err.stack || err)); }
JavaScript
0.000002
@@ -1979,30 +1979,17 @@ tsWith(%60 -$%7BproxyPrefix%7D +/ db%60) %7C%7C @@ -2010,30 +2010,17 @@ tsWith(%60 -$%7BproxyPrefix%7D +/ auth%60))
0172887f3d9835020751e8206644645be4f4ee5c
Use node backend to create projects.
website/mcapp.projects/src/app/models/api/projects-api.service.js
website/mcapp.projects/src/app/models/api/projects-api.service.js
/*@ngInject*/ function projectsAPIService(Restangular) { let onChangeFn = null; const projectsAPIRoute = _.partial(Restangular.one('v2').one, 'projects'); return { getAllProjects: function() { return projectsAPIRoute().getList(); }, getProject: function(projectId) { return projectsAPIRoute(projectId).get(); }, createProject: function(projectName, projectDescription) { return Restangular.one('projects').customPOST({ name: projectName, description: projectDescription }).then(function(p) { if (onChangeFn) { onChangeFn(p); } return p; }) }, getProjectSamples: function(projectID) { return projectsAPIRoute(projectID).one('samples').getList(); }, getProjectSample: function(projectID, sampleID) { return Restangular.one('sample').one('details', sampleID).get() .then(function(samples) { return samples[0]; }); }, getProjectProcesses: function(projectID) { return projectsAPIRoute(projectID).one('processes').getList(); }, getProjectProcess: function(projectId, processId) { return projectsAPIRoute(projectId).one('processes', processId).get(); }, updateProjectProcess: function(projectID, process) { return projectsAPIRoute(projectID).one('processes', process.id).customPUT(process).then(function(p) { if (onChangeFn) { onChangeFn(p); } return p; }); }, updateProject: function(projectID, projectAttrs) { return projectsAPIRoute(projectID).customPUT(projectAttrs); }, createProjectProcess: function(projectID, process) { return projectsAPIRoute(projectID).one('processes').customPOST(process).then(function(p) { if (onChangeFn) { onChangeFn(p); } return p; }); }, getProjectDirectory: function(projectID, dirID) { if (!dirID) { return projectsAPIRoute(projectID).one('directories').get(); } else { return projectsAPIRoute(projectID).one('directories', dirID).get(); } }, getAllProjectDirectories: function(projectId) { return projectsAPIRoute(projectId).one('directories', 'all').getList(); }, createProjectDir: function(projectID, fromDirID, path) { return projectsAPIRoute(projectID).one('directories').customPOST({ from_dir: fromDirID, path: path }).then(function(dirs) { if (onChangeFn) { onChangeFn(fromDirID, dirs); } return dirs; }); }, getProjectFile: function(projectID, fileID) { return projectsAPIRoute(projectID).one('files', fileID).get(); }, onChange: function(scope, fn) { onChangeFn = fn; scope.$on('$destroy', function() { onChangeFn = null; }); } } } angular.module('materialscommons').factory('projectsAPI', projectsAPIService);
JavaScript
0
@@ -480,16 +480,26 @@ ar.one(' +v2').one(' projects
628d00797663a6df9fc49de5f3a88b876b1d6466
Change '!=' to '!==' in simple sample.
node/device/samples/simple_sample_http.js
node/device/samples/simple_sample_http.js
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. 'use strict'; var device = require('azure-iot-device'); var connectionString = '[IoT Device Connection String]'; var client = new device.Client(connectionString, new device.Https()); // Create a message and send it to the IoT Hub every second setInterval(function(){ var windSpeed = 10 + (Math.random() * 4); // range: [10, 14] var data = JSON.stringify({ deviceId: 'myFirstDevice', windSpeed: windSpeed }); var message = new device.Message(data); message.properties.add('myproperty', 'myvalue'); console.log("Sending message: " + message.getData()); client.sendEvent(message, printResultFor('send')); }, 1000); // Monitor notifications from IoT Hub and print them in the console. setInterval(function(){ client.receive(function (err, res, msg) { if (!err && res.statusCode !== 204) { console.log('Received data: ' + msg.getData()); client.complete(msg, printResultFor('complete')); } else if (err) { printResultFor('receive')(err, res); } }); }, 1000); // Helper function to print results in the console function printResultFor(op) { return function printResult(err, res) { if (err) console.log(op + ' error: ' + err.toString()); if (res && (res.statusCode != 204)) console.log(op + ' status: ' + res.statusCode + ' ' + res.statusMessage); }; }
JavaScript
0.000005
@@ -1375,16 +1375,17 @@ sCode != += 204)) c
4ad1c0ce2c990b8c5df5829f13c2cac11c8dd6b6
Fix the typeoff
nodejs-grovepi-azureiot/GrovePiSensors.js
nodejs-grovepi-azureiot/GrovePiSensors.js
var GrovePi = require('node-grovepi').GrovePi; var DHTDigitalSensor = GrovePi.sensors.DHTDigital; var UltrasonicDigitalSensor = GrovePi.sensors.UltrasonicDigital; var LightAnalogSensor = GrovePi.sensors.LightAnalog; var AnalogSensor =GrovePi.sensors.base.Analog; function GrovePiSensors(dhtPin = 2, ultrasonicPin = 4, lightPin = 2,debug = true){ this.debug = debug; this.tempHumSensor = new DHTDigitalSensor(ultrasonicPin); this.ultrasonicSensor = new UltrasonicDigitalSensor(dhtPin); this.lightSensor = new LightAnalogSensor(lightPin); this.soundSensor = new AnalogSensor(0); } GrovePiSensors.prototype.getSoundData = function() { var res += this.soundSensor.read(); if(this.debug) { var text = 'Sound level: ' + res; console.log(text); } return { soundLevel : res }; } GrovePiSensors.prototype.getTempAndHumData = function() { var res = this.tempHumSensor.read(); var temp= res[0]; var humidity = res[1]; if(this.debug) { var text = 'T: ' + temp + ' H: ' + humidity; console.log(text); } return { temp : temp, humidity : humidity } } GrovePiSensors.prototype.getDistanceData = function() { var res = this.ultrasonicSensor.read(); if(this.debug) { var text = 'Distance: ' + res; console.log(text); } return { distance : res } } GrovePiSensors.prototype.GetLightData = function() { var res = this.lightSensor.read(); if(this.debug) { var text = 'Light: ' + res; console.log(text); } return { light : res } } GrovePiSensors.prototype.getAllSensorsData = function() { if(this.debug) { console.log('Get Sensor Data started'); } var currentTempAndHumData = this.getTempAndHumData(); var distanceData = this.getDistanceData(); var lightData = this.GetLightData(); var tempData = this.getSoundData(); if(this.debug) { console.log('Get Sensor Data ended'); } return { temp : currentTempAndHumData.temp, humidity : currentTempAndHumData.humidity, distance : distanceData.distance, light : lightData.light, } }; module.exports = GrovePiSensors
JavaScript
0.999999
@@ -649,17 +649,16 @@ var res -+ = this.s
3986d50a1402ea12b3d9b2687f39c02fcfb4c785
Fix enemy pooling
src/sprites/Enemy.js
src/sprites/Enemy.js
import Phaser from 'phaser' import SingleShot from '../weapons/SingleShot'; import SpreadShot from '../weapons/SpreadShot'; import TwinCannons from '../weapons/TwinCannons'; import Beam from '../weapons/Beam'; export default class extends Phaser.Sprite { constructor ({ game, player, x, y, weapon }) { super(game, x, y, 'enemy') this.player = player; switch (weapon) { case "SpreadShot": this.weapon = new SpreadShot(this.game, true); break; case "TwinCannons": this.weapon = new TwinCannons(this.game, true); break; case "Beam": this.weapon = new Beam(this.game, true); break; default: this.weapon = new SingleShot(this.game, true); break; } this.weapon.fireRate *= 1.75 // Init variables this.game = game this.anchor.setTo(1, 0.5) this.scale.setTo(-this.game.width / this.width * 0.05, this.game.height / this.height * 0.10); this.speed = 150 this.deltaSpeed = 5 this.health = 1; this.exists = false; // Physics and cursors this.game.physics.arcade.enable(this) this.body.velocity.x = -125; } update () { if (this.game.pseudoPause) { this.body.velocity.y = 0; this.body.velocity.x = 0; return; } if (!this.exists) { return } if (this.x <= 100 || this.health <= 0) { this.destroy(); return } this.game.physics.arcade.overlap(this.player, this.weapon, this.shotPlayer, null, this); this.weapon.fire(this); if (this.player.y > this.y && this.body.velocity.y < this.speed) { this.body.velocity.y += this.deltaSpeed; } else if (this.player.y < this.y && this.body.velocity.y > this.speed * -1) { this.body.velocity.y -= this.deltaSpeed; } else { if (this.body.velocity.y < 0) { this.body.velocity.y += this.deltaSpeed; } else if (this.body.velocity.y > 0) { this.body.velocity.y -= this.deltaSpeed; } else { this.body.velocity.y = 0; } } } shotPlayer (ship, bullet) { bullet.destroy(); } fire(x, y) { this.exists = true; this.x = x; this.y = y; } }
JavaScript
0.000121
@@ -887,16 +887,50 @@ *= 1.75 +%0A this.weaponName = weapon; %0A%0A @@ -1517,130 +1517,167 @@ if ( -! this. -exists) %7B%0A return%0A +x %3C= 100 %7C%7C this.health %3C= 0) %7B%0A this.weapon = null;%0A -%7D%0A%0A - if (this.x %3C= 100 %7C%7C this.health %3C= 0) %7B%0A this.destroy(); +this.exists = false;%0A return%0A %7D%0A%0A if (!this.exists) %7B %0A @@ -2537,16 +2537,41 @@ = true;%0A + this.health = 1;%0A @@ -2602,16 +2602,547 @@ .y = y;%0A + switch (this.weaponName) %7B%0A case %22SpreadShot%22:%0A this.weapon = new SpreadShot(this.game, true);%0A break;%0A case %22TwinCannons%22:%0A this.weapon = new TwinCannons(this.game, true);%0A break;%0A case %22Beam%22:%0A this.weapon = new Beam(this.game, true);%0A break;%0A default: %0A this.weapon = new SingleShot(this.game, true);%0A break;%0A %7D%0A this.weapon.fireRate *= 1.75%0A %7D%0A%0A%7D
384d537fc59490deacd2f665fd74b1cce87c3df0
插入page.css兼容原来的runtime
packages/chameleon-loader/src/selector.js
packages/chameleon-loader/src/selector.js
// this is a utility loader that takes a *.cml file, parses it and returns // the requested language block, e.g. the content inside <template>, for // further processing. const path = require('path') const parse = require('./parser') const getRunTimeSnippet = require('./cml-compile/runtime/index.js'); const {getScriptCode} = require('./interface-check/getScriptCode.js'); const cmlUtils = require('chameleon-tool-utils'); // 小程序才会经过该方法 module.exports = function (content) { // 处理script cml-type为json的内容 content = cmlUtils.deleteScript({content, cmlType: 'json'}); const loaderContext = this; const query = queryParse(this.query); query.check = query.check || '{}'; query.check = JSON.parse(query.check); const context = (this._compiler && this._compiler.context) || this.options.context || process.cwd() let filename = path.basename(this.resourcePath) filename = filename.substring(0, filename.lastIndexOf(path.extname(filename))) + '.vue' const sourceRoot = path.dirname(path.relative(context, this.resourcePath)) const parts = parse(content, filename, this.sourceMap, sourceRoot) let part = parts[query.type] if (Array.isArray(part)) { let index = query.index || 0; part = part[index] } let output = part.content; if (query.type === 'styles' && ~['page', 'component'].indexOf(query.fileType) && query.isInjectBaseStyle === 'true') { if (query.fileType === 'page') { output = ` @import 'chameleon-runtime/src/platform/${query.cmlType}/style/page.css'; ${output} ` } else { output = ` @import 'chameleon-runtime/src/platform/${query.cmlType}/style/index.css'; ${output} ` } } if (query.type == 'script') { // 拼接wx所需要的运行时代码,如果在loader中拼接,拼接的代码将不会过loader了 let runtimeScript = getRunTimeSnippet(query.cmlType, query.fileType); output = getScriptCode(loaderContext, query.cmlType, output, query.media, query.check); output = ` ${output}\n ${runtimeScript} ` } this.callback(null, output, part.map) } function queryParse(search) { search = search || ''; let arr = search.split(/(\?|&)/); let parmsObj = {}; for (let i = 0; i < arr.length; i++) { if (arr[i].indexOf('=') !== -1) { let keyValue = arr[i].match(/([^=]*)=(.*)/); parmsObj[keyValue[1]] = keyValue[2]; } } return parmsObj; }
JavaScript
0
@@ -1370,24 +1370,205 @@ = 'true') %7B%0A + let pageCssPath = path.join(cml.projectRoot, 'node_modules', %60chameleon-runtime/src/platform/$%7Bquery.cmlType%7D/style/page.css%60)%0A let hasPageCss = cmlUtils.isFile(pageCssPath)%0A if (quer @@ -1588,16 +1588,30 @@ = 'page' + && hasPageCss ) %7B%0A
a3583a8e6497f390f7be6616f46b27731951dafb
add stats
example/inspector.js
example/inspector.js
import Stats from 'stats.js/src/Stats'; import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; import { GUI } from 'dat.gui'; import { acceleratedRaycast, computeBoundsTree, disposeBoundsTree, MeshBVHVisualizer, SAH, CENTER, AVERAGE, getBVHExtremes, } from '../src/index.js'; THREE.Mesh.prototype.raycast = acceleratedRaycast; THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree; THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree; let stats; let scene, camera, renderer, helper, mesh, outputContainer; let mouse = new THREE.Vector2(); const modelPath = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/DragonAttenuation/glTF-Binary/DragonAttenuation.glb'; const params = { options: { strategy: SAH, maxLeafTris: 10, maxDepth: 40, rebuild: function () { updateBVH(); }, }, }; function init() { outputContainer = document.getElementById( 'output' ); // renderer setup renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setClearColor( 0, 1 ); document.body.appendChild( renderer.domElement ); // scene setup scene = new THREE.Scene(); // camera setup camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 50 ); camera.position.set( - 2.5, 2.5, 2.5 ); camera.far = 100; camera.updateProjectionMatrix(); new OrbitControls( camera, renderer.domElement ); // stats setup stats = new Stats(); document.body.appendChild( stats.dom ); window.addEventListener( 'resize', function () { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); }, false ); // Load dragon const loader = new GLTFLoader(); loader.load( modelPath, gltf => { gltf.scene.traverse( c => { if ( c.isMesh && c.name === 'Dragon' ) { mesh = c; } } ); mesh.material = new THREE.MeshBasicMaterial( { color: 0 } ); scene.add( mesh ); helper = new MeshBVHVisualizer( mesh, 40 ); helper.displayEdges = false; helper.displayParents = true; helper.color.set( 0xffffff ); helper.opacity = 5 / 255; helper.depth = 40; scene.add( helper ); updateBVH(); } ); const gui = new GUI(); const bvhFolder = gui.addFolder( 'BVH' ); bvhFolder.add( params.options, 'strategy', { CENTER, AVERAGE, SAH } ); bvhFolder.add( params.options, 'maxLeafTris', 1, 30, 1 ); bvhFolder.add( params.options, 'maxDepth', 1, 40, 1 ); bvhFolder.add( params.options, 'rebuild' ); bvhFolder.open(); } function updateBVH() { mesh.geometry.computeBoundsTree( { strategy: parseInt( params.options.strategy ), maxLeafTris: params.options.maxLeafTris, maxDepth: params.options.maxDepth, } ); helper.update(); console.log( getBVHExtremes( mesh.geometry.boundsTree ) ); } function render() { requestAnimationFrame( render ); renderer.render( scene, camera ); } init(); render();
JavaScript
0
@@ -1,44 +1,4 @@ -import Stats from 'stats.js/src/Stats';%0A impo @@ -554,19 +554,8 @@ e;%0A%0A -let stats;%0A let @@ -1592,88 +1592,8 @@ );%0A%0A -%09// stats setup%0A%09stats = new Stats();%0A%09document.body.appendChild( stats.dom );%0A%0A %09win
cd5afa980aa07571f2a094d1243500c3f9d80308
Add support for custom eventId
eventFactory.js
eventFactory.js
var assert = require('assert'); var uuid = require('uuid'); module.exports = { NewEvent: function(eventType, data, metadata) { assert(eventType); assert(data); var event = { eventId: uuid.v4(), eventType: eventType, data: data } if (metadata !== undefined) event.metadata = metadata; return event; } };
JavaScript
0
@@ -121,16 +121,25 @@ metadata +, eventId ) %7B%0A @@ -226,16 +226,27 @@ eventId: + eventId %7C%7C uuid.v4
2f833df7f4d6faba5a6e020c25e745fc76c62d3a
make output of error handler nicer
plugins/c9.ide.errorhandler/raygun_error_handler.js
plugins/c9.ide.errorhandler/raygun_error_handler.js
/** * This error handler catches window.onerror and sends them to raygun.io * * @extends Plugin * @singleton */ define(function(require, exports, module) { "use strict"; main.consumes = [ "Plugin", "info" ]; main.provides = ["error_handler"]; return main; function main(options, imports, register) { var Plugin = imports.Plugin; var info = imports.info; /***** Initialization *****/ var Raygun = require("./raygun").Raygun; var apiKey = options.apiKey; var version = options.version; var revision = options.revision; var plugin = new Plugin("Ajax.org", main.consumes); var loaded = false; function load() { if (loaded) return false; loaded = true; // without apiKey raygun throws an error if (!apiKey) return; var user = info.getUser(); var workspace = info.getWorkspace(); Raygun.init(apiKey).attach().withCustomData(function(ex) { return { user: { id: user.id, name: user.name, email: user.email }, workspace: { id: workspace.id, name: workspace.name, contents: workspace.contents }, revision: revision, data: ex && ex.data }; }); Raygun.setUser(info.getUser().name); Raygun.setVersion(version + ".0"); } function reportError(exception, customData, tags) { if (typeof exception === "string") exception = new Error(exception); if (!exception) exception = new Error("Unspecified error"); console.error(exception.stack); Raygun.send(exception, customData, tags); } /***** Lifecycle *****/ plugin.on("load", function(){ load(); }); /***** Register and define API *****/ plugin.freezePublicAPI({ /** @deprecated Use log() instead. */ reportError: reportError, log: reportError }); register(null, { "error_handler" : plugin }); } });
JavaScript
0.000002
@@ -1995,14 +1995,77 @@ tion -.stack +);%0A if (customData)%0A console.log(customData );%0A
e3df7154aab6496b10baa6b64e87f8b7cc642865
fix circular feature
deep-iterable.js
deep-iterable.js
((module) => { 'use strict'; var createClassFromSuper = require('simple-class-utils').createClass.super.handleArgs; var createClass = require('./create-class.js'); var isIterable = require('./utils/is-iterable.js'); var Root = require('./root.js').class; var _key_iterator = Symbol.iterator; class DeepIterable extends Root { constructor(base, deeper) { super(); this.base = base; this.deeper = typeof deeper === 'function' ? deeper : DeepIterable.DEFAULT_DEEPER; } * [_key_iterator]() { var deeper = this.deeper; var base = this.base; if (deeper(base, this)) { for (let element of base) { yield * new DeepIterable(element, deeper); } } else { yield base; } } static createXIterableClass(Base, deeper) { return createClassFromSuper(DeepIterable, (...args) => [new Base(...args), deeper]); } static DEFAULT_DEEPER(object) { return typeof object === 'object' && isIterable(object); } static get CIRCULAR_DEEPER() { var all = new Set(); return (object) => !all.has(object) && all.add(object); } } module.exports = createClass(DeepIterable); })(module);
JavaScript
0.000001
@@ -570,16 +570,36 @@ %0A%09%09%09if ( +isIterable(base) && deeper(b @@ -949,30 +949,8 @@ ect' - && isIterable(object) ;%0A%09%09
a26ea2a270b7a59f783bc300769585438ae75637
update demo: show matched text gray when it was matched
demo/js/index.js
demo/js/index.js
$(function(){ var getUniqueArray = function( array ){ return array.filter(function(elem, pos, self) { return self.indexOf(elem) === pos; }); }; var getUniqueWordListFromSource = function( $target ){ var tmpArray = []; $target.each(function(){ tmpArray.push( $(this).text() ); }); return getUniqueArray( tmpArray ); }; $(function(){ $('.translation').each(function(){ var $this = $(this), $source = $this.find('.source'), $target = $this.find('.target'); $target .autosize() .on('textarea.highlighter.match', function(e, data){ }) .textareaHighlighter({ // maxlength: 150, matches: [ {'className': 'matchHighlight', 'words': getUniqueWordListFromSource( $source.find('.match') )}, {'className': 'hogeHighlight', 'words': getUniqueWordListFromSource( $source.find('.hoge') )} ] }); }); $('.translation-max').each(function(){ var $this = $(this), $source = $this.find('.source'), $target = $this.find('.target'); $target .autosize() .textareaHighlighter({ matches: [ {'className': 'matchHighlight', 'words': getUniqueWordListFromSource( $source.find('.match') )}, {'className': 'hogeHighlight', 'words': getUniqueWordListFromSource( $source.find('.hoge') )} ], // maxlength: 150, maxlengthWarning: 'warning', maxlengthElement: $this.find('.maxlength') }); }); }); });
JavaScript
0
@@ -399,24 +399,361 @@ );%0A %7D;%0A%0A + var getUniqueElementListFromSource = function( $target )%7B%0A var tmpObj = %7B%7D;%0A $target.each(function()%7B%0A if (! tmpObj.hasOwnProperty($(this).text())) %7B%0A tmpObj%5B $(this).text() %5D = %5B%5D;%0A %7D%0A tmpObj%5B $(this).text() %5D.push( $(this) );%0A %7D);%0A return tmpObj;%0A %7D;%0A%0A $(functi @@ -923,32 +923,138 @@ .find('.target') +,%0A elementObj = getUniqueElementListFromSource($this.find('.source').find('.match, .hoge')) ;%0A%0A $ @@ -1156,16 +1156,689 @@ , data)%7B +%0A%0A $source.find('.added').removeClass('added');%0A%0A var i = 0, j = 0, imax = 0, jmax = 0, tmpList = null, tmpText = null;%0A%0A imax = data.textList.length;%0A%0A for (i = 0; i %3C imax; i++) %7B%0A tmpText = data.textList%5Bi%5D;%0A%0A if (elementObj%5B tmpText %5D) %7B%0A tmpList = elementObj%5B tmpText %5D;%0A jmax = tmpList.length;%0A%0A for (j = 0; j %3C jmax; j++) %7B%0A tmpList%5Bj%5D.addClass('added');%0A %7D%0A %7D%0A %7D %0A
08d1ecdab586d85d464fbe410ba2fb5061eab4f9
Fix ToolQuery query bug
src/main/js/bundles/dn_querybuilder/QueryController.js
src/main/js/bundles/dn_querybuilder/QueryController.js
/* * Copyright (C) 2018 con terra GmbH ([email protected]) * * 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 ct_when from "ct/_when"; import Filter from "ct/store/Filter"; import MemorySelectionStore from "./MemorySelectionStore"; class QueryController { activate(componentContext) { this.i18n = this._i18n.get().ui; } query(store, complexQuery, options, tool, queryBuilderWidgetModel) { this.searchReplacer(complexQuery); let queryBuilderProperties = this._queryBuilderProperties; if (queryBuilderProperties.useMemorySelectionStore) { this.memorySelectionQuery(store, complexQuery, options, tool, queryBuilderWidgetModel); } else { this.defaultQuery(store, complexQuery, options, tool, queryBuilderWidgetModel); } } memorySelectionQuery(store, complexQuery, options, tool, queryBuilderWidgetModel) { this._setProcessing(tool, true, queryBuilderWidgetModel); options.fields = {geometry: 1}; ct_when(store.query(complexQuery, options), (result) => { if (result.total > 0) { let mapWidgetModel = this._mapWidgetModel; let spatialReference = mapWidgetModel.get("spatialReference"); let wkid = spatialReference.latestWkid || wkid; let geometries = result.map((item) => { return item.geometry; }); if (geometries[0]) { ct_when(this._coordinateTransformer.transform(geometries, wkid), (transformedGeometries) => { transformedGeometries.forEach((tg, index) => { result[index].geometry = tg; }); }, this); } let memorySelectionStore = new MemorySelectionStore({ id: "querybuilder_" + store.id, masterStore: store, metadata: store.getMetadata, data: result, idProperty: store.idProperty }); this._dataModel.setDatasource(memorySelectionStore); this._setProcessing(tool, false, queryBuilderWidgetModel); } else { this._logService.warn({ id: 0, message: this.i18n.errors.noResultsError }); this._setProcessing(tool, false, queryBuilderWidgetModel); } }, (e) => { this._logService.error({ id: e.code, message: e }); this._setProcessing(tool, false, queryBuilderWidgetModel); }); } defaultQuery(store, complexQuery, options, tool, queryBuilderWidgetModel) { this._setProcessing(tool, true, queryBuilderWidgetModel); let filter = new Filter(store, complexQuery, options); ct_when(filter.query({}, {count: 0}).total, (total) => { if (total) { this._dataModel.setDatasource(filter); this._setProcessing(tool, false, queryBuilderWidgetModel); } else { this._logService.warn({ id: 0, message: this.i18n.errors.noResultsError }); this._setProcessing(tool, false, queryBuilderWidgetModel); } }, (e) => { this._setProcessing(tool, false, queryBuilderWidgetModel); this._logService.error({ id: e.code, message: e }); }); } searchReplacer(o) { for (let i in o) { let value = o[i]; if (typeof(value) === "string") { o[i] = this._replacer.replace(value); } if (value !== null && typeof(value) === "object" && !value.extent) { this.searchReplacer(value); } } } _setProcessing(tool, processing, queryBuilderWidgetModel) { queryBuilderWidgetModel.processing = processing; if (tool) { tool.set("processing", processing); } } } module.exports = QueryController;
JavaScript
0
@@ -4545,32 +4545,74 @@ rWidgetModel) %7B%0A + if(queryBuilderWidgetModel) %7B%0A queryBui @@ -4652,16 +4652,26 @@ essing;%0A + %7D%0A
b33f30cd2dc8534d069202b867d9c9827e79ec3f
add banana phone
SLACKBOT.js
SLACKBOT.js
var FS = require('fs'); var MARKOV = require('markoff'); var MARK = new MARKOV(); var API = require('slack-api'); function ISLOUD(MSG) { return MSG !== MSG.toLowerCase() && MSG === MSG.toUpperCase(); } var STARTERFILE = __dirname + '/STARTERS'; var STARTERS = FS.readFileSync(STARTERFILE, 'UTF8'); STARTERS = STARTERS.trim().split(/\n/); var SAVEFILE = __dirname + '/LOUDS'; var SAVING = false; var WAITING = []; var LOUDBOT = module.exports = function LOUDBOT() { if (!(this instanceof LOUDBOT)) return new LOUDBOT(); var THIS = this; try { THIS.LOUDS = FS.readFileSync(SAVEFILE, 'UTF8').trim().split('\n'); } catch (ERRRRROR) { THIS.LOUDS = []; } THIS.LOUDS = THIS.LOUDS.concat(STARTERS); THIS.LOUDS.forEach(function(LOUD) { MARK.addTokens(LOUD.split(/\s+/g)); }); }; LOUDBOT.prototype.LISTENUP = function LISTENUP(DATA) { var MSG = DATA.text; var THIS = this; var SPECIAL = THIS.ISSPECIAL(MSG); if (SPECIAL) return SPECIAL; if (ISLOUD(MSG)) { THIS.REMEMBER(MSG); return THIS.YELL(); } return THIS.DOEMOJI(DATA); }; var EMOJI = [ 'shipit', 'sheep', 'smiley_cat', 'smile_cat', 'heart_eyes_cat', 'kissing_cat', 'smirk_cat', 'scream_cat', 'crying_cat_face', 'joy_cat', 'pouting_cat', 'cat', 'cat2', 'thumbsup', 'thumbsdown', 'facepunch', 'sparkles', ]; LOUDBOT.prototype.DOEMOJI = function DOEMOJI(DATA) { // SOMETIMES LOUDBOT USES EMOJI if (!process.env.SLACK_TOKEN) return; if (!DATA.text.match(/(\?|!)/) || (Math.floor(Math.random() * 100) < 75)) return; var M = Math.floor(Math.random() * EMOJI.length); var OPTS = { token: process.env.SLACK_TOKEN, name: EMOJI[M], channel: DATA.channel_id, timestamp: DATA.timestamp }; API.reactions.add(OPTS, function(ERROR, RESPONSE) { if (ERROR) console.log(ERROR); }); }; var BANANAS = [ 'http://media.fi.gosupermodel.com/displaypicture?imageid=4981105&large=1', 'http://minionslovebananas.com/images/gallery/preview/Chiquita-DM2-minion-banana-1.jpg', 'http://minionslovebananas.com/images/gallery/preview/Chiquita-DM2-minion-banana-3.jpg', 'http://minionslovebananas.com/images/gallery/preview/Chiquita-DM2-minion-dave-bananas.jpg', 'http://minionslovebananas.com/images/gallery/preview/Chiquita-DM2-gallery_phil_eating_banana.jpg', 'http://minionslovebananas.com/images/right-side/fruit_head_minion.jpg', 'http://media-cache-ec0.pinimg.com/236x/c8/61/7b/c8617bc383dcbe035c77e22946439475.jpg', ]; LOUDBOT.prototype.ISSPECIAL = function ISSPECIAL(MSG) { if (!MSG) return; if (MSG.toUpperCase().match(/BANANA/)) { var M = Math.floor(Math.random() * BANANAS.length); return BANANAS[M]; } if (MSG.toUpperCase().match(/CLOWN\s*SHOES/)) { return 'https://i.cloudup.com/MhNp5cf7Fz.gif'; } }; LOUDBOT.prototype.REMEMBER = function REMEMBER(LOUD) { this.LOUDS.push(LOUD); WAITING.push(LOUD); if (SAVING) return; SAVING = true; FS.appendFile(SAVEFILE, WAITING.join('\n') + '\n', 'UTF8', function() { SAVING = false; }); WAITING.length = 0; }; LOUDBOT.prototype.YELL = function YELL() { var THIS = this; var ROLL_THE_DICE = Math.floor(Math.random() * 100); if (ROLL_THE_DICE >= 95) return MARK.generatePhrase(4, 20); var LEN = THIS.LOUDS.length; var L = Math.floor(Math.random() * LEN); var LOUD = THIS.LASTLOUD = THIS.LOUDS[L]; return LOUD; }; LOUDBOT.prototype.THELOUDS = function THELOUDS() { return this.LOUDS; };
JavaScript
0.999731
@@ -3000,16 +3000,182 @@ ;%0A %7D%0A +%09if (MSG.toUpperCase().match(/BANANA%5C.*PHONE/))%0A %7B%0A return 'https://s-media-cache-ak0.pinimg.com/736x/fb/e1/cd/fbe1cdbc1b728fbb5e157375905d576f.jpg';%0A %7D%0A %7D;%0A%0ALOUD
3f1f2244e1a95fae6650fe32ed3349b5cba7d434
update Label#domRender
dev/src/Label.js
dev/src/Label.js
/** * @scope enchant.Label.prototype */ enchant.Label = enchant.Class.create(enchant.Entity, { /** [lang:ja] * Labelオブジェクトを作成する. [/lang] [lang:en] * Create Label object. [/lang] [lang:de] * Erstellt ein Label Objekt. [/lang] * @constructs * @extends enchant.Entity */ initialize: function(text) { enchant.Entity.call(this); this.width = 300; this.text = text; this.textAlign = 'left'; }, /** [lang:ja] * 表示するテキスト. [/lang] [lang:en] * Text to be displayed. [/lang] [lang:de] * Darzustellender Text. [/lang] * @type {String} */ text: { get: function() { return this._text; }, set: function(text) { this._text = text; } }, /** [lang:ja] * テキストの水平位置の指定. * CSSの'text-align'プロパティと同様の形式で指定できる. [/lang] [lang:en] * Specifies horizontal alignment of text. * Can be set according to the format of the CSS 'text-align' property. [/lang] [lang:de] * Spezifiziert die horizontale Ausrichtung des Textes. * Kann im gleichen Format wie die CSS 'text-align' Eigenschaft angegeben werden. [/lang] * @type {String} */ textAlign: { get: function() { return this._style.textAlign; }, set: function(textAlign) { this._style.textAlign = textAlign; } }, /** [lang:ja] * フォントの指定. * CSSの'font'プロパティと同様の形式で指定できる. [/lang] [lang:en] * Font settings. * Can be set according to the format of the CSS 'font' property. [/lang] [lang:de] * Text Eigenschaften. * Kann im gleichen Format wie die CSS 'font' Eigenschaft angegeben werden. [/lang] * @type {String} */ font: { get: function() { return this._style.font; }, set: function(font) { this._style.font = font; } }, /** [lang:ja] * 文字色の指定. * CSSの'color'プロパティと同様の形式で指定できる. [/lang] [lang:en] * Text color settings. * Can be set according to the format of the CSS 'color' property. [/lang] [lang:de] * Text Farbe. * Kann im gleichen Format wie die CSS 'color' Eigenschaft angegeben werden. [/lang] * @type {String} */ color: { get: function() { return this._style.color; }, set: function(color) { this._style.color = color; } }, cvsRender: function(ctx) { if (this.text) { ctx.textBaseline = 'top'; ctx.font = this.font; ctx.fillStyle = this.color || '#000000'; ctx.fillText(this.text, 0, 0); } }, domRender: function(element) { element.innerHTML = this._text; element.style.font = this._font; element.style.color = this._color; element.style.textAlign = this._textAlign; }, detectRender: function(ctx) { ctx.fillRect(0, 0, this._boundWidth, this._boundHeight); } }); } };
JavaScript
0
@@ -2855,24 +2855,76 @@ (element) %7B%0A + if (element.innerHTML !== this._text) %7B%0A elem @@ -2943,32 +2943,42 @@ L = this._text;%0A + %7D%0A element.
9728aff063399579cce16e1e43bb308fa6c1ff2d
Use username if no displayName. Extra check to try and get email.
web/js/client.js
web/js/client.js
'use strict'; var app = angular.module('ngPeerPerks', [ 'firebase', 'config.app', 'ngRoute', 'service.lodash', 'service.participant', 'service.activity', 'directive.reward', 'directive.perk' ]) .config(function ($routeProvider, $locationProvider) { $locationProvider .html5Mode(true) ; $routeProvider .when('/', {controller: 'AppCtrl', templateUrl: '/app.html'}) .otherwise({templateUrl: '/404.html'}) ; }) .controller('AppCtrl', function ($scope, $firebaseSimpleLogin, $firebase, _, ParticipantService, ActivityService, API_URL) { var loginRef = new Firebase(API_URL); var auth; $scope.error = null; $scope.participants = ParticipantService; $scope.participants.$bind($scope, 'remoteParticipants').then(function() { auth = $firebaseSimpleLogin(loginRef); auth.$getCurrentUser().then(function(user) { $scope.user = user; }); }); $scope.activities = ActivityService; $scope.login = function() { auth.$login('github', { rememberMe: true, scope: 'user:email' }).then(function(user) { $scope.user = user; // successful login $scope.error = null; var participant = _.find($scope.participants, function(participant) { return (participant.username === $scope.user.username); }); // if not participating yet, then add the user if (!participant) { $scope.participants.$add({ email: $scope.user.thirdPartyUserData.email, name: $scope.user.displayName, username: $scope.user.username, points: { current: 0, allTime: 0, redeemed: 0, perks: 0 } }).then(function(ref) { var participant = $firebase(ref); participant.$priority = 0; participant.$save(); }); } $scope.error = null; }, function(error) { $scope.error = error.message; }); }; $scope.logout = function() { auth.$logout(); $scope.user = null; }; $scope.cancel = function() { $scope.selectReward = false; $scope.selectPerk = false; }; }) ;
JavaScript
0
@@ -1420,16 +1420,17 @@ %09email: +( $scope.u @@ -1457,16 +1457,99 @@ ta.email +) ? $scope.user.thirdPartyUserData.email : $scope.user.thirdPartyUserData.emails%5B0%5D ,%0A%09%09%09%09%09%09 @@ -1550,24 +1550,25 @@ %09%09%09%09%09%09name: +( $scope.user. @@ -1578,16 +1578,66 @@ playName +) ? $scope.user.displayName : $scope.user.username ,%0A%09%09%09%09%09%09
a3d1a8736201317ba6caddba19944a67086ba404
Remove incorrect comment (the initEvent call does work in Safari)
web/js/common.js
web/js/common.js
//////////// STUDY CALENDAR JS STYLES var SC = new Object(); SC.slideAndHide = function(element, options) { var e = $(element); new Effect.Parallel( [ new Effect.BlindUp(e, {sync:true}), new Effect.Fade(e, {sync:true}) ], $H(options).merge({ duration: 1.0 }) ); } SC.slideAndShow = function(element, options) { var e = $(element); new Effect.Parallel( [ new Effect.BlindDown(e, {sync:true}), new Effect.Appear(e, {sync:true}) ], $H(options).merge({ duration: 1.0 }) ); } SC.highlight = function(element, options) { var e = $(element) new Effect.Highlight(element, $H(options)) } SC.asyncSubmit = function(form, options) { var f = $(form); new Ajax.Request(f.action, $H(options).merge({ asynchronous: true, parameters: Form.serialize(f) })) } //////////// COOKIES /** Main fns based on http://www.quirksmode.org/js/cookies.html */ var Cookies = { add: function(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; }, get: function(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; }, clear: function(name) { Cookies.add(name, "", -1); }, set: function(name, value, days) { Cookies.clear(name) Cookies.add(name, value, days) } } ////// PROTOTYPE EXTENSIONS Element.addMethods( { // Like prototype's hide(), but uses the visibility CSS prop instead of display conceal: function() { for (var i = 0; i < arguments.length; i++) { var element = $(arguments[i]); element.style.visibility = 'hidden'; } }, // Like prototype's show(), but uses the visibility CSS prop instead of display reveal: function() { for (var i = 0; i < arguments.length; i++) { var element = $(arguments[i]); element.style.visibility = 'visible'; } } } ); ////// DOM EXTENSIONS // Adds an IE-like click() fn for other browsers if (HTMLElement && !HTMLElement.prototype.click) { HTMLElement.prototype.click = function() { // this is based on the DOM 2 standard, but doesn't seem to work in Safari var evt = this.ownerDocument.createEvent('MouseEvents'); // evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null); evt.initEvent("click", true, true); this.dispatchEvent(evt); } }
JavaScript
0
@@ -2682,91 +2682,8 @@ ) %7B%0A - // this is based on the DOM 2 standard, but doesn't seem to work in Safari%0A
cc6492c2f4781d2fad1bec5463dbb5be8e4d15ff
fix panorama-preview.test warnings
src/panorama/services/preview/panorama-preview.test.js
src/panorama/services/preview/panorama-preview.test.js
import panoPreview from './panorama-preview'; import { getByUrl } from '../../../shared/services/api/api'; jest.mock('../../../shared/services/api/api'); describe('panoPreview service', () => { it('should return an object filled with data if response is ok', () => { getByUrl.mockReturnValueOnce(Promise.resolve({ pano_id: 'pano_id', heading: 'heading', url: 'url' })); panoPreview({ latitude: 123, longitude: 321 }).then((res) => { expect(res).toEqual({ id: 'pano_id', heading: 'heading', url: 'url' }); }); expect(getByUrl).toHaveBeenCalledWith('https://acc.api.data.amsterdam.nl/panorama/thumbnail/?lat=123&lon=321&width=438&radius=180'); }); it('should return an empty object when status is 404', () => { getByUrl.mockReturnValueOnce(Promise.resolve({})); panoPreview({ latitude: 123, longitude: 321 }).then((res) => { expect(res).toEqual({}); }); }); it('should throw an error is response != ok and status != 404', async () => { getByUrl.mockReturnValueOnce(Promise.resolve({})); // const result = expect(panoPreview({ latitude: 123, longitude: 321 })).rejects.toEqual(new Error('Error requesting a panoramic view')); }); });
JavaScript
0.000001
@@ -1,26 +1,24 @@ import -panoPreview +fetchPano from '. @@ -391,35 +391,33 @@ %7D));%0A -panoPreview +fetchPano (%7B latitude: @@ -840,27 +840,25 @@ ));%0A -panoPreview +fetchPano (%7B latit @@ -1019,32 +1019,98 @@ , async () =%3E %7B%0A + const error = new Error('Error requesting a panoramic view');%0A getByUrl.moc @@ -1140,64 +1140,49 @@ e.re -solve(%7B%7D +ject(error ));%0A +%0A -// const result =%0A expect(panoPreview +await expect(fetchPano (%7B%0A @@ -1250,54 +1250,13 @@ ual( -new Error('Error requesting a panoramic view') +error );%0A
ba158560ac4f44307821a4be919696f70b6354ab
fix for genome level
public/js/p3/widget/ProteinFamiliesGridContainer.js
public/js/p3/widget/ProteinFamiliesGridContainer.js
define([ "dojo/_base/declare", "dojo/_base/lang", "dojo/on", "dojo/topic", "dijit/popup", "dijit/TooltipDialog", "./ProteinFamiliesGrid", "./GridContainer" ], function(declare, lang, on, Topic, popup, TooltipDialog, ProteinFamiliesGrid, GridContainer){ var vfc = '<div class="wsActionTooltip" rel="dna">View FASTA DNA</div><div class="wsActionTooltip" rel="protein">View FASTA Proteins</div><hr><div class="wsActionTooltip" rel="dna">Download FASTA DNA</div><div class="wsActionTooltip" rel="downloaddna">Download FASTA DNA</div><div class="wsActionTooltip" rel="downloadprotein"> '; var viewFASTATT = new TooltipDialog({ content: vfc, onMouseLeave: function(){ popup.close(viewFASTATT); } }); var dfc = '<div>Download Table As...</div><div class="wsActionTooltip" rel="text/tsv">Text</div><div class="wsActionTooltip" rel="text/csv">CSV</div><div class="wsActionTooltip" rel="application/vnd.openxmlformats">Excel</div>'; var downloadTT = new TooltipDialog({ content: dfc, onMouseLeave: function(){ popup.close(downloadTT); } }); on(downloadTT.domNode, "div:click", function(evt){ var rel = evt.target.attributes.rel.value; // console.log("REL: ", rel); var selection = self.actionPanel.get('selection'); var dataType = (self.actionPanel.currentContainerWidget.containerType == "genome_group") ? "genome" : "genome_feature"; var currentQuery = self.actionPanel.currentContainerWidget.get('query'); // console.log("selection: ", selection); // console.log("DownloadQuery: ", dataType, currentQuery); window.open("/api/" + dataType + "/" + currentQuery + "&http_authorization=" + encodeURIComponent(window.App.authorizationToken) + "&http_accept=" + rel + "&http_download"); popup.close(downloadTT); }); return declare([GridContainer], { gridCtor: ProteinFamiliesGrid, containerType: "proteinfamily_data", facetFields: [], enableFilterPanel: false, constructor: function(){ var self = this; Topic.subscribe("ProteinFamilies", lang.hitch(self, function(){ var key = arguments[0], value = arguments[1]; switch(key){ case "updatePfState": self.pfState = value; break; default: break; } })); }, _setQueryAttr: function(query){ //block default query handler for now. }, _setStateAttr: function(state){ this.inherited(arguments); if(!state){ return; } // console.log("ProteinFamiliesGridContainer _setStateAttr: ", state); if(this.grid){ // console.log(" call set state on this.grid: ", this.grid); Topic.publish("ProteinFamilies", "showLoadingMask"); this.grid.set('state', state); }else{ console.log("No Grid Yet (ProteinFamiliesGridContainer)"); } this._set("state", state); }, containerActions: GridContainer.prototype.containerActions.concat([ [ "DownloadTable", "fa fa-download fa-2x", { label: "DOWNLOAD", multiple: false, validTypes: ["*"], tooltip: "Download Table", tooltipDialog: downloadTT }, function(){ popup.open({ popup: this.containerActionBar._actions.DownloadTable.options.tooltipDialog, around: this.containerActionBar._actions.DownloadTable.button, orient: ["below"] }); }, true ] ]), selectionActions: GridContainer.prototype.selectionActions.concat([ [ "ViewFASTA", "fa icon-fasta fa-2x", { label: "FASTA", ignoreDataType: true, multiple: true, validTypes: ["*"], tooltip: "View FASTA Data", tooltipDialog: viewFASTATT }, function(selection){ // TODO: pass selection and implement detail console.log(selection); popup.open({ popup: this.selectionActionBar._actions.ViewFASTA.options.tooltipDialog, around: this.selectionActionBar._actions.ViewFASTA.button, orient: ["below"] }); }, false ], [ "ViewProteinFamiliesMembers", "fa fa-users fa-2x", { label: "Members", multiple: true, validTypes: ["*"], tooltip: "View Family Members", validContainerTypes: ["proteinfamily_data"] }, function(selection){ var query = "?and(in(genome_id,(" + this.pfState.genomeIds.join(',') + ")),in(" + this.pfState.familyType + "_id,(" + selection.map(function(sel){ return sel.family_id; }).join(',') + ")))"; Topic.publish("ProteinFamilies", "showMembersGrid", query); }, false ] ]) }); });
JavaScript
0.000022
@@ -2195,24 +2195,69 @@ %09%09%7D));%0A%09%09%7D,%0A +%09%09buildQuery: function()%7B%0A%09%09%09return %22%22;%0A%09%09%7D,%0A %09%09_setQueryA
1c3c8f086968e8d391b4a2e1c1f60e23218cd07c
Use course permission check if file is a submission
src/services/fileStorage/utils/filePermissionHelper.js
src/services/fileStorage/utils/filePermissionHelper.js
const { FileModel } = require('../model'); const { userModel } = require('../../user/model'); const getFile = id => FileModel .findOne({ _id: id }) .populate('owner') .exec(); const checkPermissions = (permission) => { return async (user, file) => { const fileObject = await getFile(file); const { permissions, refOwnerModel, owner: { _id: owner }, } = fileObject; // return always true for owner of file if (user.toString() === owner.toString()) { return Promise.resolve(true); } // or legacy course model if (refOwnerModel === 'course') { const userObject = await userModel.findOne({ _id: user }).populate('roles').exec(); const isStudent = userObject.roles.find(role => role.name === 'student'); if (isStudent) { const rolePermissions = permissions.find( perm => perm.refId && perm.refId.toString() === isStudent._id.toString(), ); return rolePermissions[permission] ? Promise.resolve(true) : Promise.reject(); } return Promise.resolve(true); } const teamMember = fileObject.owner.userIds && fileObject.owner.userIds .find(_ => _.userId.toString() === user.toString()); const userPermissions = permissions .find(perm => perm.refId && perm.refId.toString() === user.toString()); // User is either not member of Team // or file has no explicit user permissions (sharednetz files) if (!teamMember && !userPermissions) { return Promise.reject(); } return new Promise((resolve, reject) => { if (userPermissions) { return userPermissions[permission] ? resolve(true) : reject(); } const { role } = teamMember; const rolePermissions = permissions.find(perm => perm.refId.toString() === role.toString()); return rolePermissions[permission] ? resolve(true) : reject(); }); }; }; module.exports = { checkPermissions, canWrite: checkPermissions('write'), canRead: checkPermissions('read'), canCreate: checkPermissions('create'), canDelete: checkPermissions('delete'), };
JavaScript
0
@@ -86,16 +86,77 @@ model'); +%0Aconst %7B submissionModel %7D = require('../../homework/model'); %0A%0Aconst @@ -567,16 +567,100 @@ );%0A%09%09%7D%0A%0A +%09%09const isSubmission = await submissionModel.findOne(%7B fileIds: fileObject._id %7D);%0A%0A %09%09// or @@ -711,16 +711,32 @@ 'course' + %7C%7C isSubmission ) %7B%0A%09%09%09c
3a461d7fb32127aca6d426bafb5ec682a51846de
Refactor componentWillMount to async/await func instead of promises
src/web/client/src/components/services/service-list.js
src/web/client/src/components/services/service-list.js
import React from 'react' import lodash from 'lodash' import './service-list.scss' export default class ServiceList extends React.Component { constructor () { super() this.state = { services: [] } } componentWillMount () { fetch('/graphql', { method: 'post', headers: new Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ query: '{ services { id, displayName, isConfigured } }' }) }).then((response) => { response.json().then((body) => { this.setState({ services: body.data.services }) }) }) } render () { const paritionedServices = lodash.partition(this.state.services, (s) => s.isConfigured) const configuredServices = paritionedServices[0] const unconfiguredServices = paritionedServices[1] return ( <div className='service-list'> <h1 className='title'>Configured Services</h1> <table className='table'> <thead> <tr> <th>Name</th> <th className="options-column">Options</th> </tr> </thead> <tbody> { configuredServices.map((s) => ( <tr key={s.id}> <td>{s.displayName}</td> <td>Add options</td> </tr> )) } </tbody> </table> <h1 className='title'>Unconfigured Services</h1> <table className='table'> <thead> <tr> <th>Name</th> <th className="options-column">Options</th> </tr> </thead> <tbody> { unconfiguredServices.map((s) => ( <tr key={s.id}> <td>{s.displayName}</td> <td>Add options</td> </tr> )) } </tbody> </table> </div> ) } }
JavaScript
0
@@ -218,16 +218,22 @@ %0A %7D%0A%0A +async componen @@ -252,16 +252,39 @@ ) %7B%0A +const response = await fetch('/ @@ -511,73 +511,54 @@ %7D) -.then((response) =%3E %7B%0A response.json().then((body) =%3E %7B +%0A%0A const body = await response.json() %0A +%0A @@ -573,20 +573,16 @@ State(%7B%0A - se @@ -612,28 +612,8 @@ ces%0A - %7D)%0A %7D)%0A
49293f352299ce625e8c4bed71114e94aa0e4460
Create UserArticleLink in askingArticleSubmissionConsent
src/webhook/handlers/askingArticleSubmissionConsent.js
src/webhook/handlers/askingArticleSubmissionConsent.js
import { t } from 'ttag'; import ga from 'src/lib/ga'; import gql from 'src/lib/gql'; import { SOURCE_PREFIX, getArticleURL } from 'src/lib/sharedUtils'; import { ManipulationError, createArticleShareBubble, createSuggestOtherFactCheckerReply, getArticleSourceOptionFromLabel, createReasonButtonFooter, } from './utils'; export default async function askingArticleSubmissionConsent(params) { let { data, state, event, userId, replies, isSkipUser } = params; if (!event.input.startsWith(SOURCE_PREFIX)) { throw new ManipulationError( t`Please press the latest button to submit message to database.` ); } const visitor = ga(userId, state, data.searchedText); const sourceOption = getArticleSourceOptionFromLabel( event.input.slice(SOURCE_PREFIX.length) ); visitor.event({ ec: 'UserInput', ea: 'ProvidingSource', el: sourceOption.value, }); if (!sourceOption.valid) { replies = [ { type: 'text', text: t`Thanks for the info.`, }, createSuggestOtherFactCheckerReply(), ]; state = '__INIT__'; } else { visitor.event({ ec: 'Article', ea: 'Create', el: 'Yes' }); const { data: { CreateArticle }, } = await gql` mutation($text: String!) { CreateArticle(text: $text, reference: { type: LINE }) { id } } `({ text: data.searchedText }, { userId }); const articleUrl = getArticleURL(CreateArticle.id); const articleCreatedMsg = t`Your submission is now recorded at ${articleUrl}`; // Track the source of the new message. visitor.event({ ec: 'Article', ea: 'ProvidingSource', el: `${CreateArticle.id}/${sourceOption.value}`, }); replies = [ { type: 'flex', altText: articleCreatedMsg, contents: { type: 'carousel', contents: [ { type: 'bubble', body: { type: 'box', layout: 'vertical', contents: [ { type: 'text', wrap: true, text: articleCreatedMsg, }, ], }, footer: createReasonButtonFooter( articleUrl, userId, data.sessionId ), }, createArticleShareBubble(articleUrl), ], }, }, ]; // Record article ID in context for reason LIFF data.selectedArticleId = CreateArticle.id; state = '__INIT__'; } visitor.send(); return { data, state, event, userId, replies, isSkipUser }; }
JavaScript
0
@@ -325,16 +325,86 @@ tils';%0A%0A +import UserArticleLink from '../../database/models/userArticleLink';%0A%0A export d @@ -1471,24 +1471,100 @@ userId %7D);%0A%0A + await UserArticleLink.create(%7B userId, articleId: CreateArticle.id %7D);%0A%0A const ar
3c3760981f4bf88ace3e4e0c3c215250fba66b81
fix task worker status
static/js/task/controllers/task-overview.controller.js
static/js/task/controllers/task-overview.controller.js
(function () { 'use strict'; angular .module('crowdsource.task.controllers') .controller('TaskOverviewController', TaskOverviewController); TaskOverviewController.$inject = ['$window', '$location', '$scope', '$mdToast', 'Task', '$filter', '$routeParams', 'Authentication']; /** * @namespace TaskOverviewController */ function TaskOverviewController($window, $location, $scope, $mdToast, Task, $filter, $routeParams, Authentication) { var self = this; self.tasks = []; self.getStatusName = getStatusName; self.get_answer = get_answer; self.toggle = toggle; self.isSelected = isSelected; self.selectedItems = []; self.updateStatus = updateStatus; self.downloadResults = downloadResults; self.sort = sort; self.config = { order_by: "", order: "" }; activate(); function activate(){ var module_id = $routeParams.moduleId; Task.getTasks(module_id).then( function success(response) { self.tasks = response[0].tasks; self.project_name = response[0].project_name; self.module_name = response[0].module_name; }, function error(response) { $mdToast.showSimple('Could not get tasks for module.'); } ).finally(function () {}); } function getStatusName (status) { if(status == 1) { return 'created'; } else if(status == 2){ return 'in progress'; } else if(status == 3){ return 'accepted'; } else if(status == 4){ return 'returned'; } else if(status == 5){ return 'rejected'; } } function toggle(item) { var idx = self.selectedItems.indexOf(item); if (idx > -1) self.selectedItems.splice(idx, 1); else self.selectedItems.push(item); } function isSelected(item){ return !(self.selectedItems.indexOf(item) < 0); } function sort(header){ var sortedData = $filter('orderBy')(self.myProjects, header, self.config.order==='descending'); self.config.order = (self.config.order==='descending')?'ascending':'descending'; self.config.order_by = header; self.tasks = sortedData; } function get_answer(answer_list, template_item){ return $filter('filter')(answer_list, {template_item_id: template_item.id})[0]; } function updateStatus(status_id){ var request_data = { task_status: status_id, task_workers: [] }; angular.forEach(self.selectedItems, function(obj) { request_data.task_workers.push(obj.id); }); Task.updateStatus(request_data).then( function success(response) { self.selectedItems = []; var updated_task_workers = response[0]; angular.forEach(updated_task_workers, function(updated_task_worker) { for(var i = 0; i < self.tasks.length; i++) { var task = self.tasks[i]; if(task.id == updated_task_worker.task) { var task_index = i; var task_workers = task.task_workers_monitoring; for(var j = 0; j < task_workers.length; j++) { if(task_workers[j].id == updated_task_worker.id) { var task_worker_index = j; self.tasks[task_index].task_workers_monitoring[task_worker_index] = updated_task_worker; break; } } break; } } }); }, function error(response) { } ).finally(function () {}); } function downloadResults() { var params = { module_id: $routeParams.moduleId }; Task.downloadResults(params).then( function success(response) { var a = document.createElement('a'); a.href = 'data:text/csv;charset=utf-8,' + response[0].replace(/\n/g, '%0A'); a.target = '_blank'; a.download = self.project_name.replace(/\s/g,'') + '_' + self.module_name.replace(/\s/g,'') + '_data.csv'; document.body.appendChild(a); a.click(); }, function error(response) { } ).finally(function () {}); } } })();
JavaScript
0.001481
@@ -1847,9 +1847,9 @@ == -4 +5 )%7B%0A @@ -1918,33 +1918,33 @@ se if(status == -5 +4 )%7B%0A
d55c9ae843a6c54eb8b82fde6f23468ba9213748
Fix skipped tests
test/unit/specs/components/GeneratePaletteForm.spec.js
test/unit/specs/components/GeneratePaletteForm.spec.js
import { mount } from 'avoriaz'; import Vue from 'vue'; import sinon from 'sinon'; import { expect } from 'chai'; import Vuex from 'vuex'; import GeneratePaletteForm from '@/components/GeneratePaletteForm'; Vue.use(Vuex); describe('GeneratePaletteForm.vue', () => { let actions; let store; beforeEach(() => { actions = { generatePalette: sinon.stub(), generateRandomPalette: sinon.stub(), }; store = new Vuex.Store({ actions, }); }); it.skip('calls store action generateRandomPalette when random-palette is clicked', () => { const wrapper = mount(GeneratePaletteForm, { store }); const rgb = 'rgb(0,0,0)'; wrapper.find('input')[0].element.value = rgb; wrapper.find('input')[0].simulate('change'); wrapper.find('form')[0].simulate('submit'); expect(actions.generatePalette.calledOnce).to.equal(true); expect(actions.generatePalette.calledWith({ rgb })).to.equal(true); }); it('calls store action generateRandomPalette when random-palette is clicked', () => { const wrapper = mount(GeneratePaletteForm, { store }); wrapper.find('#random-generate')[0].simulate('click'); expect(actions.generateRandomPalette.calledOnce).to.equal(true); }); });
JavaScript
0
@@ -331,45 +331,8 @@ = %7B%0A - generatePalette: sinon.stub(),%0A @@ -444,13 +444,8 @@ it -.skip ('ca @@ -516,32 +516,109 @@ icked', () =%3E %7B%0A + const rgb = 'rgb(0,0,0)';%0A const $store = %7B dispatch: sinon.stub() %7D;%0A const wrappe @@ -654,46 +654,30 @@ , %7B -store %7D);%0A const rgb = 'rgb(0,0,0)' +globals: %7B $store %7D %7D) ;%0A @@ -688,29 +688,41 @@ apper.find(' -input +#generate-palette ')%5B0%5D.elemen @@ -758,13 +758,25 @@ nd(' -input +#generate-palette ')%5B0 @@ -791,14 +791,13 @@ te(' -change +input ');%0A @@ -855,39 +855,31 @@ expect( -actions.generatePalette +$store.dispatch .calledO @@ -906,32 +906,52 @@ %0A expect( -actions. +$store.dispatch.calledWith(' generatePale @@ -953,28 +953,19 @@ ePalette -.calledWith( +', %7B rgb %7D)
508d06e894bd278fba15190b2babb7b9f3a7361a
Fix ESLint errors (STRIPES-100)
ViewUser.js
ViewUser.js
import _ from 'lodash'; // We have to remove node_modules/react to avoid having multiple copies loaded. // eslint-disable-next-line import/no-unresolved import React, { Component, PropTypes } from 'react'; import Pane from '@folio/stripes-components/lib/Pane'; import PaneMenu from '@folio/stripes-components/lib/PaneMenu'; import Button from '@folio/stripes-components/lib/Button'; import KeyValue from '@folio/stripes-components/lib/KeyValue'; import { Row, Col } from 'react-bootstrap'; import TextField from '@folio/stripes-components/lib/TextField'; import MultiColumnList from '@folio/stripes-components/lib/MultiColumnList'; import Icon from '@folio/stripes-components/lib/Icon'; import Layer from '@folio/stripes-components/lib/Layer'; import IfPermission from './lib/IfPermission'; import UserForm from './UserForm'; import UserPermissions from './UserPermissions'; import UserLoans from './UserLoans'; class ViewUser extends Component { static propTypes = { params: PropTypes.object, data: PropTypes.shape({ user: PropTypes.arrayOf(PropTypes.object), availablePermissions: PropTypes.arrayOf(PropTypes.object), }), mutator: React.PropTypes.shape({ users: React.PropTypes.shape({ PUT: React.PropTypes.func.isRequired, }), }), }; static manifest = Object.freeze({ users: { type: 'okapi', path: 'users/:{userid}', clear: false, }, availablePermissions: { type: 'okapi', records: 'permissions', path: 'perms/permissions?length=100', }, usersPermissions: { type: 'okapi', records: 'permissionNames', DELETE: { pk: 'permissionName', path: 'perms/users/:{username}/permissions', }, GET: { path: 'perms/users/:{username}/permissions?full=true', }, path: 'perms/users/:{username}/permissions', }, usersLoans: { type: 'okapi', records: 'loans', GET: { path: 'loan-storage/loans?query=(userId=:{userid} AND status="Open")', }, }, }); constructor(props) { super(props); this.state = { editUserMode: false, }; this.onClickEditUser = this.onClickEditUser.bind(this); this.onClickCloseEditUser = this.onClickCloseEditUser.bind(this); } // EditUser Handlers onClickEditUser(e) { if (e) e.preventDefault(); this.setState({ editUserMode: true, }); } onClickCloseEditUser(e) { if (e) e.preventDefault(); this.setState({ editUserMode: false, }); } update(data) { // eslint-disable-next-line no-param-reassign if (data.creds) delete data.creds; // not handled on edit (yet at least) this.props.mutator.users.PUT(data).then(() => { this.onClickCloseEditUser(); }); } render() { const fineHistory = [{ 'Due Date': '11/12/2014', Amount: '34.23', Status: 'Unpaid' }]; const { data: { users, availablePermissions, usersPermissions, usersLoans }, params: { userid } } = this.props; const detailMenu = (<PaneMenu> <IfPermission {...this.props} perm="users.edit"> <button onClick={this.onClickEditUser} title="Edit User"><Icon icon="edit" />Edit</button> </IfPermission> </PaneMenu>); if (!users || users.length === 0 || !userid) return <div />; if (!_.get(this.props, ['currentPerms', 'users.read.basic'])) { return (<div> <h2>Permission Error</h2> <p>Sorry - your user permissions do not allow access to this page.</p> </div>); } const user = users.find(u => u.id === userid); if (!user) return <div />; const userStatus = (_.get(user, ['active'], '') ? 'active' : 'inactive'); return ( <Pane defaultWidth="fill" paneTitle="User Details" lastMenu={detailMenu}> <Row> <Col xs={8} > <Row> <Col xs={12}> <h2>{_.get(user, ['personal', 'last_name'], '')}, {_.get(user, ['personal', 'first_name'], '')}</h2> </Col> </Row> <Row> <Col xs={12}> <KeyValue label="Username" value={_.get(user, ['username'], '')} /> </Col> </Row> <br /> <Row> <Col xs={12}> <KeyValue label="Status" value={userStatus} /> </Col> </Row> <br /> <Row> <Col xs={12}> <KeyValue label="Email" value={_.get(user, ['personal', 'email'], '')} /> </Col> </Row> <br /> <Row> <Col xs={12}> <KeyValue label="Patron group" value={_.get(user, ['patron_group'], '')} /> </Col> </Row> </Col> <Col xs={4} > <img className="floatEnd" src="http://placehold.it/175x175" role="presentation" /> </Col> </Row> <br /> <hr /> <br /> <Row> <Col xs={3}> <h3 className="marginTopHalf">Fines</h3> </Col> <Col xs={4} sm={3}> <TextField rounded endControl={<Button buttonStyle="fieldControl"><Icon icon="clearX" /></Button>} startControl={<Icon icon="search" />} placeholder="Search" fullWidth /> </Col> <Col xs={5} sm={6}> <Button align="end" bottomMargin0 >View Full History</Button> </Col> </Row> <MultiColumnList fullWidth contentData={fineHistory} /> <hr /> <UserLoans loans={usersLoans} /> <UserPermissions availablePermissions={availablePermissions} usersPermissions={usersPermissions} viewUserProps={this.props} currentPerms={this.props.currentPerms}/> <Layer isOpen={this.state.editUserMode} label="Edit User Dialog"> <UserForm onSubmit={(record) => { this.update(record); }} initialValues={user} onCancel={this.onClickCloseEditUser} /> </Layer> </Pane> ); } } export default ViewUser;
JavaScript
0.000018
@@ -962,24 +962,107 @@ opTypes = %7B%0A + currentPerms: PropTypes.object, // eslint-disable-line react/forbid-prop-types%0A params: @@ -5891,16 +5891,17 @@ ntPerms%7D + /%3E%0A
4eeaaaeb2ede16c81f6c0513d61af5cfa98e1eed
Add function to the correct prototype.
ad/graph.js
ad/graph.js
'use strict'; var Tensor = require('../tensor.js'); // Base class for all compute graph nodes function Node(x, parents, inputs, backward, name) { this.x = x; this.parents = parents; this.inputs = inputs; if (backward !== undefined) this.backward = backward; this.outDegree = 0; this.name = name || 'node'; } Node.prototype.copy = function(other) { this.x = other.x; this.parents = other.parents; this.inputs = other.inputs; if (other.backward !== undefined) this.backward = other.backward; this.outDegree = other.outDegree; this.name = other.name; }; Node.prototype.clone = function() { var node = Object.create(Node.prototype); node.copy(this); return node; }; Node.prototype.computeOutDegree = function() { this.outDegree++; if (this.outDegree === 1) { var n = this.parents.length; while (n--) this.parents[n].computeOutDegree(); } }; Node.prototype.backpropRec = function() { this.outDegree--; if (this.outDegree === 0) { this.backward(); var n = this.parents.length; while (n--) this.parents[n].backpropRec(); } }; Node.prototype.zeroDerivatives = function() { this.zeroDerivativesImpl(); var n = this.parents.length; while (n--) this.parents[n].zeroDerivatives(); }; // By default, backward does nothing Node.prototype.backward = function() {}; // Base class for all nodes with scalar output function ScalarNode(x, parents, inputs, backward, name) { Node.call(this, x, parents, inputs, backward, name || 'scalarNode'); this.dx = 0; } ScalarNode.prototype = Object.create(Node.prototype); ScalarNode.prototype.copy = function(other) { Node.prototype.copy.call(this, other); this.dx = other.dx; }; ScalarNode.prototype.clone = function() { var node = Object.create(ScalarNode.prototype); node.copy(this); return node; }; ScalarNode.prototype.backprop = function() { this.dx = 1; this.computeOutDegree(); this.backpropRec(); }; ScalarNode.prototype.zeroDerivativesImpl = function() { this.dx = 0; }; // Base class for all nodes with tensor output function TensorNode(x, parents, inputs, backward, name) { Node.call(this, x, parents, inputs, backward, name || 'tensorNode'); this.dx = new Tensor(x.dims); } TensorNode.prototype = Object.create(Node.prototype); TensorNode.prototype.copy = function(other) { Node.prototype.copy.call(this, other); this.x = other.x.clone(); this.dx = other.dx.clone(); }; Tensor.prototype.clone = function() { var node = Object.create(Tensor.prototype); node.copy(this); return node; }; TensorNode.prototype.refCopy = function(other) { Node.prototype.copy.call(this, other); this.x = other.x.refClone(); this.dx = other.dx.refClone(); }; TensorNode.prototype.refClone = function() { var node = Object.create(Tensor.prototype); node.refCopy(this); return node; }; TensorNode.prototype.backprop = function() { this.dx.fill(1); this.computeOutDegree(); this.backpropRec(); }; TensorNode.prototype.zeroDerivativesImpl = function() { this.dx.zero(); }; module.exports = { Node: Node, ScalarNode: ScalarNode, TensorNode: TensorNode };
JavaScript
0.000001
@@ -2355,24 +2355,28 @@ );%0A%7D;%0ATensor +Node .prototype.c
10408b6d60b3c4326819688b5d52c2ba9cce6a8a
change search string
_config_.js
_config_.js
/** * Config for backend limits, thresholds, database etc * Also a layer of indirection above env variables to allow easy overrides during dev. * * :TODO: prepopulate legislator info into mongo from source data */ module.exports = { server_port : process.env.PORT, mongo_connection_uri : process.env.MONGOHQ_URL, tweet_follower_celebrity_count : 10, tweet_processor_interval : 15000, tweet_processor_batch_size : 100, tweet_processor_match : '@eff', tweet_processor_account_blacklist : [ ], twitterCreds : { consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token: process.env.TWITTER_ACCESS_TOKEN, access_token_secret: process.env.TWITTER_ACCESS_SECRET }, mongoSetup : { // configure collections to prepopulate collectionsAndIndexes : { worker_state : [], log_totals : [ { calls : 1 }, { emails : 1 }, { views : 1 }, ], tweets : [ { followers_count : 1 }, ], }, // configure records to prepopulate collectionRecords : { log_totals : [ { _id : 'overall_totals' } ], }, }, };
JavaScript
0.00001
@@ -453,12 +453,21 @@ : ' -@eff +#stopthespies ',%0A%09
5a681fef8049bdf3f349e6d8dcddeace064328db
Make reflection topic browser-independent
topics/about_reflection.js
topics/about_reflection.js
module("About Reflection (topics/about_reflection.js)"); var A = function() { this.aprop = "A"; }; var B = function() { this.bprop = "B"; }; B.prototype = new A(); test("typeof", function() { equal(__, typeof({}), 'what is the type of an empty object?'); equal(__, typeof('apple'), 'what is the type of a string?'); equal(__, typeof(-5), 'what is the type of -5?'); equal(__, typeof(false), 'what is the type of false?'); }); test("property enumeration", function() { var keys = []; var values = []; var person = {name: 'Amory Blaine', age: 102, unemployed: true}; for(var propertyName in person) { keys.push(propertyName); values.push(person[propertyName]); } ok(keys.equalTo(['__','__','__']), 'what are the property names of the object?'); ok(values.equalTo(['__',__,__]), 'what are the property values of the object?'); }); test("hasOwnProperty", function() { var b = new B(); var propertyName; var keys = []; for (propertyName in b) { keys.push(propertyName); } equal(__, keys.length, 'how many elements are in the keys array?'); deepEqual([__, __], keys, 'what are the properties of the array?'); // hasOwnProperty returns true if the parameter is a property directly on the object, // but not if it is a property accessible via the prototype chain. var ownKeys = []; for(propertyName in b) { if (b.hasOwnProperty(propertyName)) { ownKeys.push(propertyName); } } equal(__, ownKeys.length, 'how many elements are in the ownKeys array?'); deepEqual([__], ownKeys, 'what are the own properties of the array?'); }); test("constructor property", function () { var a = new A(); var b = new B(); equal(__, typeof(a.constructor), "what is the type of a's constructor?"); equal(__, a.constructor.name, "what is the name of a's constructor?"); equal(__, b.constructor.name, "what is the name of b's constructor?"); }); test("eval", function() { // eval executes a string var result = ""; eval("result = 'apple' + ' ' + 'pie'"); equal(__, result, 'what is the value of result?'); });
JavaScript
0
@@ -55,24 +55,16 @@ );%0A%0A -var A = function () %7B @@ -51,32 +51,34 @@ js)%22);%0A%0Afunction + A () %7B%0A this.ap @@ -91,33 +91,21 @@ %22A%22; - %0A%7D;%0A%0A -var B = function () %7B @@ -92,32 +92,34 @@ A%22;%0A%7D;%0A%0Afunction + B () %7B%0A this.bp @@ -434,10 +434,8 @@ ?'); -%09%09 %0A%7D); @@ -1285,17 +1285,16 @@ object, - %0A // @@ -1905,20 +1905,16 @@ ctor?%22); - %0A equ @@ -1980,20 +1980,16 @@ ctor?%22); - %0A%7D);%0A%0Ate
207f85b124bc9cc4b59acceef17d3c11713db1ff
Fix selector
github-issue-add-details.user.js
github-issue-add-details.user.js
// ==UserScript== // @name GitHub Issue Add Details // @version 1.0.9 // @description A userscript that adds a button to insert a details block into comments // @license MIT // @author Rob Garrison // @namespace https://github.com/Mottie // @include https://github.com/* // @run-at document-idle // @grant none // @require https://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=952601 // @require https://greasyfork.org/scripts/28239-rangy-inputs-mod-js/code/rangy-inputs-modjs.js?version=181769 // @icon https://github.githubassets.com/pinned-octocat.svg // @updateURL https://raw.githubusercontent.com/Mottie/Github-userscripts/master/github-issue-add-details.user.js // @downloadURL https://raw.githubusercontent.com/Mottie/Github-userscripts/master/github-issue-add-details.user.js // @supportURL https://github.com/Mottie/GitHub-userscripts/issues // ==/UserScript== (() => { "use strict"; const icon = ` <svg class="octicon" style="pointer-events:none" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"> <path d="M15.5 9h-7C8 9 8 8.6 8 8s0-1 .5-1h7c.5 0 .5.4.5 1s0 1-.5 1zm-5-5c-.5 0-.5-.4-.5-1s0-1 .5-1h5c.5 0 .5.4.5 1s0 1-.5 1h-5zM0 2h8L4 7 0 2zm8.5 10h7c.5 0 .5.4.5 1s0 1-.5 1h-7c-.5 0-.5-.4-.5-1s0-1 .5-1z"/> </svg>`, detailsBlock = [ // start details block "<details>\n<summary>Title</summary>\n\n<!-- leave a blank line above -->\n", // selected content/caret will be placed here "\n</details>\n" ]; // Add insert details button function addDetailsButton() { const button = document.createElement("button"); button.type = "button"; button.className = "ghad-details toolbar-item tooltipped tooltipped-n"; button.setAttribute("aria-label", "Add a details/summary block"); button.setAttribute("tabindex", "-1"); button.innerHTML = icon; [...document.querySelectorAll(".toolbar-commenting")].forEach(el => { if (el && !$(".ghad-details", el)) { const btn = $("[aria-label='Add a task list']", el); btn.parentNode.insertBefore(button.cloneNode(true), btn.nextSibling); } }); } function addBindings() { window.rangyInput.init(); $("body").addEventListener("click", event => { const target = event.target; if (target && target.classList.contains("ghad-details")) { let textarea = target.closest(".previewable-comment-form"); textarea = $(".comment-form-textarea", textarea); textarea.focus(); window.rangyInput.surroundSelectedText( textarea, detailsBlock[0], // prefix detailsBlock[1] // suffix ); return false; } }); } function $(str, el) { return (el || document).querySelector(str); } document.addEventListener("ghmo:container", addDetailsButton); document.addEventListener("ghmo:comments", addDetailsButton); addDetailsButton(); addBindings(); })();
JavaScript
0.000001
@@ -72,17 +72,18 @@ 1.0. -9 +10 %0A// @des @@ -2025,16 +2025,17 @@ ia-label +* ='Add a @@ -2065,26 +2065,9 @@ btn. -parentNode.insertB +b efor @@ -2094,25 +2094,8 @@ rue) -, btn.nextSibling );%0A%09
eb2ddcb3b58f8098f1b46be00ff5ab140eae2bc8
remove check on rules arguments number
packages/mjml-validator/src/MJMLRulesCollection.js
packages/mjml-validator/src/MJMLRulesCollection.js
import warning from 'warning' import { mapKeys } from 'lodash' import * as rules from './rules' const MJMLRulesCollection = {} export function registerRule(rule, name) { if (typeof rule !== 'function' || rule.length !== 2) { return warning( false, 'Your rule must be a function and must have two parameters which are the element to validate and the components object imported from mjml-core', ) } if (name) { MJMLRulesCollection[name] = rule } else { MJMLRulesCollection[rule.name] = rule } return true } mapKeys(rules, (func, name) => registerRule(func, name)) export default MJMLRulesCollection
JavaScript
0.000001
@@ -202,29 +202,8 @@ ion' - %7C%7C rule.length !== 2 ) %7B%0A @@ -274,121 +274,8 @@ tion - and must have two parameters which are the element to validate and the components object imported from mjml-core ',%0A
856d721573765b22cc3a336168650337381291ff
Fix `optimal-imports` to support v4 and v5-alpha, beta (#28812)
packages/mui-codemod/src/v5.0.0/optimal-imports.js
packages/mui-codemod/src/v5.0.0/optimal-imports.js
import { dirname } from 'path'; import addImports from 'jscodeshift-add-imports'; import getJSExports from '../util/getJSExports'; // istanbul ignore next if (process.env.NODE_ENV === 'test') { const resolve = require.resolve; require.resolve = (source) => resolve(source.replace(/^@material-ui\/core\/modern/, '../../../mui-material/src')); } export default function transformer(fileInfo, api, options) { const j = api.jscodeshift; const importModule = options.importModule || '@material-ui/core'; const targetModule = options.targetModule || '@material-ui/core'; const printOptions = options.printOptions || { quote: 'single', trailingComma: true, }; const root = j(fileInfo.source); const importRegExp = new RegExp(`^${importModule}/([^/]+/)+([^/]+)$`); const resultSpecifiers = new Map(); const addSpecifier = (source, specifier) => { if (!resultSpecifiers.has(source)) { resultSpecifiers.set(source, []); } resultSpecifiers.get(source).push(specifier); }; root.find(j.ImportDeclaration).forEach((path) => { if (path.value.importKind && path.value.importKind !== 'value') { return; } const importPath = path.value.source.value.replace(/(index)?(\.js)?$/, ''); const match = importPath.match(importRegExp); if (!match) { return; } const subpath = match[1].replace(/\/$/, ''); if (/^(internal)/.test(subpath)) { return; } const targetImportPath = `${targetModule}/${subpath}`; const whitelist = getJSExports( require.resolve(`${importModule}/modern/${subpath}`, { paths: [dirname(fileInfo.path)], }), ); path.node.specifiers.forEach((specifier, index) => { if (!path.node.specifiers.length) { return; } if (specifier.importKind && specifier.importKind !== 'value') { return; } if (specifier.type === 'ImportNamespaceSpecifier') { return; } const localName = specifier.local.name; switch (specifier.type) { case 'ImportNamespaceSpecifier': return; case 'ImportDefaultSpecifier': { const moduleName = match[2]; if (!whitelist.has(moduleName) && moduleName !== 'withStyles') { return; } addSpecifier( targetImportPath, j.importSpecifier(j.identifier(moduleName), j.identifier(localName)), ); path.get('specifiers', index).prune(); break; } case 'ImportSpecifier': if (!whitelist.has(specifier.imported.name)) { return; } addSpecifier(targetImportPath, specifier); path.get('specifiers', index).prune(); break; default: break; } }); if (!path.node.specifiers.length) { path.prune(); } }); addImports( root, [...resultSpecifiers.keys()].map((source) => j.importDeclaration(resultSpecifiers.get(source), j.stringLiteral(source)), ), ); return root.toSource(printOptions); }
JavaScript
0
@@ -267,22 +267,111 @@ resolve( -source +%0A source%0A .replace(/%5E@material-ui%5C/core%5C/es/, '../../../mui-material/src')%0A .replace @@ -430,16 +430,22 @@ al/src') +,%0A );%0A%7D%0A%0Aex @@ -1598,45 +1598,187 @@ -const whitelist = getJSExports(%0A +let loader;%0A try %7B%0A loader = require.resolve(%60$%7BimportModule%7D/modern/$%7Bsubpath%7D%60, %7B%0A paths: %5Bdirname(fileInfo.path)%5D,%0A %7D);%0A %7D catch (error) %7B%0A loader = req @@ -1799,38 +1799,34 @@ $%7BimportModule%7D/ -modern +es /$%7Bsubpath%7D%60, %7B%0A @@ -1874,22 +1874,66 @@ %7D) -,%0A +;%0A %7D%0A%0A const whitelist = getJSExports(loader );%0A%0A
80a36b18c67780d949b07ea1ecbc72ee6244513d
Add story with error
packages/react-input-feedback/src/index.stories.js
packages/react-input-feedback/src/index.stories.js
import { storiesOf } from '@storybook/react' import { createElement as r } from 'react' import Input from './index.ts' storiesOf('InputFeedback', module).add('default', () => r(Input))
JavaScript
0.000001
@@ -148,16 +148,19 @@ module) +%0A .add('de @@ -183,8 +183,103 @@ Input))%0A + .add('with error', () =%3E%0A r(Input, %7B meta: %7B error: 'Error text', touched: true %7D %7D),%0A )%0A
08f3e0ecc313dcd41378983d3ff3ea3ef5a00356
Apply PR feedback
packages/strapi-generate-new/json/database.json.js
packages/strapi-generate-new/json/database.json.js
'use strict'; module.exports = scope => { // Production/Staging Template if (['production', 'staging'].includes(scope.keyPath.split('/')[2])) { // All available settings (bookshelf and mongoose) const settingsBase = { client: scope.client.database, host: '${process.env.DATABASE_HOST || 127.0.0.1 }', port: '${process.env.DATABASE_PORT || 27017 }', srv: '${process.env.DATABASE_SRV || false }', database: '${process.env.DATABASE_NAME || strapi }', username: '${process.env.DATABASE_USERNAME || \'\' }', password: '${process.env.DATABASE_PASSWORD || \'\' }', ssl: '${process.env.DATABASE_SSL || false }' }; // Apply only settings set during the configuration const settings = Object.keys(scope.database.settings).reduce((acc, key) => { acc[key] = settingsBase[key]; return acc; }, {}); // All available options (bookshelf and mongoose) const optionsBase = { ssl: '${process.env.DATABASE_SSL || false }', authenticationDatabase: '${process.env.DATABASE_AUTHENTICATION_DATABASE || \'\' }' }; // Apply only options set during the configuration const options = Object.keys(scope.database.options).reduce((acc, key) => { acc[key] = optionsBase[key]; return acc; }, {}); return { defaultConnection: 'default', connections: { default: { connector: scope.client.connector, settings, options } } }; } return { defaultConnection: 'default', connections: { default: scope.database } }; };
JavaScript
0
@@ -728,25 +728,8 @@ %0A - const settings = Obj @@ -762,29 +762,25 @@ ttings). -reduce((acc, +forEach(( key) =%3E @@ -779,35 +779,55 @@ key) =%3E %7B%0A -acc +scope.database.settings %5Bkey%5D = settings @@ -841,38 +841,16 @@ y%5D;%0A - return acc;%0A %7D, %7B %7D);%0A%0A @@ -1137,24 +1137,8 @@ %0A - const options = Obj @@ -1174,21 +1174,17 @@ ns). -reduce((acc, +forEach(( key) @@ -1195,19 +1195,38 @@ %7B%0A -acc +scope.database.options %5Bkey%5D = @@ -1251,30 +1251,8 @@ - return acc;%0A %7D, %7B %7D);%0A @@ -1404,28 +1404,77 @@ settings -,%0A +: scope.database.settings,%0A options: scope.database. options%0A
bcde4c20fdc2904459f5925eb3e465859c4aaa78
remove console.log
layout/pulse/layer-card/component.js
layout/pulse/layer-card/component.js
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { Link, Router } from 'routes'; // Utils import { LAYERS_PLANET_PULSE } from 'utils/layers/pulse_layers'; // Components import Legend from 'layout/pulse/legend'; import WidgetChart from 'components/charts/widget-chart'; import LoginRequired from 'components/ui/login-required'; import LayerInfoModal from 'components/modal/LayerInfoModal'; import Icon from 'components/ui/Icon'; // Modal import Modal from 'components/modal/modal-component'; import SubscribeToDatasetModal from 'components/modal/SubscribeToDatasetModal'; class LayerCardComponent extends PureComponent { constructor(props) { super(props); this.state = { showSubscribeToDatasetModal: false, showInfoModal: false }; } componentWillReceiveProps(nextProps) { if ((nextProps.layerMenuPulse.layerActive && nextProps.layerMenuPulse.layerActive.id) !== (this.props.layerMenuPulse.layerActive && this.props.layerMenuPulse.layerActive.id)) { this.loadWidgets(nextProps); this.props.loadDatasetData({ id: nextProps.layerMenuPulse.layerActive.attributes.dataset }); } } loadWidgets(nextProps) { const { layerMenuPulse } = nextProps; const layerActive = layerMenuPulse.layerActive && layerMenuPulse.layerActive.id; if (layerActive) { let found = false; for (let i = 0; i < LAYERS_PLANET_PULSE.length && !found; i++) { found = LAYERS_PLANET_PULSE[i].layers.find(obj => obj.id === layerActive); } if (found) { const { widgets } = found; if (widgets && widgets.length > 0) { this.props.loadWidgetData(widgets[0]); } else { this.props.setWidget(null); } } } } handleToggleSubscribeToDatasetModal = (bool) => { this.setState({ showSubscribeToDatasetModal: bool }); } render() { const { showSubscribeToDatasetModal, showInfoModal } = this.state; const { layerMenuPulse, layerCardPulse, activeContextLayers } = this.props; const { layerActive, layerPoints } = layerMenuPulse; const { dataset, widget } = layerCardPulse; const subscribable = dataset && dataset.attributes && dataset.attributes.subscribable && Object.keys(dataset.attributes.subscribable).length > 0; const source = dataset && dataset.attributes && dataset.attributes.metadata && dataset.attributes.metadata[0].attributes.source; const layerName = layerActive && layerActive.attributes && layerActive.attributes.name; const className = classNames({ 'c-layer-card': true, '-hidden': layerActive === null }); const datasetId = (layerActive !== null) ? layerActive.attributes.dataset : null; console.log('activeContextLayers', activeContextLayers); return ( <div className={className}> <h3>{layerActive && layerActive.label}</h3> {source && <div className="source-container"> {source} </div> } {layerActive && layerActive.descriptionPulse} {layerPoints && layerPoints.length > 0 && <div className="number-of-points"> Number of objects: {layerPoints.length} </div> } <div className="legends"> {layerName && <div className="layer-container"> <span>{layerName}</span> <button type="button" className="info" aria-label="More information" onClick={() => this.setState({ showInfoModal: true })} > <Icon name="icon-info" /> <Modal isOpen={showInfoModal} className="-medium" onRequestClose={() => this.setState({ showInfoModal: false })} > <LayerInfoModal data={layerActive && layerActive.attributes} /> </Modal> </button> </div> } <Legend layerActive={layerActive} className={{ color: '-dark' }} /> {activeContextLayers.length > 0 && <div className="context-layers-legends"> { activeContextLayers.map(ctLayer => ( <div> <div className="layer-container"> <span>{ctLayer.attributes.name}</span> <button type="button" className="info" aria-label="More information" onClick={() => this.setState({ showInfoModal: true })} > <Icon name="icon-info" /> <Modal isOpen={showInfoModal} className="-medium" onRequestClose={() => this.setState({ showInfoModal: false })} > <LayerInfoModal data={ctLayer.attributes} /> </Modal> </button> </div> <Legend layerActive={ctLayer} className={{ color: '-dark' }} /> </div> )) } </div> } </div> {widget && <div> <h5>Similar content</h5> <div key={widget.id} className="widget-card" onClick={() => Router.pushRoute('explore_detail', { id: widget.attributes.dataset })} onKeyDown={() => Router.pushRoute('explore_detail', { id: widget.attributes.dataset })} role="button" tabIndex={-1} > <div className="widget-title"> {widget.attributes.name} </div> <WidgetChart widget={widget.attributes} mode="thumbnail" /> </div> </div> } <div className="card-buttons"> { datasetId && <Link route="explore_detail" params={{ id: datasetId }} > <a className="c-button -tertiary link_button" >Details</a> </Link> } { subscribable && <LoginRequired text="Log in or sign up to subscribe to alerts from this dataset"> <button className="c-button -tertiary link_button" onClick={() => this.handleToggleSubscribeToDatasetModal(true)} > Subscribe to alerts <Modal isOpen={showSubscribeToDatasetModal} onRequestClose={() => this.handleToggleSubscribeToDatasetModal(false)} > <SubscribeToDatasetModal dataset={dataset} showDatasetSelector={false} onRequestClose={() => this.handleToggleSubscribeToDatasetModal(false)} /> </Modal> </button> </LoginRequired> } </div> </div> ); } } LayerCardComponent.propTypes = { // PROPS layerMenuPulse: PropTypes.object.isRequired, layerCardPulse: PropTypes.object.isRequired, activeContextLayers: PropTypes.array.isRequired, // Actions loadDatasetData: PropTypes.func.isRequired, loadWidgetData: PropTypes.func.isRequired, setWidget: PropTypes.func.isRequired }; export default LayerCardComponent;
JavaScript
0.000006
@@ -2781,70 +2781,8 @@ l;%0A%0A - console.log('activeContextLayers', activeContextLayers);%0A%0A
99cd4e07c24755ed77ed24e6fb7de034ca214061
Update es6.typed.array-buffer.js
modules/es6.typed.array-buffer.js
modules/es6.typed.array-buffer.js
'use strict'; var $export = require('./_export'); var $typed = require('./_typed'); var buffer = require('./_typed-buffer'); var anObject = require('./_an-object'); var toAbsoluteIndex = require('./_to-absolute-index'); var toLength = require('./_to-length'); var isObject = require('./_is-object'); var ArrayBuffer = require('./_global').ArrayBuffer; var speciesConstructor = require('./_species-constructor'); var $ArrayBuffer = buffer.ArrayBuffer; var $DataView = buffer.DataView; var $isView = $typed.ABV && ArrayBuffer.isView; var $slice = $ArrayBuffer.prototype.slice; var VIEW = $typed.VIEW; var ARRAY_BUFFER = 'ArrayBuffer'; $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer }); $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { // 24.1.3.1 ArrayBuffer.isView(arg) isView: function isView(it) { return $isView && $isView(it) || isObject(it) && VIEW in it; } }); $export($export.P + $export.U + $export.F * require('./_fails')(function () { return !new $ArrayBuffer(2).slice(1, undefined).byteLength; }), ARRAY_BUFFER, { // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) slice: function slice(start, end) { if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix var len = anObject(this).byteLength; var first = toAbsoluteIndex(start, len); var final = toAbsoluteIndex(end === undefined ? len : end, len); var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first)); var viewS = new $DataView(this); var viewT = new $DataView(result); var index = 0; while (first < final) { viewT.setUint8(index++, viewS.getUint8(first++)); } return result; } }); require('./_set-species')(ARRAY_BUFFER);
JavaScript
0.999393
@@ -1397,18 +1397,16 @@ var fin -al = toAbs @@ -1527,18 +1527,16 @@ ngth(fin -al - first @@ -1634,16 +1634,16 @@ ex = 0;%0A + whil @@ -1656,18 +1656,16 @@ st %3C fin -al ) %7B%0A
fa8c1721548a74d40d173743e27ca32cbddea514
The jump is too high
projects/dwlg/main.js
projects/dwlg/main.js
var game = new Phaser.Game(640, 480, Phaser.AUTO, '', { preload: preload, create: create, update: update }); //player var player; var speed = 250; //physics var gravity = 500; //maps var map; var layer; //input var cursors; var jump; var shift; function preload(){ //loads all of the game assets this.load.image('set', 'set.png'); this.load.image('player', 'sprites/Player.png'); this.load.tilemap('map_basic', 'maps/Map_Basic.json', null, Phaser.Tilemap.TILED_JSON); } function create(){ //starts the phaser ARCADE physics game.physics.startSystem(Phaser.Physics.ARCADE); //sets the background color to the hex color #380000 game.stage.backgroundColor = '#380000'; //loads the tilemap, and sets the collision map = this.add.tilemap('map_basic'); map.addTilesetImage('set'); map.setCollisionBetween(0, 100); //adds the map layer layer = map.createLayer('Walls'); layer.resizeWorld(); //uncomment to show the collision boundries //layer.debug = true; //creates the player player = this.add.sprite(200, 200, 'player'); game.physics.arcade.enable(player); player.body.gravity.y = 500; //initializes the cursor keys(arrows) and the space bar cursors = game.input.keyboard.createCursorKeys(); jump = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); shift = game.input.keyboard.addKey(Phaser.Keyboard.SHIFT); } function update(game){ //player and map collisions game.physics.arcade.collide(player, layer); //player velocity is reset to 0 every frame, so that it will not go //infinitly in one direction. player.body.velocity.x = 0; //gets player input, and holds the player controls getPlayerInput(player); } function getPlayerInput(player){ if (cursors.left.isDown){ player.body.velocity.x = -speed; }else if (cursors.right.isDown){ player.body.velocity.x = speed; }else if(cursors.up.isDown){ player.body.gravity.y = -gravity; }else if(cursors.down.isDown){ player.body.gravity.y = gravity; } if(shift.isDown){ speed = 1000; }else{ speed = 500; } if (jump.isDown && player.body.onFloor()){ player.body.velocity.y = -500; } }
JavaScript
0.999957
@@ -2221,18 +2221,18 @@ ty.y = - +1 5 -0 0;%0A %7D
3a1ad0c467e02854c8b8cceda133c698a63fcaca
Update path for local development
fateOfAllFools.dev.user.js
fateOfAllFools.dev.user.js
// ==UserScript== // @author Robert Slifka (GitHub @rslifka) // @connect docs.google.com // @connect rslifka.github.io // @copyright 2017-2018, Robert Slifka (https://github.com/rslifka/fate_of_all_fools) // @description (DEVELOPMENT) Enhancements to the Destiny Item Manager // @grant GM_addStyle // @grant GM_getResourceText // @grant GM_getValue // @grant GM_log // @grant GM_setValue // @grant GM_xmlhttpRequest // @homepage https://github.com/rslifka/fate_of_all_fools // @license MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt // @match https://*.destinyitemmanager.com/* // @name (DEVELOPMENT) Fate of All Fools // @require file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/build/fateOfAllFools.js // @resource fateOfAllFoolsCSS file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/build/fateOfAllFools.css // @run-at document-idle // @supportURL https://github.com/rslifka/fate_of_all_fools/issues // ==/UserScript==
JavaScript
0
@@ -786,37 +786,38 @@ te_of_all_fools/ -build +public /fateOfAllFools. @@ -915,13 +915,14 @@ ols/ -build +public /fat
72fb5795e5344a6df8c91596d177255e5e80c473
Make import-insert.html less flaky
LayoutTests/fast/html/imports/resources/import-helpers.js
LayoutTests/fast/html/imports/resources/import-helpers.js
function waitAndTest(tests) { window.jsTestIsAsync = true; function runNext() { var options = tests.shift(); if (!options) return finishJSTest(); return runSingleTest(options); } function runSingleTest(options) { var ntries = 10; function checkWhenReady() { if (--ntries < 0) { testFailed("Timed out"); return finishJSTest(); } if (!options.ready()) return setTimeout(checkWhenReady, 0); options.test(); return runNext(); } debug(options.description); if (options.setup) options.setup(); checkWhenReady(); } window.setTimeout(runNext, 0); } function createPlaceholder() { var link = document.createElement("link"); link.setAttribute("href", "resources/placeholder.html"); link.setAttribute("rel", "import"); document.head.appendChild(link); return link; }
JavaScript
0.999949
@@ -262,32 +262,58 @@ (options)%0A %7B%0A + var interval = 1;%0A var ntri @@ -321,10 +321,9 @@ s = -10 +8 ;%0A @@ -483,32 +483,59 @@ %0A %7D%0A%0A + interval *= 2;%0A if ( @@ -602,17 +602,24 @@ nReady, -0 +interval );%0A%0A
55e9657309cb9bb26c6846709595c80e2c15bb2e
update sandbox server port
chat/chat.js
chat/chat.js
/** * @overview ccm component for simple chats * @author André Kless <[email protected]> 2016 */ ccm.component( { name: 'chat', config: { html: [ ccm.store, { local: 'templates.json' } ], key: 'test', store: [ ccm.store, { url: 'ws://ccm.inf.h-brs.de:8080/sandbox.js', store: 'chat' } ], style: [ ccm.load, 'style.css' ], user: [ ccm.instance, 'https://kaul.inf.h-brs.de/ccm/components/user.js' ] }, Instance: function () { var self = this; this.init = function ( callback ) { self.store.onChange = function () { self.render(); }; callback(); }; self.render = function ( callback ) { var element = ccm.helper.element( self ); self.store.get( self.key, function ( dataset ) { if ( dataset === null ) self.store.set( { key: self.key, messages: [] }, proceed ); else proceed( dataset ); function proceed( dataset ) { element.html( ccm.helper.html( self.html.get( 'main' ) ) ); var messages_div = ccm.helper.find( self, '.messages' ); for ( var i = 0; i < dataset.messages.length; i++ ) { var message = dataset.messages[ i ]; messages_div.append( ccm.helper.html( self.html.get( 'message' ), { name: ccm.helper.val( message.user ), text: ccm.helper.val( message.text ) } ) ); } messages_div.append( ccm.helper.html( self.html.get( 'input' ), { onsubmit: function () { var value = ccm.helper.val( ccm.helper.find( self, 'input' ).val() ).trim(); if ( value === '' ) return; self.user.login( function () { dataset.messages.push( { user: self.user.data().key, text: value } ); self.store.set( dataset, function () { self.render(); } ); } ); return false; } } ) ); if ( callback ) callback(); } } ); } } } );
JavaScript
0
@@ -274,17 +274,16 @@ s.de:808 -0 /sandbox
49706d3a232a481928711b92c49535a31c828cf5
Allow selectChoose to receive the parentElement of the trigger
test-support/helpers/ember-power-select.js
test-support/helpers/ember-power-select.js
import Ember from 'ember'; import Test from 'ember-test'; import wait from 'ember-test-helpers/wait'; import { click, fillIn, keyEvent, triggerEvent, find, findAll } from 'ember-native-dom-helpers'; /** * @private * @param {String} selector CSS3 selector of the elements to check the content * @param {String} text Substring that the selected element must contain * @returns HTMLElement The first element that maches the given selector and contains the * given text */ export function findContains(selector, text) { return [].slice.apply(findAll(selector)).filter((e) => e.textContent.trim().indexOf(text) > -1)[0]; } export function nativeMouseDown(selectorOrDomElement, options) { triggerEvent(selectorOrDomElement, 'mousedown', options); } export function nativeMouseUp(selectorOrDomElement, options) { triggerEvent(selectorOrDomElement, 'mouseup', options); } export function triggerKeydown(domElement, k) { keyEvent(domElement, 'keydown', k); } export function typeInSearch(scopeOrText, text) { let scope = ''; if (typeof text === 'undefined') { text = scopeOrText; } else { scope = scopeOrText; } let selectors = [ '.ember-power-select-search-input', '.ember-power-select-search input', '.ember-power-select-trigger-multiple-input', 'input[type="search"]' ].map((selector) => `${scope} ${selector}`).join(', '); return fillIn(selectors, text); } export function clickTrigger(scope, options = {}) { let selector = '.ember-power-select-trigger'; if (scope) { selector = `${scope} ${selector}`; } return click(selector, options); } export function nativeTouch(selectorOrDomElement) { triggerEvent(selectorOrDomElement, 'touchstart'); triggerEvent(selectorOrDomElement, 'touchend'); } export function touchTrigger() { nativeTouch('.ember-power-select-trigger'); } // Helpers for acceptance tests export default function() { Test.registerAsyncHelper('selectChoose', async function(_, cssPathOrTrigger, valueOrSelector, optionIndex) { let trigger, target; if (cssPathOrTrigger instanceof HTMLElement) { trigger = cssPathOrTrigger; } else { trigger = find(`${cssPathOrTrigger} .ember-power-select-trigger`); if (!trigger) { trigger = find(cssPathOrTrigger); } if (!trigger) { throw new Error(`You called "selectChoose('${cssPathOrTrigger}', '${valueOrSelector}')" but no select was found using selector "${cssPathOrTrigger}"`); } } let contentId = `${trigger.attributes['aria-owns'].value}`; let content = find(`#${contentId}`); // If the dropdown is closed, open it if (!content || content.classList.contains('ember-basic-dropdown-content-placeholder')) { await click(trigger); await wait(); } // Select the option with the given text let options = [].slice.apply(findAll(`#${contentId} .ember-power-select-option`)); let potentialTargets = options.filter((opt) => opt.textContent.indexOf(valueOrSelector) > -1); if (potentialTargets.length === 0) { // If treating the value as text doesn't gave use any result, let's try if it's a css selector let matchEq = valueOrSelector.slice(-6).match(/:eq\((\d+)\)/); if (matchEq) { let index = parseInt(matchEq[1], 10); let option = findAll(`#${contentId} ${valueOrSelector.slice(0, -6)}`)[index]; Ember.deprecate('Passing selectors with the `:eq()` pseudoselector is deprecated. If you want to select the nth option, pass a number as a third argument. E.g `selectChoose(".language-select", ".ember-power-select-option", 3)`', true, { id: 'select-choose-no-eq-pseudoselector', until: '1.8.0' }); if (option) { potentialTargets = [option]; } } else { potentialTargets = findAll(`#${contentId} ${valueOrSelector}`); } } if (potentialTargets.length > 1) { let filteredTargets = [].slice.apply(potentialTargets).filter((t) => t.textContent.trim() === valueOrSelector); if (optionIndex === undefined) { target = filteredTargets[0] || potentialTargets[0]; } else { target = filteredTargets[optionIndex] || potentialTargets[optionIndex]; } } else { target = potentialTargets[0]; } if (!target) { throw new Error(`You called "selectChoose('${cssPathOrTrigger}', '${valueOrSelector}')" but "${valueOrSelector}" didn't match any option`); } await click(target); return wait(); }); Test.registerAsyncHelper('selectSearch', async function(app, cssPathOrTrigger, value) { let trigger; if (cssPathOrTrigger instanceof HTMLElement) { trigger = cssPathOrTrigger; } else { let triggerPath = `${cssPathOrTrigger} .ember-power-select-trigger`; trigger = find(triggerPath); if (!trigger) { triggerPath = cssPathOrTrigger; trigger = find(triggerPath); } if (!trigger) { throw new Error(`You called "selectSearch('${cssPathOrTrigger}', '${value}')" but no select was found using selector "${cssPathOrTrigger}"`); } } let contentId = `${trigger.attributes['aria-owns'].value}`; let isMultipleSelect = !!find('.ember-power-select-trigger-multiple-input', trigger); let content = find(`#${contentId}`); let dropdownIsClosed = !content || content.classList.contains('ember-basic-dropdown-content-placeholder'); if (dropdownIsClosed) { await click(trigger); await wait(); } let isDefaultSingleSelect = !!find('.ember-power-select-search-input'); if (isMultipleSelect) { await fillIn(find('.ember-power-select-trigger-multiple-input', trigger), value); } else if (isDefaultSingleSelect) { await fillIn('.ember-power-select-search-input', value); } else { // It's probably a customized version let inputIsInTrigger = !!find('.ember-power-select-trigger input[type=search]', trigger); if (inputIsInTrigger) { await fillIn(find('input[type=search]', trigger), value); } else { await fillIn(`#${contentId} .ember-power-select-search-input[type=search]`, 'input'); } } return wait(); }); Test.registerAsyncHelper('removeMultipleOption', async function(app, cssPath, value) { let elem; let items = [].slice.apply(findAll(`${cssPath} .ember-power-select-multiple-options > li`)); let item = items.find((el) => el.textContent.indexOf(value) > -1); if (item) { elem = find('.ember-power-select-multiple-remove-btn', item); } try { await click(elem); return wait(); } catch(e) { console.warn('css path to remove btn not found'); throw e; } }); Test.registerAsyncHelper('clearSelected', async function(app, cssPath) { let elem = find(`${cssPath} .ember-power-select-clear-btn`); try { await click(elem); return wait(); } catch(e) { console.warn('css path to clear btn not found'); throw e; } }); }
JavaScript
0
@@ -2119,35 +2119,212 @@ -trigger = cssPathOrTrigger; +if (cssPathOrTrigger.classList.contains('ember-power-select-trigger')) %7B%0A trigger = cssPathOrTrigger;%0A %7D else %7B%0A trigger = find('.ember-power-select-trigger', cssPathOrTrigger);%0A %7D %0A
e57f745ec1f8fb2a347ef903245b022bc3672248
Remove console.log statement.
website/app/application/core/projects/project/files/files-controller.js
website/app/application/core/projects/project/files/files-controller.js
Application.Controllers.controller("FilesController", ["$scope", "projectFiles", "applySearch", "pubsub", "mcfile", "$state", "pubsub", FilesController]); function FilesController($scope, projectFiles, applySearch, $filter, mcfile, $state, pubsub) { var f = projectFiles.model.projects[$scope.project.id].dir; // Root is name of project. Have it opened by default. $scope.files = [f]; applySearch($scope, "searchInput", applyQuery); function applyQuery() { var search = { name: "" }; if ($scope.searchInput === "") { $scope.files = [projectFiles.model.projects[$scope.project.id].dir]; } else { var filesToSearch = projectFiles.model.projects[$scope.project.id].byMediaType.all; search.name = $scope.searchInput; $scope.files = $filter('filter')(filesToSearch, search); } } $scope.fileSrc = function (file) { return mcfile.src(file.id); }; var columnDefs = [ { displayName: "", field: "name", width: 350, cellClicked: cellClicked, cellRenderer: function (params) { return '<i style="color: #BFBFBF;" class="fa fa-fw fa-file"></i><span>' + '<a data-toggle="tooltip" data-placement="top" title="{{params.node.name}}">' + params.node.name + '</a></span>'; } }]; $scope.gridOptions = { columnDefs: columnDefs, rowData: $scope.files, rowSelection: 'multiple', rowsAlreadyGrouped: true, enableColResize: true, enableSorting: true, rowHeight: 30, angularCompileRows: true, icons: { groupExpanded: '<i style="color: #D2C4D5 " class="fa fa-folder-open"/>', groupContracted: '<i style="color: #D2C4D5 " class="fa fa-folder"/>' }, groupInnerCellRenderer: groupInnerCellRenderer }; //groupInnerCellRenderer does not have ability to add ng click. So as // an alternative i used event listener to display the data directory function groupInnerCellRenderer(params) { var eCell = document.createElement('span'); eCell.innerHTML = params.node.displayname; eCell.addEventListener('click', function () { projectFiles.setActiveDirectory(params.node); if ($state.current.name === 'projects.project.files') { console.log('yeah'); $state.go('projects.project.files.edit', {'file_id': ''}); } else { pubsub.send('display-directory'); } }); return eCell; } function cellClicked(params) { projectFiles.setActiveFile(params.node); $state.go('projects.project.files.edit', {'file_id': params.node.df_id}); } }
JavaScript
0
@@ -2498,45 +2498,8 @@ ) %7B%0A - console.log('yeah');%0A
1cc390262adb5c03968aee1753bcd1e8aad3b604
Fix problem launching app with webpack
webpack.config.base.js
webpack.config.base.js
/** * Base webpack config used across other specific configs */ const path = require('path'); const validate = require('webpack-validator'); const config = validate({ entry: [ 'babel-polyfill', './views/components/App.jsx' ], module: { loaders: [{ test: /\.jsx?$/, loaders: ['babel-loader'], exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }] }, output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', // https://github.com/webpack/webpack/issues/1114 libraryTarget: 'commonjs2' }, // https://webpack.github.io/docs/configuration.html#resolve resolve: { extensions: ['', '.js', '.jsx', '.json'], packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'] }, plugins: [], externals: [ // put your node 3rd party libraries which can't be built with webpack here // (mysql, mongodb, and so on..) ] }); module.exports = config;
JavaScript
0.000315
@@ -214,19 +214,8 @@ ews/ -components/ App.
ee6afcec0e84f449d0abe09c64b42c2f76bad42a
Update config.js
featurescape/fun/config.js
featurescape/fun/config.js
console.log('config.js'); var config = { domain: 'http://sbu-bmi.github.io/FeatureScapeApps', //domain: 'http://localhost:63342/FeatureScapeApps', //findAPI: 'https://falcon.bmi.stonybrook.edu', findAPI: 'http://quip1.uhmc.sunysb.edu', port: 4000, quipUrl: 'http://quip.bmi.stonybrook.edu/camicroscope_latest/osdCamicroscope.php', reserve4Url: 'http://reserve4.informatics.stonybrook.edu/dev1/osdCamicroscope.php', analysis_execution_id: 'luad:20160215', imgcoll: 'quip_images', quot: "%22", mongoUrl: 'mongodb://172.17.0.1:27015/u24_version3' };
JavaScript
0.000002
@@ -530,16 +530,18 @@ 2%22,%0A +// mongoUrl
0b05f0e00c1e4a53c0e3df531e1013cebe584ec1
allow webpack to resolve .json (#1672)
webpack.config.base.js
webpack.config.base.js
// Copyright (c) 2015-2016 Yuya Ochiai // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // This file uses CommonJS. /* eslint-disable import/no-commonjs */ 'use strict'; const childProcess = require('child_process'); const webpack = require('webpack'); const path = require('path'); const VERSION = childProcess.execSync('git rev-parse --short HEAD').toString(); const isProduction = process.env.NODE_ENV === 'production'; const codeDefinitions = { __HASH_VERSION__: JSON.stringify(VERSION), }; codeDefinitions['process.env.NODE_ENV'] = JSON.stringify(process.env.NODE_ENV); module.exports = { // Some plugins cause errors on the app, so use few plugins. // https://webpack.js.org/concepts/mode/#mode-production mode: isProduction ? 'none' : 'development', plugins: [ new webpack.DefinePlugin(codeDefinitions), ], devtool: isProduction ? false : '#inline-source-map', resolve: { alias: { renderer: path.resolve(__dirname, 'src/renderer'), main: path.resolve(__dirname, './src/main'), common: path.resolve(__dirname, './src/common'), static: path.resolve(__dirname, './src/assets'), }, extensions: ['.ts', '.tsx', '.js', '.jsx'], }, }; /* eslint-enable import/no-commonjs */
JavaScript
0
@@ -1302,16 +1302,25 @@ , '.jsx' +, '.json' %5D,%0A %7D
417664c790c6220c1ef9982b6db86a94dc427ef8
add a css class to the view pills
webapp/src/main/webapp/app/cockpit/directives/viewPills.js
webapp/src/main/webapp/app/cockpit/directives/viewPills.js
ngDefine('cockpit.directives', [ 'angular' ], function(module, angular) { 'use strict'; module.directive('viewPills', [ '$location', 'Views', function($location, Views) { var ViewPillsController = [ '$scope', 'Views', '$location', function($scope, Views, $location) { var providers = Views.getProviders({ component: $scope.id }); $scope.providers = providers; $scope.isActive = function(provider) { return $location.path().indexOf('/' + provider.id) != -1; }; $scope.getUrl = function(provider) { return '#' + $location.path().replace(/[^\/]*$/, provider.id); }; }]; return { restrict: 'EAC', scope: { id: '@' }, template: '<ul class="nav nav-pills">' + ' <li ng-repeat="provider in providers" ng-class="{ active: isActive(provider) }"><a ng-href="{{ getUrl(provider) }}">{{ provider.label }}</a></li>' + '</ul>', replace: true, controller: ViewPillsController }; }]); });
JavaScript
0.000001
@@ -1,8 +1,37 @@ +/* global ngDefine: false */%0A ngDefine @@ -58,19 +58,8 @@ ', %5B - 'angular' %5D, f @@ -76,17 +76,8 @@ dule -, angular ) %7B%0A @@ -130,64 +130,23 @@ ', %5B - '$location', 'Views', function($location, Views) %7B%0A +%0A function() %7B %0A @@ -173,16 +173,22 @@ ller = %5B +%0A '$scope @@ -189,16 +189,22 @@ $scope', +%0A 'Views' @@ -204,16 +204,22 @@ 'Views', +%0A '$locat @@ -223,16 +223,20 @@ cation', +%0A functio @@ -714,17 +714,16 @@ emplate: - %0A'%3Cul cl @@ -828,17 +828,52 @@ ider) %7D%22 -%3E + class=%22%7B%7B provider.id %7D%7D%22%3E' +%0A' %3Ca ng-hr @@ -924,16 +924,23 @@ l %7D%7D%3C/a%3E +' +%0A' %3C/li%3E' + @@ -1025,8 +1025,9 @@ %7D%5D);%0A%7D); +%0A
a0661224a0fbff6b6b0df891538f7e6ee290f9f7
Increase delay on live search fields
lib/assets/javascripts/magic_grid.js
lib/assets/javascripts/magic_grid.js
// vim: ts=4 et sw=4 sts=4 $(function () { // Micro-plugin for positioning the cursor $.fn.setCursor = $.fn.setCursor || function(pos) { return this.each(function() { if (this.setSelectionRange) { this.focus(); this.setSelectionRange(pos, pos); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }); }; // Micro-plugin for getting the position of the cursor $.fn.getCursor = $.fn.getCursor || function () { // IE doesn't have selectionStart, and I'm too lazy to implement // the IE specific version of this, so we'll just assume // the cursor is at the end of the input for this case. if (typeof this[0].selectionStart === 'undefined') { return this.value.length; } else { return this[0].selectionStart; } }; $(".magic_grid[data-remote=true]").on( "click", ".pagination a, .sorter a", function (e) { var $a = $(this), $container = $a.closest(".magic_grid[data-remote=true]"), url = $a.attr('href'); $a.addClass("ui-icon-spinner"); $container.load(url + ' #' + $container.attr('id') + " > *"); return false; }); $(".magic_grid[data-searcher]").each( function () { var $grid = $(this), grid_id = this.id, input_id = "#" + $grid.data("searcher"), live = $grid.data("live-search"), // keydown seems to be the only reliable and portable way to capture // things like backspace and delete events = (live ? "keydown change search" : "change search"), timer = null, minLength = $(input_id).data("min-length") || 3, current = $(input_id).val(); $grid.parent().on(events, input_id, function (e) { var is_manual = (e.type == 'search' || e.type == 'change' || (e.type == 'keydown' && e.which == '13') ), base_url = $grid.data("current"), params = {'magic_grid_id' : grid_id}, //40 wpm typists == 280ms //90 wpm typists == 120ms delay = is_manual ? 1 : 250; clearTimeout(timer); timer = setTimeout(function () { var $input = $(input_id), value = $input.val(), length = value.length, url = base_url + "?", relevant = is_manual || (value != current && (length >= minLength || length == 0)), pos = $input.getCursor(); clearTimeout(timer); params[grid_id + "_q"] = value; url += $.param(params); if (relevant) { if ($grid.data("remote")) { $(input_id).prop('disabled', true); $grid.load(url + ' #' + grid_id + ' > *', function () { // Move the cursor back to where it was, // less surprising that way. current = $(input_id).setCursor(pos).val(); }); } else { window.location = url; } } }, delay); e.stopImmediatePropagation(); //return (!!timer); }); }); $(".magic_grid[data-listeners]").each( function () { var $grid = $(this), listeners = $grid.data("listeners"), grid_id = this.id base_url = $grid.data("current"), get_values = function () { var $input, key, params = {}; for (var k in listeners) { key = listeners[k]; $input = $("#" + k); if ($input.is(":checkbox")) { params[key] = $input.is(":checked"); } else if ($input.is("select")) { params[key] = $input.find("option:selected").val(); } else { params[key] = $input.val(); } } return params; }, handler = function (change) { var url = base_url + "?" + $.param(get_values()); if ($grid.data("remote")) { $grid.load(url + ' #' + grid_id + " > *"); } else { window.location = url; } }; for (var k in listeners) { if ($("#" + k).hasClass("ready")) { $("#" + k).on("change", {"field": listeners[k]}, handler); } else { $("#" + k).on("ready", {"field": listeners[k]}, function (ready) { $(this).on("change", ready.data, handler); }); } } }); });
JavaScript
0
@@ -2409,16 +2409,26 @@ == 280ms +/keystroke %0A @@ -2461,16 +2461,26 @@ == 120ms +/keystroke %0A @@ -2516,10 +2516,10 @@ 1 : -2 5 +0 0;%0A
fcf65d2dd7e98a182e037d8d9e385a1c4708b7bf
Fix error reporting/returning when ensuring indices exist
webapplication/indexing/initialize/elastic-search-index.js
webapplication/indexing/initialize/elastic-search-index.js
'use strict'; /** * This initializes the ElasticSearch index. * * @param {Object} state The state of which we are about to initialize. */ const es = require('../../lib/services/elasticsearch'); const config = require('../../../shared/config'); const seriesMapping = { properties: { url: { type: 'keyword' }, title: { type: 'text', }, description: {type: 'text'}, tags: {type: 'text'}, assets: {type: 'keyword'}, dateFrom: { type: 'object', properties: { timestamp: { type: 'date' } } }, dateTo: { type: 'object', properties: { timestamp: { type: 'date' } } } } }; module.exports = (state) => { // Save the index in the context state.context.index = config.es.assetIndex; //TODO: replace all through with both indexes -- or remove use altogether seeing as index is from config console.log('Initializing the Elastic Search index: ' + state.context.index); return Promise.all([ es.indices.exists({index: config.es.assetIndex}), es.indices.exists({index: config.es.seriesIndex}), ]) .then(([{body: assetIndexExists}, {body: seriesIndexExists}]) => { const indicesToCreate = []; if(!assetIndexExists) { indicesToCreate.push({ index: config.es.assetIndex, mappings: getAssetMapping(), }); } if(!seriesIndexExists) { indicesToCreate.push({ index: config.es.seriesIndex, mappings: seriesMapping, }); } if(indicesToCreate.length < 1) { return state; } return Promise.all(indicesToCreate.map((def) => createIndex(def))) .then(() => { console.log('Indices created:', indicesToCreate); return state; }); }); //TODO: move createIndex and getAssetMapping top level function createIndex({index, mappings}) { return es.indices.create({ index, body: { settings: { max_result_window: 100000 // So sitemaps can access all assets }, mappings, }, }) .then(function() { console.log('Index created.'); return state; }, function(err) { // TODO: Add a recursive check for this message. if (err.message === 'No Living connections') { throw new Error('Is the Elasticsearch server running?'); } else { throw err; } }); } function getAssetMapping() { let fields = config.types.asset.mapping || {}; fields.id = { type: 'keyword', fields: { raw: { type: 'text', index: false, }, }, }; fields.series_ids = { type: 'keyword', }; // Get all fields that needs a raw value included in the index config.types.asset.fields .filter((field) => field.includeRaw) .forEach((field) => { fields[field.short] = { type: 'keyword', fields: { raw: { type: 'text', index: false, }, }, }; }); // Derive mappings from the asset field types // First the fields with date types config.types.asset.fields .filter((field) => field.type === 'date') .forEach((field) => { fields[field.short] = { type: 'object', properties: { timestamp: {type: 'date'}, }, }; }); // Enumurations should not have their displaystring tokenized config.types.asset.fields .filter((field) => field.type === 'enum') .forEach((field) => { fields[field.short] = { type: 'object', properties: { displaystring: { type: 'text', index: false, } } }; }); return {properties: fields}; } };
JavaScript
0
@@ -2149,23 +2149,24 @@ . -then(function() +catch((error) =%3E %7B%0A @@ -2184,304 +2184,156 @@ ole. -log('Index created.');%0A return state;%0A %7D, function(err) %7B%0A // TODO: Add a recursive check for this message.%0A if (err.message === 'No Living connections') %7B%0A throw new Error('Is the Elasticsearch server running?');%0A %7D else %7B%0A throw err;%0A %7D +error('Error while creating index', index);%0A console.dir(mappings, %7Bdepth: 10%7D);%0A console.dir(error, %7Bdepth:10%7D);%0A throw error; %0A
4410d00af624cae1e5c01d62ed3b60fe5da44c05
remove unused test properties
test/integration/init-test.js
test/integration/init-test.js
'use strict'; const fs = require('fs-extra'); const path = require('path'); const { describe, it } = require('../helpers/mocha'); const { expect } = require('../helpers/chai'); const { buildTmp, processExit, fixtureCompare: _fixtureCompare } = require('git-fixtures'); const init = require('../../src/init'); const run = require('../../src/run'); const { assertNoStaged } = require('../helpers/assertions'); describe(init, function() { this.timeout(5 * 60 * 1000); let cwd; let tmpPath; before(function() { cwd = process.cwd(); }); afterEach(function() { process.chdir(cwd); }); async function merge({ fixturesPath, blueprint, from, to = '3.2.0-beta.1', reset, compareOnly, statsOnly, runCodemods, listCodemods, createCustomDiff, commitMessage, beforeMerge = () => Promise.resolve(), afterMerge = () => Promise.resolve() }) { tmpPath = await buildTmp({ fixturesPath, commitMessage }); await beforeMerge(); process.chdir(tmpPath); let promise = init({ blueprint, from, to, reset, compareOnly, statsOnly, runCodemods, listCodemods, createCustomDiff }).then(afterMerge); return await processExit({ promise, cwd: tmpPath, commitMessage, expect }); } function fixtureCompare({ mergeFixtures }) { let actual = tmpPath; let expected = path.join(cwd, mergeFixtures); _fixtureCompare({ expect, actual, expected }); } it('can initialize the default blueprint', async function() { let { status } = await merge({ fixturesPath: 'test/fixtures/app/local', commitMessage: 'my-app', reset: true, async afterMerge() { expect(path.join(tmpPath, 'ember-cli-update.json')).to.be.a.file() .and.equal(path.join(cwd, 'test/fixtures/ember-cli-update-json/default/ember-cli-update.json')); await run('git rm --cached ember-cli-update.json', { cwd: tmpPath }); await fs.remove(path.join(tmpPath, 'ember-cli-update.json')); } }); fixtureCompare({ mergeFixtures: 'test/fixtures/app/reset/my-app' }); expect(status).to.match(/^ D app\/controllers\/application\.js$/m); assertNoStaged(status); }); });
JavaScript
0.000001
@@ -655,33 +655,8 @@ th,%0A - blueprint,%0A from,%0A @@ -698,150 +698,18 @@ com -pareOnly,%0A statsOnly,%0A runCodemods,%0A listCodemods,%0A createCustomDiff,%0A commitMessage,%0A beforeMerge = () =%3E Promise.resolve() +mitMessage ,%0A @@ -838,34 +838,8 @@ );%0A%0A - await beforeMerge();%0A%0A @@ -898,151 +898,23 @@ -blueprint,%0A from,%0A to,%0A reset,%0A compareOnly,%0A statsOnly,%0A runCodemods,%0A listCodemods,%0A createCustomDiff +to,%0A reset %0A
ce7da40d354785543e91b7a5ae7ba26c1abc6a28
Remove old entries from webpack.test.config.js
webpack.test.config.js
webpack.test.config.js
const commonConfig = require('./webpack.common'); const path = require('path'); module.exports = Object.assign(commonConfig, { entry: { test: './test/index.js', 'sandbox-basic': './sandbox/basic.js', 'sandbox-dom': './sandbox/dom.js', 'sandbox-multirender': './sandbox/multirender.js' }, output: { path: path.join(__dirname, 'dist'), publicPath: '/assets/', filename: '[name].js' }, devServer: { port: 9010 } });
JavaScript
0.000002
@@ -163,145 +163,8 @@ .js' -,%0A 'sandbox-basic': './sandbox/basic.js',%0A 'sandbox-dom': './sandbox/dom.js',%0A 'sandbox-multirender': './sandbox/multirender.js' %0A %7D
eed5fe0dc6bf80dfa75e35bbec15be12b804adfb
Fix test issue
test/e2e/Tests/TasksNumberDecrease.spec.js
test/e2e/Tests/TasksNumberDecrease.spec.js
var TaskList = require('../POMs/TasksList.js'); describe('Check that tasks count decreases after marking tasks completed', function () { beforeAll(function() { TaskList.actionsBeforeAll(); }); it('Verify that tasks count decreases after marking tasks completed', function () { //Adding two new task let timestamp = new Date(); let firstTaskName = 'first test task name ' + timestamp.toString; let secondTaskName = 'second test task name ' + timestamp.toString; TaskList.addTask(firstTaskName); TaskList.addTask(secondTaskName); //Verify that count is "2" TaskList.tasksCountNumber(2); //Clicking on checkbox for the first task, it will make it completed TaskList.checkBtnGeneral.get(0).click(); //Verify that count becomes "1" TaskList.tasksCountNumber(1); //Clicking on checkbox for the second task, it will make it completed TaskList.checkBtnGeneral.get(1).click(); //Verify that count becomes "0" TaskList.tasksCountNumber(0); }); afterEach(function() { //Deleting all existing tasks before each spec to avoid conflicts TaskList.clearAllTasks(); }); });
JavaScript
0.000003
@@ -313,19 +313,19 @@ ask%0A -let +var timesta @@ -345,19 +345,19 @@ ();%0A -let +var firstTa @@ -413,17 +413,19 @@ ring +() ;%0A -let +var sec @@ -483,16 +483,18 @@ toString +() ;%0A%0A T
03cf75d1ffe66ce09e10067a4dd69b2dbe87eee7
move plugin in the optimizations section
webpack/prod.config.js
webpack/prod.config.js
import webpack from 'webpack' import _debug from 'debug' import WebpackIsomorphicToolsPlugin from 'webpack-isomorphic-tools/plugin' import ExtractTextPlugin from 'extract-text-webpack-plugin' import CleanWebpackPlugin from 'clean-webpack-plugin' import isomorphicToolsConfig from './isomorphic.tools.config' import projectConfig, { paths } from '../config' const webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(isomorphicToolsConfig) const debug = _debug('app:webpack:config:prod') const srcDir = paths('src') const nodeModulesDir = paths('nodeModules') const globalStylesDir = paths('globalStyles') const cssLoader = [ 'css?modules', 'sourceMap', 'importLoaders=1', 'localIdentName=[name]__[local]___[hash:base64:5]' ].join('&') const { VENDOR_DEPENDENCIES, __CLIENT__, __SERVER__, __DEV__, __PROD__, __DEBUG__ } = projectConfig debug('Create configuration.') const config = { context: paths('base'), devtool: 'source-ma', entry: { app: paths('entryApp'), vendors: VENDOR_DEPENDENCIES }, output: { path: paths('dist'), filename: '[name]-[hash].js', publicPath: '/dist/' }, resolve: { root: [srcDir], extensions: ['', '.js', '.jsx'] }, module: { loaders: [ { test: /\.js[x]?$/, loader: 'babel', exclude: [nodeModulesDir], include: [srcDir], query: { cacheDirectory: true } }, { test: /\.json$/, loader: 'json' }, { test: webpackIsomorphicToolsPlugin.regular_expression('styles'), include: [srcDir], exclude: [globalStylesDir], loader: ExtractTextPlugin.extract('style', `${cssLoader}!postcss`) }, { test: /common\/styles\/global\/app\.css$/, include: [srcDir], loader: ExtractTextPlugin.extract('style', 'css?sourceMap!postcss') }, { test: /\.(woff|woff2|eot|ttf|svg)(\?v=\d+\.\d+\.\d+)?$/, loader: 'file?name=fonts/[name].[ext]' }, { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url?limit=10000' } ] }, postcss: wPack => ([ require('postcss-import')({ addDependencyTo: wPack }), require('postcss-url')(), require('postcss-cssnext')() ]), plugins: [ new CleanWebpackPlugin(['static/dist'], { root: paths('base') }), new ExtractTextPlugin('[name].[contenthash].css', { allChunks: true }), new webpack.DefinePlugin({ __CLIENT__, __SERVER__, __DEV__, __PROD__, __DEBUG__ }), new webpack.optimize.CommonsChunkPlugin('vendors', '[name].[hash].js'), // optimizations new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, screw_ie8: true, sequences: true, dead_code: true, drop_debugger: true, comparisons: true, conditionals: true, evaluate: true, booleans: true, loops: true, unused: true, hoist_funs: true, if_return: true, join_vars: true, cascade: true, drop_console: true }, output: { comments: false } }), webpackIsomorphicToolsPlugin ] } export default config
JavaScript
0.000001
@@ -2610,84 +2610,8 @@ %7D), -%0A new webpack.optimize.CommonsChunkPlugin('vendors', '%5Bname%5D.%5Bhash%5D.js'), %0A%0A @@ -3241,24 +3241,100 @@ %7D%0A %7D), +%0A new webpack.optimize.CommonsChunkPlugin('vendors', '%5Bname%5D.%5Bhash%5D.js'), %0A%0A webpac
ee44e8a291a6ae93a3f041872a760a08f8d5b470
Add custom event triggers `trigger()`
dom/events.js
dom/events.js
/* eslint-disable no-underscore-dangle */ import {splitStringValue} from "./utils"; /** * Registers an event listener for the given events * * @param {HTMLElement|HTMLElement[]} element * @param {string|string[]} type * @param {function(*):*} handler */ export function on (element, type, handler) { const list = Array.isArray(element) ? element : [element]; const types = splitStringValue(type); for (let i = 0; i < list.length; i++) { for (let j = 0; j < types.length; j++) { const node = list[i]; const eventType = types[j]; node.addEventListener(eventType, handler); if (typeof node._listeners === "undefined") { node._listeners = {}; } if (typeof node._listeners[eventType] === "undefined") { node._listeners[eventType] = []; } node._listeners[eventType].push(handler); } } } /** * Removes an event listener for the given events * * @param {HTMLElement|HTMLElement[]} element * @param {string|string[]} type * @param {function(*):*} handler */ export function off (element, type, handler) { const list = Array.isArray(element) ? element : [element]; const types = splitStringValue(type); for (let i = 0; i < list.length; i++) { for (let j = 0; j < types.length; j++) { const node = list[i]; const eventType = types[j]; node.removeEventListener(eventType, handler); if (typeof node._listeners !== "undefined" && typeof node._listeners[eventType] !== "undefined") { const index = node._listeners[eventType].indexOf(handler); if (-1 !== index) { node._listeners[eventType].splice(index, 1); } } } } } /** * Registers an event listener, that it automatically is removed after it was executed once. * * Returns the intermediate function, so that the event listener can be removed: * * const intermediate = once(element, event, handler); * off(element, event, intermediate); * * @param {HTMLElement} element * @param {string} type * @param {function(*):*} handler * @return {function():*} */ export function once (element, type, handler) { const intermediate = (...args) => { handler(...args); off(element, type, intermediate); }; on(element, type, intermediate); return intermediate; } /** * Registers an event listener, that it automatically is removed after it was executed once. * * Returns the intermediate function, so that the event listener can be removed: * * const intermediate = once(element, event, handler); * off(element, event, intermediate); * * @param {HTMLElement} element * @param {string} selector * @param {string} type * @param {function(*):*} handler * @return {function():*} */ export function live (element, selector, type, handler) { const intermediate = (event) => { if (event.target.matches(selector)) { handler(event); } }; on(element, type, intermediate); return intermediate; }
JavaScript
0
@@ -3237,28 +3237,995 @@ %0A return intermediate;%0A%7D%0A +%0A%0A/**%0A * Dispatches an event%0A *%0A * @param %7BHTMLElement%7D element%0A * @param %7Bstring%7D type%0A * @param %7B*%7D data%0A */%0Aexport function trigger (element, type, data = null)%0A%7B%0A const event = createEvent(type, %7B%0A bubbles: true,%0A cancelable: true,%0A preventDefault: false,%0A detail: data,%0A %7D);%0A%0A element.dispatchEvent(event);%0A%7D%0A%0A%0A/**%0A * Creates an event%0A *%0A * @private%0A * @param %7Bstring%7D type%0A * @param %7BCustomEventInit%7C%7Bbubbles: boolean, cancelable: boolean, preventDefault: boolean, detail: *%7D%7D args%0A * @return %7BCustomEvent%7D%0A */%0Afunction createEvent (type, args)%0A%7B%0A // @legacy IE %3C= 11 doesn't support the global CustomEvent%0A if (typeof window.CustomEvent !== %22function%22)%0A %7B%0A /** @type %7BCustomEvent%7CEvent%7D event */%0A const event = document.createEvent('CustomEvent');%0A event.initCustomEvent(type, args.bubbles, args.cancelable, args.detail);%0A return event;%0A %7D%0A%0A return new CustomEvent(type, args);%0A%7D%0A
758876ebccf1551b71203f661106e3ff8a2f3ddf
set screen size for tests to be just smaller than our mac displays (which are 1440x900)
test/e2e/utils/protractor.configuration.js
test/e2e/utils/protractor.configuration.js
exports.getConfig = function(options) { var config = { sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, framework: 'jasmine2', capabilities: { //browserName: 'internet explorer', //browserName: 'firefox', browserName: 'chrome', version: 'latest', //to specify the browser version timeZone: 'Los Angeles', // specify the timezone the browser should execute in //using firefox causes problems - not showing the right result and - //Apache log shows firefox is not requesting the server. 'chromeOptions' : { args: ['--lang=en', '--window-size=1920,1920'], // Set download path and avoid prompting for download even though // this is already the default on Chrome but for completeness prefs: { download: { 'prompt_for_download': false, 'default_directory': process.env.PWD + "/test/e2e/" } } }, 'os': 'MacOS El Capitan 10.11', 'platform': 'OS X 10.11', 'screenResolution': '1920x1440' }, specs: [ '*.spec.js' ], jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 300000, print: function() {} }, params: { // defaultTimeout: Used in tests where Protractor needs to wait for an element or where // the browser needs to do nothing for a while. Should not be >= 90000 since // Sauce Labs wil end the a session if it hasn't received a command from // test script in 90 seconds. defaultTimeout: 15000 } }; Object.assign(config, options); if (!options.configFileName && !options.testConfiguration) throw new Error("No configfile provided in protractor.conf.js"); var testConfiguration = options.testConfiguration; if (options.configFileName) { var configFileName = options.configFileName; if(options.manualTestConfig) { testConfiguration = require('../../manual/data_setup/config/' + configFileName); } else { testConfiguration = require('../data_setup/config/' + configFileName); } } var dataSetup = require('./protractor.parameterize.js'); // Look through schemaConfigurations, if any are strings (filenames), grab the json file and insert into the schemaConfigs array var schemaConfigs = testConfiguration.setup.schemaConfigurations; for (var i = 0; i < schemaConfigs.length; i++) { var schemaConfig = schemaConfigs[i]; if (typeof schemaConfig === 'string') { if(options.manualTestConfig) { schemaConfigs[i] = require(process.env.PWD + "/test/manual/data_setup/config/" + schemaConfig); } else { schemaConfigs[i] = require(process.env.PWD + "/test/e2e/data_setup/config/" + schemaConfig); } } } var dateSetupOptions = { testConfiguration: testConfiguration }; if (options.page) dateSetupOptions.page = options.page; if (typeof options.setBaseUrl == 'function') { dateSetupOptions.setBaseUrl = function(browser, data) { options.setBaseUrl(browser, data); } } var chaiseFilePath = "chaise-config-sample.js"; if (typeof options.chaiseConfigFilePath === 'string') { try { var fs = require('fs'); fs.accessSync(process.env.PWD + "/" + options.chaiseConfigFilePath); chaiseFilePath = options.chaiseConfigFilePath; } catch (e) { console.log("Config file " + options.chaiseConfigFilePath + " doesn't exists"); } } var execSync = require('child_process').execSync; var remoteChaiseDirPath = process.env.REMOTE_CHAISE_DIR_PATH; var cmd = 'sudo cp ' + ("/var/www/html/chaise/" + chaiseFilePath) + " " + ("/var/www/html/chaise/chaise-config.js"); // The tests will take this path when it is not running on Travis and remoteChaseDirPath is not null if (typeof remoteChaiseDirPath == 'string') { cmd = 'scp ' + chaiseFilePath + ' ' + remoteChaiseDirPath + '/chaise-config.js'; console.log("Copying using scp"); } else { console.log("Copying using cp on Travis"); } var code = execSync(cmd); console.log(code); if (code == 0) console.log("Copied file " + chaiseFilePath + " successfully to chaise-config.js \n"); else { console.log("Unable to copy file " + chaiseFilePath + " to chaise-config.js \n"); process.exit(1); } config.capabilities.shardTestFiles = (process.env.SHARDING == 'false' || process.env.SHARDING == false) ? false : true; config.capabilities.maxInstances = process.env.MAXINSTANCES || 4; if (options.parallel == false) { config.capabilities.shardTestFiles = false; } dataSetup.parameterize(config, dateSetupOptions); return config; };
JavaScript
0
@@ -661,14 +661,13 @@ ze=1 -920,19 +280,7 20'%5D
f078ed4dfc8331dbe47fe94f785bb48382b34283
Remove Loadable from Stop (web)
web/src/index.js
web/src/index.js
import React, { Fragment } from 'react'; import { render } from 'react-dom'; import { BrowserRouter, Switch, Route } from 'react-router-dom'; import { TransitionGroup, CSSTransition } from 'react-transition-group'; import Loadable from 'react-loadable'; import Map from 'containers/Map'; import NavBar from 'components/NavBar/NavBar'; import Loading from 'components/Loading/Loading'; import './index.css'; const Search = Loadable({ loader: () => import('containers/Search/Search'), loading: Loading }); const Favorites = Loadable({ loader: () => import('containers/Favorites/Favorites'), loading: Loading }); const Settings = Loadable({ loader: () => import('containers/Settings/Settings'), loading: Loading }); const Stop = Loadable({ loader: () => import('containers/Stop/Stop'), loading: Loading }); init(); async function init() { window.stops = await (await fetch('https://bussiaeg.ee/getstops?lat_min=60.0&lng_min=60.0&lat_max=20.0&lng_max=20.0')).json(); render(( <BrowserRouter> <Fragment> <Route render={({ location }) => ( <TransitionGroup id="pages" className={location.pathname === '/' ? 'is-empty' : ''}> <CSSTransition key={location.pathname} classNames="page" timeout={250}> <div id="page"> <Switch location={location}> <Route path="/search" component={Search} /> <Route path="/favorites" component={Favorites} /> <Route path="/settings" component={Settings} /> <Route path="/stop" component={Stop} /> </Switch> </div> </CSSTransition> </TransitionGroup> )} /> <Map /> <NavBar /> </Fragment> </BrowserRouter> ), document.getElementById('root')); }
JavaScript
0
@@ -252,42 +252,8 @@ ';%0A%0A -import Map from 'containers/Map';%0A impo @@ -344,16 +344,91 @@ oading'; +%0Aimport Map from 'containers/Map';%0Aimport Stop from 'containers/Stop/Stop'; %0A%0Aimport @@ -763,102 +763,8 @@ );%0A%0A -const Stop = Loadable(%7B%0A%09loader: () =%3E import('containers/Stop/Stop'),%0A%09loading: Loading%0A%7D);%0A%0A init
43745715d5f1861e178ea1c8bceec1ea51f3d57b
Enforce peerDependencies via defaults (#64)
src/tasks/package.js
src/tasks/package.js
const { json, install } = require('mrm-core'); const packages = [ // Utilities 'nsp', 'del-cli', 'cross-env', 'standard-version', // Jest 'jest', 'babel-jest', // Babel 'babel-cli', 'babel-polyfill', 'babel-preset-env', 'babel-plugin-transform-object-rest-spread', // ESLint 'eslint', 'eslint-plugin-import', 'eslint-config-webpack', 'lint-staged', 'pre-commit', ]; module.exports = (config) => { json('package.json') .merge({ main: 'dist/cjs.js', files: [ 'dist', ], engines: { // Some versions are skipped because of known issues, see https://github.com/webpack-contrib/organization/issues/7 node: `>= ${config.minNode} < 5.0.0 || >= 5.10`, }, scripts: { start: 'npm run build -- -w', 'appveyor:test': 'npm run test', build: "cross-env NODE_ENV=production babel src -d dist --ignore 'src/**/*.test.js'", clean: 'del-cli dist', lint: 'eslint --cache src test', 'lint-staged': 'lint-staged', prebuild: 'npm run clean', prepublish: 'npm run build', release: 'standard-version', security: 'nsp check', test: 'jest', 'test:watch': 'jest --watch', 'test:coverage': "jest --collectCoverageFrom='src/**/*.js' --coverage", 'travis:lint': 'npm run lint && npm run security', 'travis:test': 'npm run test -- --runInBand', 'travis:coverage': 'npm run test:coverage -- --runInBand', }, 'pre-commit': 'lint-staged', 'lint-staged': { '*.js': ['eslint --fix', 'git add'], }, }) .save() ; install(packages); };
JavaScript
0
@@ -738,24 +738,113 @@ %60,%0A %7D,%0A + peerDependencies: %7B%0A webpack: '%5E2.0.0 %7C%7C %3E= 3.0.0-rc.0 %7C%7C %5E3.0.0',%0A %7D,%0A script
f2cdd2bb052d3eb3b6343deb5b24347fa6a5bae6
revert bump task
src/tasks/release.js
src/tasks/release.js
import gulp from 'gulp'; import header from 'gulp-header'; import size from 'gulp-size'; import bump from 'gulp-bump'; import git from 'gulp-git'; gulp.task('tag', (done) => { var pkg = require(process.cwd() + '/package.json'), v = 'v' + pkg.version, message = 'Release ' + v; gulp.src('./*') .pipe(git.commit(message)) .pipe(gulp.dest('./')) .on('end', tag); function tag () { git.tag(v, message); git.push('origin', 'master', { args: '--tags' }); done(); } }); gulp.task('bump', (params) => { gulp.src('./package.json') .pipe(bump({ type: gulp.env.type })) .pipe(gulp.dest('./')); }); gulp.task('release', () => { // Since this is dynamic we need to use a regular old require here var banner = getBannerText(require(process.cwd() + '/package.json')); gulp.src('dist/stylesheets/*.css') .pipe(header(banner, { pkg: pkg })) .pipe(gulp.dest('dist/stylesheets')) .pipe(size()); gulp.src('dist/*.module.js') .pipe(header(banner, { pkg: pkg })) .pipe(gulp.dest('dist')) .pipe(size()); }); /** * Return a formatted string to put in the banner. * @return {[type]} [description] * * @todo Check that all params exist in package.json */ function getBannerText(pkg) { return `/**, * <%= pkg.name %> - <%= pkg.description %>, * @version v<%= pkg.version %>, * @author <%= pkg.author %>, */ `; }
JavaScript
0.000017
@@ -562,98 +562,406 @@ p', -(params) =%3E %7B%0A gulp.src('./package.json')%0A .pipe(bump(%7B type: gulp.env.type %7D +function() %7B%0A bumpHelper(%7B%7D);%0A%7D);%0A%0A gulp.task('bump:patch', function() %7B%0A bumpHelper(%7B%7D);%0A %7D);%0A%0A gulp.task('bump:minor', function() %7B%0A bumpHelper(%7Btype: 'minor'%7D);%0A %7D);%0A%0A gulp.task('bump:major', function() %7B%0A bumpHelper(%7Btype: 'major'%7D);%0A %7D);%0A%0A function bumpHelper(_options) %7B%0A return gulp.src('./package.json')%0A .pipe(bump(_options ))%0A + @@ -988,19 +988,21 @@ './'));%0A -%7D); + %7D %0A%0Agulp.t
237d91cb396977931d2d2f66a3416d4f0174f803
set mockserver Enviro to 'test'; mockeserver minor fixes
test/middleware/mockserver.js
test/middleware/mockserver.js
#!/usr/bin/env node 'use strict'; const Hapi = require('hapi'); const Sequelize = require('sequelize'); // const pg = require('pg'); const api = require('../../src/modules/middleware/index.js'); const routes = require('../../src/modules/middleware/routes/index.routes'); const rt_ctx_env = process.env.LEDWAX_ENVIRO || 'dev'; const particleConfig = require('../../src/particle-config').attributes[rt_ctx_env]; var internals = { dbConfig: require('../../src/config/sequelize.config.json')[rt_ctx_env] }; var db; module.exports.createServer = (done) => { var server = new Hapi.Server({debug: {request: ['debug'], log: ['debug']}}); server.connection({ port : 8753 }); server.route(routes); let prom = server.register( { register: require('hapi-sequelize'), options: [ { name: 'apidb', // identifier models: ['./src/modules/middleware/models/**/*.js'], // relative to /webui -- where npm test is run sequelize: new Sequelize(internals.dbConfig.database, internals.dbConfig.username, internals.dbConfig.password, internals.dbConfig.sequelize), // sequelize instance sync: true, // sync models - default false forceSync: false // force sync (drops tables) - default false } ] } ); prom.then( (data) => { }, (err) => { server.log(['error', 'mockserver'], 'there was an error registering hapi-sequelize module\n' + err); } ); server.method('particle.config', () => {return particleConfig;}); return server; };
JavaScript
0
@@ -102,19 +102,18 @@ ');%0A -// const -pg +Path = r @@ -121,17 +121,19 @@ quire('p -g +ath ');%0Acons @@ -319,11 +319,12 @@ %7C%7C ' -dev +test ';%0Ac @@ -407,19 +407,19 @@ _env%5D;%0A%0A -var +let interna @@ -501,19 +501,19 @@ env%5D%0A%7D;%0A -var +let db;%0A%0Amo @@ -558,11 +558,11 @@ %7B%0A%0A%09 -var +let ser @@ -866,17 +866,42 @@ odels: %5B -' +Path.join(__dirname, '../. ./src/mo @@ -933,61 +933,20 @@ */*. +model. js' +) %5D, - // relative to /webui -- where npm test is run %0A%09%09%09 @@ -1310,16 +1310,16 @@ m.then(%0A - %09 (data @@ -1325,16 +1325,91 @@ a) =%3E %7B%0A +%09%09%09server.log(%5B'info', 'mockserver'%5D, 'registered hapi-sequelize module');%0A %09 %7D,%0A%09%09
4c3fa5fa31e24f4633f65060ba3a4e5ee278d6ac
Update test, fix test size
test/multidevice/selectAny.js
test/multidevice/selectAny.js
"use strict"; var assert = require('chai').assert; var xdTesting = require('../../lib/index') var templates = require('../../lib/templates'); var q = require('q'); describe('MultiDevice - selectAny', function () { var test = this; test.baseUrl = "http://localhost:8090/"; it('should select a single device @large', function () { var options = { A: templates.devices.chrome(), B: templates.devices.chrome() }; return xdTesting.multiremote(options) .selectAny(device => device .getCount().then(count => assert.equal(count, 1)) ) .end() }); it('should execute promises callback @large', function () { var options = { A: templates.devices.chrome(), B: templates.devices.chrome() }; var queue = ''; return xdTesting.multiremote(options) .then(() => queue += '0') .selectAny(device => { queue += '1'; return device.then(() => { queue += '2'; }); }) .then(() => queue += '3') .then(() => assert.equal(queue, '0123')) .end(); }); });
JavaScript
0
@@ -316,21 +316,22 @@ device @ -large +medium ', funct @@ -498,32 +498,94 @@ remote(options)%0A + .getCount().then(count =%3E assert.equal(count, 2))%0A .sel @@ -762,13 +762,14 @@ ck @ -large +medium ', f
2bb7a65a1d0b9d4d7b6a537d205199fdb6cf8338
Fix misusing assert.notStrictEqual() in the test for Option<T>.flatMap()
test/option-t/test_flatmap.js
test/option-t/test_flatmap.js
'use strict'; const assert = require('assert'); const { createSome, createNone, } = require('../../__dist/cjs/Option'); describe('Option<T>.flatMap()', function(){ describe('self is `None`', function () { let option = null; let isNotCalled = true; before(function(){ const none = createNone(); option = none.flatMap(function(){ isNotCalled = false; }); }); it('the returned value shoule be `None`', function() { assert.strictEqual(option.isNone, true); }); it('the passed function should not be called', function() { assert.strictEqual(isNotCalled, true); }); }); describe('self is `Some<T>`', function () { describe('callback returns `None`', function () { let option = null; before(function(){ const some = createSome(1); option = some.flatMap(function(){ return createNone(); }); }); it('the returned value shoule be `None`', function() { assert.strictEqual(option.isNone, true); }); }); describe('callback returns `Some<T>`', function () { const EXPECTED = '1'; let option = null; before(function(){ const some = createSome(1); option = some.flatMap(function(val){ assert.strictEqual(val !== EXPECTED, true); return createSome(EXPECTED); }); }); it('the returned value shoule be `Some<T>`', function() { assert.strictEqual(option.isSome, true); }); it('the returned containing value shoule be expected', function() { assert.strictEqual(option.unwrap(), EXPECTED); }); }); describe('`fn` don\'t returns `Option<T>`', function () { let error = null; before(function(){ const some = createSome(1); try { some.flatMap(function(val){ const rv = 'hoge'; assert.notStrictEqual(val !== rv); return rv; }); } catch (e) { error = e; } }); after(function(){ error = null; }); it('should throw an error', function() { assert.strictEqual(error instanceof TypeError, true); }); it('the error message should be the expected', function() { assert.strictEqual(error.message, 'Option<T>.flatMap()\' param `fn` should return `Option<T>`.'); }); }); }); });
JavaScript
0.000678
@@ -2264,20 +2264,17 @@ qual(val - !== +, rv);%0A
69bf5c5ccc450cc8e884bea9b685ba86b54b04a8
Update nextMillenniumBidAdapter.js (#7972)
modules/nextMillenniumBidAdapter.js
modules/nextMillenniumBidAdapter.js
import { isStr, _each, getBidIdParameter } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER } from '../src/mediaTypes.js'; const BIDDER_CODE = 'nextMillennium'; const ENDPOINT = 'https://pbs.nextmillmedia.com/openrtb2/auction'; const SYNC_ENDPOINT = 'https://statics.nextmillmedia.com/load-cookie.html?v=4'; const TIME_TO_LIVE = 360; export const spec = { code: BIDDER_CODE, supportedMediaTypes: [BANNER], isBidRequestValid: function(bid) { return !!( bid.params.placement_id && isStr(bid.params.placement_id) ); }, buildRequests: function(validBidRequests, bidderRequest) { const requests = []; window.nmmRefreshCounts = window.nmmRefreshCounts || {}; _each(validBidRequests, function(bid) { window.nmmRefreshCounts[bid.adUnitCode] = window.nmmRefreshCounts[bid.adUnitCode] || 0; const postBody = { 'id': bid.auctionId, 'ext': { 'prebid': { 'storedrequest': { 'id': getBidIdParameter('placement_id', bid.params) } }, 'nextMillennium': { 'refresh_count': window.nmmRefreshCounts[bid.adUnitCode]++, } } } const gdprConsent = bidderRequest && bidderRequest.gdprConsent; const uspConsent = bidderRequest && bidderRequest.uspConsent if (gdprConsent || uspConsent) { postBody.regs = { ext: {} } if (uspConsent) { postBody.regs.ext.us_privacy = uspConsent; } if (gdprConsent) { if (typeof gdprConsent.gdprApplies !== 'undefined') { postBody.regs.ext.gdpr = gdprConsent.gdprApplies ? 1 : 0; } if (typeof gdprConsent.consentString !== 'undefined') { postBody.user = { ext: { consent: gdprConsent.consentString } } } } } requests.push({ method: 'POST', url: ENDPOINT, data: JSON.stringify(postBody), options: { contentType: 'application/json', withCredentials: true }, bidId: bid.bidId }); }); return requests; }, interpretResponse: function(serverResponse, bidRequest) { const response = serverResponse.body; const bidResponses = []; _each(response.seatbid, (resp) => { _each(resp.bid, (bid) => { bidResponses.push({ requestId: bidRequest.bidId, cpm: bid.price, width: bid.w, height: bid.h, creativeId: bid.adid, currency: response.cur, netRevenue: false, ttl: TIME_TO_LIVE, meta: { advertiserDomains: bid.adomain || [] }, ad: bid.adm }); }); }); return bidResponses; }, getUserSyncs: function (syncOptions, responses, gdprConsent, uspConsent) { if (!syncOptions.iframeEnabled) { return } let syncurl = gdprConsent && gdprConsent.gdprApplies ? `${SYNC_ENDPOINT}&gdpr=1&gdpr_consent=${gdprConsent.consentString}` : SYNC_ENDPOINT let bidders = [] if (responses) { _each(responses, (response) => { _each(Object.keys(response.body.ext.responsetimemillis), b => bidders.push(b)) }) } if (bidders.length) { syncurl += `&bidders=${bidders.join(',')}` } return [{ type: 'iframe', url: syncurl }]; }, }; registerBidder(spec);
JavaScript
0
@@ -3180,24 +3180,134 @@ ponse) =%3E %7B%0A + if (!(response && response.body && response.body.ext && response.body.ext.responsetimemillis)) return%0A _eac
e94b69e74f6880674bd8ccb9aa7bfe56f826ca3e
Make the information visible when the query succeeds
src/twitterclient.js
src/twitterclient.js
// Copyright (c) 2012, David Haglund // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. $(document).ready(function() { var url = 'https://api.twitter.com/1/users/show.json?callback=?&include_entities=true&screen_name=', query; $('#userSearch').submit(function() { $("#twitterResults").html(''); query = $("#queryString").val(); $.jsonp({ url: url + query, success: function(jsonTwitter) { $('#screen_name').text(jsonTwitter.screen_name); $('#name').text(jsonTwitter.name); $('#location').text(jsonTwitter.location); $('#description').text(jsonTwitter.description); $('#followers').text(jsonTwitter.followers_count); $('#following').text(jsonTwitter.friends_count); $('#created').text(jsonTwitter.created_at); $('#tweets').text(jsonTwitter.statuses_count); $('#user_info').removeClass('invisible'); }, error: function(d, msg) { console.log("error!"); } }); return false; }); });
JavaScript
0.00054
@@ -2189,56 +2189,210 @@ -$('#description').text(jsonTwitter.description); +if (jsonTwitter.description != %22%22) %7B%0A $('#description').text(jsonTwitter.description);%0A %7D else %7B%0A $('#description').html('&nbsp;');%0A %7D %0A
3fabfb25222709d444c7dd334db3efeb029de146
fix test in firefox
test/test-js-regress-GH-14.js
test/test-js-regress-GH-14.js
var common = require('../lib/common'); var test = require('tape'); test('should be able to detect ftypmp42 as a valid mp4 header type', function (t) { var buf = new Buffer(12); buf[0] = '0x00' buf[1] = '0x00' buf[2] = '0x00' buf[3] = '0x18' buf[4] = '0x66' // f buf[5] = '0x74' // t buf[6] = '0x79' // y buf[7] = '0x70' // p buf[8] = '0x6D' // m buf[9] = '0x70' // p buf[10] = '0x34' // 4 buf[11] = '0x32' // 2 var types = [ { buf: new Buffer('ftypmp42'), tag: require('../lib/id4'), offset: 4, } ] t.equal(common.getParserForMediaType(types, buf), require('../lib/id4'), 'type'); t.end(); });
JavaScript
0.000001
@@ -174,336 +174,175 @@ fer( -12);%0A buf%5B0%5D = '0x00'%0A buf%5B1%5D = '0x00'%0A buf%5B2%5D = '0x00'%0A buf%5B3%5D = '0x18'%0A buf%5B4%5D = '0x66' // f%0A buf%5B5%5D = '0x74' // t%0A buf%5B6%5D = '0x79' // y%0A buf%5B7%5D = '0x70' // p%0A buf%5B8%5D = '0x6D' // m%0A buf%5B9%5D = '0x70' // p%0A buf%5B10%5D = '0x34' // 4%0A buf%5B11%5D = '0x32' // 2%0A%0A var types = %5B%0A %7B%0A buf: new Buffer('ftypmp42' +%5B0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34, 0x32%5D)%0A%0A var types = %5B%0A %7B%0A buf: new Buffer(%5B0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34, 0x32%5D ),%0A
0b0e941a582c0cf9f364f612991c9613a925ceca
Increase timeout in CssComposer test
test/specs/css_composer/e2e/CssComposer.js
test/specs/css_composer/e2e/CssComposer.js
module.exports = { run() { describe('E2E tests', () => { var fixtures; var fixture; var gjs; var cssc; var clsm; var domc; var rulesSet; var rulesSet2; before(() => { fixtures = $("#fixtures"); fixture = $('<div class="csscomposer-fixture"></div>'); }); beforeEach(done => { //this.timeout(5000); gjs = grapesjs.init({ stylePrefix: '', storageManager: { autoload: 0, type:'none' }, assetManager: { storageType: 'none', }, container: 'csscomposer-fixture', }); cssc = gjs.CssComposer; clsm = gjs.SelectorManager; domc = gjs.DomComponents; fixture.empty().appendTo(fixtures); gjs.render(); rulesSet = [ { selectors: [{name: 'test1'}, {name: 'test2'}] }, { selectors: [{name: 'test2'}, {name: 'test3'}] }, { selectors: [{name: 'test3'}] } ]; rulesSet2 = [ { selectors: [{name: 'test1'}, {name: 'test2'}], state:':active' }, { selectors: [{name: 'test2'}, {name: 'test3'}] }, { selectors: [{name: 'test3'}], mediaText:'(max-width: 900px)' } ]; done(); }); afterEach(() => { gjs = null; cssc = null; clsm = null; }); after(() => { fixture.remove(); }); it('Rules are correctly imported from default property', () => { var gj = grapesjs.init({ stylePrefix: '', storageManager: { autoload: 0, type:'none' }, assetManager: { storageType: 'none', }, cssComposer: { rules: rulesSet}, container: 'csscomposer-fixture', }); var cssc = gj.editor.get('CssComposer'); expect(cssc.getAll().length).toEqual(rulesSet.length); var cls = gj.editor.get('SelectorManager').getAll(); expect(cls.length).toEqual(3); }); it('New rule adds correctly the class inside selector manager', () => { var rules = cssc.getAll(); rules.add({ selectors: [{name: 'test1'}] }); expect(clsm.getAll().at(0).get('name')).toEqual('test1'); }); it('New rules are correctly imported inside selector manager', () => { var rules = cssc.getAll(); rulesSet.forEach(item => { rules.add(item); }); var cls = clsm.getAll(); expect(cls.length).toEqual(3); expect(cls.at(0).get('name')).toEqual('test1'); expect(cls.at(1).get('name')).toEqual('test2'); expect(cls.at(2).get('name')).toEqual('test3'); }); it('Add rules from the new component added as a string with style tag', () => { var comps = domc.getComponents(); var rules = cssc.getAll(); comps.add("<div>Test</div><style>.test{color: red} .test2{color: blue}</style>"); expect(comps.length).toEqual(1); expect(rules.length).toEqual(2); }); it('Add raw rule objects with addCollection', () => { cssc.addCollection(rulesSet); expect(cssc.getAll().length).toEqual(3); expect(clsm.getAll().length).toEqual(3); }); it('Add raw rule objects twice with addCollection do not duplucate rules', () => { var rulesSet2Copy = JSON.parse(JSON.stringify(rulesSet2)); var coll1 = cssc.addCollection(rulesSet2); var coll2 = cssc.addCollection(rulesSet2Copy); expect(cssc.getAll().length).toEqual(3); expect(clsm.getAll().length).toEqual(3); expect(coll1).toEqual(coll2); }); it("Extend css rule style, if requested", () => { var style1 = {color: 'red', width: '10px'}; var style2 = {height: '20px', width: '20px'}; var rule1 = { selectors: ['test1'], style: style1, }; var rule2 = { selectors: ['test1'], style: style2, }; var ruleOut = cssc.addCollection(rule1)[0]; // ruleOut is a Model ruleOut = JSON.parse(JSON.stringify(ruleOut)); var ruleResult = { mediaText: '', selectors: [{ active: true, label: 'test1', name: 'test1', type: 'class', }], selectorsAdd: '', state: '', stylable: true, style: { color: 'red', width: '10px' } }; expect(ruleOut).toEqual(ruleResult); var ruleOut = cssc.addCollection(rule2, {extend: 1})[0]; ruleOut = JSON.parse(JSON.stringify(ruleOut)); ruleResult.style = { color: 'red', height: '20px', width: '20px', } expect(ruleOut).toEqual(ruleResult); }); it("Do not extend with different selectorsAdd", () => { var style1 = {color: 'red', width: '10px'}; var style2 = {height: '20px', width: '20px'}; var rule1 = { selectors: [], selectorsAdd: '*', style: style1, }; var rule2 = { selectors: [], selectorsAdd: 'p', style: style2, }; var rule1Out = cssc.addCollection(rule1, {extend: 1})[0]; var rule2Out = cssc.addCollection(rule2, {extend: 1})[0]; rule1Out = JSON.parse(JSON.stringify(rule1Out)); rule2Out = JSON.parse(JSON.stringify(rule2Out)); var rule1Result = { mediaText: '', selectors: [], selectorsAdd: '*', state: '', stylable: true, style: { color: 'red', width: '10px' } }; var rule2Result = { mediaText: '', selectors: [], selectorsAdd: 'p', state: '', stylable: true, style: { height: '20px', width: '20px', } }; expect(rule1Out).toEqual(rule1Result); expect(rule2Out).toEqual(rule2Result); }); it('Add raw rule objects with width via addCollection', () => { var coll1 = cssc.addCollection(rulesSet2); expect(coll1[2].get('mediaText')).toEqual(rulesSet2[2].mediaText); }); }); } };
JavaScript
0
@@ -396,18 +396,16 @@ -// this.tim
769520bf1ac90987d942cec4e08bd78b34480c5c
Add submit button to upload images dialog
app/assets/javascripts/views/experiences/add_image_to_experience_form.js
app/assets/javascripts/views/experiences/add_image_to_experience_form.js
function addImageToExperienceForm(experienceID) { var assetURL = "/users/" + getCurrentUser() + "/assets/new" $.ajax({ method: "get", url: assetURL, }) .done(function(response){ var postURL = "/users/" + getCurrentUser() + "/assets" clearMainFrame() hideMainMenu() var $experienceID = $("<input>").attr({ type: "hidden", value: experienceID, name: "assets[experience_id]" }) $dropzone = $(response) $dropzone.find('#multi-upload').append($experienceID) appendToMainFrame($dropzone) var dropzone = new Dropzone("#multi-upload", { url: postURL }); // s3Run() }) }
JavaScript
0
@@ -508,16 +508,101 @@ enceID)%0A + $submit = $(%22%3Cinput type='submit'%3E%22).addClass(%22form-submit%22).appendTo($dropzone)%0A appe
d675c0cf10e92eee9a549d059bd10f20dd8d6ba7
fix conflict
test/unit/angular-carousel.js
test/unit/angular-carousel.js
/*global beforeEach, afterEach, describe, it, inject, expect, module, spyOn, fullcalendar, angular, $*/ describe('carousel', function () { 'use strict'; var scope, $compile, $sandbox; beforeEach(module('angular-carousel')); beforeEach(inject(function ($rootScope, _$compile_) { scope = $rootScope; $compile = _$compile_; $sandbox = $('<div id="sandbox"></div>').appendTo($('body')); })); afterEach(function() { $sandbox.remove(); scope.$destroy(); }); function compileTpl() { var sampleData = { scope: { items: [ {text: '1st slide'}, {text: '2nd slide'}, {text: '3rd slide'} ] }, template: '<ul carousel><li ng-repeat="item in items">{{ item.text }}</li></ul>' }; angular.extend(scope, sampleData.scope); var $element = $(sampleData.template).appendTo($sandbox); $element = $compile($element)(scope); scope.$digest(); return $element; } describe('check directive compilation', function () { it('should add a wrapper div around the ul/li', function () { var elm = compileTpl(); expect(elm.parent().hasClass('carousel-container')).toBe(true); }); it('should add a class to the ul', function () { var elm = compileTpl(); expect(elm.hasClass('carousel-slides')).toBe(true); }); it('should add announcer attribute to each slide', function () { var elm = compileTpl(); expect(elm.find('li[slide-announcer=true]').length).toBe(3); }); it('should add announcer attribute to each slide dynamically', function () { var elm = compileTpl(); scope.items.push({text:'4th slide'}); scope.$digest(); expect(elm.find('li[slide-announcer=true]').length).toBe(4); }); it('generated container outerWidth should match the ul outerWidth', function () { var elm = compileTpl(); scope.$digest(); expect(elm.parent().outerWidth()).toBe(elm.outerWidth()); }); }); });
JavaScript
0.031708
@@ -66,29 +66,8 @@ ule, - spyOn, fullcalendar, ang
c240ae3ab08f9640bb3a15cb1ee66a707eea7029
Remove typo in numeric validator unit test
test/unit/specs/validators/numeric.spec.js
test/unit/specs/validators/numeric.spec.js
import numeric from 'src/validators/numeric' describe('numeric validator', () => { it('should validate undefined', () => { expect(numeric(undefined)).to.be.true }) it('should validate null', () => { expect(numeric(null)).to.be.true }) it('should validate empty string', () => { expect(numeric('')).to.be.true }) it('should validate numbers', () => { expect(numeric('01234')).to.be.true }) it('should not validate space', () => { expect(numeric(' ')).to.be.false }) it('should not validate english letters', () => { expect(numeric('abcdefghijklmnopqrstuvwxyz')).to.be.false }) it('should not validate english letters uppercase', () => { expect(numeric('ABCDEFGHIJKLMNOPQRSTUVWXYZ')).to.be.false }) it('should not validate alphanum', () => { expect(numeric('abc123')).to.be.falsesSt }) it('should not validate padded letters', () => { expect(numeric(' 123 ')).to.be.false }) it('should not validate unicode', () => { expect(numeric('🎉')).to.be.false }) it('should not validate negative numbers', () => { expect(numeric('-123')).to.be.false }) it('should not validate decimal numbers', () => { expect(numeric('0.1')).to.be.false expect(numeric('1.0')).to.be.false }) it('should not validate negative decimal numbers', () => { expect(numeric('-123.4')).to.be.false }) })
JavaScript
0.000018
@@ -844,11 +844,8 @@ alse -sSt %0A %7D
f076a9d390816b25f6952d0c7bb26ecaacd2c308
Remove needless code
tests/dummy/app/initializers/router-ext.js
tests/dummy/app/initializers/router-ext.js
import Ember from 'ember'; let hasRan = false; let newSetup = true; function initialize() { if (hasRan) { return; } hasRan = true; Ember.Router.reopen({ assetLoader: Ember.inject.service(), setupRouter() { let isSetup = this._super(...arguments); if (newSetup) { // Different versions of routerMicrolib use the names `getRoute` vs // `getHandler`. if (this._routerMicrolib.getRoute !== undefined) { this._routerMicrolib.getRoute = this._handlerResolver( this._routerMicrolib.getRoute.bind(this._routerMicrolib) ); } else if (this._routerMicrolib.getHandler !== undefined) { this._routerMicrolib.getHandler = this._handlerResolver( this._routerMicrolib.getHandler.bind(this._routerMicrolib) ); } } return isSetup; }, _handlerResolver(original) { return (name) => { return this.get('assetLoader').loadBundle('test').then(() => { return original(name); }); }; } }); } export default { name: 'router-ext', initialize };
JavaScript
0.9998
@@ -270,32 +270,8 @@ s);%0A - if (newSetup) %7B%0A @@ -340,18 +340,16 @@ ute%60 vs%0A - // @@ -369,18 +369,16 @@ .%0A - if (this @@ -412,34 +412,32 @@ == undefined) %7B%0A - this._ro @@ -485,34 +485,32 @@ lver(%0A - this._routerMicr @@ -554,31 +554,27 @@ ib)%0A - - );%0A - %7D else @@ -627,34 +627,32 @@ ined) %7B%0A - this._routerMicr @@ -694,34 +694,32 @@ lver(%0A - - this._routerMicr @@ -773,22 +773,10 @@ - );%0A %7D +); %0A
f8a7fd62d549c067fa6d7af325ddb0c2a0a8619e
更新 currCase
client/containers/Project/Interface/InterfaceCol/InterfaceCaseContent.js
client/containers/Project/Interface/InterfaceCol/InterfaceCaseContent.js
import React, { Component } from 'react' import { connect } from 'react-redux'; import PropTypes from 'prop-types' import { withRouter } from 'react-router' import axios from 'axios' import { message } from 'antd' import { fetchInterfaceColList, setColData, fetchCaseData } from '../../../../reducer/modules/interfaceCol' import { Postman } from '../../../../components' @connect( state => { return { interfaceColList: state.interfaceCol.interfaceColList, currColId: state.interfaceCol.currColId, currCaseId: state.interfaceCol.currCaseId, currCase: state.interfaceCol.currCase, isShowCol: state.interfaceCol.isShowCol, currProject: state.project.currProject } }, { fetchInterfaceColList, fetchCaseData, setColData } ) @withRouter export default class InterfaceCaseContent extends Component { static propTypes = { match: PropTypes.object, interfaceColList: PropTypes.array, fetchInterfaceColList: PropTypes.func, fetchCaseData: PropTypes.func, setColData: PropTypes.func, history: PropTypes.object, currColId: PropTypes.number, currCaseId: PropTypes.number, currCase: PropTypes.object, isShowCol: PropTypes.bool, currProject: PropTypes.object } constructor(props) { super(props) } getColId(colList, currCaseId) { let currColId = 0; colList.forEach(col => { col.caseList.forEach(caseItem => { if (+caseItem._id === currCaseId) { currColId = col._id; } }) }) return currColId; } async componentWillMount() { const result = await this.props.fetchInterfaceColList(this.props.match.params.id) let { currCaseId } = this.props; const params = this.props.match.params; const { actionId } = params; currCaseId = +actionId || +currCaseId || result.payload.data.data[0].caseList[0]._id; let currColId = this.getColId(result.payload.data.data, currCaseId); this.props.history.push('/project/' + params.id + '/interface/case/' + currCaseId) this.props.fetchCaseData(currCaseId) this.props.setColData({currCaseId: +currCaseId, currColId, isShowCol: false}) } componentWillReceiveProps(nextProps) { const oldCaseId = this.props.match.params.actionId const newCaseId = nextProps.match.params.actionId if (oldCaseId !== newCaseId) { let currColId = this.getColId(this.props.interfaceColList, newCaseId); this.props.fetchCaseData(newCaseId); this.props.setColData({currCaseId: +newCaseId, currColId, isShowCol: false}) } } savePostmanRef = (postman) => { this.postman = postman; } updateCase = async () => { const { caseEnv: case_env, pathname: path, method, pathParam: req_params, query: req_query, headers: req_headers, bodyType: req_body_type, bodyForm: req_body_form, bodyOther: req_body_other } = this.postman.state; const {_id: id, casename} = this.props.currCase; const res = await axios.post('/api/col/up_case', { id, casename, case_env, path, method, req_params, req_query, req_headers, req_body_type, req_body_form, req_body_other }); if (res.data.errcode) { message.error(res.data.errmsg) } else { message.success('更新成功') } } render() { const { currCase, currProject } = this.props; const data = Object.assign({}, currCase, currProject, {_id: currCase._id}); return ( <div style={{padding: '6px 0'}}> <h1 style={{marginLeft: 8}}>{currCase.casename}</h1> <div> <Postman data={data} type="case" saveTip="更新保存修改" save={this.updateCase} ref={this.savePostmanRef} /> </div> </div> ) } }
JavaScript
0.000001
@@ -3342,16 +3342,52 @@ '%E6%9B%B4%E6%96%B0%E6%88%90%E5%8A%9F')%0A + this.props.fetchCaseData(id);%0A %7D%0A
104e2c02bb6fbb10dcde73376fcddd643d8fe748
Fix adding sentences using IME
webroot/js/sentences_lists.add_new_sentence_to_list.js
webroot/js/sentences_lists.add_new_sentence_to_list.js
/** * Tatoeba Project, free collaborative creation of multilingual corpuses project * Copyright (C) 2009-2010 HO Ngoc Phuong Trang <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ $(document).ready(function() { $("#text").keyup(function(e){ if (e.keyCode == 13) { save(); } }); $("#submitNewSentenceToList").click(function(){ save(); }); function save(){ $("#list_add_loader").show(); var sentenceText = $("#text").val(); var listId = $("#sentencesList").attr('data-list-id'); var rootUrl = get_tatoeba_root_url(); $.post(rootUrl + "/sentences_lists/add_new_sentence_to_list/" , { "listId": listId, "sentenceText" : sentenceText, "sentenceLang" : "auto" } , function(data){ $("#text").val(""); $("#session_expired").remove(); $(".sentencesList").watch("prepend", data); $("#list_add_loader").hide(); } , "html"); } });
JavaScript
0.012933
@@ -878,10 +878,12 @@ .key -up +down (fun
f641e94c1c64a7e8dfde55a88fb12a5c0d49db93
Format code.
website/app/application/core/login/login-controller.js
website/app/application/core/login/login-controller.js
(function(module) { module.controller('LoginController', LoginController); LoginController.$inject = ["$state", "User", "toastr", "mcapi", "pubsub", "model.projects", "projectFiles", "$anchorScroll", "$location"]; /* @ngInject */ function LoginController($state, User, toastr, mcapi, pubsub, projects, projectFiles, $anchorScroll, $location) { var ctrl = this; ctrl.cancel = cancel; ctrl.gotoID = gotoID; ctrl.login = login; //////////////////// function login () { mcapi('/user/%/apikey', ctrl.email, ctrl.password) .success(function (u) { User.setAuthenticated(true, u); pubsub.send("tags.change"); projects.clear(); projectFiles.clear(); projects.getList().then(function (projects) { if (projects.length === 0) { $state.go("projects.create"); } else { $state.go('projects.project.home', {id: projects[0].id}); } }); }) .error(function (reason) { ctrl.message = "Incorrect Password/Username!"; toastr.error(reason.error, 'Error', { closeButton: true }); }).put({password: ctrl.password}); } function cancel() { $state.transitionTo('home'); } function gotoID(id) { // set the location.hash to the id of // the element you wish to scroll to. $location.hash(id); // call $anchorScroll() $anchorScroll(); } } }(angular.module('materialscommons')));
JavaScript
0.000001
@@ -2,16 +2,17 @@ function + (module) @@ -141,20 +141,16 @@ - %22mcapi%22, @@ -178,20 +178,16 @@ jects%22,%0A - @@ -539,17 +539,16 @@ on login - () %7B%0A
e891643396d84f493dec902c3c209c5f7013caa9
fix string error
www/CookieJar.js
www/CookieJar.js
/* * Copyright 2013 Ernests Karlsons * https://github.com/bez4pieci * http://www.karlsons.net * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var exec = require('cordova/exec'); var tag = "CookieJar"; /** * @constructor */ function CookieJar() { } /** * Get device info * * @param {Function} successCallback The function to call when cookies cleared successfully * @param {Function} errorCallback The function to call when there was an error (OPTIONAL) */ CookieJar.prototype.clear = function (successCallback, errorCallback) { exec(successCallback, errorCallback, tag. "clear", []); }; /** * Get device info * * @param {Function} successCallback The function to call when cookies cleared successfully * @param {Function} errorCallback The function to call when there was an error (OPTIONAL) */ CookieJar.prototype.get = function (successCallback, errorCallback, URL, target) { if (!URL) { // throw error throw "Function call must include a URL target parameter"; return; } // build paramaters object var paramaters = { URL: URL } // if optional target included, add to object if (target) { paramaters.target = target; } exec(successCallback, errorCallback, tag, "get", [paramaters]); }; module.exports = new CookieJar();
JavaScript
0.000776
@@ -1619,17 +1619,9 @@ tag -.%0A +, %22cl
3c28b4e1ac63120fed2099fe768435fb3ea9fdb7
remove old code/license [skip ci]
packages/babel-plugin-transform-regenerator/src/index.js
packages/babel-plugin-transform-regenerator/src/index.js
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ export default require("regenerator-transform");
JavaScript
0
@@ -1,332 +1,20 @@ -/**%0A * Copyright (c) 2014, Facebook, Inc.%0A * All rights reserved.%0A *%0A * This source code is licensed under the BSD-style license found in the%0A * https://raw.github.com/facebook/regenerator/master/LICENSE file. An%0A * additional grant of patent rights can be found in the PATENTS file in%0A * the same directory.%0A */%0A%0Aexport default +module.exports = req
b8e1f82f3710d1bda436e9c57f6c819efe610362
fix leave editor modal
core/client/app/components/modals/leave-editor.js
core/client/app/components/modals/leave-editor.js
import ModalComponent from 'ghost/components/modals/base'; export default ModalComponent.extend({ actions: { confirm() { this.get('confirm').finally(() => { this.send('closeModal'); }); } } });
JavaScript
0
@@ -158,16 +158,18 @@ onfirm') +() .finally
010be07663e5506694de2ae2a4f008c64df60c35
Add task id to the modal
public/javascripts/Admin/src/Admin.GSVLabelView.js
public/javascripts/Admin/src/Admin.GSVLabelView.js
function AdminGSVLabel() { var self = {}; var _init = function() { _resetModal(); }; function _resetModal() { self.modal = $('<div class="modal fade" id="labelModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">'+ '<div class="modal-dialog" role="document" style="width: 430px">'+ '<div class="modal-content">'+ '<div class="modal-header">'+ '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+ '<h4 class="modal-title" id="myModalLabel">Label</h4>'+ '</div>'+ '<div class="modal-body">'+ '<div id="svholder" style="width: 400px; height:300px">'+ '</div>'+ '<div class="modal-footer">'+ '<table class="table table-striped" style="font-size:small">'+ '<tr>'+ '<th>Time Submitted</th>'+ '<td id="timestamp"></td>'+ '</tr>'+ '<tr>'+ '<th>Label Type</th>'+ '<td id="label-type-value"></td>'+ '</tr>'+ '<tr>'+ '<th>Severity</th>'+ '<td id="severity"></td>'+ '</tr>'+ '<tr>'+ '<th>Temporary</th>'+ '<td id="temporary"></td>'+ '</tr>'+ '<tr>'+ '<th>Description</th>'+ '<td id="description"></td>'+ '</tr>'+ '</table>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'); self.panorama = AdminPanorama(self.modal.find("#svholder")[0]); self.modalTimestamp = self.modal.find("#timestamp"); self.modalLabelTypeValue = self.modal.find("#label-type-value"); self.modalSeverity = self.modal.find("#severity"); self.modalTemporary = self.modal.find("#temporary"); self.modalDescription = self.modal.find("#description"); } function showLabel(labelId) { _resetModal(); self.modal.modal({ 'show': true }); var adminLabelUrl = "/adminapi/label/" + labelId; $.getJSON(adminLabelUrl, function (data) { _handleData(data); }); } function _handleData(labelMetadata) { self.panorama.changePanoId(labelMetadata['gsv_panorama_id']); self.panorama.setPov({ heading: labelMetadata['heading'], pitch: labelMetadata['pitch'], zoom: labelMetadata['zoom'] }); var adminPanoramaLabel = AdminPanoramaLabel(labelMetadata['label_type_key'], labelMetadata['canvas_x'], labelMetadata['canvas_y'], labelMetadata['canvas_width'], labelMetadata['canvas_height']); self.panorama.renderLabel(adminPanoramaLabel); self.modalTimestamp.html(new Date(labelMetadata['timestamp'] * 1000)); self.modalLabelTypeValue.html(labelMetadata['label_type_value']); self.modalSeverity.html(labelMetadata['severity'] != null ? labelMetadata['severity'] : "No severity"); self.modalTemporary.html(labelMetadata['temporary'] ? "True": "False"); self.modalDescription.html(labelMetadata['description'] != null ? labelMetadata['description'] : "No description"); self.panorama.refreshGSV(); } _init(); self.showLabel = showLabel; return self; }
JavaScript
0.000008
@@ -1988,32 +1988,215 @@ '%3C/tr%3E'+%0A + '%3Ctr%3E' +%0A '%3Cth%3ETask ID%3C/th%3E' +%0A '%3Ctd id=%22task%22%3E%3C/td%3E' +%0A '%3C/tr%3E'+%0A @@ -2721,24 +2721,75 @@ cription%22);%0A + self.modalTask = self.modal.find(%22#task%22);%0A %7D%0A%0A f @@ -4102,16 +4102,144 @@ ption%22); +%0A self.modalTask.html(%22%3Ca href='/admin/task/%22+labelMetadata%5B'audit_task_id'%5D+%22'%3E%22+labelMetadata%5B'audit_task_id'%5D+%22%3C/a%3E%22); %0A%0A
655710bd141ca7c0f54310bd5b49712f0ff04def
configure gruntfile to copy needed codemirror files to assets dir
www/Gruntfile.js
www/Gruntfile.js
module.exports = function (grunt) { grunt.loadNpmTasks( 'grunt-browserify' ) grunt.loadNpmTasks( 'gruntify-eslint' ) grunt.loadNpmTasks( 'grunt-contrib-copy' ) grunt.loadNpmTasks( 'grunt-contrib-less' ) var allJSFilesInJSFolder = 'js/**/*.js' var distFolder = '../wikipedia/assets/' grunt.initConfig( { browserify: { distMain: { src: [ 'index-main.js', allJSFilesInJSFolder, '!preview-main.js' ], dest: `${distFolder}index.js` }, distPreview: { src: [ 'preview-main.js', 'js/utilities.js' ], dest: `${distFolder}preview.js` }, distAbout: { src: [ 'about-main.js' ], dest: `${distFolder}about.js` } }, less: { all: { options: { compress: true, yuicompress: true, optimization: 2 }, files: [ { src: 'less/**/*.less', dest: `${distFolder}styleoverrides.css` } ] } }, eslint: { src: [ '*.js', allJSFilesInJSFolder ], options: { fix: false } }, copy: { main: { files: [ { src: [ '*.html', '*.css', 'ios.json', 'languages.json', 'mainpages.json', '*.png', '*.pdf' ], dest: distFolder }, { src: 'node_modules/wikimedia-page-library/build/wikimedia-page-library-transform.css', dest: `${distFolder}wikimedia-page-library-transform.css` }, { src: 'node_modules/wikimedia-page-library/build/wikimedia-page-library-transform.css.map', dest: `${distFolder}wikimedia-page-library-transform.css.map` } ] } } } ) grunt.registerTask('default', [ 'eslint', 'browserify', 'less', 'copy' ]) }
JavaScript
0
@@ -1908,16 +1908,232 @@ ss.map%60%0A + %7D,%0A %7B%0A expand: true,%0A cwd: '../Carthage/Checkouts/mediawiki-extensions-CodeMirror/resources/',%0A src: %5B'**'%5D,%0A dest: %60$%7BdistFolder%7Dcodemirror/resources/%60%0A
fae22b745a40bbeb49bc7c1d811045782831e1b7
fix flaky test with removal of Date.now() checks
packages/cf-component-notifications/test/Notification.js
packages/cf-component-notifications/test/Notification.js
import React from 'react'; import renderer from 'react-test-renderer'; import { render, unmountComponentAtNode } from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import { Notification } from '../../cf-component-notifications/src/index'; import jsdom from 'jsdom'; // timeout as second arg is so annoying function delay(timeout, cb) { setTimeout(cb, timeout); } beforeEach(function() { const doc = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.document = doc; global.window = doc.defaultView; global.root = global.document.createElement('div'); global.document.body.appendChild(global.root); }); afterEach(function() { unmountComponentAtNode(global.root); global.document.body.removeChild(global.root); }); test('should call onClose after a set delay', done => { let start = Date.now(); let onClose = () => { let end = Date.now(); expect(end - start).toBeLessThan(300); expect(end - start).toBeGreaterThan(50); done(); }; render( <Notification type="info" message="Foo" delay={200} onClose={onClose} />, global.root ); }); test('should persist when told to', done => { let called = false; let onClose = () => called = true; render( <Notification type="info" message="Bar" delay={0} persist={true} onClose={onClose} />, global.root ); delay(50, () => { expect(called).toBeFalsy(); done(); }); }); test('should pause the timeout while the mouse is hovering the notification', done => { let called = false; let onClose = () => called = true; let instance = render( <Notification type="info" message="Baz" delay={100} onClose={onClose} />, global.root ); delay(50, () => { TestUtils.Simulate.mouseEnter( TestUtils.findRenderedDOMComponentWithClass( instance, 'cf-notifications__item' ) ); delay(150, () => { expect(called).toBeFalsy(); TestUtils.Simulate.mouseLeave( TestUtils.findRenderedDOMComponentWithClass( instance, 'cf-notifications__item' ) ); delay(150, () => { expect(called).toBeTruthy(); done(); }); }); }); }); test('should close on click', done => { let called = false; let onClose = () => called = true; let instance = render( <Notification type="info" message="Baz" delay={100} onClose={onClose} />, global.root ); delay(50, () => { TestUtils.Simulate.click( TestUtils.findRenderedDOMComponentWithClass( instance, 'cf-notifications__item_close' ) ); expect(called).toBeTruthy(); done(); }); }); test('should not render a close button when closable is false', () => { let instance = render( <Notification type="info" message="Baz" closable={false} onClose={() => {}} />, global.root ); let found = TestUtils.scryRenderedDOMComponentsWithClass( instance, 'cf-notifications__item_close' ); expect(found.length).toBe(0); }); test('should not render a progress when persist is true', () => { let instance = render( <Notification type="info" message="Baz" persist={true} onClose={() => {}} />, global.root ); let found = TestUtils.scryRenderedDOMComponentsWithClass( instance, 'cf-notifications__item_progress' ); expect(found.length).toBe(0); });
JavaScript
0
@@ -816,172 +816,32 @@ %3E %7B%0A - let start = Date.now();%0A%0A let onClose = () =%3E %7B%0A let end = Date.now();%0A expect(end - start).toBeLessThan(300);%0A expect(end - start).toBeGreaterThan(50); +%0A let onClose = () =%3E %7B %0A
04adbf203075613dfc8f70fb4a6008c7acdc2311
remove parens from single param arrow functions
src/utils/generic.js
src/utils/generic.js
export function deepAssign (target, ...sources) { if (isObject(target)) { sources.forEach((source) => { forOwn(source, (property) => { if (isObject(source[property])) { if (!target[property] || !isObject(target[property])) { target[property] = {}; } deepAssign(target[property], source[property]); } else { target[property] = source[property]; } }); }); return target; } else { throw new TypeError('Expected an object literal.'); } } export function deepEqual (first, second) { if (isObject(first)) { let bool = true; forOwn(second, (property) => { if (bool) { if (isObject(second[property])) { bool = deepEqual(first[property], second[property]); } else if (first[property] !== second[property]) bool = false; } }); return bool; } else { throw new TypeError('Expected an object literal.'); } } export function isObject (object) { return object !== null && typeof object === 'object' && (object.constructor === Object || Object.prototype.toString.call(object) === '[object Object]'); } export function forOwn (object, callback) { if (isObject(object)) { for (const property in object) { if (object.hasOwnProperty(property)) { callback(property); } } } else { throw new TypeError('Expected an object literal.'); } } export const nextUniqueId = (() => { let uid = 0; return () => uid++; })();
JavaScript
0.000001
@@ -90,16 +90,14 @@ ach( -( source -) =%3E @@ -116,25 +116,24 @@ source, -( property ) =%3E %7B%0A%09 @@ -116,33 +116,32 @@ source, property -) =%3E %7B%0A%09%09%09%09if (is @@ -584,25 +584,24 @@ second, -( property ) =%3E %7B%0A%09 @@ -592,17 +592,16 @@ property -) =%3E %7B%0A%09%09
7d8733e303e92f10ba4539c56f3c29fe0aef806e
Add missing paren.
wnprc_billing/resources/queries/ehr_billing/invoice.js
wnprc_billing/resources/queries/ehr_billing/invoice.js
require("ehr/triggers").initScript(this); function onUpsert(helper, scriptErrors, row, oldRow) { LABKEY.Query.selectRows({ requiredVersion: 9.1, schemaName: 'ehr_billing', queryName: 'invoiceRuns', columns: ['objectId, runDate'], filterArray: [LABKEY.Filter.create('objectId', row.invoiceRunId, LABKEY.Filter.Types.EQUAL)], scope: this, success: function (results) { var billingRunDate; var pmtReceivedDate; var format = "E MMM dd yyyy"; if (!results || !results.rows || results.rows.length < 1) return; //get billing run date billingRunDate = EHR.Server.Utils.normalizeDate(results.rows[0]["runDate"]["value"]); console.log("billingRunDate results = ", billingRunDate); //get invoice sent date var invoiceSentDate = EHR.Server.Utils.normalizeDate(row.invoiceSentOn); if (row.paymentAmountReceived && !row.paymentReceivedOn) { EHR.Server.Utils.addError(scriptErrors, 'paymentReceivedOn', "Payment Received On cannot be blank if there is Payment Amount Received amount", 'ERROR'); return false; } //validations //error if payment received is greater than //error if invoice sent date is before billing run date if (helper.getJavaHelper().dateCompare(billingRunDate, invoiceSentDate, format) > 0) { EHR.Server.Utils.addError(scriptErrors, 'invoiceSentDate', "Invoice Sent date" + " date (" + helper.getJavaHelper().formatDate(invoiceSentDate, format, false) + ") is before " + " Billing Run Date (" + helper.getJavaHelper().formatDate(billingRunDate, format, false) + ").", 'ERROR'); return false; } if (row.paymentReceivedOn) { pmtReceivedDate = EHR.Server.Utils.normalizeDate(row.paymentReceivedOn); //error if payment received date is before billing run date if (helper.getJavaHelper().dateCompare(billingRunDate, pmtReceivedDate, format) > 0) { EHR.Server.Utils.addError(scriptErrors, 'paymentReceivedOn', "Payment received date" + " date (" + helper.getJavaHelper().formatDate(pmtReceivedDate, format, false) + ") is before " + " Billing Run Date (" + helper.getJavaHelper().formatDate(billingRunDate, format, false) + ").", 'ERROR'); return false; } }, failure: function (error) { console.log(error); } }); //calculate balanceDue if (row.paymentAmountReceived != null) { if (oldRow.balanceDue != null) { row.balanceDue = oldRow.balanceDue - row.paymentAmountReceived; } else { row.balanceDue = row.invoiceAmount - row.paymentAmountReceived; } } else { row.balanceDue = row.invoiceAmount; } if(row.balanceDue <= 0) { row.fullPaymentReceived = true; } else { row.fullPaymentReceived = false; } }
JavaScript
0.00007
@@ -2585,32 +2585,50 @@ return false;%0A + %7D%0A %7D%0A%0A
df46bb81776cba0723fa09a686bd13a2bb9ccd7d
Remove info message after 5sec.
public/js/app/controllers/ApplicationController.js
public/js/app/controllers/ApplicationController.js
define(["app/app", "ember"], function(App, Ember) { "use strict"; App.ApplicationController = Ember.Controller.extend({ hasMessage: function() { var message = this.get('session.message') return message && message.length > 0 }.property('session.message'), displayError: function(error) { this.get('session').set('message', error.responseJSON.err) } }) })
JavaScript
0
@@ -314,24 +314,168 @@ on(error) %7B%0A + window.setTimeout(function () %7B%0A $(%22.box-message%22).slideUp(300, function () %7B%0A $(this).remove()%0A %7D)%0A %7D, 5000)%0A this.g
d44b5b0c41b019774c6d0ba79cc29927455e921d
create tests for the model
tests/subscriptions-api/subscription.model.spec.js
tests/subscriptions-api/subscription.model.spec.js
var request = require('mongoose'), app = require('http://localhost:4000/subscriptions');
JavaScript
0
@@ -1,92 +1,2387 @@ var -request = require('mongoose'),%0A app = require('http://localhost:4000/subscriptions' +app = require('./../../server.js');%0Avar SubscriptionModel = require('./../../app/models/subscription.model');%0Avar subscription;%0Avar id;%0Avar deleteID;%0Avar updateID;%0Avar edit;%0A%0Adescribe('SubscriptionModel Unit Test:', function () %7B%0A // body...%0A beforeEach(function (done) %7B%0A // body...%0A subscription = new SubscriptionModel(%7B%0A post: %7B%0A title: %22trial post%22%0A %7D%0A %7D);%0A id = '552869c248fe746b69d9237a';%0A updateID = '55286a42362a62716912e397';%0A edit = %7B%0A post: %7B%0A title: 'how about a change',%0A comments: true,%0A edits: false%0A %7D%0A %7D;%0A deleteID = '55286bc188d99d9469149bae';%0A done();%0A %7D);%0A describe('Save Subscription - ', function () %7B%0A // body...%0A %0A it('should save without problems', function (done) %7B%0A // body...%0A subscription.save(function(error)%7B%0A expect(error).toBeNull();%0A done();%0A %7D);%0A%0A %7D);%0A%0A %7D);%0A%0A describe('Get Subscriptions - ', function () %7B%0A // body...%0A%0A it('should get all Subscriptions', function (done) %7B%0A // body...%0A SubscriptionModel.find(function (error, Subscriptions) %7B%0A // body...%0A expect(error).toBeNull();%0A expect(Subscriptions).toBeTruthy();%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%0A describe('Get One Subscription - ', function () %7B%0A // body...%0A%0A it('should get one subscription', function (done) %7B%0A // body...%0A SubscriptionModel.findById(id, function (error, subscriptions) %7B%0A // body...%0A expect(error).toBeNull();%0A expect(subscriptions).toBeTruthy();%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%0A describe('Edit One Subscription - ', function () %7B%0A // body...%0A%0A it('should get one subscription and edit content', function (done) %7B%0A // body...%0A SubscriptionModel.findByIdAndUpdate(updateID, edit, function (error, subscriptions) %7B%0A // body...%0A expect(error).toBeNull();%0A expect(subscriptions).toBeTruthy();%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%0A describe('Delete One Subscription - ', function () %7B%0A // body...%0A%0A it('should get one subscription and delete it', function (done) %7B%0A // body...%0A SubscriptionModel.findByIdAndRemove(deleteID, function (error, subscription) %7B%0A // body...%0A expect(error).toBeNull();%0A expect(subscriptions).not.toBeTruthy();%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%0A%7D );
dbe8a2344c666f8cbf066ea902fb48f6a8bf3bf6
fix optional parameters and implement callbacks
www/analytics.js
www/analytics.js
function UniversalAnalyticsPlugin() {}; UniversalAnalyticsPlugin.prototype.startTrackerWithId = function(id) { cordova.exec(function() {}, function() {}, 'UniversalAnalytics', 'startTrackerWithId', [id]); }; UniversalAnalyticsPlugin.prototype.trackView = function(screen) { cordova.exec(function() {}, function() {}, 'UniversalAnalytics', 'trackView', [screen]); }; UniversalAnalyticsPlugin.prototype.addCustomDimension = function(key, value) { cordova.exec(function() {}, function() {}, 'UniversalAnalytics', 'addCustomDimension', [key, value]); }; UniversalAnalyticsPlugin.prototype.trackEvent = function(category, action, label, value) { cordova.exec(function() {}, function() {}, 'UniversalAnalytics', 'trackEvent', [category, action, label, value]); }; module.exports = new UniversalAnalyticsPlugin();
JavaScript
0
@@ -101,16 +101,32 @@ ction(id +, success, error ) %7B%0A%09cor @@ -139,36 +139,22 @@ xec( -function() %7B%7D, function() %7B%7D +success, error , 'U @@ -268,16 +268,32 @@ n(screen +, success, error ) %7B%0A%09cor @@ -306,36 +306,22 @@ xec( -function() %7B%7D, function() %7B%7D +success, error , 'U @@ -439,24 +439,40 @@ n(key, value +, success, error ) %7B%0A%09cordova @@ -481,36 +481,22 @@ xec( -function() %7B%7D, function() %7B%7D +success, error , 'U @@ -647,54 +647,248 @@ alue +, success, error ) %7B%0A -%09cordova.exec(function() %7B%7D, function() %7B%7D +%0A%09if ( typeof label === 'undefined' %7C%7C label === null )%0A%09%09label = '';%0A%0A%09if ( typeof value === 'undefined' %7C%7C value === null )%0A%09%09value = 0;%0A%0A%09var args = %5B category , action , label , value %5D;%0A%0A%09cordova.exec(success, error , 'U @@ -1009,9 +1009,8 @@ ugin();%0A -%0A
200964edff92648408f479ffd8fed199e9494e17
Use numberpicker up/down buttons for up/down keys (fixes #1232)
public/viewjs/components/numberpicker.js
public/viewjs/components/numberpicker.js
$(".numberpicker-down-button").unbind('click').on("click", function() { var inputElement = $(this).parent().parent().find('input[type="number"]'); inputElement.val(parseFloat(inputElement.val()) - 1); inputElement.trigger('keyup'); inputElement.trigger('change'); }); $(".numberpicker-up-button").unbind('click').on("click", function() { var inputElement = $(this).parent().parent().find('input[type="number"]'); inputElement.val(parseFloat(inputElement.val()) + 1); inputElement.trigger('keyup'); inputElement.trigger('change'); }); $(".numberpicker").on("keyup", function() { if ($(this).attr("data-not-equal") && !$(this).attr("data-not-equal").toString().isEmpty() && $(this).attr("data-not-equal") == $(this).val()) { $(this)[0].setCustomValidity("error"); } else { $(this)[0].setCustomValidity(""); } }); $(".numberpicker").each(function() { new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.type == "attributes" && (mutation.attributeName == "min" || mutation.attributeName == "max" || mutation.attributeName == "data-not-equal" || mutation.attributeName == "data-initialised")) { var element = $(mutation.target); var min = element.attr("min"); var decimals = element.attr("data-decimals"); var max = ""; if (element.hasAttr("max")) { max = element.attr("max"); } if (element.hasAttr("data-not-equal")) { var notEqual = element.attr("data-not-equal"); if (notEqual != "NaN") { if (max.isEmpty()) { element.parent().find(".invalid-feedback").text(__t("This cannot be lower than %1$s or equal %2$s and needs to be a valid number with max. %3$s decimal places", parseFloat(min).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: decimals }), parseFloat(notEqual).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: decimals }), decimals)); } else { element.parent().find(".invalid-feedback").text(__t("This must be between %1$s and %2$s, cannot equal %3$s and needs to be a valid number with max. %4$s decimal places", parseFloat(min).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: decimals }), parseFloat(max).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: decimals }), parseFloat(notEqual).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals }), decimals)); } return; } } if (max.isEmpty()) { element.parent().find(".invalid-feedback").text(__t("This cannot be lower than %1$s and needs to be a valid number with max. %2$s decimal places", parseFloat(min).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: decimals }), decimals)); } else { element.parent().find(".invalid-feedback").text(__t("This must between %1$s and %2$s and needs to be a valid number with max. %3$s decimal places", parseFloat(min).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: decimals }), parseFloat(max).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: decimals }), decimals)); } } }); }).observe(this, { attributes: true }); }); $(".numberpicker").attr("data-initialised", "true"); // Dummy change to trigger MutationObserver above once
JavaScript
0
@@ -3398,8 +3398,255 @@ ve once%0A +%0A$(%22.numberpicker%22).on(%22keydown%22, function(e)%0A%7B%0A%09if (e.key == %22ArrowUp%22)%0A%09%7B%0A%09%09e.preventDefault();%0A%09%09$(%22.numberpicker-up-button%22).click();%0A%09%7D%0A%09else if (e.key == %22ArrowDown%22)%0A%09%7B%0A%09%09e.preventDefault();%0A%09%09$(%22.numberpicker-down-button%22).click();%0A%09%7D%0A%7D);%0A
4022f0ad98948a27db464f2f11e84c811c3a1165
Move process.nextTick() to run() method
lib/emitters/custom-event-emitter.js
lib/emitters/custom-event-emitter.js
var util = require("util") , EventEmitter = require("events").EventEmitter module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); } util.inherits(CustomEventEmitter, EventEmitter) CustomEventEmitter.prototype.run = function() { var self = this return this } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct) return this } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct) return this } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }) return this } return CustomEventEmitter })()
JavaScript
0
@@ -198,125 +198,8 @@ is;%0A - process.nextTick(function() %7B%0A if (self.fct) %7B%0A self.fct.call(self, self)%0A %7D%0A %7D.bind(this));%0A %7D%0A @@ -318,16 +318,144 @@ f = this +;%0A %0A process.nextTick(function() %7B%0A if (self.fct) %7B%0A self.fct.call(self, self)%0A %7D%0A %7D.bind(this));%0A %0A ret @@ -454,32 +454,33 @@ %0A return this +; %0A %7D%0A%0A CustomEv
d968fe324bddd13c645d75aa874c811cfcc98056
Edit function for password validation
server/helpers/encrypt.js
server/helpers/encrypt.js
import bcrypt from 'bcrypt'; module.exports = { encryptPassword(password) { const passwordHash = bcrypt.hashSync(password, 10); return passwordHash; }, };
JavaScript
0.000001
@@ -75,16 +75,19 @@ d) %7B%0A + // const p @@ -134,16 +134,19 @@ 10);%0A + // return @@ -159,16 +159,150 @@ rdHash;%0A + const salt = bcrypt.genSaltSync(10);%0A const hash = bcrypt.hashSync(password, salt);%0A return %7B%0A hash,%0A salt%0A %7D;%0A %7D,%0A%0A%7D;
c3df2f941dccf5e135ac48408fccc25cf3c5da30
attach promise utils atop bluebird
src/utils/promise.js
src/utils/promise.js
/* Copyright 2019 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // @flow // Returns a promise which resolves with a given value after the given number of ms export const sleep = (ms: number, value: any): Promise => new Promise((resolve => { setTimeout(resolve, ms, value); })); // Returns a promise which resolves when the input promise resolves with its value // or when the timeout of ms is reached with the value of given timeoutValue export async function timeout(promise: Promise, timeoutValue: any, ms: number): Promise { const timeoutPromise = new Promise((resolve) => { const timeoutId = setTimeout(resolve, ms, timeoutValue); promise.then(() => { clearTimeout(timeoutId); }); }); return Promise.race([promise, timeoutPromise]); } // Returns a Deferred export function defer(): {resolve: () => {}, reject: () => {}, promise: Promise} { let resolve; let reject; const promise = new Promise((_resolve, _reject) => { resolve = _resolve; reject = _reject; }); return {resolve, reject, promise}; }
JavaScript
0.000002
@@ -573,16 +573,126 @@ se.%0A*/%0A%0A +// This is only here to allow access to methods like done for the time being%0Aimport Promise from %22bluebird%22;%0A%0A // @flow