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
7fc3348c70a06e5c90338e4f92bcb47677b72372
Add timestamp to server sent ADDTEXT messages
server/lib/textLine.js
server/lib/textLine.js
// // Copyright 2009-2014 Ilkka Oksanen <iao@iki.fi> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS // IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // 'use strict'; var co = require('co'), wait = require('co-wait'), Faker = require('Faker'), redis = require('./redis').createClient(), log = require('./log'), windowHelper = require('./windows'), conf = require('./conf'); // TDB Consider options: // // timestamp // type // rememberurl // hidden if (conf.get('frontend:demo_mode') === true) { co(function *() { while (1) { yield wait(4000); var demoUserEmail = conf.get('frontend:demo_user_email'); var demoUserId = parseInt(yield redis.hget('index:user', demoUserEmail)); var sentenceLength = Math.floor((Math.random() * 30 ) + 1); if (demoUserId) { var details = yield redis.srandmember('windowlist:' + demoUserId); if (details) { // User has at least one window var url = ''; if (!(Math.floor(Math.random() * 10 ))) { var randomImgFileName = Math.floor(Math.random() * 1000000); url = 'http://placeimg.com/640/480/nature/' + randomImgFileName + '.jpg'; } var windowId = parseInt(details.split(':')[0]); var msg = { body: Faker.Lorem.sentence(sentenceLength) + ' ' + url, nick: Faker.Name.firstName(), cat: 'msg', windowId: windowId }; yield processTextLine(demoUserId, msg, null); } } else { log.error('Demo user doesn\'t exist.'); } } })(); } exports.broadcast = function *(userId, network, msg) { var windowIds = yield windowHelper.getWindowIdsForNetwork(userId, network); for (var i = 0; i < windowIds.length; i++) { msg.windowId = windowIds[i]; yield processTextLine(userId, msg, null); } }; exports.send = function *(userId, network, name, type, msg) { msg.windowId = yield windowHelper.getWindowId(userId, network, name, type); yield processTextLine(userId, msg, null); }; exports.sendByWindowId = function *(userId, windowId, msg, excludeSession) { msg.windowId = windowId; yield processTextLine(userId, msg, excludeSession); }; exports.sendFromUserId = function *(userId, targetUserId, msg) { msg.windowId = yield windowHelper.getWindowIdByTargetUserId(targetUserId, userId); yield processTextLine(targetUserId, msg, null); }; function *processTextLine(userId, msg, excludeSession) { if (!('windowId' in msg)) { return; } msg.id = 'ADDTEXT'; msg.type = 0; // TBD var command = JSON.stringify(msg); yield redis.run('processTextLine', userId, msg.windowId, command, excludeSession); }
JavaScript
0.000001
@@ -3340,16 +3340,60 @@ ; // TBD +%0A msg.ts = Math.round(Date.now() / 1000); %0A%0A va
73012229c0152af0865953d6a15d4902945d9695
Change else statement
server/models/index.js
server/models/index.js
'use strict'; import dotenv from 'dotenv'; import fs from 'fs'; import path from 'path'; import Sequelize from 'sequelize'; dotenv.config(); const basename = path.basename(module.filename); const env = process.env.NODE_ENV || 'development'; const config = require('../../server/config/config')[env]; const db = {}; let sequelize; if (config.use_env_variable) { sequelize = new Sequelize(process.env.DB_URL, { dialect: 'postgres' }); } else { sequelize = new Sequelize(process.env.DB_URL, { dialect: 'postgres' }); } fs .readdirSync(__dirname) .filter((file) => { return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); }) .forEach((file) => { const model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach((modelName) => { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
JavaScript
0.000027
@@ -444,18 +444,9 @@ );%0A%7D - else %7B%0A +%0A sequ @@ -481,34 +481,32 @@ s.env.DB_URL, %7B%0A - dialect: 'post @@ -511,23 +511,19 @@ stgres'%0A - %7D); -%0A%7D %0A%0Afs%0A .
7725b6ed02b8d4406364adf4daa542c566cb492a
Fix check
server/publications.js
server/publications.js
/* P U B L I C A T I O N S . J S * BRL-CAD * * Copyright (c) 1995-2013 United States Government as represented by * the U.S. Army Research Laboratory. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this file; see the file named COPYING for more * information. */ /** @file OGV/server/publications * @brief publishes data from server to client */ Meteor.publish('modelFiles', () => ModelFiles.find()) Meteor.publish('objFiles', () => OBJFiles.find()) Meteor.publish('comments', () => Comments.find()) Meteor.publish('profilePictures', () => ProfilePictures.find()) Meteor.publish('lovers', () => Lovers.find()) Meteor.publish('ogvSettings', () => OgvSettings.find()) Meteor.publish('sharedModels', () => SharedModels.find()) Meteor.publish('notifications', () => Notifications.find()) Meteor.publish('posts', () => Posts.find()) /** * Not every detail about user is published to client * for security reasons */ Meteor.publish('profiles', () => Meteor.users.find({}, { fields: { emails: 1, profile: 1, roles: 1, }, }) ) Meteor.publish('userProfile', function (id) { check(id) Meteor._sleepForMs(1000) // try to find the user by id const user = Meteor.users.findOne({ _id: id, }) // if we can't find it, mark the subscription as ready and quit if (!user) { this.ready() return } // if the user we want to display the profile is the currently logged in user... if (this.userId === user._id) { // then we return the corresponding full document via a cursor return Meteor.users.find(this.userId) } // if we are viewing only the public part, strip the "profile" // property from the fetched document, you might want to // set only a nested property of the profile as private // instead of the whole property return Meteor.users.find(user._id) })
JavaScript
0.000001
@@ -1670,16 +1670,24 @@ check(id +, String )%0A Me
642aa363b2f3a3d717f03e9b1ebf78885dcac7fa
Clean up 4chan routes
server/routes/4chan.js
server/routes/4chan.js
import Axios from 'axios'; import express from 'express'; import {morphBoard, morphThread, extractBoardList} from '../helpers/morph-4chan'; import defaultRequest from '../helpers/request-config-4chan.js'; console.log("Default request is", defaultRequest); const router = express.Router(); router.get('/boards', function(req, res, next){ const url = `http://a.4cdn.org/boards.json`; Axios(url, defaultRequest) .then(function(boardList) { res.send(extractBoardList(boardList.data.boards)); }).catch( err => errorHandler(err)); }); router.get('/:boardID', function(req, res){ const boardID = req.params.boardID; const url = 'https://a.4cdn.org/' +boardID+ '/catalog.json'; console.log("Board::", url, defaultRequest) Axios(url, defaultRequest) .then(function(board) { res.send(morphBoard(board.data, boardID)) }).catch(err => errorHandler(err)) }); router.get('/:boardID/:threadID', function(req, res, next){ const boardID = req.params.boardID; const threadID = req.params.threadID; const url = 'http://a.4cdn.org/'+boardID+'/thread/'+threadID+'.json'; if (isNaN(threadID)) next(); defaultRequest.headers['Origin'] = 'http://boards.4chan.org/' +boardID; Axios(url, defaultRequest) .then(function(threads) { res.send(morphThread(threads.data.posts, boardID)); }).catch( err => errorHandler(err)); }); function errorHandler(err){ console.error(err.message, err); throw new Error(err) } module.exports = router;
JavaScript
0.000003
@@ -1,31 +1,4 @@ -import Axios from 'axios';%0A impo @@ -36,144 +36,63 @@ rt %7B -morphBoard, morphThread, extractBoardList%7D from '../helpers/morph-4chan';%0Aimport defaultRequest from '../helpers/request-config- +%0A%09getBoardlist, %0A%09getBoard, %0A%09getThread%0A%7D from './ 4chan -.js ';%0A%0A @@ -107,46 +107,22 @@ log( -%22Default request is%22, defaultRequest); +getBoardlist)%0A %0Acon @@ -178,1225 +178,103 @@ s', -function(req, res, next)%7B%0A const url = %60http://a.4cdn.org/boards.json%60;%0A Axios(url, defaultRequest)%0A .then(function(boardList) %7B%0A res.send(extractBoardList(boardList.data.boards));%0A %7D).catch( err =%3E errorHandler(err));%0A%7D);%0A%0A%0Arouter.get('/:boardID', function(req, res)%7B%0A const boardID = req.params.boardID;%0A const url = 'https://a.4cdn.org/' +boardID+ '/catalog.json';%0A console.log(%22Board::%22, url, defaultRequest)%0A Axios(url, defaultRequest)%0A .then(function(board) %7B%0A res.send(morphBoard(board.data, boardID))%0A %7D).catch(err =%3E errorHandler(err))%0A%7D);%0A%0A%0Arouter.get('/:boardID/:threadID', function(req, res, next)%7B%0A const boardID = req.params.boardID;%0A const threadID = req.params.threadID;%0A const url = 'http://a.4cdn.org/'+boardID+'/thread/'+threadID+'.json';%0A%0A if (isNaN(threadID)) next();%0A%0A defaultRequest.headers%5B'Origin'%5D = 'http://boards.4chan.org/' +boardID;%0A Axios(url, defaultRequest)%0A .then(function(threads) %7B%0A res.send(morphThread(threads.data.posts, boardID));%0A %7D).catch( err =%3E errorHandler(err));%0A%7D);%0A%0A%0Afunction errorHandler(err)%7B%0A console.error(err.message, err);%0A throw new Error(err)%0A%7D +getBoardlist);%0Arouter.get('/:boardID', getBoard);%0Arouter.get('/:boardID/:threadID', getThread); %0A%0Amo @@ -294,10 +294,8 @@ = router -;%0A
6d3cf81622dbd7a05499cfcf443eda9f7f8b608a
Update books.js
server/routes/books.js
server/routes/books.js
/*jslint node: true, unparam: true, nomen: true, vars: true*/ 'use strict'; var router = require('express').Router(); router.get('/', function (req, res) { if (req.query.timestamp) { req.db.cachestamps.findOne({collectionName: 'books'}, function (err, result) { res.json({ timestamp: result.timestamp }); }); } else if (req.query.from || req.query.count) { req.db.books .find() .skip(req.query.from || 0) .limit(req.query.count) .exec(function (err, results) { res.json(results); }); } else { req.db.books.find(function (err, results) { res.json(results); }); } }); module.exports = router;
JavaScript
0.000001
@@ -1,5 +1,4 @@ -%09 /*js
71b9be30047e34154758bdb9f37da6bbddef211c
Fix csv export error by adding cookieParser middleware
server/routes/lists.js
server/routes/lists.js
const bodyParser = require('body-parser'); const multer = require('multer')({ dest: 'server/controllers/list/uploads/' }); const parseJson = bodyParser.json(); const cookieParser = require('cookie-parser')(); // List controllers const getLists = require('../controllers/list/get-lists'); const getListSubscribers = require('../controllers/list/get-list-subscribers'); const exportListSubscribersCSV = require('../controllers/list/export-list-subscribers-csv'); const addSubscribers = require('../controllers/list/add-subscribers'); const importCSV = require('../controllers/list/import-csv'); const subscribeToList = require('../controllers/list/subscribe'); const deleteSubscribers = require('../controllers/list/delete-subscribers'); const deleteLists = require('../controllers/list/delete-lists'); // Middleware const { apiIsAuth } = require('./middleware/auth'); const { writeAccess, readAccess } = require('./middleware/acl'); // Permission const listPermission = require('../controllers/permissions/acl-lib/acl-list-permissions'); // Higher order functions decorating with the permission type const writeListAccess = (req, res, next) => writeAccess(req, res, next, listPermission); const readListAccess = (req, res, next) => readAccess(req, res, next, listPermission); module.exports = function(app, io) { // Get all lists app.get('/api/list/manage', apiIsAuth, cookieParser, readListAccess, (req, res) => { getLists(req, res); }); // Get all subscribers of a list app.get('/api/list/subscribers', apiIsAuth, parseJson, cookieParser, readListAccess, (req, res) => { getListSubscribers(req, res); }); // Get a single email using the list subscription key app.get('/api/list/subscribe', (req, res) => { subscribeToList(req, res); }); // temp route for testing csv export of list subscribers app.get('/api/list/subscribers/csv', apiIsAuth, readListAccess, (req, res) => { exportListSubscribersCSV(req, res); }); // Post new subscribers app.post('/api/list/add/subscribers', apiIsAuth, writeListAccess, (req, res) => { addSubscribers(req, res); }); // Post new list via csv import app.post('/api/list/add/csv', apiIsAuth, multer.single('csv'), cookieParser, writeListAccess, (req, res) => { importCSV(req, res, io); }); // Delete subscribers app.delete('/api/list/subscribers', apiIsAuth, parseJson, cookieParser, writeListAccess, (req, res) => { deleteSubscribers(req, res); }); // Delete lists app.delete('/api/list/manage', apiIsAuth, parseJson, cookieParser, writeListAccess, (req, res) => { deleteLists(req, res); }); };
JavaScript
0.000009
@@ -1874,16 +1874,30 @@ iIsAuth, + cookieParser, readLis
419db3eb2be4dbc427d4ba92462fb80ed6994fbe
Fix missing variable
webpack.production.config.js
webpack.production.config.js
const Webpack = require('webpack'); const path = require('path'); const fs = require('fs'); const ExtractTextPlugin = require("extract-text-webpack-plugin"); const HtmlWebpackPlugin = require('html-webpack-plugin'); const nodeModulesPath = path.resolve(__dirname, 'node_modules'); const buildPath = path.resolve(__dirname, 'build'); const mainPath = path.resolve(__dirname, 'src', 'index.js'); const config = { // We change to normal source mapping devtool: 'source-map', entry: mainPath, output: { path: buildPath, filename: '/dist/bundle.js' }, resolve: { root: path.resolve('./src'), extensions: ['', '.js'] }, module: { loaders: [{ test: /\.js$/, loader: 'babel', exclude: [nodeModulesPath] }, { test: /\.(jpe?g|png|gif|svg|ico)$/i, loaders: [ 'file?hash=sha512&digest=hex&name=dist/images/[name]-[hash].[ext]', 'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false' ] }, { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }] }, plugins: [ new ExtractTextPlugin('/dist/styles.css', { allChunks: true }), new HtmlWebpackPlugin({ templateContent: function () { var htmlTemplate = path.join(__dirname, 'src', 'index.html'); var template = fs.readFileSync(htmlTemplate, 'utf8'); return template.replace('<script src="/build/bundle.js"></script>', ''); }, hash: true, filename: 'index.html', inject: 'body' // Inject all scripts into the body }), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': '"production"' } }) ] }; module.exports = config;
JavaScript
0.998703
@@ -1,15 +1,15 @@ const -W +w ebpack =
907d38c8b6beeb0ebd11a1db6b8f87fc79a5e606
Set default widget width to 6 columns (task #5719)
webroot/plugins/qobo.grid.js
webroot/plugins/qobo.grid.js
var GridLayout = VueGridLayout.GridLayout; var GridItem = VueGridLayout.GridItem; new Vue({ el: "#grid-app", components: { GridLayout, GridItem, }, data: { targetElement: '#dashboard-options', dashboard:[], elements: [], widgetTypes: [], searchModules: [], layout: [], index:0, token: api_token // getting token from global variable into vue app. }, beforeMount: function () { this.getGridElements(); this.getLayoutElements(); }, mounted: function () { this.index = this.layout.length; }, beforeUpdate: function () { this.$nextTick(function () { this.adjustBoxesHeight(); }); }, watch: { // save all the visible options into dashboard var layout: { handler: function () { var that = this; this.dashboard = []; if (this.layout.length > 0) { this.layout.forEach(function (element) { that.dashboard.push({ i: element.i, h: element.h, w: element.w, x: element.x, y: element.y, id: element.data.id, type: element.type, }); }); } $(this.targetElement).val(JSON.stringify(this.dashboard)); }, deep: true } }, methods: { getElementBackground: function (item) { let colorClass = 'info'; if (item.hasOwnProperty('color')) { colorClass = item.color; } return 'box-' + colorClass; }, getElementIcon: function (item) { let className = 'cube'; if ('saved_search' === item.type) { console.log(item.data.name); console.log(item.icon); } if (item.hasOwnProperty('icon')) { className = item.icon; } return 'fa-' + className; }, getLayoutElements: function () { let gridLayout = []; if (typeof grid_layout !== undefined ) { gridLayout = grid_layout; this.layout = JSON.parse(gridLayout); } }, getGridElements: function () { var that = this; let types = []; let models = []; $.ajax({ type: 'post', dataType: 'json', url: '/search/widgets/index', headers: { 'Authorization': 'Bearer ' + this.token } }).then(function (response) { that.elements = response; that.elements.forEach(function (element) { if (!types.includes(element.type)) { types.push(element.type); } if (element.type == 'saved_search' && !models.includes(element.data.model)) { models.push(element.data.model); } }); that.widgetTypes = types.sort(); that.searchModules = models.sort(); }); }, addItem: function (item) { let element = { x: 0, y: this.getLastRow(), w: 2, h: 2, i: this.getUniqueId(), draggable: true, }; let layoutElement = Object.assign({}, element, item); this.layout.push(layoutElement); this.index = this.layout.length; }, removeItem: function (item) { this.layout.splice(this.layout.indexOf(item), 1); this.index = this.layout.index; }, getUniqueId: function () { return '_' + Math.random().toString(36).substr(2, 9); }, getLastRow: function () { let last = 0; if (!this.layout.length) { return last; } this.layout.forEach(function (element) { if (element.y >= last) { last = element.y; } }); last++; return last; }, camelize: function (str) { str = str.replace(/(?:\_|\W)(.)/g, function (match, chr) { return ' ' + chr.toUpperCase(); }); return str.charAt(0).toUpperCase() + str.slice(1); }, getActiveTab: function (type, defaultValue, cssClass) { return cssClass + ' ' + (type == defaultValue ? 'active' : ''); }, adjustBoxesHeight: function () { var maxHeight = Math.max.apply(null, $("div.available-widget").map(function () { return $(this).height(); }).get()); $("div.available-widget").height(maxHeight + 5); } } });
JavaScript
0
@@ -3594,17 +3594,17 @@ w: -2 +6 ,%0A
6eb5337e8ada34a441e744cd015463e36ab4d747
Update alert banner for HashiConf Global 2021 (#12650)
website/data/alert-banner.js
website/data/alert-banner.js
export const ALERT_BANNER_ACTIVE = true // https://github.com/hashicorp/web-components/tree/master/packages/alert-banner export default { tag: 'Event', url: 'https://hashiconf.com/global/?utm_campaign=22Q3_WW_HASHICONFGLOBAL_EVENT-USER&utm_source=CorpBanner&utm_medium=EVT&utm_offer=EVENT-USER', text: 'Join us for HashiConf Global - product updates, technical sessions, workshops & more', linkText: 'Register now', // Set the expirationDate prop with a datetime string (e.g. '2020-01-31T12:00:00-07:00') // if you'd like the component to stop showing at or after a certain date expirationDate: '2021-10-01T12:00:00-07:00', }
JavaScript
0
@@ -144,13 +144,17 @@ g: ' -Event +Oct%C2%A019-21 ',%0A @@ -311,20 +311,25 @@ t: ' -Join us for +The%C2%A0countdown%C2%A0to%C2%A0 Hash @@ -337,71 +337,50 @@ Conf - +%C2%A0 Global - - product updates, technical sessions, workshops & more +%C2%A0is%C2%A0on.%C2%A0View%C2%A0the%C2%A0full%C2%A0schedule%C2%A0now. ',%0A @@ -395,36 +395,37 @@ t: ' -Register now +View%C2%A0Schedule ',%0A // - Set the +%C2%A0Set%C2%A0the%C2%A0 expi @@ -438,29 +438,29 @@ Date - +%C2%A0 prop - +%C2%A0 with - a +%C2%A0a%C2%A0 datetime str @@ -459,22 +459,22 @@ time - +%C2%A0 string - +%C2%A0 (e.g. - +%C2%A0 '202 @@ -506,27 +506,27 @@ // - if +%C2%A0if%C2%A0 you'd - +%C2%A0 like - the +%C2%A0the%C2%A0 comp @@ -534,47 +534,47 @@ nent - to +%C2%A0to%C2%A0 stop - +%C2%A0 showing - at or +%C2%A0at%C2%A0or%C2%A0 after - a +%C2%A0a%C2%A0 certain - +%C2%A0 date @@ -601,18 +601,18 @@ 2021-10- -0 1 +9 T12:00:0
5320ebe852de41fab02b25f4aa01078c33b8ac7d
Update alert-banner.js
website/data/alert-banner.js
website/data/alert-banner.js
export const ALERT_BANNER_ACTIVE = true // https://github.com/hashicorp/web-components/tree/master/packages/alert-banner export default { linkText: 'Learn more!', url: 'https://www.hashicorp.com/blog/announcing-general-availability-of-hashicorp-nomad-1-0', tag: 'ANNOUNCEMENT', text: 'Nomad 1.0 is now generally available, which includes 5 major new features and many improvements.', // Set the `expirationDate prop with a datetime string (e.g. `2020-01-31T12:00:00-07:00`) // if you'd like the component to stop showing at or after a certain date expirationDate: '2021-02-08T09:00:00-07:00', }
JavaScript
0.000001
@@ -151,16 +151,17 @@ 'Le -arn more +t us know !',%0A @@ -180,219 +180,200 @@ s:// -www.hashicorp.com/blog/announcing-general-availability-of-hashicorp-nomad-1-0',%0A tag: 'ANNOUNCEMENT',%0A text:%0A 'Nomad 1.0 is now generally available, which includes 5 major new features and many improvements +docs.google.com/forms/d/e/1FAIpQLSeTre9Uvsfohl3yKLdTf0jUACT2GQgvGBsbp4fZvARpFwdv-g/viewform',%0A tag: 'FREE SWAG',%0A text:%0A 'Share your Nomad success story for a chance to win a special swag .',%0A
0182090fa137728c7f55002642fc4f5beb4e8dd1
fix "edit this page" links
website/docusaurus.config.js
website/docusaurus.config.js
module.exports = { title: 'Redux-Saga', tagline: 'An intuitive Redux side effect manager.', url: 'https://redux-saga.js.org/', baseUrl: '/', onBrokenLinks: 'throw', onBrokenMarkdownLinks: 'warn', favicon: 'static/img/favicon/favicon.ico', organizationName: 'redux-saga', projectName: 'redux-saga', themeConfig: { image: 'static/img/Redux-Saga-Logo-Portrait.png', colorMode: { defaultMode: 'light', }, prism: { theme: require('prism-react-renderer/themes/github'), darkTheme: require('prism-react-renderer/themes/dracula'), }, navbar: { title: 'Redux-Saga', logo: { alt: 'Redux-Saga Logo', src: 'static/img/Redux-Saga-Logo.png', }, items: [ { label: 'Introduction', to: 'docs/introduction/GettingStarted', position: 'left', }, { label: 'Basics', to: 'docs/basics/DeclarativeEffects', position: 'left', }, { label: 'Advanced', to: 'docs/advanced/Channels', position: 'left', }, { label: 'API', to: 'docs/api', position: 'left', }, { label: 'GitHub', href: 'https://github.com/redux-saga/redux-saga', position: 'right', }, { label: 'npm', href: 'https://www.npmjs.com/package/redux-saga', position: 'right', }, { label: 'cdnjs', href: 'https://cdnjs.com/libraries/redux-saga', position: 'right', }, ], }, footer: { links: [ { title: 'Docs', items: [ { label: 'Introduction', href: 'docs/introduction/BeginnerTutorial', }, { label: 'Basic Concepts', href: 'docs/basics/DeclarativeEffects', }, { label: 'Advanced Concepts', href: 'docs/advanced/Channels', }, { label: 'API Reference', href: 'docs/api', }, ], }, { title: 'Resources', items: [ { label: 'Glossary', href: 'docs/Glossary', }, { label: 'Troubleshooting', href: 'docs/Troubleshooting', }, { label: 'External Resources', href: 'docs/ExternalResources', }, ], }, { title: 'Sources', items: [ { label: 'GitHub', href: 'https://github.com/redux-saga/redux-saga', }, { label: 'npm', href: 'https://www.npmjs.com/package/redux-saga', }, { label: 'cdnjs', href: 'https://cdnjs.com/libraries/redux-saga', }, ], }, ], logo: { alt: 'Redux-Saga Logo', src: 'static/img/Redux-Saga-Logo-Landscape.png', }, copyright: `Copyright © ${new Date().getFullYear()} Redux-Saga. Built with Docusaurus.`, }, }, presets: [ [ '@docusaurus/preset-classic', { docs: { path: '../docs', sidebarPath: require.resolve('./sidebars.js'), editUrl: 'https://github.com/react-redux/react-redux/edit/master/docs/', }, theme: { customCss: [ require.resolve('./src/css/custom.scss'), require.resolve('./src/css/theme-light.scss'), require.resolve('./src/css/theme-dark.scss'), ], }, }, ], ], plugins: ['docusaurus-plugin-sass'], };
JavaScript
0.000001
@@ -3494,29 +3494,27 @@ m/re -act-redux/react-redux +dux-saga/redux-saga /edi
475ceb548f4339f3a25d4ce46188265875f76107
Update table classes
website/static/cms_editor.js
website/static/cms_editor.js
function init_tinymce(config) { var default_config = { selector: 'textarea', body_class: 'page-content', content_css : [ '/static/min/page.css', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' ], height: 260, browser_spellcheck: true, plugins : 'anchor advlist autolink link image lists charmap print preview fullscreen table imagetools textcolor colorpicker searchreplace code codesample autoresize', toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | codesample', table_default_attributes: { class: 'table table-bordered table-hover' }, autoresize_max_height: 600, table_class_list: [ {title: 'Default', value: 'table table-bordered table-hover'}, {title: 'Striped', value: 'table table-bordered table-hover table-striped'}, {title: 'Without borders', value: 'table table-hover table-striped'}, {title: 'Striped, without borders', value: 'table table-hover table-striped'} ], codesample_languages: [ {text: 'HTML/XML', value: 'markup'}, {text: 'JavaScript', value: 'javascript'}, {text: 'CSS', value: 'css'}, {text: 'Python', value: 'python'}, {text: 'Bash', value: 'bash'}, ] } update_object(default_config, config) tinymce.init(default_config) }
JavaScript
0.000001
@@ -925,24 +925,31 @@ %7Btitle: ' +Hover, Striped', va @@ -1029,9 +1029,25 @@ e: ' -W +Hover, Striped, w itho @@ -1123,23 +1123,21 @@ title: ' -Striped +Hover , withou @@ -1173,30 +1173,62 @@ le-hover - table-striped +'%7D,%0A %7Btitle: 'Clear', value: 'table '%7D%0A
bbbc338fc6f2db0a008f1c4160eb5a3a8bc1d3ee
Include stack traces in error messages
bin/penguin.js
bin/penguin.js
#!/usr/bin/env node 'use strict' const { Transform } = require('stream') const resolveMod = require('resolve') const subarg = require('subarg') const commands = { build: 'build.js', pack: 'pack.js', serve: 'serve.js', run: 'run.js', publish: 'publish.js' } const command = commands[process.argv[2]] if (!command) { console.error('unrecognized command!') process.exit(1) } const pkg = require(`${process.cwd()}/package.json`).penguin if (!Array.isArray(pkg.languages)) { console.error('penguin: no languages in package.json specified. e.g.:') console.error( ` { "penguin": { "languages": ["en"] } } ` ) process.exit(1) } else { parseArgs(subarg(process.argv.slice(3))) .then(opts => { const result = require(`${__dirname}/${command}`)(opts) if (!result) return if (typeof result.then === 'function') { return result.then(v => process.stdout.write(stringifyValue(v))) } else if (typeof result.pipe === 'function') { result .pipe(new Transform({ objectMode: true, transform (chunk, enc, callback) { callback(null, stringifyValue(chunk)) } })) .pipe(process.stdout) } else { console.warn('penguin: Command returned invalid return type') } }) .catch(err => { console.error('penguin-%s: %s', process.argv[2], err.message) process.exit(1) }) } function parseArgs (args) { const config = require(`${process.cwd()}/package.json`).penguin const basedir = args.basedir || args.b || process.cwd() const buildDir = args['build-dir'] || 'build' const port = args.port || args.p || 3000 const ext = args['view-engine'] || args.v const staticPrefix = args['static'] || args.s const transformArgs = args.transform || args.t const publishDriverArgs = args['publish-driver'] const databaseDriverArgs = args['database-driver'] || args.d const viewDriverArgs = args['view-driver'] const middlewareArgs = args['middleware'] || args.m const moduleArgs = [publishDriverArgs, databaseDriverArgs, viewDriverArgs] const middleware = Array.isArray(middlewareArgs) ? middlewareArgs : (middlewareArgs ? [middlewareArgs] : []) const transforms = Array.isArray(transformArgs) ? transformArgs : (transformArgs ? [transformArgs] : []) return Promise.all([ ...moduleArgs.map(a => ( a ? createModuleFromArgs(a, { basedir }) : Promise.resolve() )), Promise.all(middleware.map(a => createModuleFromArgs(a, { basedir }))), Promise.all(transforms.map(a => createModuleFromArgs(a, { basedir }))) ]).then(([publishDriver, databaseDriver, viewDriver, middleware, transforms]) => ( { config, basedir, buildDir, port, staticPrefix, ext, publishDriver, databaseDriver, viewDriver, middleware, transforms } )) } function stringifyValue (v) { return v ? (typeof v !== 'string' ? JSON.stringify(v) : v) : '' } function createModuleFromArgs (a, opts) { const name = a._[0] const args = Object.assign({}, a, { _: a._.slice(1) }) return createModule(name, opts, args) } function createModule (mod, opts, ...args) { return new Promise((resolve, reject) => { resolveMod(mod, opts, (err, p) => { if (err) return reject(err) let o try { o = require(p)(...args) } catch (e) { return reject(e) } resolve(o) }) }) }
JavaScript
0
@@ -1418,15 +1418,13 @@ err. -message +stack )%0A
922f25a5699b8f3522313de53c20343394012049
add `.ico` loader
server/builder.js
server/builder.js
/** * Module dependencies */ var fs = require('fs'); var exists = fs.existsSync; module.exports = function(r, app, opts, NODE_ENV) { var Builder = r('poe-ui-builder'); var webpack = r('webpack'); if (!Builder) return; var entry = opts.entry; var builder = app.builder = Builder(entry, webpack); var es6 = load('babel-loader?optional=runtime&modules=commonStrict&cacheDirectory=' + (opts.assetCache || '/tmp')); var ast2template = load('ast2template-loader?root=' + r.resolve(entry + '/root.js', 'silent')); /** * JS */ builder.module.loaders.push({ test: /\.(js)$/, exclude: /node_modules/, loader: es6 }); builder.module.loaders.push({ test: /\.(js)$/, include: /node_modules\/[^\/]+\/blocks/, loader: es6 }); builder.resolve.extensions.push('.json'); builder.addLoader('json', load('json-loader')); /** * Markup */ builder.resolve.extensions.push('.jade'); builder.addLoader('jade', load((NODE_ENV === 'development' ? 'react-component-loader!' : '') + es6 + '!onus-loader!' + ast2template + '!jade2ast-loader')); /** * CSS */ var styleLoader = load('style-loader'); builder.addLoader(/\.(ess\?(dynamic|raw))$/, load('ess-loader!' + es6 + '!' + ast2template + '&pass-through=1!ess2ast-loader')); builder.addStyle('css', load('css-loader')); builder.addStyle(/\.(ess)$/, load('css-loader!autoprefixer-loader!ess-loader!' + es6 + '!' + ast2template + '&pass-through=1!ess2ast-loader'), styleLoader); /** * Fonts */ builder.addLoader('woff', load('url-loader?limit=10000&mimetype=application/font-woff')); builder.addLoader('ttf', load('url-loader?limit=10000&mimetype=application/octet-stream')); builder.addLoader('eot', load('file-loader')); /** * Images */ builder.addLoader('png', load('file-loader')); builder.addLoader('jpg', load('file-loader')); builder.addLoader('gif', load('file-loader')); builder.addLoader('svg', load('file-loader')); function load(str) { return str.split('!').map(function(loader) { var parts = loader.split('?'); parts[0] = r.resolve(parts[0], 'warn'); return parts.join('?'); }).join('!'); } };
JavaScript
0.000015
@@ -1967,24 +1967,73 @@ e-loader')); +%0A builder.addLoader('ico', load('file-loader')); %0A%0A function @@ -2231,8 +2231,9 @@ ;%0A %7D%0A%7D; +%0A
f55172cdc84cbc009d9ce3f323259170c02e51bd
Add -L to list apps and enhace -h
bin/r2frida.js
bin/r2frida.js
#!/usr/bin/env node /* ** r2frida main commandline program ** --pancake 2015 */ var spawnSync = require('child_process').spawnSync; var colors = require ('colors'); var fs = require ('fs'); /* actions */ const Option = { showHelp: function() { die ('Usage: r2frida [-h|-v] [-f adb|ip] [-n|-s] [-l|procname|pid]', 0); }, showVersion: function() { const package_json = '' + fs.readFileSync('../package.json'); const version = JSON.parse (package_json).version; die (version, 0); }, enterShell: function(target) { target && exec (process.execPath, ['main.js', target]); die ('Missing target', 1); }, enterBatchShell: function(target) { target && exec (process.execPath, ['main.js', '-n', target]); die ('Missing target', 1); }, forwardPort: function(target) { target || die ('Missing target', 1); if (target == 'adb') { exec ('adb', ['forward', 'tcp:27042', 'tcp:27042']); } else { exec ('ssh', ['-L', '27042:localhost:27042', 'root@'+target]); } exec ('r2', ['r2pipe://node r2io-frida.js ' + target]); }, startR2: function(target) { exec ('r2', ['r2pipe://node r2io-frida.js ' + target]); }, listProcesses: function() { var frida = require ('frida'); frida.getRemoteDevice().then(function(device) { device.enumerateProcesses().then (function(procs) { for (var i in procs.reverse()) { var p = procs[i]; console.log(p.pid + '\t' + p.name); } }) }); } } /* main */ Main (process.argv.slice(2), { '-h': Option.showHelp, '-v': Option.showVersion, '-s': Option.enterShell, '-n': Option.enterBatchShell, '-f': Option.forwardPort, '-l': Option.listProcesses }); function Main(argv, options) { var target = undefined; process.chdir (__dirname + '/../src'); for (var i in argv) { var opt = options [argv[+i]]; if (opt) { return opt (argv[+i + 1]); } if (target) { die ("Invalid parameter: '" + argv[+i] + "'", 1); } target = argv[+i]; } target && Option.startR2(target); Option.showHelp (); } /* utils */ function die(msg, ret) { var println = ret ? console.error : console.log; var color = ret ? colors.red : colors.yellow; println (color (msg)); process.exit (ret); } function exec(cmd, args) { var res = spawnSync (cmd, args, { stdio: [0, 1, 2] }); process.exit (res.status); }
JavaScript
0
@@ -200,16 +200,100 @@ ons */%0A%0A +const helpmsg = 'Usage: r2frida %5B-h%7C-v%5D %5B-f adb%7Cip%5D %5B-n%7C-s%5D %5B-l%7C-L%7Cprocname%7Cpid%5D';%0A%0A const Op @@ -303,24 +303,28 @@ n = %7B%0A show +Long Help: functi @@ -343,44 +343,113 @@ ie ( -'Usage: r2frida %5B-h%7C-v%5D %5B +%5Bhelpmsg,%0A ' -l list processes',%0A ' -L list applications',%0A ' -f +%5B adb%7Cip%5D %5B-n%7C @@ -448,34 +448,235 @@ ip%5D -%5B-n%7C-s%5D %5B-l%7Cprocname%7Cpid%5D' + forward port to frida-server',%0A ' -v show version information',%0A ' -n batch mode no prompt',%0A ' -s enter the r2node shell'%5D.join('%5Cn'));%0A %7D,%0A showHelp: function() %7B%0A die (helpmsg , 0) @@ -1853,20 +1853,348 @@ %7D);%0A + %7D,%0A listApplications: function() %7B%0A var frida = require ('frida');%0A frida.getRemoteDevice().then(function(device) %7B%0A device.enumerateApplications().then (function(procs) %7B%0A for (var i in procs.reverse()) %7B%0A var p = procs%5Bi%5D;%0A console.log(p.pid + '%5Ct' + p.name);%0A %7D%0A %7D)%0A %7D);%0A %7D%0A - %7D%0A%0A/* ma @@ -2246,24 +2246,28 @@ Option.show +Long Help,%0A '-v' @@ -2375,16 +2375,16 @@ rdPort,%0A - '-l': @@ -2403,16 +2403,49 @@ rocesses +,%0A '-L': Option.listApplications %0A%7D);%0A%0Afu
54947867f83002434644bcb3c9e1b85d32ba2825
Set token as unique
server/init_db.js
server/init_db.js
const Knex = require("knex") const knex = Knex(require("./knexfile.js")[process.env.NODE_ENV || "development"]) // Create table knex.schema.createTableIfNotExists("users", (table) => { table.string("id").primary() table.string("token") table.boolean("revoked") table.timestamps(true, true) }) .then(() => console.log("Users table initialize done.")) knex.schema.createTableIfNotExists("item_dislike", (table) => { table.string("by_whom") table.string("username") table.string("id") table.boolean("state") table.timestamps(true, true) table.primary("by_whom", "id") }) .then(() => console.log("Item_dislike table initialize done.")) knex.schema.createTableIfNotExists("access_log", (table) => { table.string("method") table.string("ip") table.integer("status") table.string("path") table.integer("length") table.string("ua") table.string("lang") table.string("protocol") table.string("user") table.timestamps(true, true) }) .then(() => console.log("Access_log table initialize done."))
JavaScript
0.000757
@@ -237,16 +237,25 @@ %22token%22) +.unique() %0A tab
79205f7db320a755224ed9e0fabc82261e1409b5
fix App configError method (#1864)
packages/netlify-cms-core/src/components/App/App.js
packages/netlify-cms-core/src/components/App/App.js
import PropTypes from 'prop-types'; import React from 'react'; import { hot } from 'react-hot-loader'; import { translate } from 'react-polyglot'; import ImmutablePropTypes from 'react-immutable-proptypes'; import styled from 'react-emotion'; import { connect } from 'react-redux'; import { Route, Switch, Redirect } from 'react-router-dom'; import { Notifs } from 'redux-notifications'; import TopBarProgress from 'react-topbar-progress-indicator'; import { loadConfig } from 'Actions/config'; import { loginUser, logoutUser } from 'Actions/auth'; import { currentBackend } from 'src/backend'; import { createNewEntry } from 'Actions/collections'; import { openMediaLibrary } from 'Actions/mediaLibrary'; import MediaLibrary from 'MediaLibrary/MediaLibrary'; import { Toast } from 'UI'; import { Loader, colors } from 'netlify-cms-ui-default'; import history from 'Routing/history'; import { SIMPLE, EDITORIAL_WORKFLOW } from 'Constants/publishModes'; import Collection from 'Collection/Collection'; import Workflow from 'Workflow/Workflow'; import Editor from 'Editor/Editor'; import NotFoundPage from './NotFoundPage'; import Header from './Header'; TopBarProgress.config({ barColors: { '0': colors.active, '1.0': colors.active, }, shadowBlur: 0, barThickness: 2, }); const AppMainContainer = styled.div` min-width: 800px; max-width: 1440px; margin: 0 auto; `; const ErrorContainer = styled.div` margin: 20px; `; const ErrorCodeBlock = styled.pre` margin-left: 20px; font-size: 15px; line-height: 1.5; `; class App extends React.Component { static propTypes = { auth: ImmutablePropTypes.map, config: ImmutablePropTypes.map, collections: ImmutablePropTypes.orderedMap, loadConfig: PropTypes.func.isRequired, loginUser: PropTypes.func.isRequired, logoutUser: PropTypes.func.isRequired, user: ImmutablePropTypes.map, isFetching: PropTypes.bool.isRequired, publishMode: PropTypes.oneOf([SIMPLE, EDITORIAL_WORKFLOW]), siteId: PropTypes.string, useMediaLibrary: PropTypes.bool, openMediaLibrary: PropTypes.func.isRequired, showMediaButton: PropTypes.bool, t: PropTypes.func.isRequired, }; static configError(config) { const t = this.props.t; return ( <ErrorContainer> <h1>{t('app.app.errorHeader')}</h1> <div> <strong>{t('app.app.configErrors')}:</strong> <ErrorCodeBlock>{config.get('error')}</ErrorCodeBlock> <span>{t('app.app.checkConfigYml')}</span> </div> </ErrorContainer> ); } componentDidMount() { const { loadConfig } = this.props; loadConfig(); } handleLogin(credentials) { this.props.loginUser(credentials); } authenticating() { const { auth, t } = this.props; const backend = currentBackend(this.props.config); if (backend == null) { return ( <div> <h1>{t('app.app.waitingBackend')}</h1> </div> ); } return ( <div> <Notifs CustomComponent={Toast} /> {React.createElement(backend.authComponent(), { onLogin: this.handleLogin.bind(this), error: auth && auth.get('error'), isFetching: auth && auth.get('isFetching'), inProgress: (auth && auth.get('isFetching')) || false, siteId: this.props.config.getIn(['backend', 'site_domain']), base_url: this.props.config.getIn(['backend', 'base_url'], null), authEndpoint: this.props.config.getIn(['backend', 'auth_endpoint']), config: this.props.config, clearHash: () => history.replace('/'), })} </div> ); } handleLinkClick(event, handler, ...args) { event.preventDefault(); handler(...args); } render() { const { user, config, collections, logoutUser, isFetching, publishMode, useMediaLibrary, openMediaLibrary, t, showMediaButton, } = this.props; if (config === null) { return null; } if (config.get('error')) { return App.configError(config); } if (config.get('isFetching')) { return <Loader active>{t('app.app.loadingConfig')}</Loader>; } if (user == null) { return this.authenticating(t); } const defaultPath = `/collections/${collections.first().get('name')}`; const hasWorkflow = publishMode === EDITORIAL_WORKFLOW; return ( <div> <Notifs CustomComponent={Toast} /> <Header user={user} collections={collections} onCreateEntryClick={createNewEntry} onLogoutClick={logoutUser} openMediaLibrary={openMediaLibrary} hasWorkflow={hasWorkflow} displayUrl={config.get('display_url')} showMediaButton={showMediaButton} /> <AppMainContainer> {isFetching && <TopBarProgress />} <div> <Switch> <Redirect exact from="/" to={defaultPath} /> <Redirect exact from="/search/" to={defaultPath} /> {hasWorkflow ? <Route path="/workflow" component={Workflow} /> : null} <Route exact path="/collections/:name" component={Collection} /> <Route path="/collections/:name/new" render={props => <Editor {...props} newRecord />} /> <Route path="/collections/:name/entries/:slug" component={Editor} /> <Route path="/search/:searchTerm" render={props => <Collection {...props} isSearchResults />} /> <Route component={NotFoundPage} /> </Switch> {useMediaLibrary ? <MediaLibrary /> : null} </div> </AppMainContainer> </div> ); } } function mapStateToProps(state) { const { auth, config, collections, globalUI, mediaLibrary } = state; const user = auth && auth.get('user'); const isFetching = globalUI.get('isFetching'); const publishMode = config && config.get('publish_mode'); const useMediaLibrary = !mediaLibrary.get('externalLibrary'); const showMediaButton = mediaLibrary.get('showMediaButton'); return { auth, config, collections, user, isFetching, publishMode, showMediaButton, useMediaLibrary, }; } const mapDispatchToProps = { openMediaLibrary, loadConfig, loginUser, logoutUser, }; export default hot(module)( connect( mapStateToProps, mapDispatchToProps, )(translate()(App)), );
JavaScript
0
@@ -2177,23 +2177,16 @@ %7D;%0A%0A -static configEr @@ -4061,19 +4061,20 @@ return -App +this .configE
cff1951c21755ee2b661f36bed1aac24dcc95e25
Fix rejudge script
bin/rejudge.js
bin/rejudge.js
const mongoose = require('mongoose'); const assert = require('assert'); const Contest = require('../models/Contest'); const Submission = require('../models/Submission'); const Language = require('../models/Language'); const validation = require('../lib/validation'); const languagesData = require('../data/languages'); require('../models/User'); mongoose.Promise = global.Promise; (async () => { await mongoose.connect('mongodb://localhost:27017/esolang-battle'); const contest = await Contest.findOne({id: '5'}); const languages = await Language.find({contest, solution: {$ne: null}}); // rollback for (const language of languages) { console.log(`Rejudging language ${language.slug}...`); const languageData = languagesData[contest.id].find( (l) => l && l.slug === language.slug ); assert(languageData); while (true) { const submission = await Submission.findOne({ contest, language, status: 'success', }).sort({createdAt: -1}).exec(); if (!submission) { console.log('Solution not found.'); language.solution = null; await language.save(); break; } console.log(`Rejudging submission ${submission._id}...`); await validation.validate({ submission, language: languageData, solution: null, contest, noInputGeneration: true, }); const newSubmission = await Submission.findOne({_id: submission._id}); assert(newSubmission); if (newSubmission.status === 'success') { console.log(`Solution found as ${newSubmission._id}`); language.solution = newSubmission; await language.save(); break; } console.log(`${newSubmission._id} is invalid`); } } mongoose.connection.close(); })();
JavaScript
0.000001
@@ -582,16 +582,31 @@ e: null%7D +, slug: 'c-gcc' %7D);%0A%0A%09// @@ -1429,16 +1429,47 @@ ission); +%0A%09%09%09console.log(newSubmission); %0A%0A%09%09%09if
428dd4b45887235794d5a8c8ef42ce1eb5c5340e
fix for remove class + css on completion
bannersSrc/lib/initial.js
bannersSrc/lib/initial.js
// Setup banner namespace window.creative = window.creative || {}; //console.log("src/lib/initial.js:: creative = ", window.creative); require("./lazyLoad"); creative.adCompleted = false; // Checks if Enabler is loaded creative.init = function () { creative.detectIE(); creative.setupDOMElements(); if (Enabler.isInitialized()) { creative.enablerInitHandler(); } else { Enabler.addEventListener(studio.events.StudioEvent.INIT, creative.enablerInitHandler); } }; /** * enablerInitHandler * Checks if page is loaded, or waits for it to load, then inits pageLoadHandler() */ creative.enablerInitHandler = function (event) { if ( creative.dynamicDataAvailable ) { creative.dynamicDataAvailable(); } creative.domEl.tapArea.addEventListener('click', creative.exitClickHandler); creative.domEl.loader.addEventListener('click', creative.exitClickHandler); // Check if page is loaded if (Enabler.isPageLoaded()) { creative.pageLoadHandler(); } else { Enabler.addEventListener(studio.events.StudioEvent.PAGE_LOADED, creative.pageLoadHandler); } }; // Once page has loaded, init the ad creative.pageLoadHandler = function (event) { creative.loadPolite(); }; creative.isAndroidNativeBrowser = (function () { var ua = navigator.userAgent.toLowerCase(); return ua.indexOf('android') != -1 && ua.indexOf('mobile') != -1 && ua.indexOf('chrome') == -1; })(); var firstElementLoaded = false; // Load polite CSS and JS creative.loadPolite = function () { if (creative.isAndroidNativeBrowser === true) { LazyLoad.js("polite.js"); LazyLoad.css("polite.css"); // FORCES ANDROID ONLY FONT SMOOTHING document.querySelector('.banner').classList.add("is-android"); addAuxiliaryLoader(); }else{ LazyLoad.js("polite.js",creative.onJSLoaded); } }; creative.onJSLoaded = function () { LazyLoad.css("polite.css",creative.onCSSLoaded); }; creative.onCSSLoaded = function () { creative.smoothHideLoader(); }; function addAuxiliaryLoader() { creative.auxiliaryLoader = setInterval(doPoll, 100); }; function removeAuxiliaryLoader() { window.clearInterval(creative.auxiliaryLoader); }; function doPoll() { if(document.styleSheets.length > 1) { removeAuxiliaryLoader(); creative.smoothHideLoader(); } }; creative.showAd = function() { // Hide loader document.querySelector('.loader').className = "loader is-hidden"; // start the creative creative.startBannerAnimation(); }; creative.smoothHideLoader = function () { // Show banner content document.querySelector('.banner-content').className = "banner-content"; document.querySelector('.loader').className = "loader is-smoothLoaderFading"; setTimeout(function(){ creative.showAd(); }, 500); } /** * Add days to today * Used in the creative.exitClickCreate() method * format as 20140730 */ creative.addDays = function(theDate, days) { var newDate = new Date(theDate.getTime() + days*24*60*60*1000); return newDate.getFullYear() + ('0' + (newDate.getMonth()+1)).slice(-2) + ('0' + newDate.getDate()).slice(-2); }; /** * Exit click handler * This creates the Exit link. If there are {out} or {rtn} flags then we know its a dynamic exit. * &out=20140731&rtn=20140820 */ creative.exitClickCreate = function() { //console.log("exitClickCreate fired"); return creative.dynamicData.exitURL.Url; }; creative.exitClickHandler = function (event) { event.preventDefault(); Enabler.exit("clicktrough"); }; /// helper functions // return true or false if the element got the class creative.hasClass = function ( className, element) { return element.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(element.className); }; // add a class to an element creative.addClass = function( classname, element ) { var cn = element.className; //test for existance if( cn.indexOf( classname ) != -1 ) { return; } //add a space if the element already has class if( cn != '' ) { classname = ' '+classname; } element.className = cn+classname; }; // remove a class to an element creative.removeClass = function( classname, element ) { var cn = '.'+element.className; var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" ); cn = cn.replace( rxp, '' ); element.className = cn; element.offsetWidth = element.offsetWidth; }; creative.removeFromString = function (str,value ) { var newStr = str.replace(value, ""); return newStr } /* * detect IE * returns version of IE or false, if browser is not Internet Explorer */ creative.detectIE = function () { var bannerContent = document.querySelector('.banner-content'); var defaultImg = document.querySelector('#default-img'); var loader = document.querySelector('.loader'); var isIE9 = /MSIE 9/i.test(navigator.userAgent); if (isIE9 ) { // alert("IE 9 or below, show static image."); creative.addClass('is-hidden',bannerContent); creative.addClass('is-hidden',loader); } else { creative.addClass('is-hidden',defaultImg); } }; var pfx = ["webkit", "moz", "MS", "o", ""]; creative.prefixedEvent = function (element, type, callback) { for (var p = 0; p < pfx.length; p++) { if (!pfx[p]) type = type.toLowerCase(); element.addEventListener(pfx[p]+type, callback, false); } } // Start creative once all elements in window are loaded. window.addEventListener('load', creative.init.bind(creative));
JavaScript
0
@@ -4091,12 +4091,8 @@ n = -'.'+ elem
a938be4893cd2fefb61786f4af003f3329f0a85e
Disable lint rule
lib/node_modules/@stdlib/assert/is-boolean/test/test.try2serialize.js
lib/node_modules/@stdlib/assert/is-boolean/test/test.try2serialize.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var serialize = require( './../lib/try2serialize.js' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.equal( typeof serialize, 'function', 'main export is a function' ); t.end(); }); tape( 'the function returns `true` if able to serialize', function test( t ) { t.equal( serialize( true ), true, 'returns true' ); t.equal( serialize( new Boolean( true ) ), true, 'returns true' ); t.equal( serialize( false ), true, 'returns true' ); t.equal( serialize( new Boolean( false ) ), true, 'returns true' ); t.end(); }); tape( 'the function returns `false` if unable to serialize', function test( t ) { t.equal( serialize( {} ), false, 'returns false' ); t.end(); });
JavaScript
0.000001
@@ -1102,32 +1102,71 @@ returns true' ); + // eslint-disable-line no-new-wrappers %0A%09t.equal( seria @@ -1268,24 +1268,63 @@ rns true' ); + // eslint-disable-line no-new-wrappers %0A%09t.end();%0A%7D
5956337914821e1b5a93211ceefb02474c4dc352
improve assignment testcase
__tests__/ACD.test.js
__tests__/ACD.test.js
import { readFileSync } from 'fs'; import { convert } from '../src'; describe('Test from ACD Jcamp generator', () => { it('COSY simulated spectrum', () => { let result = convert( readFileSync(`${__dirname}/data/acd/test1_cosy.jdx`).toString(), ); expect(result.entries[0].ntuples).toHaveLength(3); expect(result.entries[0].twoD).toBe(true); expect(result.entries[0].contourLines).toBeInstanceOf(Object); }); it('assignment', () => { let result = convert(readFileSync(`${__dirname}/data/acd/assignment.jdx`)); expect(result.flatten).toHaveLength(5); }); });
JavaScript
0.020735
@@ -537,16 +537,56 @@ nt.jdx%60) +, %7B%0A keepRecordsRegExp: /.*/,%0A %7D );%0A e @@ -624,16 +624,104 @@ gth(5);%0A + const meta = result.flatten%5B1%5D.info;%0A expect(Object.keys(meta)).toHaveLength(9);%0A %7D);%0A%7D)
e8e9ad614cb35cadb4a49bf4d7e102f09933bc4c
Use base Widget class to check version and patch subscribe method.
components/dashboards-web-component/src/utils/WidgetClassRegistry.js
components/dashboards-web-component/src/utils/WidgetClassRegistry.js
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. */ /** * Registry that maintains widget classes against their names. */ class WidgetClassRegistry { constructor() { this.registry = new Map(); } /** * Registers a widget class. * @param {string} widgetName widget name * @param {class} widgetClass widget class * @throws {Error} if a class is already registered for the specified widget name */ registerWidgetClass(widgetName, widgetClass) { if (this.registry.get(widgetName)) { return; } this.registry.set(widgetName, widgetClass); } /** * Returns class of a registered widget * @param {string} widgetName widget name * @returns {class} widget class */ getWidgetClass(widgetName) { return this.registry.get(widgetName); } /** * Returns names of all registered widgets. * @returns {string[]} widget names */ getRegisteredWidgetNames() { return Array.from(this.registry.keys()); } } const instance = new WidgetClassRegistry(); export default instance; // Following is to maintain backward compatibility with SP-4.0.0, SP-4.1.0 /** * Checks whether given widget class extends from a deprecated version of @wso2-dashboards/widget class. * @param {class} widgetClass class to be checked * @returns {boolean} true if extend from a deprecated version of the Widget class, otherwise false * @private */ function extendsFromDeprecatedWidgetClassVersion(widgetClass) { return !Object.getPrototypeOf(widgetClass.prototype).version; } /** * Patches given widget class which extends from a deprecated version of @wso2-dashboards/widget class, to be * compatible with newer versions. * @param {class} widgetClass widget class to be patched * @private */ function patchWidgetClass(widgetClass) { const superWidgetClassPrototype = Object.getPrototypeOf(widgetClass.prototype); // Patch subscribe method. superWidgetClassPrototype.subscribe = function (listenerCallback, publisherId, context) { const self = this; if (!publisherId) { const publisherIds = self.props.configs.pubsub.publishers; if (publisherIds && Array.isArray(publisherIds)) { publisherIds.forEach(id => self.props.glEventHub.on(id, listenerCallback)); } } else { self.props.glEventHub.on(publisherId, listenerCallback, context); } }; } global.dashboard = {}; global.dashboard.registerWidget = function (widgetId, widgetObj) { console.warn(`[DEPRECATED] Widget '${widgetId}' uses deprecated function ` + '\'window.dashboard.registerWidget(widgetId, widgetObj)\'. ' + 'Instead please use \'Widget.registerWidgetClass(widgetName, widgetClass)\' function.'); if (extendsFromDeprecatedWidgetClassVersion(widgetObj)) { console.warn(`[DEPRECATED] Widget '${widgetId}' extends from a deprecated version of the Widget ` + '(@wso2-dashboards/widget) class. Please use the newest version.'); patchWidgetClass(widgetObj); } instance.registerWidgetClass(widgetId, widgetObj); };
JavaScript
0
@@ -667,16 +667,63 @@ e.%0A */%0A%0A +import Widget from '@wso2-dashboards/widget';%0A%0A /**%0A * R @@ -2209,17 +2209,16 @@ return -! Object.g @@ -2254,16 +2254,47 @@ totype). +constructor.version !== Widget. version; @@ -2721,465 +2721,34 @@ e = -function (listenerCallback, publisherId, context) %7B%0A const self = this;%0A if (!publisherId) %7B%0A const publisherIds = self.props.configs.pubsub.publishers;%0A if (publisherIds && Array.isArray(publisherIds)) %7B%0A publisherIds.forEach(id =%3E self.props.glEventHub.on(id, listenerCallback));%0A %7D%0A %7D else %7B%0A self.props.glEventHub.on(publisherId, listenerCallback, context);%0A %7D%0A %7D +Widget.prototype.subscribe ;%0A%7D%0A
3bcb91a78510349fa6c4801ab7db1f69359e378b
Change style files
__tests__/app.spec.js
__tests__/app.spec.js
'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); describe('generator-batangularjs:app', () => { beforeAll(() => helpers.run(path.join(__dirname, '../generators/app')) ); let files = [ 'index.html', 'package.json', 'webpack.config.js', '.editorconfig', '.eslintrc.js', '.gitignore', '.yo-rc.json', 'app/app.component.js', 'app/app.module.js', 'app/app.scss', 'app/components/components.module.js', 'app/components/home/home.module.js', 'app/components/home/home.component.js', 'app/components/home/home.component.html', 'app/common/common.module.js' ]; files.forEach(file => it(`create ${file}`, () => assert.file([file]))); });
JavaScript
0.000001
@@ -466,16 +466,26 @@ app/app. +component. scss',%0A @@ -656,24 +656,71 @@ nent.html',%0A + 'app/components/home/home.component.scss',%0A 'app/com
42ba8e3d5583be1c72168e0108a4850696b06d7f
Remove extra spaces.
demo_modules/big_image_carousel/big_image_carousel.js
demo_modules/big_image_carousel/big_image_carousel.js
/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ const ModuleInterface = require('lib/module_interface'); const register = require('register'); const wallGeometry = require('wallGeometry'); class BigImageCarouselServer extends ModuleInterface.Server { } // Create a polygon extending from x,y by w,h. // p5 must be a P5.js instance. class BigImageCarouselSketch { constructor(p5, surface, extraArgs) { this.p5 = p5; this.surface = surface; this.tiles = null; this.image_list_config = extraArgs; } preload() { var p5 = this.p5; this.backgroundColor = p5.color(120); const asset = require('client/asset/asset'); this.tiles = new Array(); for (let path in this.image_list_config) { let images = this.image_list_config[path]; for (let i in images) { // TODO(jgessner): switch to functional style. let image = images[i]; for (let x = 0; x < image.num_x_tiles; x++) { let tilePath = asset(path + image.name + '_tile-' + x + '_' + this.surface.virtualOffset.y + '.' + image.extension); this.tiles.push(p5.loadImage(tilePath)); } } } } setup() { var p5 = this.p5; p5.noFill(); p5.stroke(255, 0, 0); p5.strokeWeight(4); // Each instance will only ever draw images from one Y offset, but many X offsets. this.sum_tile_width = 0; for (let x = 0; x < this.tiles.length; x++) { this.sum_tile_width += this.tiles[x].width; } if (this.sum_tile_width < this.surface.wallRect.w) { let initial_sum_tile_width = this.sum_tile_width; while (this.sum_tile_width < this.surface.wallRect.w) { this.tiles = this.tiles.concat(this.tiles); this.sum_tile_width += initial_sum_tile_width; } } // Pre-draw the images off-screen so we don't need to load them or decode them while drawing. for (let i in this.tiles) { p5.image(this.tiles[i], -10000, -10000); } } draw(t) { var p5 = this.p5; if (this.tiles == null) { return; } if (this.surface.virtualOffset.y == null) { return; } // x_0 is the actual position that the first tile should be drawn at. // Make sure to draw integer pixel positions or performance will suffer. let x_0 = Math.floor((((t - this.surface.startTime) / 9) % (2*this.sum_tile_width)) - this.sum_tile_width); // for each iteration: // - translate x zero // - fit all of the tiles necessary into a given window (the overall width)) // states: // - only draw positive // - draw negative and positive // - // from all of the images, figure out the total width. That strip will be the thing that cycles. // if sum of all image widths > wall width, identify the starting let x_offset = x_0; // walk backwards through the list to draw the tail end until we have no more of it. // Draw the "positive" images. const screen_right_edge = this.surface.virtualRect.x + this.surface.virtualRect.w; for (let x = 0; x < this.tiles.length; x++) { let image = this.tiles[x]; let right_x = x_offset + image.width; // Do we need to draw this image? if ((x_offset >= this.surface.virtualRect.x && x_offset <= screen_right_edge) || (right_x >= this.surface.virtualRect.x && right_x < screen_right_edge)) { p5.image(image, x_offset, this.surface.virtualRect.y); } x_offset += image.width; } if (x_0 < 0) { // need to fill in images on the right. while (x_offset < this.surface.wallRect.w) { for (let x = 0; x < this.tiles.length; x++) { let image = this.tiles[x]; let right_x = x_offset + image.width; // Do we need to draw this image? if ((x_offset >= this.surface.virtualRect.x && x_offset <= screen_right_edge) || (right_x >= this.surface.virtualRect.x && right_x < screen_right_edge)) { p5.image(image, x_offset, this.surface.virtualRect.y); } x_offset += image.width; } } } if (x_0 > 0) { x_offset = x_0; for (let x = this.tiles.length - 1; x >= 0; x--) { let image = this.tiles[x]; x_offset -= image.width; let right_x = x_offset + image.width; // Do we need to draw this image? if ((x_offset >= this.surface.virtualRect.x && x_offset <= screen_right_edge) || (right_x >= this.surface.virtualRect.x && right_x < screen_right_edge)) { p5.image(image, x_offset, this.surface.virtualRect.y); } } } } } class BigImageCarouselClient extends ModuleInterface.Client { constructor(config) { super(); this.config = config; } finishFadeOut() { if (this.surface) { this.surface.destroy(); } } willBeShownSoon(container, deadline) { const P5Surface = require('client/surface/p5_surface'); this.surface = new P5Surface(container, wallGeometry, BigImageCarouselSketch, deadline, this.config); } draw(time, delta) { this.surface.p5.draw(time); } } register(BigImageCarouselServer, BigImageCarouselClient);
JavaScript
0.000121
@@ -1076,18 +1076,17 @@ = null; - %0A + %0A thi @@ -1118,17 +1118,16 @@ raArgs;%0A -%0A %7D%0A%0A p @@ -1282,17 +1282,16 @@ Array(); - %0A for @@ -2362,17 +2362,16 @@ e_width; - %0A %7D @@ -3037,17 +3037,16 @@ e x zero - %0A // @@ -3209,17 +3209,16 @@ // - - %0A // @@ -3309,24 +3309,24 @@ at cycles.%0A%0A + // if su @@ -3382,17 +3382,16 @@ starting - %0A let
e8a12360cc1faf2874c19691d3dbfb0418df5aff
remove unused route
both/router.js
both/router.js
Router.configure({ layoutTemplate: 'layout' }); Meteor.startup(function () { if (Meteor.isClient) { var location = Iron.Location.get(); if (location.queryObject.platformOverride) { Session.set('platformOverride', location.queryObject.platformOverride); } } }); Router.map(function() { this.route('tabs.one', {path: '/'}); // this.route('sfNewUser', {path: '/'}); this.route('actionSheet'); this.route('backdrop'); this.route('forms', { data: function () { return { post: Posts.find().fetch()[0] }; } }); this.route('headersFooters'); this.route('lists'); this.route('postLists'); //this.route('postDetails'); this.route('newPost'); this.route('loading'); this.route('modal'); this.route('navigation'); this.route('navigation.one', {path: '/navigation/one'}); this.route('navigation.two', {path: '/navigation/two'}); this.route('navigation.three', {path: '/navigation/three'}); this.route('popover'); this.route('popup'); this.route('sideMenu'); this.route('slideBox'); // this.route('tabs.one', {path: '/tabs/one', layoutTemplate: 'tabsLayout'}); this.route('tabs.two', {path: '/tabs/two', layoutTemplate: 'tabsLayout'}); this.route('tabs.three', {path: '/tabs/three', layoutTemplate: 'tabsLayout'}); this.route('tabs.four', {path: '/tabs/four', layoutTemplate: 'tabsLayout'}); this.route('userAccounts'); this.route('sfNewpost'); this.route('sfNewUser'); this.route('userLogin'); this.route('/users/:_id', { name: 'userInfo', data: function() { return SofitUsers.findOne(this.params._id); } }); this.route("profile", { waitOn: function() { return [Meteor.subscribe('images')]; } }); Router.route('/posts/:_id', { name: 'postDetails', data: function() { return Lmingposts.findOne(this.params._id); } }); });
JavaScript
0.000007
@@ -1620,115 +1620,8 @@ );%0A%0A - this.route(%22profile%22, %7B%0A waitOn: function() %7B%0A return %5BMeteor.subscribe('images')%5D;%0A %7D%0A %7D);%0A%0A Ro
d9a22726f10d587188cf9b13f9152d460a179e81
Make territory filter mandatory
erpnext/accounts/report/inactive_sales_items/inactive_sales_items.js
erpnext/accounts/report/inactive_sales_items/inactive_sales_items.js
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Inactive Sales Items"] = { "filters": [ { fieldname: "territory", label: __("Territory"), fieldtype: "Link", options: "Territory" }, { fieldname: "item", label: __("Item"), fieldtype: "Link", options: "Item" }, { fieldname: "item_group", label: __("Item Group"), fieldtype: "Link", options: "Item Group" }, { fieldname: "based_on", label: __("Based On"), fieldtype: "Select", options: "Sales Order\nSales Invoice", default: "Sales Order" }, { fieldname: "days", label: __("Days Since Last order"), fieldtype: "Select", options: [30, 60, 90], default: 30 }, ] };
JavaScript
0.000001
@@ -302,16 +302,29 @@ rritory%22 +,%0A%09%09%09reqd: 1, %0A%09%09%7D,%0A%09%09
a856537b97ed26338a152a01e454502f0a92416b
Add pig latin solution
Strings/PigLatin/pig_latin_2.js
Strings/PigLatin/pig_latin_2.js
function pigIt(str){ //Code here }
JavaScript
0.999997
@@ -1,36 +1,502 @@ -function pigIt(str)%7B%0A //Code here%0A%7D +/* it uses a regex to create 3 groups: 1) first letter, 2) rest of the word, then 3) either space or end of the string. The %22g%22 in the end of it means that it has not to stop at the first match, but it has to find all the (non overlapping) occurrences of it.%0AThat is the red part; the rest reutilizes the groups (using %5C$n, with n being the group number) to recompose the string :)*/%0Afunction pigIt(str)%7B%0A return str.replace(/(%5Cw)(%5Cw*)(%5Cs%7C$)/g, %22%5C$2%5C$1ay%5C$3%22);%0A%7D%0A%0Aconsole.log(pigIt(process.argv%5B2%5D));
56db9405daadfdce05aec5c2bd9d5d57c1a076db
add PropertyName object to DesktopListing
packages/react-ui-ag/src/Listings/DesktopListing.js
packages/react-ui-ag/src/Listings/DesktopListing.js
import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import themed from 'react-themed' import classnames from 'classnames' import { ListingComponents } from '@rentpath/react-ui-core' import Listing from './Listing' @themed([ 'DesktopListing', 'BedsAndBaths', 'UnitLevelAvailabilityAndLastUpdated', 'LastUpdated', 'Phone', ], { pure: true }) export default class DesktopListing extends PureComponent { static propTypes = { listing: PropTypes.object, theme: PropTypes.object, className: PropTypes.string, ratings: PropTypes.object, } static defaultProps = { theme: {}, listing: {}, ratings: {}, } get renderInfo() { const { theme, listing, ratings } = this.props const { singleFamily, rating, lastUpdated, phone } = listing return ( <React.Fragment> <ListingComponents.Price /> <div className={theme.BedsAndBaths}> <ListingComponents.Bedroom data-tid="bedroom" /> <ListingComponents.Bathroom /> </div> {singleFamily ? <ListingComponents.Availability /> : ( <div className={theme.UnitLevelAvailabilityAndLastUpdated}> <ListingComponents.UnitLevelAvailability /> {lastUpdated && <div className={theme.LastUpdated}>{lastUpdated}</div>} </div> ) } {singleFamily ? <ListingComponents.Address /> : <ListingComponents.PropertyName /> } {rating && !singleFamily && <ListingComponents.Ratings data-tid="ratings" {...ratings} /> } {phone && !singleFamily && <div className={theme.Phone} data-tid="phone">{phone}</div> } </React.Fragment> ) } render() { const { theme, className, listing, ratings, ...props } = this.props return ( <Listing listing={listing} className={classnames( className, theme.DesktopListing )} listingInfoComponents={this.renderInfo} {...props} /> ) } }
JavaScript
0.000001
@@ -580,20 +580,56 @@ object,%0A + propertyName: PropTypes.object,%0A %7D%0A - %0A stati @@ -696,16 +696,38 @@ gs: %7B%7D,%0A + propertyName: %7B%7D,%0A %7D%0A%0A g @@ -740,24 +740,24 @@ derInfo() %7B%0A - const %7B @@ -779,16 +779,30 @@ ratings +, propertyName %7D = thi @@ -1554,16 +1554,34 @@ ertyName + %7B...propertyName%7D /%3E%0A
337aed906c69a6a3c63a3d384124a665d1d53d59
Fix flow type for GraphQLResponse
packages/relay-runtime/network/RelayNetworkTypes.js
packages/relay-runtime/network/RelayNetworkTypes.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule RelayNetworkTypes * @flow * @format */ 'use strict'; import type {ConcreteOperation, RequestNode} from 'RelayConcreteNode'; import type RelayObservable, {ObservableFromValue} from 'RelayObservable'; import type { CacheConfig, Disposable, } from 'react-relay/classic/environment/RelayCombinedEnvironmentTypes'; import type {Variables} from 'react-relay/classic/tools/RelayTypes'; /** * An interface for fetching the data for one or more (possibly interdependent) * queries. */ export type Network = {| execute: ExecuteFunction, |}; export type PayloadData = {[key: string]: mixed}; export type PayloadError = { message: string, locations?: Array<{ line: number, column: number, }>, }; /** * The shape of a GraphQL response as dictated by the * [spec](http://facebook.github.io/graphql/#sec-Response) */ export type GraphQLResponse = {| data?: ?PayloadData, errors?: Array<PayloadError>, |}; /** * The data returned from Relay's execute function, which includes both the * raw GraphQL network response as well as any related client metadata. */ export type ExecutePayload = {| // The operation executed operation: ConcreteOperation, // The variables which were used during this execution. variables: Variables, // The response from GraphQL execution response: GraphQLResponse, // Default is false isOptimistic?: boolean, |}; /** * A function that returns an Observable representing the response of executing * a GraphQL operation. */ export type ExecuteFunction = ( request: RequestNode, variables: Variables, cacheConfig: CacheConfig, uploadables?: ?UploadableMap, ) => RelayObservable<ExecutePayload>; /** * A function that executes a GraphQL operation with request/response semantics. * * May return an Observable or Promise of a plain GraphQL server response, or * a composed ExecutePayload object supporting additional metadata. */ export type FetchFunction = ( request: RequestNode, variables: Variables, cacheConfig: CacheConfig, uploadables: ?UploadableMap, ) => ObservableFromValue<ExecutePayload> | ObservableFromValue<GraphQLResponse>; /** * A function that executes a GraphQL subscription operation, returning one or * more raw server responses over time. * * May return an Observable, otherwise must call the callbacks found in the * fourth parameter. */ export type SubscribeFunction = ( request: RequestNode, variables: Variables, cacheConfig: CacheConfig, observer?: LegacyObserver<GraphQLResponse>, ) => | RelayObservable<ExecutePayload> | RelayObservable<GraphQLResponse> | Disposable; export type Uploadable = File | Blob; // $FlowFixMe this is compatible with classic api see D4658012 export type UploadableMap = {[key: string]: Uploadable}; // Supports legacy SubscribeFunction definitions. Do not use in new code. export type LegacyObserver<-T> = {| +onCompleted?: ?() => void, +onError?: ?(error: Error) => void, +onNext?: ?(data: T) => void, |};
JavaScript
0.000005
@@ -1060,20 +1060,100 @@ sponse = - %7B%7C%0A +%0A %7C %7B%0A data: PayloadData,%0A errors?: Array%3CPayloadError%3E,%0A %7D%0A %7C %7B%0A data?: @@ -1167,24 +1167,28 @@ adData,%0A + errors ?: Array @@ -1171,33 +1171,32 @@ ta,%0A errors -? : Array%3CPayloadE @@ -1202,17 +1202,20 @@ Error%3E,%0A -%7C + %7D;%0A%0A/**%0A
13c284fbcaf8033828bd0dd3edfe9594d342fcca
fix reddit links
services/feeds.js
services/feeds.js
const config = require("../config.json"); const feeds = require("../core/json/feeds.json"); const Redis = require("redis"); const schedule = require("node-schedule"); const needle = require("needle"); const querystring = require("../core/util/query_string"); const redis = Redis.createClient(); const jobs = {}; function log(str) { if (typeof str === "string") { console.log(`${new Date().toJSON()} [L_CRON] ${str}`); } else { console.log(str); } } function encodeURL(url, qs) { if (qs) url += querystring(qs); return url; } async function consumeResponse(feed, body) { if (feed.action === "store") { redis.set(feed.key, JSON.stringify(body), (err) => { err ? console.error(err) : log(`stored feed ${feed.name} in redis`); }); } else if (feed.action === "publish") { let post = {}; post.author = feed.name; if (feed.key === "listen:rss:blog") { post.title = body.rss.channel.item[0].title; post.link = body.rss.channel.item[0].link; post.guid = body.rss.channel.item[0].guid._; } if (feed.key === "listen:rss:steamnews" && body.appnews.newsitems[0].is_external_url === false) { post.title = body.appnews.newsitems[0].title; post.link = body.appnews.newsitems[0].url; post.guid = body.appnews.newsitems[0].gid; } if (feed.key === "listen:rss:belvedere" || feed.key === "listen:rss:cyborgmatt") { post.title = body.feed.entry[0].title; post.link = `https://www.reddit.com${body.feed.entry[0].link.$.href}`; post.guid = body.feed.entry[0].id; } if (post.guid) { redis.get(`${feed.key}:last`, (err, reply) => { if (err) { console.error(err); } else if (reply !== post.guid) { log(`new post found for ${feed.name}, publishing`); redis.publish(feed.key, JSON.stringify(post)); redis.set(`${feed.key}:last`, post.guid, (err) => { if (err) console.error(err); }); } }); } } } function executeJob(feed) { let url = encodeURL(feed.url, feed.querystring); let headers = {}; if (feed.authtype) { if (feed.authtype === "twitch") { headers["Client-ID"] = config.twitch.client_id; } } if (feed.headers) { for (header in feed.headers) { headers[header] = feed.headers[header]; } } needle.get(url, { headers }, (err, response, body) => { if (err || response.statusCode !== 200) { console.error(`something wrong with ${feed.name}.`); console.error(err); console.error(`status code: ${response.statusCode}`); } else { consumeResponse(feed, body); } }); } redis.on("ready", () => { feeds.forEach((feed) => { log(`executing first job ${feed.name}`); executeJob(feed); }); feeds.forEach((feed) => { log(`subscribing to feed ${feed.name}: ${feed.cron}`); jobs[feed.key] = schedule.scheduleJob(feed.cron, function(feed) { log(`executing job ${feed.name}`); executeJob(feed); }.bind(null, feed)); }); });
JavaScript
0.000032
@@ -1575,33 +1575,8 @@ k = -%60https://www.reddit.com$%7B body @@ -1601,18 +1601,16 @@ k.$.href -%7D%60 ;%0A
d5cd79015524ebdcf2894b3a5cc5a4b33ca92c9f
Fix caret positioning issues
jquery.textareaAutoHeight.js
jquery.textareaAutoHeight.js
$.fn.textareaAutoHeight = function(){ var $elm = this, $clonedField = $elm.clone(), originalFieldHeight = $elm.height(); $elm.height(originalFieldHeight); $clonedField.css({left: "-9999px",position: "absolute"}); $clonedField.appendTo("body"); $elm.keydown(function(e){ if(e.which == 8){ var currentVal = $(this).val(), currentHeight = $clonedField[0].scrollHeight, newVal = null; var domNode = $(this)[0]; var selection = $(this).getSelection(); if(selection.length > 0){ newVal = currentVal.substr(0, selection.start) + currentVal.substr(selection.end, currentVal.length); } else { newVal = currentVal.substr(0, selection.start - 1) + currentVal.substr(selection.end, currentVal.length); } $clonedField.val(newVal); var newHeight = $clonedField[0].scrollHeight; if(newHeight < currentHeight){ $(this).height(newHeight); $(this).val(newVal); var selectionStart = selection.start, selectionEnd = selection.end; if(selectionStart != selectionEnd){ selectionEnd = selectionStart; } else { selectionStart -= 1; selectionEnd -= 1; } $(this).prop("selectionStart", selectionStart); $(this).prop("selectionEnd", selectionEnd); return false; } } }); $elm.keypress(function(e){ var charPressed = String.fromCharCode(e.which), currentValue = $(this).val(), newValue = currentValue + charPressed, currentHeight = $clonedField[0].scrollHeight; $clonedField.val(newValue); var newHeight = $clonedField[0].scrollHeight; if(newHeight > currentHeight){ $(this).height($clonedField[0].scrollHeight); } $(this).val(newValue); return false; }); };
JavaScript
0
@@ -1554,33 +1554,127 @@ -newValue = currentValue + +currentHeight = $clonedField%5B0%5D.scrollHeight,%0A selection = $(this).getSelection();%0A%0A if(e.which == 13)%7B%0A cha @@ -1685,290 +1685,894 @@ ssed -, + = %22%5Cn%22; %0A +%7D%0A%0A -currentHeight = $clonedField%5B0%5D.scrollHeight;%0A %0A $clonedField.val(newValue);%0A %0A var newHeight = $clonedField%5B0%5D.scrollHeight;%0A %0A if(newHeight %3E currentHeight)%7B%0A $(this).height($clonedField%5B0%5D.scrollHeight);%0A %7D%0A %0A $(this).val(newValue);%0A +function stringWithStringInsertedAt(index, original, str)%7B%0A var firstPart = original.substr(0, index),%0A secondPart = original.substr(index, original.length);%0A%0A return firstPart + str + secondPart;%0A %7D%0A %0A newValue = stringWithStringInsertedAt(selection.start, currentValue, charPressed);%0A $clonedField.val(newValue);%0A %0A var newHeight = $clonedField%5B0%5D.scrollHeight;%0A %0A if(newHeight %3E currentHeight)%7B%0A $(this).height($clonedField%5B0%5D.scrollHeight);%0A %7D%0A %0A $(this).val(newValue);%0A %0A var selectionStart = selection.start,%0A selectionEnd = selection.end;%0A%0A if(selectionStart != selectionEnd)%7B%0A selectionEnd = selectionStart;%0A %7D else %7B%0A selectionStart += 1;%0A selectionEnd += 1;%0A %7D%0A%0A $(this).prop(%22selectionStart%22, selectionStart);%0A $(this).prop(%22selectionEnd%22, selectionEnd);%0A %0A
36abebe4d6663324c7c9e26c0e63367a2e3b3714
Update xss-shrapnel.js
xss-shrapnel.js
xss-shrapnel.js
// ==UserScript== // @name Submit form // @namespace * // @description Submit form // @include * // @version 1 // @grant none // ==/UserScript== var bForceUrlEncoded = 1 var bFillHiddenForms = 0 var iPayload = 0 var aPayloads = ['aaa"bbb\'ccc<ddd>eee', 'aaa"bbb\'eee', 'aaa"eee', 'aaa"bbb\'ccc>ddd<eee', 'aaa"bbb\'ccc<<ddd>ddd<ddd>>eee', 'aaa\\"bbb\'ccc<ddd>fff</eee>'] var regex = /aaa.*?eee/g window.addEventListener ( 'keydown', function (e) { if (e.altKey || e.modifiers) { if (e.keyCode == 72) { var sPrompt = prompt ('Fill hidden forms?', bFillHiddenForms) sPrompt == null || (bFillHiddenForms = parseInt (sPrompt)) } if (e.keyCode == 80) { var sPrompt = prompt ('Choose payload', iPayload) sPrompt == null || (iPayload = parseInt (sPrompt) % aPayloads.length) } if (e.target.form) { var parentForm = e.target.form e.keyCode == 83 && submitForm (parentForm) e.keyCode == 65 && fillForm (parentForm) && submitForm (parentForm) } if (e.keyCode == 82) checkResults () } }, false ) window.addEventListener ('DOMContentLoaded', checkResults, false) window.addEventListener ('load', checkResults, false) function checkResults () { alert (document.getElementsByTagName ('html') [0].innerHTML.match (regex).join ('\r\n')) } function submitForm (form) { var aPostData = [] for (var i = 0; i < form.length; i++) { var sPostData = encodeURIComponent (form [i].name) + '=' + encodeURIComponent (form [i].value) form [i].name && aPostData.indexOf (sPostData) == -1 && aPostData.push (sPostData) } bForceUrlEncoded && (form.enctype = 'application/x-www-form-urlencoded') var sFormAction = form.action ? form.action : location.protocol + '//' + location.host + location.pathname var sDelimeter = form.method == 'post' ? '\r\n\r\n' : '?' var sFormData = sFormAction + sDelimeter + aPostData.join ('&') confirm (sFormData) && HTMLFormElement.prototype.submit.call (form) } function fillForm (form) { for (var i = 0; i < form.length; i++) { var element = form [i] var payload = aPayloads [iPayload] if (element.tagName == 'SELECT' || element.type == 'file') { element.outerHTML = '<input name="' + htmlEncode (element.name) + '" value="' + htmlEncode (payload) + '" />' continue } if (!bFillHiddenForms && element.type == 'hidden') continue element.value = payload } return 1 } function htmlEncode (str) { return str.replace (/</g, '&lt;').replace (/>/g, '&gt;').replace (/"/g, '&quot;').replace (/'/g, '&#39;') }
JavaScript
0
@@ -861,16 +861,54 @@ length)%0A +%09%09%09%09%0A%09%09%09%09alert (aPayloads %5BiPayload%5D)%0A %09%09%09%7D%0A%09%09%09
b88ccc024d0c8b2f6988129f51e641e86359572c
Create initial backbone models
src/main/webapp/js/app.js
src/main/webapp/js/app.js
/** * @fileoverview * Provides methods for connecting the app's frontend to the endpoints API. * * @author trevor.nelson1@gmail.com (Trevor Nelson) * Based off of the hello-endpoints-archectype. */ /** * Initialize the app namespace on pageload */ (function() { window.App = { Models: {}, Collections: {}, Views: {} }; /** * function for returning a template underscore object. */ window.template = function(id) { return _.template( $('#' + id).html() ); }; });
JavaScript
0.000001
@@ -480,12 +480,326 @@ );%0A%09%7D;%0A +%09%0A%09App.Models.Account = Backbone.Model.extend(%7B%0A%09%09defaults: %7B%0A%09%09%09'id': '',%0A%09%09%09'username': '',%0A%09%09%09'email': '',%0A%09%09%09'dashboards': %5B%5D%0A%09%09%7D%0A%09%7D);%0A%09%0A%09App.Models.Dashboard = Backbone.Model.extend(%7B%0A%09%09defaults: %7B%0A%09%09%09'widgets': %5B%5D%0A%09%09%7D%0A%09%7D);%0A%09%0A%09App.Models.Widget = Backbone.Model.extend(%7B%0A%09%09defaults: %7B%0A%09%09%09'title': ''%0A%09%09%7D%0A%09%7D);%0A %7D);%0A
666ffe8b469e30968a67d1b2a83e20b86194d9dd
apply the attributes in one action
src/jquery.emailaddressmunging.js
src/jquery.emailaddressmunging.js
(function($) { $.fn.emailAddressMunging = function(opts) { return this.each(function() { var $el = $(this); var $newEl; // get email address var mail = $.fn.emailAddressMunging._createEmail($el.text()); // make a new link element with email address $newEl = $('<a href="mailto:'+ mail + '">' + mail + '</a>'); // copy attributes from old element $.each(this.attributes, function(i, attr){ // dont overwrite our href and workarounds for IE if(attr.value !== 'null' && attr.value !== '' && attr.name !== 'dataFormatAs' && attr.name !== 'href' ){ // SMELL: would performance be better if we made just one call to attr with a map? $newEl.attr(attr.name, attr.value); } }); // replace existing element with our new one $el.replaceWith($newEl); }); }; // creates the email adress from the parsed string $.fn.emailAddressMunging._createEmail = function(mail){ // replace (at) and [at] mail = mail.replace(/(\[|\()at(\]|\))/i, '@'); // replace (dot) and [dot] mail = mail.replace(/(\[|\()dot(\]|\))/ig, '.'); // remove white space mail = mail.replace(/ /g, ''); return mail; }; })(jQuery);
JavaScript
0.000167
@@ -130,44 +130,8 @@ s);%0A - var $newEl;%0A %0A @@ -234,28 +234,16 @@ ext());%0A - %0A @@ -251,139 +251,28 @@ -// make a new link element with email address%0A $newEl = $('%3Ca href=%22mailto:'+ mail + '%22%3E' + mail + '%3C/a%3E');%0A +var attributes = %7B%7D; %0A @@ -583,91 +583,48 @@ -// SMELL: would performance be better if we made just one call to attr with a map?%0A +attributes%5Battr.name%5D = attr.value;%0A @@ -631,24 +631,26 @@ +%7D%0A $newEl.a @@ -645,44 +645,17 @@ -$newEl.attr(attr.name, attr.value + %7D );%0A +%0A @@ -666,42 +666,144 @@ - %7D%0A %7D);%0A +// make a new link element with email address%0A $newEl = $('%3Ca href=%22mailto:'+ mail + '%22%3E' + mail + '%3C/a%3E').attr(attributes);%0A %0A @@ -912,20 +912,16 @@ %0A %7D;%0A - %0A // @@ -1332,21 +1332,16 @@ %0A %7D;%0A - %0A %7D)(jQuer
469e6885247fec1c6a73add0c4b034bc0bed5fda
add michael :heart:
db/seeds/tapin-demo.js
db/seeds/tapin-demo.js
const hasher = require('feathers-authentication-local/lib/utils/hash') const { flatten, map, pick, merge } = require('ramda') const groups = [ { name: "Ruru Kāhui Ako", description: "Ruru Kāhui Ako" }, { name: "School Supplies R'Us", description: "If you're yearning for some learning, we'll set your mind churning" } ] const agents = [ { name: 'Dan Lewis', description: "I'm Dan - I love building things, from sheds to organisations", avatar: 'https://raw.githubusercontent.com/root-systems/handbook/master/members/dan.png', email: 'dan@rootsystems.nz', password: 'password' }, { name: 'Iain Kirkpatrick', description: "I'm Iain - I love basketball and programming while watching basketball", avatar: 'https://raw.githubusercontent.com/root-systems/handbook/master/members/iain.png', email: 'iain@rootsystems.nz', password: 'password' }, { name: 'Sarah Rogers', description: "I'm Sarah - I love bargain hunting and adding to my vast repertoire of Simpsons knowledge", avatar: 'https://raw.githubusercontent.com/root-systems/handbook/master/members/sarah.png', email: 'sarah@rootsystems.nz', password: 'password' }, { name: 'Mikey Williams', description: "I'm Mikey - I love making mad science and participating in cooperative ecosystems", avatar: 'https://raw.githubusercontent.com/root-systems/handbook/master/members/mikey.png', email: 'mikey@rootsystems.nz', password: 'password' } ] exports.seed = function (knex, Promise) { var groupId, supplierId // insert group / supplier agents return Promise.all([ knex('agents').insert({ type: 'group' }).returning('id'), knex('agents').insert({ type: 'group' }).returning('id') ]) .then((ids) => { ids = flatten(ids) groupId = ids[0] supplierId = ids[1] // insert group profiles return Promise.all(groups.map((group, i) => { const profile = merge(group, { agentId: ids[i] }) return knex('profiles').insert(profile).returning('agentId') })) }) .then(() => { // insert supplier relationships return knex('relationships').insert({ relationshipType: 'supplier', sourceId: groupId, targetId: supplierId }) }) .then(() => { // insert agents const devPersonAgent = {} return Promise.all([ knex('agents').insert(devPersonAgent).returning('id'), knex('agents').insert(devPersonAgent).returning('id'), knex('agents').insert(devPersonAgent).returning('id'), knex('agents').insert(devPersonAgent).returning('id') ]) }) .then((ids) => { ids = flatten(ids) // insert person profiles return Promise.all(agents.map((agent, i) => { const profile = merge(pick(['name', 'description', 'avatar'], agent), { agentId: ids[i] }) return knex('profiles').insert(profile).returning('agentId') })) }) .then((ids) => { ids = flatten(ids) // hash person credentials return Promise.all(agents.map((agent, i) => { const credential = merge(pick(['email', 'password'], agent), { agentId: ids[i] }) return hashCredential(credential) })) .then((credentials) => { // insert person credentials return Promise.all(credentials.map((credential) => { return knex('credentials').insert(credential).returning('agentId') })) }) // not sure why, but credentials .returning doesn't return the correct agentIds, hack for now .then(() => ids) }) .then((ids) => { // insert person relationships return Promise.all(agents.map((agent, i) => { const relationship = { relationshipType: i === 0 ? 'admin' : 'member', sourceId: groupId, targetId: ids[i] } return knex('relationships').insert(relationship).returning('agentId') })) }) } function hashCredential (credential) { return hasher(credential.password) .then(hashedPassword => { return Object.assign(credential, { password: hashedPassword }) }) }
JavaScript
0.00015
@@ -1497,16 +1497,299 @@ ssword'%0A + %7D,%0A %7B%0A name: 'Michael Smith',%0A description: %22I'm Michael - I love exploring the globe and wearing radical socks%22,%0A avatar: 'https://raw.githubusercontent.com/root-systems/handbook/master/members/michael.png',%0A email: 'michael@rootsystems.nz',%0A password: 'password'%0A %7D%0A%5D%0A%0Ae @@ -2806,32 +2806,93 @@ eturning('id'),%0A + knex('agents').insert(devPersonAgent).returning('id'),%0A knex('agen
d6e318d95d274c3590d202f2ed8f55d3b82074a1
Add spec for the last missing line
spec/Krtek.bundle.spec.js
spec/Krtek.bundle.spec.js
/* eslint import/no-extraneous-dependencies:0 */ /* eslint no-param-reassign:0 */ import test from 'ava'; import sinon from 'sinon'; import Krtek from '../src/Krtek'; import Cache from '../src/Cache'; test.beforeEach((t) => { t.context.krtekInstance = new Krtek(); t.context.jsCode = ` console.log('foo'); console.log('bar'); `; t.context.jsCode2 = ` console.log('foo'); console.log(1 + 1); `; t.context.krtekInstance.setJsCode(t.context.jsCode); t.context.req = sinon.spy(); t.context.res = sinon.spy(); }); test.cb('triggers bundle event', (t) => { t.plan(2); t.context.krtekInstance.on('bundle', (req, res) => { t.is(req, t.context.req); t.is(res, t.context.res); t.end(); }); t.context.krtekInstance.bundle( t.context.req, t.context.res ); }); test('throws error if jsCode not given', (t) => { t.context.krtekInstance.setJsCode(null); t.throws( () => t.context.krtekInstance.bundle(t.context.req, t.context.res), /Nothing to bundle - no JavaScript code given./ ); }); test.cb('loads code from cache if any', (t) => { t.plan(3); const code = '\'use strict\';'; const cache = new Cache({ string: code }); t.context.krtekInstance.setJsCode(code); t.context.krtekInstance.on('done', (req, res, result) => { t.is(req, t.context.req); t.is(res, t.context.res); t.is(code, result); t.end(); }); cache.set(code).then( () => { t.context.krtekInstance.bundle(t.context.req, t.context.res); } ); }); test.cb('bundles the code', (t) => { t.plan(4); t.context.krtekInstance.minifier = null; t.context.krtekInstance.cacheOptions = null; t.context.krtekInstance.setJsCode(t.context.jsCode2); t.context.krtekInstance.on('done', (req, res, result) => { t.is(req, t.context.req); t.is(res, t.context.res); t.regex(result, /console\.log/); t.not(result, t.context.jsCode2); t.end(); }); t.context.krtekInstance.bundle(t.context.req, t.context.res); }); test.cb('minifies the code', (t) => { t.plan(3); t.context.krtekInstance.bundler = null; t.context.krtekInstance.cacheOptions = null; t.context.krtekInstance.setJsCode(t.context.jsCode2); t.context.krtekInstance.on('done', (req, res, result) => { t.is(req, t.context.req); t.is(res, t.context.res); t.regex(result, /console\.log\(2\)/); t.end(); }); t.context.krtekInstance.bundle(t.context.req, t.context.res); }); test.cb('caches the code', (t) => { t.plan(1); t.context.krtekInstance.bundler = null; t.context.krtekInstance.minifier = null; t.context.krtekInstance.setJsCode(t.context.jsCode2); t.context.krtekInstance.on('done', () => { const cache = new Cache({ string: t.context.jsCode2 }); cache.get().then((cacheResult) => { t.is(cacheResult, t.context.jsCode2); t.end(); }); }); t.context.krtekInstance.bundle(t.context.req, t.context.res); }); test.cb('it does all the things sequentially', (t) => { t.plan(4); const random = Math.random().toString(36).slice(2); const code = `console.log('${random}'); console.log(1+ 1);`; t.context.krtekInstance.setJsCode(code); t.context.krtekInstance.on('done', (req, res, result) => { t.regex(result, new RegExp(random)); t.regex(result, /console\.log\(2\)/); t.regex(result, /function/); const cache = new Cache({ string: code }); cache.get().then((cacheResult) => { t.is(cacheResult, result); t.end(); }); }); t.context.krtekInstance.bundle(t.context.req, t.context.res); });
JavaScript
0.000003
@@ -194,16 +194,70 @@ /Cache'; +%0Aimport FileProvider from '../src/cache/FileProvider'; %0A%0Atest.b @@ -3622,28 +3622,432 @@ xt.req, t.context.res);%0A%7D);%0A +%0Atest.cb('returns error if something fails', (t) =%3E %7B%0A t.plan(1);%0A%0A t.context.krtekInstance.cacheOptions = %7B%0A provider: new FileProvider(%7B%0A folder: '/non/existing/folder'%0A %7D)%0A %7D;%0A%0A t.context.krtekInstance.on('error', (req, res, err) =%3E %7B%0A t.regex(err.message, /ENOENT: no such file or directory/);%0A t.end();%0A %7D);%0A%0A t.context.krtekInstance.bundle(t.context.req, t.context.res);%0A%7D);%0A
e751590242eda7acbcac5a2ba5d35efabbcf5d39
Add a constructor for a component of the save-button
js/components/content-header.js
js/components/content-header.js
(function(app) { 'use strict'; var jCore = require('jcore'); var helper = app.helper || require('../helper.js'); var dom = app.dom || require('../dom.js'); var Button = app.Button || require('./button.js'); var SidebarToggleButton = app.SidebarToggleButton || require('./sidebar-toggle-button.js'); var LoadButton = helper.inherits(function(props) { LoadButton.super_.call(this, props); }, Button); var ContentHeader = helper.inherits(function(props) { ContentHeader.super_.call(this); this.element = this.prop(props.element); this.sidebarToggleButton = this.prop(new SidebarToggleButton({ element: this.sidebarToggleButtonElement(), collapser: props.sidebarCollapser, expander: props.sidebarExpander })); this.sidebarToggleButton().registerTapListener(); }, jCore.Component); ContentHeader.prototype.sidebarToggleButtonElement = function() { return dom.child(this.element(), 0); }; ContentHeader.prototype.loadButtonElement = function() { return dom.child(this.element(), 1); }; ContentHeader.prototype.saveButtonElement = function() { return dom.child(this.element(), 2); }; ContentHeader.prototype.redraw = function() { this.sidebarToggleButton().redraw(); }; if (typeof module !== 'undefined' && module.exports) module.exports = ContentHeader; else app.ContentHeader = ContentHeader; })(this.app || (this.app = {}));
JavaScript
0.000001
@@ -411,24 +411,133 @@ , Button);%0A%0A + var SaveButton = helper.inherits(function(props) %7B%0A SaveButton.super_.call(this, props);%0A %7D, Button);%0A%0A var Conten
10e6375778ba2fd52089a776f63fbf0bf1ad19b4
Define variable.
scripts/__tests__/gridTitle-test.js
scripts/__tests__/gridTitle-test.js
jest.dontMock('../gridTitle.jsx'); jest.dontMock('../columnProperties.js'); var React = require('react'); var GridTitle = require('../gridTitle.jsx'); var TestUtils = require('react-addons-test-utils'); var ColumnProperties = require('../columnProperties.js'); describe('GridTitle', function() { var title; var columns; var columnSettings; var sortObject; var multipleSelectOptions; beforeEach(function(){ columns = ["one", "two", "three"]; columnSettings = new ColumnProperties(columns, [], "children", [], []); sortObject = { enableSort: true, changeSort: null, sortColumn: "", sortAscending: true, sortDefaultComponent: null, sortAscendingClassName: "", sortDescendingClassName: "", sortAscendingComponent: null, sortDescendingComponent: null }; multipleSelectSettings = { isMultipleSelection: false, toggleSelectAll: function(){}, getIsSelectAllChecked: function(){}, toggleSelectRow: function(){}, getSelectedRowIds: function(){}, getIsRowChecked: function(){} }; title = TestUtils.renderIntoDocument(<GridTitle columns={columns} columnSettings={columnSettings} sortSettings={sortObject} multipleSelectionSettings={multipleSelectSettings} />); }); it('calls sortDefaultComponent in table init', function(){ sortObject['sortDefaultComponent'] = 'UPDOWN'; //re-call it again with sortDefaultComponent title = TestUtils.renderIntoDocument(<GridTitle columns={columns} columnSettings={columnSettings} sortSettings={sortObject} multipleSelectionSettings={multipleSelectSettings} />); var node = TestUtils.findRenderedDOMComponentWithTag(title, 'thead'); var headings = TestUtils.scryRenderedDOMComponentsWithTag(node, 'th'); expect(headings.length).toEqual(3); for(var i = 0, l = headings.length; i < l; i++) { var heading = headings[i]; expect(heading.props.children[1]).toEqual(sortObject['sortDefaultComponent']); } }); it('calls method when clicked', function(){ var node = TestUtils.findRenderedDOMComponentWithTag(title, 'thead'); var headings = TestUtils.scryRenderedDOMComponentsWithTag(node, 'th'); var mock = jest.genMockFunction(); title.props.sortSettings.changeSort = mock; expect(headings.length).toEqual(3); var first = headings[0]; expect(TestUtils.isDOMComponent(first)).toBe(true); expect(title.props.sortSettings.sortColumn).toEqual(""); //todo: can we just get this from jsdom? var someEvent = { "target":{ "dataset":{ "title": "one" } } }; React.addons.TestUtils.Simulate.click(first, someEvent); expect(mock.mock.calls.length).toEqual(1); expect(mock.mock.calls[0]).toEqual({0: 'one'}); }); it('doesnt sort column where sort is disabled', function(){ var newMeta = [{ "columnName": "one", "order": 2, "locked": false, "visible": true, "displayName": "Name", "sortable" : false }]; var columnSettings2 = new ColumnProperties(columns, [], "children", newMeta, []); var title2 = TestUtils.renderIntoDocument(<GridTitle columns={columns} columnSettings={columnSettings2} sortSettings={sortObject} multipleSelectionSettings={multipleSelectSettings} />); var node = TestUtils.findRenderedDOMComponentWithTag(title2, 'thead'); var headings = TestUtils.scryRenderedDOMComponentsWithTag(node, 'th'); var mock = jest.genMockFunction(); title2.props.sortSettings.changeSort = mock; expect(headings.length).toEqual(3); var first = headings[0]; var second = headings[1]; expect(TestUtils.isDOMComponent(first)).toBe(true); expect(TestUtils.isDOMComponent(second)).toBe(true); expect(title2.props.sortSettings.sortColumn).toEqual(""); //todo: can we just get this from jsdom? var someEvent = { "target":{ "dataset":{ "title": "one" } } }; var otherEvent = { "target":{ "dataset":{ "title": "two" } } }; React.addons.TestUtils.Simulate.click(first, someEvent); expect(mock.mock.calls.length).toEqual(0); React.addons.TestUtils.Simulate.click(second, otherEvent); expect(mock.mock.calls.length).toEqual(1); expect(mock.mock.calls[0]).toEqual({0:"two"}); }); });
JavaScript
0.000005
@@ -382,16 +382,45 @@ Options; +%0A%09var multipleSelectSettings; %0A%0A%09befor
0aac4748db35f8d3f48e463d4ac69e4c67e52f8c
Allow for trail color to set from props
src/Circle.js
src/Circle.js
import React, { Component, PropTypes } from 'react'; import cx from 'classnames'; import s from './style/circle.scss'; export default class Circle extends Component { static propTypes = { prefixClass: PropTypes.string, percent: PropTypes.number, className: PropTypes.className, strokeWidth: PropTypes.number, strokeColor: PropTypes.string, trailColor: PropTypes.string, style: PropTypes.object } getPathStyles() { const { prefixClass, percent, strokeWidth, gapDegree = 0, gapPosition } = this.props; const radius = 50 - (strokeWidth / 2); const beginPositionX = 0; const beginPositionY = -radius; const endPositionX = 0; const endPositionY = -2 * radius; const pathString = `M 50,50 m ${beginPositionX},${beginPositionY} a ${radius},${radius} 0 1 1 ${endPositionX},${-endPositionY} a ${radius},${radius} 0 1 1 ${-endPositionX},${endPositionY}`; const len = Math.PI * 2 * radius; const trailPathStyle = { strokeDasharray: `${len - gapDegree}px ${len}px`, strokeDashoffset: `-${gapDegree / 2}px`, transition: 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s', }; const strokePathStyle = { strokeDasharray: `${(percent / 100) * (len - gapDegree)}px ${len}px`, strokeDashoffset: `-${gapDegree / 2}px`, transition: 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s', }; return { pathString, trailPathStyle, strokePathStyle }; } render() { const { prefixClass, strokeWidth, strokeColor, trailColor, style, className, ...restProps } = this.props; const classes = cx(s[`${prefixClass}-circle`], className); const { pathString, trailPathStyle, strokePathStyle } = this.getPathStyles(); delete restProps.percent; delete restProps.gapDegree; delete restProps.gapPosition; return ( <svg className={classes} viewBox="0 0 100 100" style={style} {...restProps} > <path d={pathString} stroke="#efefef" strokeWidth={strokeWidth} fillOpacity="0" style={trailPathStyle} /> <path d={pathString} stroke={strokeColor} strokeWidth={strokeWidth} fillOpacity="0" ref={(path) => { this.path = path; }} style={strokePathStyle} /> </svg> ); } }
JavaScript
0
@@ -2065,16 +2065,31 @@ stroke= +%7BtrailColor %7C%7C %22#efefef @@ -2089,16 +2089,17 @@ #efefef%22 +%7D %0A
895af9841dbe91517ddb1cceb7221725ece6a7df
Fix load-button to reload file
js/components/load-button.js
js/components/load-button.js
(function(app) { 'use strict'; var dom = app.dom || require('../dom.js'); var Button = app.Button || require('./button.js'); var LoadButton = Button.inherits(function(props) { this.loader = props.loader; this.registerChangeListener(); }); LoadButton.prototype.inputElement = function() { return dom.child(this.element(), 2); }; LoadButton.prototype.registerChangeListener = function() { dom.on(this.inputElement(), 'change', LoadButton.prototype.onchange.bind(this)); }; LoadButton.prototype.ontap = function() { dom.click(this.inputElement()); }; LoadButton.prototype.onchange = function(event) { this.loader(dom.file(dom.target(event))); }; if (typeof module !== 'undefined' && module.exports) { module.exports = LoadButton; } else { app.LoadButton = LoadButton; } })(this.app || (this.app = {}));
JavaScript
0.000001
@@ -496,32 +496,127 @@ d(this));%0A %7D;%0A%0A + LoadButton.prototype.resetInput = function() %7B%0A dom.value(this.inputElement(), '');%0A %7D;%0A%0A LoadButton.pro @@ -745,20 +745,19 @@ -this.loader( +var file = dom. @@ -779,18 +779,89 @@ (event)) -) ; +%0A if (file) %7B%0A this.loader(file);%0A this.resetInput();%0A %7D %0A %7D;%0A%0A
28bd4cc1fad99c2a11cbc7b02d134c9e89b500c2
Add number parameter to dice command
commands.js
commands.js
const fs = require('fs'); // Commands are called with the following arguments: // commands[command](message, config, msg, ...parameters) // msg is the message content without the prefix or command module.exports = { 'ping': (message) => { message.reply("pong!"); }, // _ denotes arguments we don't care about 'echo': (message, _, msg) => { if (msg) { message.channel.send(msg); } }, 'prefix': (message, config, _, newPrefix) => { if (newPrefix) { config.prefix = newPrefix; fs.writeFile("./config.json", JSON.stringify(config, null, 4), err => console.error); message.channel.send(`Prefix successfully set to '${newPrefix}'`) } else { message.channel.send("Please provide a prefix."); } }, 'die': (message, config) => { if (message.author.id === config.ids.soupmaster) { message.channel.send("Emptying can...") .then(() => { console.log("Forced to disconnect."); process.exit(0); }); } }, 'factcheck': (message, _, msg) => { let bool1 = (Math.random() > 0.5), bool2 = (Math.random() > 0.5), str; if (msg) { str = `${message.author}'s claim, "${msg}",` str = bool1 ? `${str} is obviously ${bool2.toString()}.` : `${str} can't possibly be ${bool2.toString()}.`; } else { str = bool1 ? `${message.author} is always ${bool2 ? "right" : "wrong"}.` : `${message.author} is never ${bool2 ? "right" : "wrong"}.` } message.channel.send(str); }, 'coin': (message) => { let bool = (Math.random() > 0.5); message.channel.send(bool ? "Heads." : "Tails."); }, 'dice': (message) => { message.channel.send(Math.floor(Math.random()*6) + 1); } }
JavaScript
0.000004
@@ -725,18 +725,16 @@ efix%7D'%60) - %0A @@ -1883,38 +1883,67 @@ 'dice': (message -) =%3E %7B +, _, _, n) =%3E %7B%0A n = n %7C%7C 6; %0A message @@ -1981,17 +1981,17 @@ andom()* -6 +n ) + 1);%0A @@ -1997,8 +1997,9 @@ %0A %7D%0A%7D +%0A
e607529b5c40404526a4598a1d16415e7ee0fdae
Add todo for infinite scroll article compatibility
src/Config.js
src/Config.js
/** * Import, get, and set configuration values. * * @todo Initialization should die when no valid account or inventory. */ ( function ( root, factory ) { if ( typeof define === 'function' && define.amd ) { define( [ 'jquery', './Util' ], factory ); } else if ( typeof exports === 'object' ) { module.exports = factory( require( 'jquery' ), require( './Util' ) ); } else { root.AdManager = root.AdManager || {}; root.AdManager.Config = factory( root.jQuery, root.AdManager.Util ); } } ( this, function ( $, Util ) { var name = 'Config', debugEnabled = true, debug = debugEnabled ? Util.debug : function () {}, config = {}, defaults = { account: null, // DFP account ID adClass: 'app_ad_unit', // Outer ad wrap adUnitTargetClass: 'app_unit_target', // Inner ad wrap clientType: false, // Used to filter inventory context: 'body', // Selector for ad filling container enabled: true, // Turn off ads insertExclusion: [], // Inventory to exclude from dynamic insertion insertionEnabled: false, // Enable dynamic insertion insertion: { pxBetweenUnits: 800, // Minimum space b/w dynamically inserted units adHeightLimit: 1000, // Max-height for dynamic units insertExclusion: [ // Skip these elements when inserting units 'img', 'iframe', 'video', 'audio', '.video', '.audio', '.app_ad_unit' ] }, inventory: [], // Inventory of ad units pageConfigAttr: false, // Selector for dynamic config import targeting: [] // Key value pairs to send with DFP request }; ////////////////////////////////////////////////////////////////////////////////////// /** * Merge passed config with defaults. * * @param {Object} newConfig */ function init( newConfig ) { config = $.extend( defaults, newConfig ); } /** * Set config value by key. * * @param {String} key * @param {Mixed} value * @return {Object} config */ function set( key, value ) { return setConfigValue( config, key, value ); } /** * Get config value by key. * Pass no key to get entire config object. * * @param {String|Null} key Optional. * @return {Mixed} */ function get( key ) { key = key || false; if ( ! key ) { return config; } // get selector from className // use with `adClass`, `adUnitTargetClass`, etc. var index = key.indexOf( 'Selector', this.length - 'Selector'.length ); if ( index !== -1 ) { key = key.slice( 0, index ) + 'Class'; return '.' + getConfigValue( config, key ).replace( /^\./, '' ); } return getConfigValue( config, key ); } /** * Set config value. * Uses recursion to set nested values. * * @param {Object} config * @param {String} key * @param {Mixed} value * @return {Object} config */ function setConfigValue( config, key, value ) { if ( typeof key === 'string' ) { key = key.split( '.' ); } if ( key.length > 1 ) { setConfigValue( config[ key.shift() ], key, value ); } else { config[ key[0] ] = value; } return config; } /** * Get config value. * Uses recursion to get nested values. * * @param {Object} config * @param {String} key * @return {Mixed} */ function getConfigValue( config, key ) { if ( typeof key === 'string' ) { key = key.split( '.' ); } if ( key.length > 1 ) { return getConfigValue( config[ key.shift() ], key ); } else { return key[0] in config ? config[ key[0] ] : null; } } /** * Import JSON page config data from DOM. * * This imports inline JSON via data attribute * and extends an existing config with it. * * @todo Reenable usage in the project. * Ascertain the correct place to use. * Previous usage was in `Manager.isEnabled()`. * * @param {Object} options.$context * @param {String} options.attrName * @return {Object} */ function importConfig( options ) { var $context = options.$context, attrName = options.attrName, existConfig = options.existConfig, selector, newConfig, data = {}; selector = '*[data-' + attrName + ']'; newConfig = $.extend( {}, existConfig ); data = $context.find( selector ).data( attrName ); if ( typeof newConfig === 'object' ) { newConfig = $.extend( newConfig, data ); } return newConfig; } ////////////////////////////////////////////////////////////////////////////////////// return { init: init, set: set, get: get, importConfig: importConfig }; } ) );
JavaScript
0
@@ -118,16 +118,98 @@ entory.%0A + * @todo Add optional dynamically-determined context for use in infinite scroll.%0A */%0A( fu
ac738dac727ca97de18751c55da8472a24f8a62c
Make `Move()` fire callback directly when duration is 0.
js/foundation.util.motion.js
js/foundation.util.motion.js
'use strict'; !function($) { /** * Motion module. * @module foundation.motion */ const initClasses = ['mui-enter', 'mui-leave']; const activeClasses = ['mui-enter-active', 'mui-leave-active']; const Motion = { animateIn: function(element, animation, cb) { animate(true, element, animation, cb); }, animateOut: function(element, animation, cb) { animate(false, element, animation, cb); } } function Move(duration, elem, fn){ var anim, prog, start = null; // console.log('called'); function move(ts){ if(!start) start = window.performance.now(); // console.log(start, ts); prog = ts - start; fn.apply(elem); if(prog < duration){ anim = window.requestAnimationFrame(move, elem); } else{ window.cancelAnimationFrame(anim); elem.trigger('finished.zf.animate', [elem]).triggerHandler('finished.zf.animate', [elem]); } } anim = window.requestAnimationFrame(move); } /** * Animates an element in or out using a CSS transition class. * @function * @private * @param {Boolean} isIn - Defines if the animation is in or out. * @param {Object} element - jQuery or HTML object to animate. * @param {String} animation - CSS class to use. * @param {Function} cb - Callback to run when animation is finished. */ function animate(isIn, element, animation, cb) { element = $(element).eq(0); if (!element.length) return; var initClass = isIn ? initClasses[0] : initClasses[1]; var activeClass = isIn ? activeClasses[0] : activeClasses[1]; // Set up the animation reset(); element .addClass(animation) .css('transition', 'none'); requestAnimationFrame(() => { element.addClass(initClass); if (isIn) element.show(); }); // Start the animation requestAnimationFrame(() => { element[0].offsetWidth; element .css('transition', '') .addClass(activeClass); }); // Clean up the animation when it finishes element.one(Foundation.transitionend(element), finish); // Hides the element (for out animations), resets the element, and runs a callback function finish() { if (!isIn) element.hide(); reset(); if (cb) cb.apply(element); } // Resets transitions and removes motion-specific classes function reset() { element[0].style.transitionDuration = 0; element.removeClass(`${initClass} ${activeClass} ${animation}`); } } Foundation.Move = Move; Foundation.Motion = Motion; }(jQuery);
JavaScript
0
@@ -505,16 +505,172 @@ led');%0A%0A + if (duration === 0) %7B%0A fn.apply(elem);%0A elem.trigger('finished.zf.animate', %5Belem%5D).triggerHandler('finished.zf.animate', %5Belem%5D);%0A return;%0A %7D%0A%0A functi @@ -709,32 +709,10 @@ t = -window.performance.now() +ts ;%0A
324fb51e363c669ec70cdd04df95f3407e8f0bef
update redirect
js/fw/config/RouterConfig.js
js/fw/config/RouterConfig.js
/** * RouterConfig collect route information from each feature and combine them * with ngRoute. * * * @author Howard.Zuo * @date Apr 28th, 2015 * */ (function(define) { 'use strict'; define(['lodash', 'tpl!etc/config.json'], function(_, tpl) { var Configurator = function(features, app) { this.features = features; this.app = app; this.config = JSON.parse(tpl()); }; Configurator.prototype.run = function() { if (!this.features || this.features.length === 0) { console.warn('No features loaded'); return; } var self = this; var routes = _.chain(this.features) .filter('routes') .pluck('routes') .flatten() .value(); this.app.constant('Routes', routes); this.app.config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) { //config each router _.each(routes, function(ro) { $routeProvider .when(ro.when, _.omit(ro, ['when'])); }); //config default page var defaultRouter = _.find(routes, 'isDefault'); if (defaultRouter) { $routeProvider.otherwise({ redirectTo: self.config.base + defaultRouter.when }); } $locationProvider.html5Mode(false); } ]); }; return Configurator; }); }(define));
JavaScript
0.000001
@@ -1492,27 +1492,8 @@ tTo: - self.config.base + def
bd883dc8452bf1c46d9e242c746bb9049e61ee2d
Fix bug #47902
count_words_and_characters/scripts/code.js
count_words_and_characters/scripts/code.js
(function(window, undefined) { window.Asc.plugin.init = function(text) { var str = text var REGEX_CHINESE = /[\u3000-\u303f]|[\u3040-\u309f]|[\u30a0-\u30ff]|[\uff00-\uff9f]|[\u4e00-\u9faf]|[\u4e00-\u9fff]|[\u3400-\u4dbf]|[\u{20000}-\u{2a6df}]|[\u{2a700}-\u{2b73f}]|[\u{2b740}-\u{2b81f}]|[\u{2b820}-\u{2ceaf}]|[\uf900-\ufaff]|[\u3300-\u33ff]|[\ufe30-\ufe4f]|[\uf900-\ufaff]|[\u{2f800}-\u{2fa1f}]/u; var REPLACE_REGEX = /[\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\u4e00-\u9fff\u3400-\u4dbf\u{20000}-\u{2a6df}\u{2a700}-\u{2b73f}\u{2b740}-\u{2b81f}\u{2b820}-\u{2ceaf}\uf900-\ufaff\u3300-\u33ff\ufe30-\ufe4f\uf900-\ufaff\u{2f800}-\u{2fa1f}]/gu; var hasChine = REGEX_CHINESE.test(str); var chars = text.replace(/\r*\n/g, '').replace(/\t/g,"").length; var words = text.replace(/—*\u3000-\u303f/g,"").replace(REPLACE_REGEX,"").match(/\S+/g); words = (words) ? words.length : 0; if (hasChine) { str = str.replace(/\u3000-\u303f/g, ""); //remove Japanese-style punctuation // .match(/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff\u3300-\u33ff\ufe30-\ufe4f\uf900-\ufaff]/g); //without single unicode characters words += str.match(REPLACE_REGEX).length; } var lines = text.split(/\r\n/); // // lines.length--; //will be like ms if (lines[lines.length-1] == "") lines.length--; document.getElementById("charsNoSpaces").innerHTML = "Characters without spaces: " + text.replace(/\s+/g, '').length; document.getElementById("chars").innerHTML = "Total characters: " + chars; document.getElementById("words").innerHTML = "Words count: " + words; document.getElementById("lines").innerHTML = "Paragraphs count: " + lines.length; }; window.Asc.plugin.button = function() { this.executeCommand("close", ""); }; })(window, undefined);
JavaScript
0
@@ -112,16 +112,32 @@ SE = /%5B%5C +u3131-%5CuD79D%5D%7C%5B%5C u3000-%5Cu @@ -484,32 +484,45 @@ 9f%5Cu4e00-%5Cu9faf%5C +u3131-%5CuD79D%5C u4e00-%5Cu9fff%5Cu34 @@ -683,16 +683,60 @@ f%7D%5D/gu;%0A +%09%09// /%5B%5Cu3131-%5CuD79D%5D/ugi korean characters%0A %09%09var ha
7323c90456d006777c32495b13910430b9d7dbb0
Remove unnecessary use()
examples/javascript/02_googleassistant/multisurface-conversations/src/app.js
examples/javascript/02_googleassistant/multisurface-conversations/src/app.js
'use strict'; // ------------------------------------------------------------------ // APP INITIALIZATION // ------------------------------------------------------------------ const { App } = require('jovo-framework'); const { GoogleAssistant, NotificationPlugin } = require('jovo-platform-googleassistant'); const app = new App(); const googleAssistant = new GoogleAssistant(); googleAssistant.use(new NotificationPlugin()); app.use( googleAssistant ); // ------------------------------------------------------------------ // APP LOGIC // ------------------------------------------------------------------ app.setHandler({ async LAUNCH() { const availableSurfaces = this.$googleAction.getAvailableSurfaces(); if (availableSurfaces.includes('actions.capability.SCREEN_OUTPUT')) { this.$googleAction.newSurface( ['actions.capability.SCREEN_OUTPUT'], 'Let\'s move you to a screen device for cards and other visual responses', 'Title') } }, ON_NEW_SURFACE() { if (this.$googleAction.isNewSurfaceConfirmed()) { this.tell('Hello Smartphone'); } else { this.tell('Hello Speaker'); } } }); module.exports.app = app;
JavaScript
0
@@ -381,56 +381,8 @@ );%0A%0A -googleAssistant.use(new NotificationPlugin());%0A%0A app.
e47478b23112fa21327d4c1a35e41abae2e6f617
Change the dropdown menus to align right
src/Header.js
src/Header.js
import React from 'react'; import { Navbar, Nav, NavDropdown, DropdownItem, Dropdown, Form } from 'react-bootstrap'; import AboutDialog from './dialogs/AboutDialog.js'; import BenchmarkDialog from './dialogs/BenchmarkDialog.js'; import AuthorDialog from './dialogs/AuthorDialog.js'; import ThanksDialog from './dialogs/ThanksDialog.js'; import PrivacyDialog from './dialogs/PrivacyDialog.js'; class Header extends React.Component { constructor(props) { super(props); this.state = { showAbout: false, showBenchmark: false, showAuthor: false, showThanks: false, showPrivacy: false, showEasterEgg: this.shouldShowEasterEgg(), showingEasterEgg: false, }; } shouldShowEasterEgg() { let currentTime = new Date(); return currentTime.getMonth() === 11 && currentTime.getDate() < 27; } openInfo(key) { if (key) { if (key === 'about') { this.openAbout(); } else if (key === 'benchmark') { this.openBenchmark(); } else if (key === 'author') { this.openAuthor(); } else if (key === 'favicon') { this.openFavicon(); } else if (key === 'privacy') { this.openPrivacy(); } } } openAbout() { this.setState({ showAbout: true }); } closeAbout() { this.setState({ showAbout: false }); } openBenchmark() { this.setState({ showBenchmark: true }); } closeBenchmark() { this.setState({ showBenchmark: false }); } openAuthor() { this.setState({ showAuthor: true }); } closeAuthor() { this.setState({ showAuthor: false }); } openFavicon() { this.setState({ showThanks: true }); } closeFavicon() { this.setState({ showThanks: false }); } openPrivacy() { this.setState({ showPrivacy: true }); } closePrivacy() { this.setState({ showPrivacy: false }); } easterEgg() { if (this.state.showingEasterEgg) this.props.setStyle(''); else this.props.setStyle('Christmas.css'); this.setState({ showingEasterEgg: !this.state.showingEasterEgg }); } render() { return ( <Navbar bg="dark" variant="dark" collapseOnSelect> <Nav className="mr-auto"> <Nav hidden={!this.state.showEasterEgg} onSelect={() => this.easterEgg()}> <Nav.Link eventKey><img src="ico/christmas-tree.svg" className="line-img" alt="A surprise?" /></Nav.Link> </Nav> <Navbar.Brand> Quick C++ Benchmark </Navbar.Brand> </Nav> <Form inline> <Navbar.Collapse className="mr-sm-2"> <Nav> <NavDropdown title="Support Quick Bench" id="basic-nav-dropdown"> <DropdownItem href="https://www.patreon.com/bePatron?u=8599781" target="_blank"><img src="ico/Patreon.svg" className="line-img" alt="Patreon icon" /> Support on Patreon</DropdownItem> </NavDropdown> <NavDropdown title="More" id="basic-nav-dropdown" onSelect={this.openInfo.bind(this)}> <DropdownItem eventKey="about">About Quick-bench</DropdownItem> <DropdownItem eventKey="benchmark">How to write my benchmarks</DropdownItem> <Dropdown.Divider /> <DropdownItem href="https://github.com/FredTingaud/quick-bench-front-end" target="_blank">GitHub project - front-end</DropdownItem> <DropdownItem href="https://github.com/FredTingaud/quick-bench-back-end" target="_blank">GitHub project - back-end</DropdownItem> <Dropdown.Divider /> <DropdownItem eventKey="privacy">Privacy</DropdownItem> <DropdownItem eventKey="favicon">Thanks</DropdownItem> <DropdownItem eventKey="author">About the author</DropdownItem> </NavDropdown> </Nav> </Navbar.Collapse> </Form> <AboutDialog show={this.state.showAbout} onHide={() => this.closeAbout()} /> <BenchmarkDialog show={this.state.showBenchmark} onHide={() => this.closeBenchmark()} /> <AuthorDialog show={this.state.showAuthor} onHide={() => this.closeAuthor()} /> <PrivacyDialog show={this.state.showPrivacy} onHide={() => this.closePrivacy()} /> <ThanksDialog show={this.state.showThanks} onHide={() => this.closeFavicon()} /> </Navbar> ); } } export default Header;
JavaScript
0.000001
@@ -3068,16 +3068,27 @@ ropdown%22 + alignRight %3E%0A @@ -3453,16 +3453,27 @@ d(this)%7D + alignRight %3E%0A
bc825f0453590733feb405dfe1c7e8c4c2276f4b
Update new tab base URL to auto-forward + display user-friendly title
src/Header.js
src/Header.js
!(function( global ) { var Opera = function() {}; Opera.prototype.REVISION = '1'; Opera.prototype.version = function() { return this.REVISION; }; Opera.prototype.buildNumber = function() { return this.REVISION; }; Opera.prototype.postError = function( str ) { console.log( str ); }; var opera = global.opera || new Opera(); var manifest = chrome.app.getDetails(); // null in injected scripts / popups navigator.browserLanguage=navigator.language; //Opera defines both, some extensions use the former var isReady = false; var _delayedExecuteEvents = [ // Example: // { 'target': opera.extension, 'methodName': 'message', 'args': event } ]; // Pick the right base URL for new tab generation var newTab_BaseURL = 'data:text/html,<!--tab_%s-->'; function addDelayedEvent(target, methodName, args) { if(isReady) { target[methodName].apply(target, args); } else { _delayedExecuteEvents.push({ "target": target, "methodName": methodName, "args": args }); } };
JavaScript
0
@@ -796,18 +796,92 @@ l,%3C! ---tab_%25s-- +DOCTYPE html%3E%3C!--tab_%25s--%3E%3Ctitle%3ELoading...%3C/title%3E%3Cscript%3Ehistory.forward()%3C/script %3E';%0A
fc88d874e5a0495f1876062a723fc3114d9fc40a
Put a banner in the client bundle
webpack/build.js
webpack/build.js
const esbuild = require("esbuild"); const isProduction = false; esbuild.buildSync({ entryPoints: ['./src/platform/current/server/serverStartup.ts'], bundle: true, outfile: './build/server/js/bundle2.js', platform: "node", sourcemap: true, minify: false, define: { "process.env.NODE_ENV": isProduction ? "\"production\"" : "\"development\"", "webpackIsServer": true, }, external: [ "akismet-api", "mongodb", "canvas", "express", "mz", "pg", "pg-promise", "mathjax", "mathjax-node", "mathjax-node-page", "jsdom", "@sentry/node", "node-fetch", "later", "turndown", "apollo-server", "apollo-server-express", "graphql", "bcrypt", "node-pre-gyp", "@lesswrong", "intercom-client", ], }) esbuild.buildSync({ entryPoints: ['./src/platform/current/client/clientStartup.ts'], bundle: true, target: "es6", sourcemap: true, outfile: "./build/client/js/bundle.js", minify: false, define: { "process.env.NODE_ENV": isProduction ? "\"production\"" : "\"development\"", "webpackIsServer": false, "global": "window", }, });
JavaScript
0
@@ -59,16 +59,409 @@ false;%0A%0A +const clientBundleBanner = %60/*%0A * LessWrong 2.0 (client JS bundle)%0A * Copyright (c) 2020 the LessWrong development team. See http://github.com/LessWrong2/Lesswrong2%0A * for source and license details.%0A *%0A * Includes CkEditor.%0A * Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.%0A * For licensing, see https://github.com/ckeditor/ckeditor5/blob/master/LICENSE.md%0A */%60%0A%0A esbuild. @@ -1303,32 +1303,62 @@ minify: false,%0A + banner: clientBundleBanner,%0A define: %7B%0A
4cb9ddb86d15af7440ef7fa290156ddacb6d97c9
Remove the modal'scallback when in the action's payload
redactions/modal.js
redactions/modal.js
/** * CONSTANTS */ const MODAL_TOGGLE = 'MODAL_TOGGLE'; const MODAL_SET_OPTIONS = 'MODAL_SET_OPTIONS'; const MODAL_LOADING = 'MODAL_LOADING'; const MODAL_EXECUTE_CLOSE_CALLBACK = 'MODAL_EXECUTE_CLOSE_CALLBACK'; // REDUCER const initialState = { open: false, options: { children: null, childrenProps: null, size: '', // Callback executed if the user closes the modal (user interaction) // (not executed when toggleModal is executed) onCloseModal: null }, loading: false }; export default function (state = initialState, action) { switch (action.type) { case MODAL_TOGGLE: return Object.assign({}, state, { open: action.payload }); case MODAL_SET_OPTIONS: return Object.assign({}, state, { options: action.payload }); case MODAL_LOADING: return Object.assign({}, state, { loading: action.payload }); case MODAL_EXECUTE_CLOSE_CALLBACK: if (state.options.onCloseModal) { // We make the call asynchronous to avoid blocking the state // from being computed setTimeout(() => state.options.onCloseModal(), 0); } return state; default: return state; } } /** * ACTIONS * - closeModal * - toggleModal * - modalLoading * - setModalOptions */ export function closeModal() { return dispatch => dispatch({ type: MODAL_TOGGLE }); } export function toggleModal(open, opts = {}, userInteraction = false) { return (dispatch) => { if (open && opts) { dispatch({ type: MODAL_SET_OPTIONS, payload: opts }); } if (userInteraction) { dispatch({ type: MODAL_EXECUTE_CLOSE_CALLBACK }); } dispatch({ type: MODAL_TOGGLE, payload: open }); }; } export function modalLoading(loading) { return dispatch => dispatch({ type: MODAL_LOADING, payload: loading }); } export function setModalOptions(opts) { return dispatch => dispatch({ type: MODAL_SET_OPTIONS, payload: opts }); }
JavaScript
0.000003
@@ -737,16 +737,24 @@ state, %7B +%0A options @@ -755,30 +755,223 @@ ptions: -action.payload +Object.assign(%7B%7D, state.options, action.payload, %7B%0A // We remove the callback if not present%0A onCloseModal: action.payload.onCloseModal ? action.payload.onCloseModal : null%0A %7D)%0A %7D);%0A
0b83b11e147fe65870c4dcb5db19bb46c0d4ff76
remove redundant tab changing calls
js/views/conversationTabs.js
js/views/conversationTabs.js
var ChangeVotesView = require("../views/change-votes"); var CommentView = require('../views/vote-view'); var CommentFormView = require("../views/comment-form"); var ConversationStatsHeader = require('../views/conversation-stats-header'); var eb = require("../eventBus"); var Handlebones = require("handlebones"); var template = require("../tmpl/conversationTabs"); var display = require("../util/display"); var Utils = require("../util/utils"); module.exports = Handlebones.ModelView.extend({ name: "conversation-tabs-view", template: template, ANALYZE_TAB: "analyzeTab", GROUP_TAB: "groupTab", METADATA_TAB: "metadata_pill", VOTE_TAB: "commentViewTab", WRITE_TAB: "commentFormTab", from: {}, gotoTab: function(id) { this.currentTab = id; this.$("#" + id).click(); }, gotoVoteTab: function() { this.gotoTab(this.VOTE_TAB); }, gotoWriteTab: function() { this.gotoTab(this.WRITE_TAB); }, gotoAnalyzeTab: function() { this.gotoTab(this.ANALYZE_TAB); }, gotoGroupTab: function() { this.gotoTab(this.GROUP_TAB); }, context: function() { var c = _.extend({}, Handlebones.ModelView.prototype.context.apply(this, arguments)); if (this.currentTab === this.VOTE_TAB) { c.voteActive = true; } if (this.currentTab === this.WRITE_TAB) { c.writeActive = true; } if (this.currentTab === this.ANALYZE_TAB) { c.analyzeActive = true; } if (this.currentTab === this.GROUP_TAB) { c.groupActive = true; } if (display.xs()) { c.smallTabs = true; } c.use_background_content_class = display.xs(); return c; }, events: { // Before shown "show.bs.tab": function (e) { var to = e.target; var from = e.relatedTarget; // console.log("to", to.id); // console.log("from", from.id); this.currentTab = to.id; if (to && to.id === this.WRITE_TAB) { this.trigger("beforeshow:write"); } // previous tab if (from && from.id === this.WRITE_TAB) { this.trigger("beforehide:write"); } if(from && from.id === this.ANALYZE_TAB) { this.trigger("beforehide:analyze"); } if(to && to.id === this.ANALYZE_TAB) { this.trigger("beforeshow:analyze"); } if(from && from.id === this.GROUP_TAB) { this.trigger("beforehide:group"); this.doShowTabsUX(); } if(to && to.id === this.GROUP_TAB) { this.trigger("beforeshow:group"); this.doShowGroupUX(); } if(to && to.id === this.VOTE_TAB) { this.trigger("beforeshow:vote"); } }, // After shown "shown.bs.tab": function (e) { var to = e.target; // e.relatedTarget // previous tab if(e.target && e.target.id === this.ANALYZE_TAB) { this.trigger("aftershow:analyze"); } if(e.target && e.target.id === this.GROUP_TAB) { this.trigger("aftershow:group"); } if (e.target && e.target.id === this.WRITE_TAB) { this.trigger("aftershow:write"); } // console.log("setting from", to); // this.from = to; } }, doShowGroupUX: function() { this.model.set("showGroupHeader", true); this.model.set("showTabs", false); }, doShowTabsUX: function() { this.model.set("showGroupHeader", false); this.model.set("showTabs", true); }, onAnalyzeTab: function() { return this.ANALYZE_TAB === this.currentTab; }, onVoteTab: function() { return this.VOTE_TAB === this.currentTab; }, onGroupTab: function() { return this.GROUP_TAB === this.currentTab; }, initialize: function(options) { Handlebones.ModelView.prototype.initialize.apply(this, arguments); var that = this; // start with the vote tab this.currentTab = this.VOTE_TAB; eb.on(eb.clusterClicked, function(gid) { if (gid === -1) { that.doShowTabsUX(); } else { that.doShowGroupUX(); } }); } });
JavaScript
0.000001
@@ -3831,168 +3831,8 @@ B;%0A%0A - eb.on(eb.clusterClicked, function(gid) %7B%0A if (gid === -1) %7B%0A that.doShowTabsUX();%0A %7D else %7B%0A that.doShowGroupUX();%0A %7D%0A %7D);%0A%0A %7D%0A
eccc9721de0091237b71864af1e2099cc7e89b6f
fix create-user-form init after refactor
js/views/create-user-form.js
js/views/create-user-form.js
var View = require("../view"); var template = require("../tmpl/create-user-form"); var PolisStorage = require("../util/polisStorage"); var $ = require("jquery"); module.exports = View.extend({ name: "create-user-form", template: template, gotoCreate: function() { this.model.set("create", true); }, gotoSignIn: function() { this.model.set("create", false); }, events: { "click .gotoSignIn": "gotoSignIn", "click .gotoCreate": "gotoCreate", "submit form": function(event){ if (this.model.get("create")) { return this.createUser.call(this, event); } else { return this.signIn.call(this, event); } }, "invalid": function(errors){ console.log("invalid form input" + errors[0].name); console.log(errors); //_.each(errors, function(err){ $("input[name=\""+errors[0].name+"\"]").closest("label").append(errors[0].message); // relationship between each input and error name //}) } }, initialize: function(){ var urlPrefix = "https://www.polis.io/"; if (-1 === document.domain.indexOf(".polis.io")) { urlPrefix = "http://localhost:5000/"; } }, createUser: function(event) { var that = this; event.preventDefault(); this.serialize(function(attrs, release){ // Incorporate options, like zinvite. var zinvite = that.model.get("zinvite"); if (zinvite) { attrs.zinvite = zinvite; } $.ajax({ url: urlPrefix + "v3/auth/new", type: "POST", dataType: "json", xhrFields: { withCredentials: true }, crossDomain: true, data: attrs }).then(function(data) { that.trigger("authenticated"); release(); }, function(err) { alert("login was unsuccessful"); release(); }); }); }, signIn: function(event) { var that = this; event.preventDefault(); this.serialize(function(attrs, release){ $.ajax({ url: urlPrefix + "v3/auth/login", type: "POST", dataType: "json", xhrFields: { withCredentials: true }, crossDomain: true, data: attrs }).then(function(data) { release(); that.trigger("authenticated"); }, function(err) { release(); alert("login was unsuccessful"); }); }); }, validateInput: function(attrs){ var errors = []; if(attrs.email === ""){ errors.push({name: "description", message: "hey there... you need an email"}); } return errors; }, initialize: function(options) { this.model = options.model; this.listenTo(this, "rendered", function(){ this.$("#conductor").anystretch("img/conductor.jpeg"); }); } });
JavaScript
0.000007
@@ -1042,201 +1042,8 @@ %7D,%0A - initialize: function()%7B%0A var urlPrefix = %22https://www.polis.io/%22;%0A if (-1 === document.domain.indexOf(%22.polis.io%22)) %7B%0A urlPrefix = %22http://localhost:5000/%22;%0A %7D%0A %7D,%0A @@ -1064,32 +1064,32 @@ nction(event) %7B%0A + var that = t @@ -1349,32 +1349,37 @@ (%7B%0A url: +that. urlPrefix + %22v3/ @@ -1901,16 +1901,21 @@ url: +that. urlPrefi @@ -2573,115 +2573,154 @@ his. -listenTo(this, %22rendered%22, function()%7B%0A this.$(%22#conductor%22).anystretch(%22img/conductor.jpeg%22) +urlPrefix = %22https://www.polis.io/%22;%0A if (-1 === document.domain.indexOf(%22.polis.io%22)) %7B%0A this.urlPrefix = %22http://localhost:5000/%22 ;%0A %7D -); %0A %7D
ad61aa306b9d90c566aa18e45ccf9c17462aa0a0
make modal button options do the right thing. closes #104
www/js/events.js
www/js/events.js
var EVENTS = (function() { var onBeginClick = function() { UI.navigateToInterstitial(); } var onBeginStoryClick = function() { AUDIO.playAudio($audioPlayer, ASSETS_SLUG + 'geology-edit616.mp3'); if ($(this).hasClass('guided')) { VR.turnOnAnimations(); } if ($(this).hasClass('vr-device')) { UI.setupVRUI(); VR.enterVR(); } else { UI.setupDeviceNarrativeUI(); } VR.setCurrentScene(0); VR.changeVRScene(); UI.updateSceneData(); UI.toggleAudioPlayer(); UI.setupConclusionCard(); UI.navigateToVR(); } var onZenButtonClick = function(e) { currentScene = $(this).data('scene'); var ambiAudio = ASSETS_SLUG + $scene.data('ambi'); AUDIO.playAudio($ambiPlayer, ambiAudio); VR.enterMomentOfZen(); UI.setupDeviceZenUI(); } var onFullscreenButtonClick = function() { if ( document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement ) { UTILS.exitFullscreen(); } else { UTILS.requestFullscreen(); } } var onMore360Click = function() { UTILS.exitFullscreen(); UI.navigateToConclusion(); AUDIO.stopAllAudio(); UI.toggleAudioPlayer(); } var onPlayClick = function() { AUDIO.resumeAudio(); UI.toggleAudioPlayer(); } var onPauseClick = function() { AUDIO.pauseAudio(); UI.toggleAudioPlayer(); } var onMuteClick = function() { AUDIO.toggleAmbiAudio(); UI.toggleMuteButton(); } var onModalCloseClick = function() { UI.closeModal($(this)); } var onLearnMoreClick = function() { UI.showDetailModal(); } var onCursorClick = function() { if ($audioPlayer.data('jPlayer').status.paused) { AUDIO.resumeAudio(); } else { AUDIO.pauseAudio(); } } var onVREnter = function() { UI.setupVRUI(); } var onVRExit = function() { var scene = UTILS.getParameterByName('scene', window.location.href); if (scene) { UI.setupDeviceZenUI(); } else { UI.setupDeviceNarrativeUI(); } } var onSceneSwitch = function() { VR.changeVRScene(); UI.updateSceneData(); } var onTimeupdate = function(e) { var position = e.jPlayer.status.currentTime; VR.getNewVRSceneFromAudioPosition(position); } var onSeek = function(e) { VR.cancelAnimation(); } var onEnded = function(e) { UTILS.exitFullscreen(); UI.navigateToConclusion(); AUDIO.stopAllAudio(); VR.cancelAnimation(); } var onRestartStoryClick = function(e) { UI.navigateToInterstitial(); } var onModalDeviceClick = function(e) { UI.setupDeviceZenUI(); var ambiAudio = ASSETS_SLUG + $scene.data('ambi'); AUDIO.playAudio($ambiPlayer, ambiAudio); } var onModalVRClick = function(e) { UI.setupVRUI(); var ambiAudio = ASSETS_SLUG + $scene.data('ambi'); AUDIO.playAudio($ambiPlayer, ambiAudio); } return { 'onBeginClick': onBeginClick, 'onBeginStoryClick': onBeginStoryClick, 'onZenButtonClick': onZenButtonClick, 'onFullscreenButtonClick': onFullscreenButtonClick, 'onMore360Click': onMore360Click, 'onMuteClick': onMuteClick, 'onPlayClick': onPlayClick, 'onPauseClick': onPauseClick, 'onModalCloseClick': onModalCloseClick, 'onLearnMoreClick': onLearnMoreClick, 'onCursorClick': onCursorClick, 'onVREnter': onVREnter, 'onVRExit': onVRExit, 'onSceneSwitch': onSceneSwitch, 'onTimeupdate': onTimeupdate, 'onSeek': onSeek, 'onEnded': onEnded, 'onRestartStoryClick': onRestartStoryClick, 'onModalDeviceClick': onModalDeviceClick, 'onModalVRClick': onModalVRClick } })();
JavaScript
0.00004
@@ -3221,32 +3221,54 @@ = function(e) %7B%0A + VR.enterVR();%0A UI.setup
0d8a4e781ac5c4cf2026c1fdeb1c2b24044f467a
increase how long we wait for geolocating to complete
www/js/locate.js
www/js/locate.js
var Locate = ( function() { return { locating: 0, lookup: function(q) { var that = this; if (!q) { this.trigger('failed', { msg: FMS.strings.missing_location } ); return false; } var url = CONFIG.FMS_URL + '/ajax/lookup_location?term=' + q; var x = $.ajax( { url: url, dataType: 'json', timeout: 30000, success: function(data, status) { if ( status == 'success' ) { if ( data.latitude ) { that.trigger('located', { coordinates: { latitude: data.latitude, longitude: data.longitude } } ); } else if ( data.suggestions ) { that.trigger( 'failed', { locs: data.suggestions } ); } else { that.trigger( 'failed', { msg: data.error } ); } } else { that.trigger( 'failed', { msg: FMS.strings.location_problem } ); } }, error: function(data, status, errorThrown) { that.trigger( 'failed', { msg: FMS.strings.location_problem } ); } } ); }, geolocate: function( minAccuracy ) { this.locating = 1; $('#ajaxOverlay').show(); var that = this; this.watch_id = navigator.geolocation.watchPosition( function(location) { if ( that.watch_id == undefined ) { console.log( 'no watch id' ); return; } if ( minAccuracy && location.coords.accuracy > minAccuracy ) { that.trigger('locating', location.coords.accuracy); } else { console.log( 'located with accuracy of ' + location.coords.accuracy ); that.locating = 0; navigator.geolocation.clearWatch( that.watch_id ); delete that.watch_id; that.check_location(location.coords); } }, function() { if ( that.watch_id == undefined ) { return; } that.locating = 0; navigator.geolocation.clearWatch( that.watch_id ); delete that.watch_id; that.trigger('failed', { msg: FMS.strings.geolocation_failed } ); }, { timeout: 7000, enableHighAccuracy: true } ); }, check_location: function(coords) { var that = this; $.ajax( { url: CONFIG.FMS_URL + 'report/new/ajax', dataType: 'json', data: { latitude: coords.latitude, longitude: coords.longitude }, timeout: 10000, success: function(data) { if (data.error) { that.trigger('failed', { msg: data.error } ); return; } that.trigger('located', { coordinates: coords, details: data } ) }, error: function (data, status, errorThrown) { that.trigger('failed', { msg: FMS.strings.location_check_failed } ); } } ); } }});
JavaScript
0
@@ -2409,9 +2409,10 @@ ut: -7 +20 000,
e93c978b00bea052657c6b27bfade481fe5c6f99
Set the link's text content as the search hint
www/js/search.js
www/js/search.js
function getSearchUrlBase(tree, noredirect) { // Figure out the right path separator to use with virtroot sep = virtroot[virtroot.length - 1] === '/' ? '' : '/'; var url = virtroot + sep + 'search.cgi?tree=' + tree; var date = new Date (); url += "&request_time=" + date.getTime (); if (noredirect == true) { url += "&noredirect=1" } return url; } function doSearch(id) { var f = document.getElementById(id); var args = f.string.value.split(/ +/); var string = ""; var url = getSearchUrlBase (f.tree.value, false); for (var i = 0; i < args.length; i++) { var arg = args[i]; if (/^path:.+/.exec(arg)) url += "&path=" + encodeURIComponent(/^path:(.+)/.exec(arg).slice(1,2)); else if (/^ext:.+/.exec(arg)) url += "&ext=" + encodeURIComponent(/^ext:(.+)/.exec(arg).slice(1,2)); else if (/^type:.+/.exec(arg)) url += "&type=" + encodeURIComponent(/^type:(.+)/.exec(arg).slice(1,2)); else if (/^member:.+/.exec(arg)) url += "&member=" + encodeURIComponent(/^member:(.+)/.exec(arg).slice(1,2)); else if (/^derived:.+/.exec(arg)) url += "&derived=" + encodeURIComponent(/^derived:(.+)/.exec(arg).slice(1,2)); else if (/^callers:.+/.exec(arg)) url += "&callers=" + encodeURIComponent(/^callers:(.+)/.exec(arg).slice(1,2)); else if (/^macro:.+/.exec(arg)) url += "&macro=" + encodeURIComponent(/^macro:(.+)/.exec(arg).slice(1,2)); else if (/^warnings:.*/.exec(arg)) { var warnings = /^warnings:(.*)/.exec(arg).slice(1,2); // see if user did warnings:<nothing>, meaning "show all warnings" if (warnings == '') warnings = '*'; url += "&warnings=" + encodeURIComponent(warnings); } else { string += arg + " "; continue; } } if (string.length > 0) { string = string.substring(0, string.length-1); if (/^\/.+\/$/.exec(string)) { string = string.substring(1, string.length-1); url += "&regexp=on"; } url += "&string=" + encodeURIComponent(string); } window.location = url; return false; } function checkShowHintBox(form_id, div_id, link_id) { var url = window.location.href; var pattern = /string=([^&#]+)/; var match = url.match (pattern); var search = RegExp.$1; if (search.length > 0) { showHintBox(form_id, div_id, link_id, search); } } function showHintBox(form_id, id, link_id, string) { var form = document.getElementById(form_id) var div = document.getElementById(id); var link = document.getElementById(link_id); var url = getSearchUrlBase(form.tree.value, true); url += "&string=" + encodeURIComponent(string); link.innerHTML = string; link.href= url div.style.display = "block"; } function hideHintBox(id) { var div = document.getElementById(id); div.style.display='none' }
JavaScript
0.000034
@@ -2659,17 +2659,19 @@ ink. -innerHTML +textContent = s
88926fec10532ea4be077d3491a54a65fff9f3e3
Make links inside commented text clickable in rich text
www/pad/links.js
www/pad/links.js
define([ 'jquery', '/common/hyperscript.js', '/common/common-ui-elements.js', '/customize/messages.js' ], function ($, h, UIElements, Messages) { var onLinkClicked = function (e, inner) { var $target = $(e.target); if (!$target.is('a')) { return; } var href = $target.attr('href'); if (!href) { return; } var $inner = $(inner); e.preventDefault(); e.stopPropagation(); if (href[0] === '#') { var anchor = $inner.find(href); if (!anchor.length) { return; } anchor[0].scrollIntoView(); return; } var $iframe = $('html').find('iframe').contents(); var rect = e.target.getBoundingClientRect(); var rect0 = inner.getBoundingClientRect(); var l = (rect.left - rect0.left)+'px'; var t = rect.bottom + $iframe.scrollTop() +'px'; var a = h('a', { href: href}, href); var link = h('div.cp-link-clicked.non-realtime', { contenteditable: false, style: 'top:'+t+';left:'+l }, [ a ]); var $link = $(link); $inner.append(link); if (rect.left + $link.outerWidth() - rect0.left > $inner.width()) { $link.css('left', 'unset'); $link.css('right', 0); } $(a).click(function (ee) { ee.preventDefault(); ee.stopPropagation(); var bounceHref = window.location.origin + '/bounce/#' + encodeURIComponent(href); window.open(bounceHref); $link.remove(); }); $link.on('mouseleave', function () { $link.remove(); }); }; var removeClickedLink = function ($inner) { $inner.find('.cp-link-clicked').remove(); }; return { init : function (Ckeditor, editor) { if (!Ckeditor.plugins.link) { return; } var inner = editor.document.$.body; var $inner = $(inner); // Bubble to open the link in a new tab $inner.click(function (e) { removeClickedLink($inner); if (e.target.nodeName.toUpperCase() === 'A') { return void onLinkClicked(e, inner); } }); // Adds a context menu entry to open the selected link in a new tab. var getActiveLink = function() { var anchor = Ckeditor.plugins.link.getSelectedLink(editor); // We need to do some special checking against widgets availability. var activeWidget = editor.widgets && editor.widgets.focused; // If default way of getting links didn't return anything useful.. if (!anchor && activeWidget && activeWidget.name === 'image' && activeWidget.parts.link) { // Since CKEditor 4.4.0 image widgets may be linked. anchor = activeWidget.parts.link; } return anchor; }; editor.addCommand( 'openLink', { exec: function() { var anchor = getActiveLink(); if (anchor) { var href = anchor.getAttribute('href'); if (href) { var bounceHref = window.location.origin + '/bounce/#' + encodeURIComponent(href); window.open(bounceHref); } } } }); if (typeof editor.addMenuItem === 'function') { editor.addMenuItem('openLink', { label: Messages.openLinkInNewTab, command: 'openLink', group: 'link', order: -1 }); } if (editor.contextMenu) { editor.contextMenu.addListener(function(startElement) { if (startElement) { var anchor = getActiveLink(); if (anchor && anchor.getAttribute('href')) { return {openLink: Ckeditor.TRISTATE_OFF}; } } }); editor.contextMenu._.panelDefinition.css.push('.cke_button__openLink_icon {' + Ckeditor.skin.getIconStyle('link') + '}'); } } }; });
JavaScript
0.000001
@@ -268,24 +268,113 @@ ('a')) %7B - return; +%0A $target = $target.closest('a');%0A if (!$target.length) %7B return; %7D%0A %7D%0A @@ -2267,16 +2267,51 @@ === 'A' + %7C%7C $(e.target).closest('a').length ) %7B%0A
b70c5b417b192f01c179b86a29f3d38b2cfcf473
make a wildcardplugin out of it
esResponseTimes.js
esResponseTimes.js
#! /usr/bin/env node var program = require('commander'); var _ = require('lodash'); var request = require('request-json'); var moment = require('moment-timezone'); program .version('0.0.1') .usage('node index.js <config>') // .option('-p, --peppers', 'Add peppers') // .option('-P, --pineapple', 'Add pineapple') // .option('-b, --bbq', 'Add bbq sauce') // .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') .parse(process.argv); var username = process.env.ESUSER; var password = process.env.ESPW; var host = process.env.ESHOSTURL || 'http://localhost:9200'; var client = request.createClient(host); if (username) { client.setBasicAuth(username, password); } var hostname = process.argv[1].split('_')[1]; if (!hostname) { hostname = 'prod'; } //var dbObjects = require(program.args[0]); //var locale = program.args[1]; //var objName = program.args[2]; if (program.args[0] && program.args[0] ==='config') { console.log( "graph_title "+ hostname +" Backend ResponseTime\n"+ "graph_vlabel milliseconds\n"+ "graph_scale no\n"+ "graph_category responsetimes\n"+ "graph_info Percentiles of responsetimes on "+hostname+" backend\n"+ "50p.label 50% below this\n"+ "75p.label 75% below this\n"+ "95p.label 95% below this\n"+ "99p.label 99% below this\n" + "50p.info 50% of all request had a response time lower than this value\n" + "75p.info 75% of all request had a response time lower than this value\n" + "95p.info 95% of all request had a response time lower than this value\n" + "99p.info 99% of all request had a response time lower than this value\n" ); process.exit(0); } var myQuery = { "query": { "filtered": { "query": { "match_all": {} }, "filter": { "and": [ { "term": { "hostname": hostname } }, { "term": { "tags": "bunyan" } }, { "range": { "@timestamp": { "gt": "now-5m" } } }, { "term": { "level": "info" } }, { "term": { "message": "finished" } } ] } } }, "aggs": { "responsetimeAvg": { "percentiles": { "field": "responsetime" } } } }; function formatValue(val) { if (val === 'NaN') { return 0; } else if (_.isString(val)) { return parseFloat(val); } else { return val; } } var url = '/logstash-' + moment().format('YYYY.MM.DD') + '/_search?search_type=count'; client.get(url, {json: myQuery}, function(err, res, body) { if (err) { console.log(err); process.exit(1); } console.log('50p.value ' + formatValue(body.aggregations.responsetimeAvg['50.0']).toFixed(1)); console.log('75p.value ' + formatValue(body.aggregations.responsetimeAvg['75.0']).toFixed(1)); console.log('95p.value ' + formatValue(body.aggregations.responsetimeAvg['95.0']).toFixed(1)); console.log('99p.value ' + formatValue(body.aggregations.responsetimeAvg['99.0']).toFixed(1)); });
JavaScript
0.000002
@@ -3224,25 +3224,24 @@ it(1);%0A %7D%0A -%0A console. @@ -3308,27 +3308,33 @@ eAvg -%5B'50.0'%5D).toFixed(1 +.values%5B'50.0_as_string'%5D ));%0A @@ -3413,27 +3413,33 @@ eAvg -%5B'75.0'%5D).toFixed(1 +.values%5B'75.0_as_string'%5D ));%0A @@ -3518,27 +3518,33 @@ eAvg -%5B'95.0'%5D).toFixed(1 +.values%5B'95.0_as_string'%5D ));%0A @@ -3623,27 +3623,33 @@ eAvg -%5B'99.0'%5D).toFixed(1 +.values%5B'99.0_as_string'%5D ));%0A
694b4b853a54f99ca10564ab376c98e027b38c34
Use for...of
esm/setchildren.js
esm/setchildren.js
import { mount } from './mount.js'; import { unmount } from './unmount.js'; import { getEl, isNode } from './util.js'; export const setChildren = (parent, ...children) => { const parentEl = getEl(parent); let current = traverse(parent, children, parentEl.firstChild); while (current) { const next = current.nextSibling; unmount(parent, current); current = next; } }; function traverse (parent, children, _current) { let current = _current; for (let i = 0; i < children.length; i++) { const child = children[i]; if (!child) { continue; } let childEl = getEl(child); if (childEl === current) { current = current.nextSibling; continue; } if (isNode(childEl)) { mount(parent, child, current); continue; } if (child.length != null) { current = traverse(parent, child, current); } } return current; }
JavaScript
0
@@ -472,51 +472,8 @@ or ( -let i = 0; i %3C children.length; i++) %7B%0A cons @@ -480,17 +480,18 @@ t child -= +of childre @@ -495,13 +495,11 @@ dren -%5Bi%5D;%0A +) %7B %0A
b74584c0f249e8aa75905b1dfd7bc47566b791df
Fix comments for mouse handler which were outdated.
Examples/Skeleton/Skeleton.js
Examples/Skeleton/Skeleton.js
/*global require*/ require({ baseUrl : '../../Source' }, ['Cesium'], function(Cesium) { "use strict"; //A real application should require only the subset of modules that //are actually used, instead of requiring the Cesium module, which //includes everything. var canvas = document.getElementById('glCanvas'); var ellipsoid = Cesium.Ellipsoid.WGS84; // Used in many Sandbox examples var scene = new Cesium.Scene(canvas); var primitives = scene.getPrimitives(); // Bing Maps var bing = new Cesium.BingMapsTileProvider({ server : 'dev.virtualearth.net', mapStyle : Cesium.BingMapsStyle.AERIAL, // Some versions of Safari support WebGL, but don't correctly implement // cross-origin image loading, so we need to load Bing imagery using a proxy. proxy : Cesium.FeatureDetection.supportsCrossOriginImagery() ? undefined : new Cesium.DefaultProxy('/proxy/') }); var cb = new Cesium.CentralBody(ellipsoid); cb.dayTileProvider = bing; cb.nightImageSource = '../../Images/land_ocean_ice_lights_2048.jpg'; cb.specularMapSource = '../../Images/earthspec1k.jpg'; if (scene.getContext().getMaximumTextureSize() > 2048) { cb.cloudsMapSource = '../../Images/earthcloudmaptrans.jpg'; cb.bumpMapSource = '../../Images/earthbump1k.jpg'; } cb.showSkyAtmosphere = true; cb.showGroundAtmosphere = true; primitives.setCentralBody(cb); scene.getCamera().frustum.near = 1.0; scene.getCamera().getControllers().addCentralBody(); var transitioner = new Cesium.SceneTransitioner(scene, ellipsoid); /////////////////////////////////////////////////////////////////////////// // Add examples from the Sandbox here: /////////////////////////////////////////////////////////////////////////// scene.setAnimation(function() { //scene.setSunPosition(scene.getCamera().position); scene.setSunPosition(Cesium.SunPosition.compute().position); // Add code here to update primitives based on changes to animation time, camera parameters, etc. }); (function tick() { scene.render(); Cesium.requestAnimationFrame(tick); }()); /////////////////////////////////////////////////////////////////////////// // Example mouse & keyboard handlers var handler = new Cesium.EventHandler(canvas); handler.setMouseAction(function(movement) { /* ... */ // Use movement.startX, movement.startY, movement.endX, movement.endY }, Cesium.MouseEventType.MOVE); function keydownHandler(e) { switch (e.keyCode) { case "3".charCodeAt(0): // "3" -> 3D globe cb.showSkyAtmosphere = true; cb.showGroundAtmosphere = true; transitioner.morphTo3D(); break; case "2".charCodeAt(0): // "2" -> Columbus View cb.showSkyAtmosphere = false; cb.showGroundAtmosphere = false; transitioner.morphToColumbusView(); break; case "1".charCodeAt(0): // "1" -> 2D map cb.showSkyAtmosphere = false; cb.showGroundAtmosphere = false; transitioner.morphTo2D(); break; default: break; } } document.addEventListener('keydown', keydownHandler, false); canvas.oncontextmenu = function() { return false; }; /////////////////////////////////////////////////////////////////////////// // Example resize handler var onResize = function () { var width = canvas.clientWidth; var height = canvas.clientHeight; if (canvas.width === width && canvas.height === height) { return; } canvas.width = width; canvas.height = height; scene.getContext().setViewport({ x: 0, y: 0, width: width, height: height }); scene.getCamera().frustum.aspectRatio = width / height; }; window.addEventListener('resize', onResize, false); onResize(); });
JavaScript
0
@@ -2483,56 +2483,38 @@ tart -X, movement.startY, movement.endX, movement.endY +Position, movement.endPosition %0A @@ -2636,25 +2636,24 @@ arCodeAt(0): - // %223%22 -%3E 3 @@ -2829,25 +2829,24 @@ arCodeAt(0): - // %222%22 -%3E C @@ -3043,17 +3043,16 @@ deAt(0): - // %221%22 @@ -3531,17 +3531,16 @@ function - () %7B%0A @@ -3833,16 +3833,17 @@ x + : 0,%0A @@ -3852,16 +3852,17 @@ y + : 0,%0A @@ -3875,16 +3875,17 @@ width + : width, @@ -3903,16 +3903,17 @@ height + : height
e3caf9c56672cef45a42f0aff74201ff6837b5de
use new signals hash
scripted/src/extensions/time/time-extension.js
scripted/src/extensions/time/time-extension.js
/** * @fileOverview An extension to Exhibit adding a view using SIMILE Timeline. * @author David Huynh * @author <a href="mailto:ryanlee@zepheira.com">Ryan Lee</a> * @example Load this file like so: * <script src="http://host/exhibit/3.0.0/exhibit-api.js"></script> * <script src="http://host/exhibit/3.0.0/extensions/time-extension.js"></script> * where "host" is wherever the Exhibit files are based on the web. Valid * parameters are: * bundle [true|false]: load extension files one by one or bundled in one file * timelinePrefix <String>: Which host to find Timeline, defaults to * "http://api.simile-widgets.org" * timelineVersion <String>: Which version of Timeline to use, defaults to * "2.3.1" */ /** * This extension is subject to ugly, ugly hacks because Timeline a) relies * on SimileAjax, which Exhibit 3.0 no longer does, and b) Timeline's method * of loading (via SimileAjax) is outdated and not compatible with Exhibit. * * In order to compensate, this file uses two polling loops and a modified * version of the SimileAjax loader. The first polling loop waits until * jQuery is available, which is mostly a network latency concern. The * second polling loop waits until Timeline has loaded and is defined in * the window context, which is also mostly a network latency concern. * But the extension must take advantage of Exhibit's delay mechanism so * Exhibit will delay creation until Timeline has finished loading. The * modified SimileAjax loader does not load SimileAjax jQuery or allow * SimileAjax to modify jQuery but has to define some of the material * in SimileAjax as a consequence. See load-simile-ajax.js. */ (function loadTimeExtension(){ /** * Ugly polling hack #1. */ setTimeout(function() { if (typeof jQuery === "undefined") { loadTimeExtension(); } else { $(document).one("loadExtensions.exhibit", function() { var javascriptFiles, cssFiles, paramTypes, url, scriptURLs, cssURLs, ajaxURLs, i, delayID, finishedLoading, localesToLoad; delayID = Exhibit.generateDelayID(); $(document).trigger( "delayCreation.exhibit", delayID ); Exhibit.TimeExtension = { "params": { "bundle": true, "timelinePrefix": "http://api.simile-widgets.org", "timelineVersion": "2.3.1" }, "urlPrefix": null, "locales": [ "en", "de", "es", "fr", "nl", "sv" ] }; javascriptFiles = [ "timeline-view.js" ]; cssFiles = [ "timeline-view.css" ]; paramTypes = { "bundle": Boolean, "timelinePrefix": String, "timelineVersion": String }; if (typeof Exhibit_TimeExtension_urlPrefix === "string") { Exhibit.TimeExtension.urlPrefix = Exhibit_TimeExtension_urlPrefix; if (typeof Exhibit_TimeExtension_parameters !== "undefined") { Exhibit.parseURLParameters(Exhibit_TimeExtension_parameters, Exhibit.TimeExtension.params, paramTypes); } } else { url = Exhibit.findScript(document, "/time-extension.js"); if (url === null) { Exhibit.Debug.exception(new Error("Failed to derive URL prefix for SIMILE Exhibit Time Extension files")); return; } Exhibit.TimeExtension.urlPrefix = url.substr(0, url.indexOf("time-extension.js")); Exhibit.parseURLParameters(url, Exhibit.TimeExtension.params, paramTypes); } scriptURLs = []; cssURLs = []; if (typeof SimileAjax === "undefined") { /** * Ugly SimileAjax hack. See load-simile-ajax.js. */ scriptURLs.push(Exhibit.TimeExtension.urlPrefix + "load-simile-ajax.js"); } if (typeof Timeline === "undefined") { scriptURLs.push(Exhibit.TimeExtension.params.timelinePrefix + "/timeline/" + Exhibit.TimeExtension.params.timelineVersion + "/timeline-api.js?bundle=true"); } if (Exhibit.TimeExtension.params.bundle) { scriptURLs.push(Exhibit.TimeExtension.urlPrefix + "time-extension-bundle.js"); cssURLs.push(Exhibit.TimeExtension.urlPrefix + "time-extension-bundle.css"); } else { Exhibit.prefixURLs(scriptURLs, Exhibit.TimeExtension.urlPrefix + "scripts/", javascriptFiles); Exhibit.prefixURLs(cssURLs, Exhibit.TimeExtension.urlPrefix + "styles/", cssFiles); } localesToLoad = Exhibit.Localization.getLoadableLocales(Exhibit.TimeExtension.locales); for (i = 0; i < localesToLoad.length; i++) { scriptURLs.push(Exhibit.TimeExtension.urlPrefix + "locales/" + localesToLoad[i] + "/locale.js"); } Exhibit.includeCssFiles(document, "", cssURLs); Exhibit.includeJavascriptFiles(document, "", scriptURLs); /** * Ugly polly hack #2. */ finishedLoading = function() { setTimeout(function() { if (typeof Timeline === "undefined") { finishedLoading(); } else { $(document).trigger("delayFinished.exhibit", delayID); } }, 500); }; finishedLoading(); }); } }, 500); }());
JavaScript
0.000003
@@ -1772,32 +1772,52 @@ ut(function() %7B%0A + var loader;%0A if (type @@ -1911,49 +1911,16 @@ -$(document).one(%22loadExtensions.exhibit%22, +loader = fun @@ -6393,18 +6393,206 @@ %7D -) ; +%0A if (Exhibit.signals%5B%22loadExtensions.exhibit%22%5D) %7B%0A loader();%0A %7D else %7B%0A $(document).one(%22loadExtensions.exhibit%22, loader);%0A %7D %0A
688845da01d1cdc0f8be5341261809ee56d7fd3b
Allow <input ... df-autocomplete-submit-on-select> option that instructs the autocompleted input to submit its parent form when the user makes a selection
modules/directives/autocomplete/autocomplete.js
modules/directives/autocomplete/autocomplete.js
angular.module('dataform.directives').directive('dfAutocompleteDatalist', ['$document', '$timeout', function($document, $timeout) { return { restrict: 'A', require: 'ngModel', link: function(scope, elem, attrs, ngModel) { if (!attrs.dfAutocompleteDatalist) throw new Error('df-autocomplete-datalist attribute must not be empty'); var $datalist = $document.find('ol[df-datalist]#' + attrs.dfAutocompleteDatalist); if (!$datalist.length) { throw new Error('df-autocomplete-datalist attribute value "' + attrs.dfAutocompleteDatalist + '" ' + 'must refer to DOM ID of existing <ol df-datalist> element'); } $datalist.hide(); var dlScope = $datalist.scope(); // Position the datalist right underneath this <input> and make it take up the full width. function setDatalistPosition() { var dim = angular.extend({width: elem[0].offsetWidth, height: elem[0].offsetHeight}, elem.position()); $datalist.css({top: dim.top + dim.height, left: dim.left, width: dim.width}); } var handlers = { select: function($event, value) { $event.stopPropagation(); $event.preventDefault(); $datalist.hide(); scope.$apply(function() { scope[attrs.ngModel] = value; }); } }; function syncToDatalist() { dlScope.query = ngModel.$viewValue; dlScope._$ac_on = handlers; } // Listen on the input value. ngModel.$viewChangeListeners.push(function() { syncToDatalist(); }); // Listen on our ngModel value. scope.$watch(attrs.ngModel, function() { syncToDatalist(); }, true); // Show datalist when focused. elem.on('focus', function($event) { setDatalistPosition(); syncToDatalist(); $datalist.show(); }); // Hide datalist when blurred, UNLESS we're hovering the datalist. // This is to avoid removing the datalist before the click event registers. var $datalist_mousedOver = false; $datalist.on('mouseenter', function() { $datalist_mousedOver = true; }); $datalist.on('mouseleave', function() { $datalist_mousedOver = false; }); elem.on('blur', function($event) { if (!$datalist_mousedOver) { $datalist.hide(); } }); // If the element loaded in a focused state (e.g., <input autofocus>), the // focus event handler won't be called unless we manually trigger it. if (elem.is(':focus')) { elem.trigger('focus'); } } }; }]); angular.module('dataform.directives').directive('dfDatalist', [function() { return { restrict: 'A', link: function(scope, elem, attrs) { elem.addClass('df-datalist'); elem.delegate('li[df-value]', 'click', function($event) { var $li = angular.element($event.currentTarget); var value = $li.scope().$eval($li.attr('df-value')); scope._$ac_on.select($event, value); }); } }; }]);
JavaScript
0.000001
@@ -1327,24 +1327,411 @@ %7D); +%0A%0A // Allow %3Cinput ... df-autocomplete-submit-on-select%3E option that instructs this%0A // directive to submit its parent form when the user makes a selection.%0A if (attrs.hasOwnProperty('dfAutocompleteSubmitOnSelect')) %7B%0A console.log('SELECT');%0A if (elem.parent().is('form')) %7B%0A elem.parent().submit();%0A %7D%0A %7D %0A %7D%0A
b90f61dd35b7889f05a21fbc29e6340b895de497
Update latex_envs.js
nbextensions/usability/latex_envs/latex_envs.js
nbextensions/usability/latex_envs/latex_envs.js
/* */ var conversion_to_html = false; var config_toolbar_present=false; var cite_by, bibliofile, eqNumInitial, eqNum, eqLabelWithNumbers; //These variables are initialized in init_config() //EQUATIONS //var eqNumInitial = 0; //var eqNum = eqNumInitial; // begins equation numbering at eqNum+1 //var eqLabelWithNumbers = true; //if true, label equations with equation numbers; otherwise using the tag specified by \label //BIBLIOGRAPHY //var cite_by = 'apalike' //cite by 'number', 'key' or 'apalike' var current_citInitial=1; var current_cit=current_citInitial; // begins citation numbering at current_cit //var bibliofile = 'biblio.bib' //or IPython.notebook.notebook_name.split(".")[0]+."bib" //citations templates ........................................................ var etal=3; //list of authors is completed by et al. if there is more than etal authors var cit_tpl = { // feel free to add more types and customize the templates 'INPROCEEDINGS': '%AUTHOR:InitialsGiven%, ``_%TITLE%_\'\', %BOOKTITLE%, %MONTH% %YEAR%.', 'TECHREPORT': '%AUTHOR%, ``%TITLE%\'\', %INSTITUTION%, number: %NUMBER%, %MONTH% %YEAR%.', 'ARTICLE' : '%AUTHOR:GivenFirst%, ``_%TITLE%_\'\', %JOURNAL%, vol. %VOLUME%, number %NUMBER%, pp. %PAGES%, %MONTH% %YEAR%.', 'INBOOK' : '%AUTHOR:Given%, ``_%TITLE%_\'\', in %BOOKTITLE%, %EDITION%, %PUBLISHER%, pp. %PAGES%, %MONTH% %YEAR%.', 'UNKNOWN' : '%AUTHOR:FirstGiven%, ``_%TITLE%_\'\', %MONTH% %YEAR%.' } /* The keys are the main types of documents, eg inproceedings, article, inbook, etc. To each key is associated a string where the %KEYWORDS% are the fields of the bibtex entry. The keywords are replaced by the correponding bibtex entry value. The template string can formatted with additional words and effects (markdown or LaTeX are commands are supported) Authors can be formatted according to the following keywords: - %AUTHOR:FirstGiven%, i.e. John Smith - %AUTHOR:GivenFirst%, i.e. Smith John - %AUTHOR:InitialsGiven%, i.e. J. Smith - %AUTHOR:GivenInitials%, i.e. Smith J. - %AUTHOR:Given%, i.e. Smith */ // ***************************************************************************** define(["require", 'base/js/namespace', "nbextensions/usability/latex_envs/thmsInNb4", "nbextensions/usability/latex_envs/bibInNb4", "nbextensions/usability/latex_envs/initNb"], function (require,Jupyter, thmsInNb, bibsInNb,initNb) { var maps = initmap(); environmentMap=maps[0]; cmdsMap=maps[1]; eqLabNums=maps[2]; cit_table = maps[3]; init_config(); cfg= Jupyter.notebook.metadata.latex_envs; var MarkdownCell = require('notebook/js/textcell').MarkdownCell; var TextCell = require('notebook/js/textcell').TextCell; var mathjaxutils = require('notebook/js/mathjaxutils'); var security=require("base/js/security") var marked = require('components/marked/lib/marked'); //define(["require"], function (require) { var load_css = function(name) { var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = require.toUrl(name); //link.href = name; document.getElementsByTagName("head")[0].appendChild(link); }; var load_ipython_extension = require(['base/js/namespace'], function(Jupyter){ "use strict"; if (Jupyter.version[0] < 3) { console.log("This extension requires Jupyter or IPython >= 3.x") return } var _on_reload = true; /* make sure cells render on reload */ /* Override original markdown render function */ /* The idea was took from python-markdown extension https://gist.github.com/juhasch/c37408a0d79156f28c17#file-python-markdown-js */ // for IPython v 3+ / Jupyter 4 MarkdownCell.prototype.render = function () { var cont = TextCell.prototype.render.apply(this); if (cont || Jupyter.notebook.dirty || _on_reload) { var that = this; var text = this.get_text(); var math = null; if (text === "") { text = this.placeholder; } var text_and_math = mathjaxutils.remove_math(text); text = text_and_math[0]; math = text_and_math[1]; marked(text, function (err, html) { html = mathjaxutils.replace_math(html, math); html = thmsInNbConv(marked,html); //<----- thmsInNb patch here html = security.sanitize_html(html); html = $($.parseHTML(html)); // add anchors to headings html.find(":header").addBack(":header").each(function (i, h) { h = $(h); var hash = h.text().replace(/ /g, '-'); h.attr('id', hash); h.append( $('<a/>') .addClass('anchor-link') .attr('href', '#' + hash) .text('¶') ); }); // links in markdown cells should open in new tabs html.find("a[href]").not('[href^="#"]').attr("target", "_blank"); that.set_rendered(html); that.typeset(); that.events.trigger("rendered.MarkdownCell", {cell: that}); }); } return cont; }; //init_cells(); readBibliography(function (){ init_cells(); createReferenceSection(); }); /* on reload */ $([Jupyter.events]).on('status_started.Kernel', function() { //init_cells(); readBibliography(function (){ init_cells(); createReferenceSection(); }); _on_reload = false; }) Jupyter.toolbar.add_buttons_group([ { id : 'doReload', label : 'LaTeX_envs: Refresh rendering of labels, equations and citations', icon : 'fa-refresh', callback : init_cells }, { 'label' : 'Read bibliography and generate references section', 'icon' : 'fa-book', 'callback': generateReferences }, { 'label' : 'LaTeX_envs: Some configuration options (toogle toolbar)', 'icon' : 'fa-wrench', 'callback': config_toolbar } ]); // }); }); //end of load_ipython_extension function console.log("Loading latex_envs.css"); //load_css('/nbextensions/latex_envs.css') load_css('./latex_envs.css') //load_ipython_extension(); return { load_ipython_extension: load_ipython_extension, }; }); //End of run_this //run_this(); console.log("Loading ./latex_envs.js");
JavaScript
0.000001
@@ -2169,17 +2169,16 @@ equire%22, - %0A%09'base/ @@ -2240,24 +2240,17 @@ InNb4%22,%0A - +%09 %22nbexten
319b858e7767c974967ed3cd768855ad8e2172d3
fix typo in comment (#13883)
examples/with-firebase/context/userContext.js
examples/with-firebase/context/userContext.js
import { useState, useEffect, createContext, useContext } from 'react' import firebase from '../firebase/clientApp' export const UserContext = createContext() export default function UserContextComp({ children }) { const [user, setUser] = useState(null) const [loadingUser, setLoadingUser] = useState(true) // Helpful, to update the UI accordingly. useEffect(() => { // Listen authenticated user const unsubscriber = firebase.auth().onAuthStateChanged(async (user) => { try { if (user) { // User is signed in. const { uid, displayName, email, photoURL } = user // You could also look for the user doc in your Firestore (if you have one): // const userDoc = await firebase.firestore().doc(`users/${uid}`).get() setUser({ uid, displayName, email, photoURL }) } else setUser(null) } catch (error) { // Most probably a connection error. Handle appropiately. } finally { setLoadingUser(false) } }) // Unsubscribe auth listener on unmount return () => unsubscriber() }, []) return ( <UserContext.Provider value={{ user, setUser, loadingUser }}> {children} </UserContext.Provider> ) } // Custom hook that shorhands the context! export const useUser = () => useContext(UserContext)
JavaScript
0.000005
@@ -942,16 +942,17 @@ e approp +r iately.%0A
9d54d81a76b3674737458b9a8f146d91a51a1b8d
remove unnecessary pre-processor for all ~/src files
build/karma.js
build/karma.js
import { argv } from 'yargs'; import config from '../config'; import webpackConfig from '../webpack.config'; const KARMA_ENTRY_FILE = 'karma.entry.js'; function makeDefaultConfig () { const karma = { files : [ './node_modules/phantomjs-polyfill/bind-polyfill.js', './tests/**/*.js', './' + KARMA_ENTRY_FILE ], singleRun : !argv.watch, frameworks : ['mocha', 'sinon-chai', 'chai-as-promised', 'chai'], preprocessors : { [KARMA_ENTRY_FILE] : ['webpack'], [`${config.get('dir_src')}/**/*.js`] : ['webpack'], [`${config.get('dir_test')}/**/*.js`] : ['webpack'] }, reporters : ['spec'], browsers : ['PhantomJS'], webpack : { devtool : 'inline-source-map', resolve : webpackConfig.resolve, plugins : webpackConfig.plugins .filter(plugin => !plugin.__KARMA_IGNORE__), module : { loaders : webpackConfig.module.loaders }, sassLoader : webpackConfig.sassLoader }, webpackMiddleware : { noInfo : true }, coverageReporter : { reporters : config.get('coverage_reporters') }, plugins : [ require('karma-webpack'), require('karma-mocha'), require('karma-chai'), require('karma-chai-as-promised'), require('karma-sinon-chai'), require('karma-coverage'), require('karma-phantomjs-launcher'), require('karma-spec-reporter') ] }; if (config.get('coverage_enabled')) { karma.reporters.push('coverage'); karma.webpack.module.preLoaders = [{ test : /\.(js|jsx)$/, include : /src/, loader : 'isparta' }]; } return karma; } export default (karmaConfig) => karmaConfig.set(makeDefaultConfig());
JavaScript
0.000001
@@ -511,66 +511,8 @@ '%5D,%0A - %5B%60$%7Bconfig.get('dir_src')%7D/**/*.js%60%5D : %5B'webpack'%5D,%0A
932098d74ebab32e0844dd7295eb595d41b9fcdc
Fix setCenterPoint when zooming
src/Render.js
src/Render.js
import React from 'react'; import ReactDOM from 'react-dom'; import Wire from './Wire.js'; import { createElement } from './utils'; import { registerEvents } from './dom-handler.js' import { NodeGraph } from './react/components'; import { _p } from './points'; const config = { width: 800, height: 600 }; export default class Render { constructor (id, cfg) { this.config = { ...config, ...cfg }; this._aux = {}; this._state = null; this._wires = []; this.offset = { x: 0, y: 0 }; this.zoom = 1; this.disableZoom = false; this.disableDragging = false; const element = document.getElementById(id); if (element) { this.reactDOM(element); } return this; } registerEvents () { registerEvents.call(this); } reactDOM (element) { const { wrapper, Component } = this.config; const svg = createElement('svg', { class: 'svg-content', preserveAspectRatio: "xMidYMid meet" }); this.loadContainer(svg); element.classList.add('sticky__canvas'); element.appendChild(this._svg); ReactDOM.render( <NodeGraph ref={ref => this.react = ref} getNodes={() => wrapper.nodes} getOffset={() => this.offset} getZoom={() => this.zoom} />, svg ); } loadContainer (svg) { const { width, height } = this.config; this._svg = svg; svg.type = 'container'; this.matchViewBox(); this.setCanvasSize({ width, height }); this.registerEvents(); } matchViewBox() { const { width, height } = this._svg.getBoundingClientRect(); this._svg.setAttribute('viewBox', `0, 0, ${width} ${height}`); } setCanvasSize({ width, height }) { this._svg.style.width = width; this._svg.style.height = height; this._svg.setAttribute('width', width); this._svg.setAttribute('height', height); this._svg.setAttribute('viewBox', `0 0 ${width} ${height}`); } addElement (el) { this._svg.appendChild(el); } removeElement (el) { if (this._svg.contains(el)) this._svg.removeChild(el); } startDrag (port) { this.setState('dragging'); this._aux['wire'] = wire; this.addElement(wire._el); } startAttach (port) { let wire = new Wire(port.wrapper); wire._inverted = port.wrapper.direction === 'in'; this.setState('attaching'); this._aux['wire'] = wire; this.addElement(wire._el); } endAttach (port) { if (this.isState('attaching')) { this.setState(null); var wire = this._aux['wire']; wire._cp2 = port.wrapper; this.addWire(wire); delete this._aux['wire']; } } addWire (wire) { if (!wire.seal()) { this.removeElement(wire._el); return false; } wire.render(this.offset, this.zoom); this._wires.push(wire); this.addElement(wire._el); return true; } removeWire (wire) { const index = this._wires.indexOf(wire); if (index == -1) return; this._wires.splice(index, 1); } renderWires () { this._wires.forEach(wire => { wire.render(this.offset, this.zoom); }) } renderGrid (offset, zoom = 1) { const zOffset = _p.multiply(offset, zoom); this._svg.style.backgroundPositionX = `${zOffset.x}px`; this._svg.style.backgroundPositionY = `${zOffset.y}px`; this._svg.style.backgroundSize = `${50 * zoom}px ${50 * zoom}px`; this._svg.style.backgroundImage = ` linear-gradient(to right, grey 1px, transparent 1px), linear-gradient(to bottom, grey 1px, transparent 1px); `; this._svg.style.backgroundImage = ` linear-gradient(to right, grey ${1 * zoom}, transparent ${1 * zoom}), linear-gradient(to bottom, grey ${1 * zoom}, transparent ${1 * zoom}) `; } sealOrDiscard (...cps) { const wire = new Wire(...cps); if (this.addWire(wire)) return wire; return null; } setState (state) { return this._state = state; } isState (state) { return this._state === state; } getCanvasSize () { const { width, height } = this.config; return _p.add([width, height], 0); } getCenterPoint () { const vOffset = _p.multiply(this.offset, this.zoom); const vCanvasSize = _p.multiply(this.getCanvasSize(), this.zoom); return _p.subtract( _p.divide(vCanvasSize, 2), vOffset, ); } setCenterPoint (point) { const vPoint = _p.divide(_p.multiply(point, -1), this.zoom); this.offset = _p.add( _p.divide(this.getCanvasSize(), 2), vPoint, ); this.forceUpdate(); } forceUpdate () { if (this.react) this.react.forceUpdate(); this.renderGrid(this.offset, this.zoom); } setZoom (value) { this.zoom = value; this.forceUpdate(); } setOffset (point) { this.offset = point; this.forceUpdate(); } }
JavaScript
0.000002
@@ -4218,25 +4218,17 @@ Size(), -this.zoom +1 );%0A r @@ -4355,22 +4355,24 @@ nt = _p. -divide +multiply (_p.mult @@ -4392,32 +4392,94 @@ 1), this.zoom);%0A + const vCanvasSize = _p.multiply(this.getCanvasSize(), 1);%0A this.offset @@ -4504,24 +4504,17 @@ .divide( -this.get +v CanvasSi @@ -4515,18 +4515,16 @@ nvasSize -() , 2),%0A @@ -4542,16 +4542,69 @@ %0A );%0A + this.offset = _p.divide(this.offset, this.zoom);%0A this
2412be8acb161b6d59a862bd403d5da2b60b2fad
Add more logs for errors
server/services/qr-codes-service.js
server/services/qr-codes-service.js
'use strict'; let qrCode = require('node-qrcode'); let fs = require('fs'); let path = require('path'); const QR_CODES_DIRECTORY = path.join('./', 'public', 'qr-codes'); const DEFAULT_IMAGE_EXTENSION = 'png'; class QrCodesService { getQrCodeForTouristSite(touristSiteId) { let that = this; let promise = new Promise(function (resolve, reject) { fs.readFile(that.getQrCodeFilePath(touristSiteId), function (err, file) { if (err) { reject(err); return; } resolve(file); }); }); return promise; } createQrCode(touristSiteId) { let qrCodePath = this.getQrCodeFilePath(touristSiteId); return qrCode({ text: touristSiteId, size: 5, qrcodePath: qrCodePath }); } createQrCodesForAllTouristSites() { let that = this; let TouristSite = require('mongoose').model('TouristSite'); let promise = new Promise(function (resolve, reject) { fs.readdir(QR_CODES_DIRECTORY, function(err, files) { TouristSite.find({isApprovedForVisiting: true}, '_id') .then(function(allTouristSites) { let promises = []; allTouristSites.forEach(function(touristSite) { let touristSiteFileName = `${touristSite._id}.${DEFAULT_IMAGE_EXTENSION}`; if (files.indexOf(touristSiteFileName) < 0) { promises.push(that.createQrCode(touristSite._id)); } }); Promise.all(promises) .then(function (result) { resolve('All QR Codes are created.'); }, reject); }, reject); }); }); return promise; } getAllGeneratedQrCodesList() { let that = this; let promise = new Promise(function (resolve, reject) { fs.readdir(QR_CODES_DIRECTORY, function(err, files) { if (err) { reject(err); return; } resolve(files); }); }); return promise; } getQrCodeFilePath(name) { return `${QR_CODES_DIRECTORY}/${name}.${DEFAULT_IMAGE_EXTENSION}`; } } module.exports = { QrCodesService: QrCodesService, defaultInstance: new QrCodesService() };
JavaScript
0
@@ -93,24 +93,68 @@ re('path');%0A +let logger = require('./../common/logger');%0A const QR_COD @@ -488,32 +488,61 @@ if (err) %7B%0A + logger.err(err);%0A reje @@ -1785,53 +1785,233 @@ %7D, -reject);%0A %0A %7D, reject +function (err) %7B%0A logger.err(err);%0A reject(err);%0A %7D);%0A %0A %7D, function (err) %7B%0A logger.err(err);%0A reject(err);%0A %7D );%0A
1f4219e3ce7629814a027da7e00b969954f38be4
comment improvements webcam
src/Webcam.js
src/Webcam.js
/** * Webcam base class * * @class Webcam * @constructor * @param {Object} options composition options * used to set * */ "use strict"; var CHILD_PROCESS = require('child_process'); var EXEC = CHILD_PROCESS.exec; var FS = require( "fs" ); var Utils = require( __dirname + "/utils/Utils.js" ); var EventDispatcher = require( __dirname + "/utils/EventDispatcher.js" ); var CameraUtils = require( __dirname + "/utils/CameraUtils.js" ); /* * Main class * */ function Webcam( options ) { var scope = this; scope.shots = []; scope.opts = Utils.setDefaults( options, Webcam.Defaults ); } Webcam.prototype = { constructor: Webcam, /** * Main opts from construction * * @property opts * @type {Object} * */ opts: {}, /** * picture shots * * @mproperty shots * @type {Array} * */ shots: [], /** * Basic camera instance clone * * @method clone * * @return Webcam * */ clone: function() { return new this.constructor( this.opts ); }, /** * Clear shot and camera memory data * * @method clear * */ clear: function() { var scope = this; scope.shots = []; }, /** * List available cameras * * @method list * * @param {Function} callback returns a list of camers * */ list: CameraUtils.getCameras, /** * Has camera * * @method hasCamera * * @param {Function} callback returns a Boolean * */ hasCamera: function( callback ) { var scope = this; scope.list( function( list ) { callback && callback( !! list.length ); }); }, /** * Capture shot * * @method capture * * @param {String} location * @param {Function} callback * */ capture: function( location, callback ) { var scope = this; var fileType = Webcam.OutputTypes[ scope.opts.output ]; var location = location || ""; location = location.match( /\..*$/ ) ? location : location + "." + fileType; //Shell statement grab var sh = scope.generateSh( location ); if( scope.opts.verbose ) { console.log( sh ); } //Shell execute EXEC( sh, function( err, out, derr ) { if( err ) { console.log( derr ); throw err; } if( scope.opts.verbose && out ) { console.log( out ); } //Callbacks scope.shots.push( location ); scope.dispatch({ type: "capture" }); callback && callback( location ); }); }, /** * Generate cli command string * * @method generateSh * * @return {String} * */ generateSh: function( location ) { return ""; }, /** * Get shot buffer from location * 0 indexed * * @method getShot * * @param {Number} shot Index of shots called * @param {Function} callback Returns a call from FS.readFile data * * @return {Boolean} * */ getShot: function( shot, callback ) { var scope = this; var shotLocation = scope.shots[ shot ]; if( ! shotLocation ) { return false; } FS.readFile( shotLocation, function( err, data ) { if( err ) { throw err; } callback && callback( data ); }); return true; }, /** * Get last shot taken image data * * @method getLastShot * * @param {Function} callback Returns last shot from getShot return * * @return {Boolean} Successful getShot * */ getLastShot: function( callback ) { var scope = this; return scope.getShot( scope.shots.length - 1, callback ); }, /** * Get shot base64 as image * if passed Number will return a base 64 in the callback * * @method getBase64 * * @param {Number|FS.readFile} shot To be converted * @param {Function} callback Returns base64 string * * @return {Boolean|String} * */ getBase64: function( shot, callback ) { var scope = this; //Typeof number for a getShot callback if( typeof( shot ) === "number" ) { scope.getShot( shot, function( data ) { callback( scope.getBase64( data ) ); }); return true; } //Data use return "data:image/" + scope.opts.output + ";base64," + new Buffer( shot ).toString( "base64" ); } }; EventDispatcher.prototype.apply( Webcam.prototype ); /** * Base defaults for option construction * * @property Webcam.Defaults * * @type Object * */ Webcam.Defaults = { width: 1280, height: 720, delay: 0, quality: 100, output: "jpeg", device: false, verbose: true }; /** * Global output types * Various for platform * * @property Webcam.OutputTypes * * @type Object * @static * */ Webcam.OutputTypes = { "jpeg": "jpg", "png": "png", "bmp": "bmp" }; //Export module.exports = Webcam;
JavaScript
0
@@ -830,17 +830,16 @@ * @ -m property @@ -4969,16 +4969,27 @@ Object%0A + * @static%0A *%0A */%0A%0A
f9280a3a8e027631e7bf279b4e3fd74e8912f272
Add styling for form fields and submit button
registration.ios.js
registration.ios.js
import React, { Component } from 'react'; import NavigationBar from 'react-native-navbar' import Button from 'react-native-button'; import { AppRegistry, StyleSheet, Text, TextInput, View, SegmentedControlIOS, Image, Switch, DatePickerIOS, Navigator, } from 'react-native' class Registration extends Component { navigate(routeName) { this.props.navigator.push({ name: routeName }); } render() { return ( <View> <NavigationBar title={{ title: 'TipTap!' , tintColor: 'black' , }} leftButton={{ title: 'Back', tintColor: 'black', handler: this.navigate.bind(this, "main")} } style={{ backgroundColor: "#D3D3D3" , }} statusBar={{ tintColor: "white" , }} /> <View style={{padding: 50}}> <TextInput style={{height: 30}} placeholder="First Name" onChangeText={(text) => this.setState({text})} /> <TextInput style={{height: 30}} placeholder="Last Name" onChangeText={(text) => this.setState({text})} /> <TextInput secureTextEntry={true} style={{height: 30}} placeholder="Photo URL" onChangeText={(text) => this.setState({text})} /> <TextInput secureTextEntry={true} style={{height: 30}} placeholder="Payment URL" onChangeText={(text) => this.setState({text})} /> <Button style={{fontSize: 25, color: 'green'}} styleDisabled={{color: 'red'}} onPress={this.navigate.bind(this, "main")}> Submit Registration </Button> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); export default Registration
JavaScript
0
@@ -823,34 +823,111 @@ style=%7B%7B -height: 30 +fontSize: 20, height: 50, borderColor: 'gray', borderWidth: 3, padding: 3, marginTop: 1 %7D%7D%0A @@ -940,16 +940,17 @@ holder=%22 + First Na @@ -1054,34 +1054,111 @@ style=%7B%7B -height: 30 +fontSize: 20, height: 50, borderColor: 'gray', borderWidth: 3, padding: 3, marginTop: 1 %7D%7D%0A @@ -1171,16 +1171,17 @@ holder=%22 + Last Nam @@ -1287,59 +1287,102 @@ s -ecureTextEntry=%7Btrue%7D%0A style=%7B%7Bheight: 30 +tyle=%7B%7BfontSize: 20, height: 50, borderColor: 'gray', borderWidth: 3, padding: 3, marginTop: 1 %7D%7D%0A @@ -1404,16 +1404,17 @@ holder=%22 + Photo UR @@ -1523,60 +1523,102 @@ s -ecureTextEntry=%7Btrue%7D%0A style=%7B%7Bheight: 30 +tyle=%7B%7BfontSize: 20, height: 50, borderColor: 'gray', borderWidth: 3, padding: 3, marginTop: 1 %7D%7D%0A @@ -1641,16 +1641,17 @@ holder=%22 + Payment @@ -1788,16 +1788,103 @@ 'green' +, borderColor: 'green', borderWidth: 7, borderRadius: 15, marginTop: 15, paddingTop: 15 %7D%7D%0A
57e8e56d307f9185322b104be4dcc14d60669ae0
Copy bindings when changing binded object
source/binding.js
source/binding.js
Sandwich.Module.define('Binding', ['Namespace'], function ( Namespace ) { // Create a namespace object got our bindings var NS = new Namespace(), observer = new PB.Observer(); return { set: function ( namespace, object ) { NS.set(namespace, object); }, get: function ( namespace ) { return NS.get(namespace); }, on: function ( namespace, types, callback, context ) { var object = this.get(namespace); if( !object.on || typeof object.on !== 'function' ) { Sandwich.Error.report('Tried calling on which is no method'); } object.on(types, callback, context); }, off: function () { } /*emit: function () { }*/ }; }); Sandwich.Application.register('Binding', function () { return Sandwich.Module.getInstance('Binding'); });
JavaScript
0
@@ -180,57 +180,462 @@ ;%0A%0A%09 -return %7B%0A%0A%09%09set: function ( namespace, object ) %7B +/**%0A%09 *%0A%09 */%0A%09function copyListeners ( object, listeners ) %7B%0A%0A%09%09var type;%0A%0A%09%09for( type in listeners ) %7B%0A%0A%09%09%09if( listeners.hasOwnProperty(type) ) %7B%0A%0A%09%09%09%09listeners%5Btype%5D.forEach(function ( obj ) %7B%0A%0A%09%09%09%09%09object.on(type, obj.fn, obj.context);%0A%09%09%09%09%7D);%0A%09%09%09%7D%0A%09%09%7D%0A%09%7D;%0A%0A%09return %7B%0A%0A%09%09set: function ( namespace, object ) %7B%0A%0A%09%09%09var prev = this.get(namespace);%0A%0A%09%09%09if( prev ) %7B%0A%0A%09%09%09%09copyListeners(object, prev.listeners);%0A%0A%09%09%09%09// Unbind listeners%0A%09%09%09%09prev.off();%0A%09%09%09%7D %0A%0A%09%09 @@ -921,36 +921,33 @@ rt(' -Tried calling on which is no +Object does not have %60on%60 met @@ -1040,36 +1040,44 @@ %0A%09%09/ -* +/ emit: -function () %7B%0A%0A%0A%09%09%7D*/ +observer.emit.bind(observer) %0A%09%7D;
67d35f316ed44189e24b6b2ff3e0555ccbc80175
update lighthouse assertions
.lighthouserc.js
.lighthouserc.js
module.exports = { ci: { assert: { preset: 'lighthouse:no-pwa', assertions: { // Superflous text like "Introduction" on the homepage has a really // low color contrast, but is also not essential text. 'color-contrast': 'warn', }, }, }, }
JavaScript
0
@@ -85,24 +85,98 @@ sertions: %7B%0A + 'uses-rel-preconnect': 'off',%0A 'unused-javascript': 'off',%0A // S @@ -301,16 +301,80 @@ al text. + I do still%0A // want warnings for other elements, though. %0A
c816bfa1df1f976cf8aa71f99d8aecac6c77bb99
Remove font CDN
server/app/config/config.js
server/app/config/config.js
'use strict'; module.exports = (function () { var csp = { 'default-src': '\'none\'', 'connect-src': '\'self\'', 'font-src': ['\'self\'', 'http://netdna.bootstrapcdn.com/'], 'script-src': ['\'self\'', '\'unsafe-eval\'', '\'unsafe-inline\'', 'ajax.googleapis.com', 'www.google-analytics.com'], 'style-src': ['\'self\'', '\'unsafe-inline\'', 'netdna.bootstrapcdn.com'], sandbox: ['allow-forms', 'allow-same-origin', 'allow-scripts'], 'report-uri': ['/report-violation'], reportOnly: false, setAllHeaders: false, safari5: false }; switch (process.env.NODE_ENV) { case 'production': return { csp: csp, db: 'mongodb://localhost/test', public: 'build/' }; case 'travis': return { csp: {}, // PhantomJS has issues with CSP db: 'mongodb://localhost/test', public: 'build/' }; default: return { csp: csp, db: 'mongodb://localhost/test', public: 'client/app/' }; } }());
JavaScript
0.000022
@@ -161,42 +161,49 @@ f%5C'' -, 'http://netdna.bootstrapcdn.com/ +%5D,%0A 'img-src': %5B'%5C'self%5C'', 'data: '%5D,%0A
99cf2f883a07a8a2f80ddf92dabc86c3bb45b9f5
Make sure to flag up noop on Journey updates for watched journeys
server/listeners/journey.js
server/listeners/journey.js
"use strict"; const Journeys = require('../../models/journeys'); const Users = require('../../models/users'); const sync = require('../../sync/sync'); const debug = require('../../util/debug'); function error(operation, journey, err) { console.error(`Journey: Error performing ${operation} on ${journey.uid}`, err, err.stack); } function success(operation, journey) { console.log(`Journey: Successfully performed ${operation} on ${journey.uid}`); } function noop(operation, journey) { debug(`Journey: Nothing to be done for ${operation} on ${journey.uid}`); } function updateUsers(users, journey) { if (!users || !users.length) { return Promise.resolve(false); } return Promise.all(users.map(user => sync.update(user, journey))); } Journeys.on('update', function(journey, updates) { Users.findForJourney(journey.uid, journey.ssd) .then((users) => updateUsers(users, journey)) .then((updated) => updated ? success('update', journey) : noop('update', journey)) .catch((err) => error('update', journey, err)); });
JavaScript
0
@@ -145,16 +145,61 @@ /sync'); +%0Aconst watcher = require('../../sync/watch'); %0A%0Aconst @@ -541,20 +541,108 @@ ) %7B%0A -debu +const log = watcher.isJourneyWatched(journey.uid, journey.ssd) ? console.log : debug;%0A lo g(%60Journ
7faa049b19236a9c8a59f5e473fcc0878d23fb9f
Update vic.js
chat-plugins/vic.js
chat-plugins/vic.js
exports.commands = { v: 'vic', popup("<body background="http://static.spin.com/files/141201-r%C3%B6yksopp-skulls-music-video-watch-cabin-rave-creepy.png"><center><img src="http://images.cooltext.com/4547425.png" width="350" height="70" alt="OPVictreebel" /><br></center><br><center><img src="http://www.screwattack.com/sites/default/files/jigglypuff.gif" height="" width=""><br><img src="http://images.cooltext.com/4547442.png" width="197" height="103" alt="'Run!'" /><audio src="https://api.soundcloud.com/tracks/177061189/stream?client_id=02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea" controls="" style="width: 99% ; border: 2px solid #ffffFF ; background-color: #ffffff" target="_blank"></audio></body>"); } };
JavaScript
0.000001
@@ -38,16 +38,22 @@ %09popup(%22 +%7Chtml%7C %3Cbody ba
d461eae1bfa290bd19ab63e0eba0039e9cc2a33d
Update activate.js
services/editor/service-worker/src/activate.js
services/editor/service-worker/src/activate.js
import { CACHE_NAME, urls } from './constants'; import activateSocket from './activateSocket'; import { refresh } from './data-actions'; import getUrl from './getUrl'; import activateSocket from './activateSocket'; import { refresh } from './data-actions'; export default async function activate() { const cache = await caches.open(CACHE_NAME); const cachedKeys = await cache.keys(); const urlsToCacheSet = new Set(urls.CACHE); const keysToDelete = cachedKeys.filter(key => !urlsToCacheSet.has(getUrl(key))); await Promise.all( keysToDelete.map(key => (console.log('deleting from cache', key.url), cache.delete(key))), ); try { activateSocket(); await refresh(); } catch (error) { console.error('error while loading cache', error); } self.clients.claim(); }
JavaScript
0.000001
@@ -45,97 +45,8 @@ s';%0A -import activateSocket from './activateSocket';%0Aimport %7B refresh %7D from './data-actions';%0A impo
9b595e47eb2620b1f412df35feacda5f56a1c969
Remove deletion of `@ember/jquery` in addon blueprint
blueprints/addon/index.js
blueprints/addon/index.js
'use strict'; const fs = require('fs-extra'); const path = require('path'); const walkSync = require('walk-sync'); const chalk = require('chalk'); const stringUtil = require('ember-cli-string-utils'); const { uniq } = require('ember-cli-lodash-subset'); const SilentError = require('silent-error'); const sortPackageJson = require('sort-package-json'); let date = new Date(); const normalizeEntityName = require('ember-cli-normalize-entity-name'); const stringifyAndNormalize = require('../../lib/utilities/stringify-and-normalize'); const directoryForPackageName = require('../../lib/utilities/directory-for-package-name'); const FileInfo = require('../../lib/models/file-info'); const replacers = { 'package.json'(content) { return this.updatePackageJson(content); }, }; const ADDITIONAL_DEV_DEPENDENCIES = require('./additional-dev-dependencies.json').devDependencies; const description = 'The default blueprint for ember-cli addons.'; module.exports = { description, appBlueprintName: 'app', filesToRemove: [ 'tests/dummy/app/styles/.gitkeep', 'tests/dummy/app/templates/.gitkeep', 'tests/dummy/app/views/.gitkeep', 'tests/dummy/public/.gitkeep', 'Brocfile.js', 'testem.json', ], updatePackageJson(content) { let contents = JSON.parse(content); contents.name = stringUtil.dasherize(this.options.entity.name); contents.description = this.description; delete contents.private; contents.scripts = contents.scripts || {}; contents.keywords = contents.keywords || []; contents.dependencies = contents.dependencies || {}; contents.devDependencies = contents.devDependencies || {}; // npm doesn't like it when we have something in both deps and devDeps // and dummy app still uses it when in deps contents.dependencies['ember-cli-babel'] = contents.devDependencies['ember-cli-babel']; delete contents.devDependencies['ember-cli-babel']; // Move ember-cli-htmlbars into the dependencies of the addon blueprint by default // to prevent error: // `Addon templates were detected but there are no template compilers registered for (addon-name)` contents.dependencies['ember-cli-htmlbars'] = contents.devDependencies['ember-cli-htmlbars']; delete contents.devDependencies['ember-cli-htmlbars']; // 95% of addons don't need ember-data or ember-fetch, make them opt-in instead delete contents.devDependencies['ember-data']; delete contents.devDependencies['ember-fetch']; // 100% of addons don't need ember-cli-app-version, make it opt-in instead delete contents.devDependencies['ember-cli-app-version']; // addons should test _without_ jquery by default delete contents.devDependencies['@ember/jquery']; if (contents.keywords.indexOf('ember-addon') === -1) { contents.keywords.push('ember-addon'); } Object.assign(contents.devDependencies, ADDITIONAL_DEV_DEPENDENCIES); // add `ember-compatibility` script in addons contents.scripts['test:ember-compatibility'] = 'ember try:each'; contents['ember-addon'] = contents['ember-addon'] || {}; contents['ember-addon'].configPath = 'tests/dummy/config'; return stringifyAndNormalize(sortPackageJson(contents)); }, buildFileInfo(intoDir, templateVariables, file) { let mappedPath = this.mapFile(file, templateVariables); let options = { action: 'write', outputBasePath: path.normalize(intoDir), outputPath: path.join(intoDir, mappedPath), displayPath: path.normalize(mappedPath), inputPath: this.srcPath(file), templateVariables, ui: this.ui, }; if (file in replacers) { options.replacer = replacers[file].bind(this); } return new FileInfo(options); }, beforeInstall() { const version = require('../../package.json').version; const prependEmoji = require('../../lib/utilities/prepend-emoji'); this.ui.writeLine(chalk.blue(`Ember CLI v${version}`)); this.ui.writeLine(''); this.ui.writeLine(prependEmoji('✨', `Creating a new Ember addon in ${chalk.yellow(process.cwd())}:`)); }, afterInstall() { let packagePath = path.join(this.path, 'files', 'package.json'); let bowerPath = path.join(this.path, 'files', 'bower.json'); [packagePath, bowerPath].forEach((filePath) => { fs.removeSync(filePath); }); }, locals(options) { let entity = { name: 'dummy' }; let rawName = entity.name; let name = stringUtil.dasherize(rawName); let namespace = stringUtil.classify(rawName); let addonEntity = options.entity; let addonRawName = addonEntity.name; let addonName = stringUtil.dasherize(addonRawName); let addonNamespace = stringUtil.classify(addonRawName); let hasOptions = options.welcome || options.yarn || options.ciProvider; let blueprintOptions = ''; if (hasOptions) { let indent = `\n `; let outdent = `\n `; blueprintOptions = indent + [ options.welcome && '"--welcome"', options.yarn && '"--yarn"', options.ciProvider && `"--ci-provider=${options.ciProvider}"`, ] .filter(Boolean) .join(',\n ') + outdent; } return { addonDirectory: directoryForPackageName(addonName), name, modulePrefix: name, namespace, addonName, addonNamespace, emberCLIVersion: require('../../package').version, year: date.getFullYear(), yarn: options.yarn, welcome: options.welcome, blueprint: 'addon', blueprintOptions, embroider: false, lang: options.lang, ciProvider: options.ciProvider, }; }, files(options) { let appFiles = this.lookupBlueprint(this.appBlueprintName).files(options); let addonFilesPath = this.filesPath(this.options); let ignoredCITemplate = this.options.ciProvider !== 'travis' ? '.travis.yml' : '.github'; let addonFiles = walkSync(addonFilesPath, { ignore: [ignoredCITemplate] }); return uniq(appFiles.concat(addonFiles)); }, mapFile() { let result = this._super.mapFile.apply(this, arguments); return this.fileMapper(result); }, fileMap: { '^app/.gitkeep': 'app/.gitkeep', '^app.*': 'tests/dummy/:path', '^config.*': 'tests/dummy/:path', '^public.*': 'tests/dummy/:path', '^addon-config/environment.js': 'config/environment.js', '^addon-config/ember-try.js': 'config/ember-try.js', '^npmignore': '.npmignore', }, fileMapper(path) { for (let pattern in this.fileMap) { if (new RegExp(pattern).test(path)) { return this.fileMap[pattern].replace(':path', path); } } return path; }, normalizeEntityName(entityName) { entityName = normalizeEntityName(entityName); if (this.project.isEmberCLIProject() && !this.project.isEmberCLIAddon()) { throw new SilentError('Generating an addon in an existing ember-cli project is not supported.'); } return entityName; }, srcPath(file) { let path = `${this.path}/files/${file}`; let superPath = `${this.lookupBlueprint(this.appBlueprintName).path}/files/${file}`; return fs.existsSync(path) ? path : superPath; }, };
JavaScript
0
@@ -2635,117 +2635,8 @@ %5D;%0A%0A - // addons should test _without_ jquery by default%0A delete contents.devDependencies%5B'@ember/jquery'%5D;%0A%0A
d33ac3413519840b7c7a9afae03bcd9539956aa0
fix for bind after ajax submit
src/method/ajax_submit.js
src/method/ajax_submit.js
AS.container.addBindListener(function(root) { $(root).find('form[data-ajax-form]').each(function() { var _this = this, $form = $(_this), options = $form.data('dataAjaxForm'), beforeSubmit, success ; if (!options) { options = { target: $form, replaceTarget: true }; } beforeSubmit = options.beforeSubmit; success = options.success; options.beforeSubmit = function() { if (typeof $.blockUI == 'function') { $.blockUI(); } if (beforeSubmit) { beforeSubmit.apply(this, arguments); } }; options.success = function(responseText, statusText, xhr, jqForm) { if (typeof $.unblockUI == 'function') { $.unblockUI(); } if (typeof success == 'function') { success.apply(this, arguments); } else if (typeof success == 'object') { AS.execute(jqForm, success); } }; setTimeout(function() { $form.ajaxForm(options); }, 100); }); }); AS.container.set('ajax.submit', function(options) { var $form, opt, $target, $block, blockOptions; AS.ajaxSubmit = { setDefaultButton: function(frm, btn) { var $frm = $(frm).first(), $btn = $(btn).first(); $frm.on('submit', function(e) { var $frm = $(this); if (!$frm.data('asSubmit')) { e.preventDefault(); e.stopPropagation(); setTimeout(function() { $btn.click(); }, 20); return false; } }) } }; if (options.form) { $form = $(options.form); } else { $form = options.$dom.closest('form'); } if (!$form || !$form.length) { throw new SyntaxError('No form for ajax.submit'); } $form = $form.first(); $form.data('asSubmit', true); opt = typeof 'options.options' == 'object' ? options.options : { target: $form, replaceTarget: true }; if (options.block) { if (options.block === true && typeof $.blockUI == 'function') { $.blockUI(options.blockOptions); } else if (options.block == '$target') { $block = $target; } else { $block = $(options.block); } if ($block && typeof $block.block == 'function') { $block.block(options.blockOptions) } } $target = $(opt.target); opt.success = function(response, statusText, jqXHR, jqForm) { AS.bind($target); if (typeof $form.unblock == 'function') { $form.unblock(); } if (options.block && typeof $.unblockUI == 'function') { $.unblockUI(); } if ($block && typeof $block.unblock == 'function') { $block.unblock(); } if (options.success) { AS.execute(options.dom, options.success, null, jqForm); } }; $form.ajaxSubmit(opt); });
JavaScript
0
@@ -205,16 +205,54 @@ Form'),%0A + $parent = $form.parent(),%0A @@ -825,32 +825,62 @@ xhr, jqForm) %7B%0A + AS.bind($parent);%0A if ( @@ -1381,16 +1381,25 @@ kOptions +, $parent ;%0A%0A A @@ -2795,16 +2795,48 @@ target); +%0A $parent = $target.parent(); %0A%0A op @@ -2912,21 +2912,21 @@ S.bind($ -t +p ar -g e +n t);%0A
258722cac4453a98c36fbca3a15b25517e1cc399
Use typeof in undefined check
bulbs/special_coverage/static/special_coverage/js/special-coverage-loader.js
bulbs/special_coverage/static/special_coverage/js/special-coverage-loader.js
module.exports = (function () { // eslint-disable-line no-unused-vars function isUndefined (suspect) { return suspect === undefined; // eslint-disable-line no-undefined } function requireArgument (value, message) { if (isUndefined(value)) { throw new Error(message); } } function assign (target, source) { Object.keys(source).forEach(function (key) { target[key] = source[key]; }); } function defaults (target, source) { Object.keys(source).forEach(function (key) { if (!target[key]) { target[key] = source[key]; } }); } function SpecialCoverageLoader (element, listElement, options) { requireArgument(element, 'new SpecialCoverageLoader(element, listElement, options): element is undefined'); requireArgument(listElement, 'new SpecialCoverageLoader(element, listElement, options): listElement is undefined'); requireArgument(element.dataset.total, 'new SpecialCoverageLoader(element, listElement, options): element has no data-total value'); requireArgument(element.dataset.perPage, 'new SpecialCoverageLoader(element, listElement, options): element has no data-per-page value'); options = options || {}; this.total = parseInt(element.dataset.total, 10); this.perPage = parseInt(element.dataset.perPage, 10); this.currentPage = 1; this.listElement = listElement; this.element = element; this.isLoading = false; this.defaultText = element.innerHTML; this.loadingText = 'Loading...'; defaults(options, { baseUrl: window.location.href, }); assign(this, options); element.addEventListener('click', function () { var url = this.buildUrl(this.currentPage, this.perPage, this.baseUrl); this.loadMore(url); }.bind(this)); } assign(SpecialCoverageLoader.prototype, { nextOffset: function (currentPage, perPage) { requireArgument(currentPage, 'SpecialCoverageLoader.nextOffset(currentPage, perPage): currentPage is undefined'); requireArgument(perPage, 'SpecialCoverageLoader.nextOffset(currentPage, perPage): perPage is undefined'); return currentPage * perPage; }, buildUrl: function (currentPage, perPage, baseUrl) { requireArgument(currentPage, 'SpecialCoverageLoader.buildUrl(currentPage, perPage, baseUrl, offset): currentPage is undefined'); requireArgument(perPage, 'SpecialCoverageLoader.buildUrl(currentPage, perPage, baseUrl, offset): perPage is undefined'); requireArgument(baseUrl, 'SpecialCoverageLoader.buildUrl(currentPage, perPage, baseUrl, offset): baseUrl is undefined'); var offset = this.nextOffset(currentPage, perPage); return [baseUrl, 'more', offset].join('/'); }, loadMore: function (url) { if (this.isLoading) { return; } requireArgument(url, 'SpecialCoverageLoader.loadMore(url): url is undefined'); this.isLoading = true; this.element.innerHTML = this.loadingText; $.ajax({ url: url, type: 'get', dataType: 'html', }) .done(this.handleLoadMoreSuccess.bind(this)) .fail(this.handleLoadMoreFailure.bind(this)); }, toggleLoadingState: function (loadingState, element) { requireArgument(loadingState, 'SpecialCoverageLoader.toggleLoadingState(loadingState, element): loadingState is undefined'); requireArgument(element, 'SpecialCoverageLoader.toggleLoadingState(loadingState, element): element is undefined'); this.isLoading = !loadingState; element.innerHTML = this.isLoading ? this.loadingText : this.defaultText; }, handleLoadMoreSuccess: function (response) { this.toggleLoadingState(this.isLoading, this.element); requireArgument(response, 'SpecialCoverageLoader.handleLoadMoreSuccess(response): response is undefined'); response = response.trim(); if (response) { this.currentPage += 1; this.listElement.innerHTML = this.listElement.innerHTML + response; } this.setButtonVisibility(response); }, handleLoadMoreFailure: function (response) { this.toggleLoadingState(this.isLoading, this.element); requireArgument(response, 'SpecialCoverageLoader.handleLoadMoreFailure(response): response id undefined'); var message = [ 'SpecialCoverageLoader.loadMore("', this.buildUrl(this.currentPage, this.perPage, this.baseUrl), '"): server responded with "', response.status, ' ', response.statusText, '"', ].join(''); console.log(message); }, hideElement: function () { this.element.style.display = 'none'; }, isLastPage: function (total, listElement) { requireArgument(total, 'SpecialCoverageLoader.isLastPage(total, listElement): total is undefined'); requireArgument(listElement, 'SpecialCoverageLoader.isLastPage(total, listElement): listElement is undefined'); return total === listElement.children.length; }, setButtonVisibility: function (response) { requireArgument(response, 'SpecialCoverageLoader.setButtonVisibility(response): response is undefined'); if (!response || this.isLastPage(this.total, this.listElement)) { this.hideElement(); } }, }); return SpecialCoverageLoader; })();
JavaScript
0
@@ -113,20 +113,29 @@ urn +typeof( suspect +) === +' unde @@ -143,45 +143,10 @@ ined +' ; - // eslint-disable-line no-undefined %0A %7D
692a8551b35d9b624bcdf0ec04e8639c2e911695
Correct field name
src/model/transactions.js
src/model/transactions.js
import { Schema } from "mongoose"; import { connectionAPI, connectionDefault } from "../config"; // Request Schema definition const RequestDef = { host: String, port: String, path: String, headers: Object, querystring: String, body: String, method: String, timestamp: { type: Date, required: true } }; // Response Schema definition const ResponseDef = { status: Number, headers: Object, body: String, timestamp: Date }; const ErrorDetailsDef = { message: String, stack: String }; // OrchestrationMetadata Schema const OrchestrationMetadataDef = { name: { type: String, required: true }, group: String, request: { type: RequestDef, required: false }, // this is needed to prevent Validation error, see https://github.com/jembi/openhim-console/issues/356#issuecomment-188708443 response: ResponseDef, error: ErrorDetailsDef }; // Route Schema const RouteMetadataDef = { name: { type: String, required: true }, request: RequestDef, response: ResponseDef, orchestrations: [OrchestrationMetadataDef], properties: Object, error: ErrorDetailsDef }; // Trasnaction schema const TransactionSchema = new Schema({ clientID: Schema.Types.ObjectId, clientIP: String, parentID: { type: Schema.Types.ObjectId, index: true }, childIDs: [Schema.Types.ObjectId], channelID: { type: Schema.Types.ObjectId }, request: RequestDef, response: ResponseDef, routes: [RouteMetadataDef], orchestrations: [OrchestrationMetadataDef], properties: Object, canRerun: { type: Boolean, default: true }, autoRetry: { type: Boolean, default: false }, // auto rerun this transaction (e.g. if error'd) autoRetryAttempt: Number, wasRerun: { type: Boolean, default: false }, error: ErrorDetailsDef, status: { type: String, required: true, enum: ["Processing", "Failed", "Completed", "Successful", "Completed with error(s)"] } }); TransactionSchema.index("request.timestamp"); TransactionSchema.index({channelID: 1, "request.timestamp": -1}); TransactionSchema.index({status: 1, "request.timestamp": -1}); TransactionSchema.index({childId: 1, "request.timestamp": -1}) // Compile schema into Model export const TransactionModelAPI = connectionAPI.model("Transaction", TransactionSchema); export const TransactionModel = connectionDefault.model("Transaction", TransactionSchema);
JavaScript
0.000201
@@ -2146,17 +2146,18 @@ (%7BchildI -d +Ds : 1, %22re
65013f9cdb18f9a78bcf9bed8dc4e77ca9d5fed3
fix uuid
app/assets/javascripts/scripts/plugins/workspace.data/mvc/workspace.data.view.js
app/assets/javascripts/scripts/plugins/workspace.data/mvc/workspace.data.view.js
/** * Created with JetBrains RubyMine. * User: teamco * Date: 11/24/12 * Time: 10:13 PM * To change this template use File | Settings | File Templates. */ define( [ 'modules/View', 'plugins/preferences/preferences', 'element/header.element', 'element/footer.element', 'plugins/workspace.data/element/workspace.data.content.element', 'plugins/workspace.data/element/workspace.data.preferences.element', 'plugins/workspace.data/element/workspace.data.add.page.element', 'plugins/workspace.data/element/workspace.data.element' ], /** * Define WorkspaceDataView * @param {BaseView} BaseView * @param {BasePreferences} BasePreferencesElement * @param {BaseView} Header * @param {BaseView} Footer * @param {WorkspaceDataContentElement} WorkspaceDataContentElement * @param {WorkspaceDataPreferencesElement} WorkspaceDataPreferencesElement * @param {WorkspaceDataAddPageElement} WorkspaceDataAddPageElement * @param {WorkspaceDataElement} WorkspaceDataElement * @returns {*} */ function defineWorkspaceDataView(BaseView, BasePreferencesElement, Header, Footer, WorkspaceDataContentElement, WorkspaceDataPreferencesElement, WorkspaceDataAddPageElement, WorkspaceDataElement) { /** * Define view * @class WorkspaceDataView * @extends BaseView * @extends BasePreferencesElement * @constructor */ var WorkspaceDataView = function WorkspaceDataView() { }; return WorkspaceDataView.extend( 'WorkspaceDataView', { /** * Render WorkspaceData * @memberOf WorkspaceDataView * @returns {boolean} */ renderWorkspaceData: function renderWorkspaceData() { if (this.isCached('$workspacedata', WorkspaceDataElement)) { return false; } /** * Define WorkspaceData element * @type {WorkspaceDataElement} */ this.elements.$workspacedata = new WorkspaceDataElement(this, { id: this.createUUID(), $container: this.elements.$container.$ }); }, /** * Render workspace.data content * @memberOf WorkspaceDataView * @param data * @returns {boolean} */ renderContent: function renderContent(data) { /** * Define content * @type {{}} */ this.elements.items = {}; this.elements.$workspacedata.empty(); this.renderCreatePage(); this.renderFilter( this.updateFooterContent.bind(this) ); /** * Get current page * @type {Page} */ var page = this.controller.getPage(); var i = 0, l = data.length, show, current; for (i; i < l; i++) { if (!data[i]) { this.scope.logger.warn('Undefined item', data, i); return false; } /** * Show in tabs * @type {string} */ show = this.controller.checkShowInTabs(data[i]) ? '' : ' hide'; /** * Define current page style * @type {string} */ current = page === data[i] ? ' current' : ''; /** * Render item * @type {WorkspaceDataContentElement} */ var $item = new WorkspaceDataContentElement(this, { style: 'page content' + current + show, id: [ data[i].model.getConfig('uuid'), 'workspace-data-view' ].join('-'), $container: this.elements.$workspacedata.$, data: data[i], counter: i + 1 }); this.elements.items[$item.id] = $item; } this.elements.$workspacedata.scrollCover( this.elements.$container.$ ); this.elements.$filter.updateData({ items: this.elements.items, focusOn: 'input' }); this.updateFooterContent(); }, /** * Update footer content * @memberOf WorkspaceDataView */ updateFooterContent: function updateFooterContent() { this.renderFooter(Footer, this.elements.$workspacedata); }, /** * Render create new page * @memberOf WorkspaceDataView */ renderCreatePage: function renderCreatePage() { /** * Render add new pages * @type {WorkspaceDataAddPageElement} */ this.elements.$addPage = new WorkspaceDataAddPageElement(this, { style: 'add-page', $container: this.elements.$workspacedata.$, events: { click: ['prepareCreatePage'] } }); }, /** * Render create page wizard * @memberOf WorkspaceDataView * @param {{ * workspace: Workspace, * style: string, * [type]: string, * title: string, * text: string, * $html * }} opts */ renderCreatePageWizard: function renderCreatePageWizard(opts) { /** * Define buttons * @type {{ * approve: {text: string, events: {click: string}}, * reject: {text: string, events: {click: string[]}} * }} */ var buttons = { approve: { text: 'OK', type: 'success', events: { click: 'approveCreatePage' } }, reject: { text: 'Cancel', events: { click: ['rejectModalEvent'] } } }; this.modalDialog({ style: opts.style, type: opts.type || 'info', title: opts.title, text: opts.workspace.model.getUUID(), html: opts.$html, cover: true, buttons: buttons }); }, /** * Show preferences * @memberOf WorkspaceDataView * @param config * @param {boolean} current */ showPreferences: function showPreferences(config, current) { this.openPreferences({ config: config, current: current, $html: this.controller.definePreferences(config.uuid).$, style: 'workspace-data-prefs preferences', title: 'Page preferences', buttons: { destroyPageWidgets: { text: 'Destroy widgets', type: 'danger', events: { click: 'destroyPageWidgets' } } } }); }, /** * Render Prefs * @memberOf WorkspaceDataView * @param {Page} page * @returns {WorkspaceDataPreferencesElement} */ renderPreferences: function renderPreferences(page) { /** * Define WorkspaceData Preferences Element * @type {WorkspaceDataPreferencesElement} */ this.elements.$preferences = new WorkspaceDataPreferencesElement(this, { data: page.model.getConfig('preferences'), page: page }); return this.elements.$preferences; }, /** * Render workspace.data * @memberOf WorkspaceDataView */ render: function render() { this.scope.observer.publish( this.scope.eventmanager.eventList.successRendered, this.renderWorkspaceData.bind(this) ); } }, BaseView.prototype, BasePreferencesElement.prototype ) } );
JavaScript
0.013232
@@ -4344,24 +4344,26 @@ +uu id: %5B%0A
8dfd371c6f4378530c89a66e623f1429b3ed04c3
Build pdf sandbox.
build/build.js
build/build.js
/* * Spreed WebRTC. * Copyright (C) 2013-2014 struktur AG * * This file is part of Spreed WebRTC. * * 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/>. * */ /*jshint -W030 */ ({ logLevel: 2, baseUrl: '../static/js', mainConfigFile: '../static/js/main.js', optimize: 'uglify2', uglify2: { output: { beautify: false }, compress: { sequences: true, global_defs: { DEBUG: false } }, warnings: false, mangle: true }, wrap: false, useStrict: false, dir: './out', skipDirOptimize: true, removeCombined: true, modules: [ { name: 'main', exclude: [ 'base' ] }, { name: 'base', include: [ 'pdf.compatibility' ] }, { name: 'app', exclude: [ 'main', 'base' ], inlineText: true, }, { name: 'pdf', dir: './out/libs/pdf', exclude: [ 'base' ] }, { name: 'pdf.worker', dir: './out/libs/pdf', override: { skipModuleInsertion: true } }, { name: 'sandboxes/youtube', dir: './out/sandboxes', override: { skipModuleInsertion: true } } ] })
JavaScript
0
@@ -1685,16 +1685,128 @@ ue%0A%09%09%09%7D%0A +%09%09%7D,%0A%09%09%7B%0A%09%09%09name: 'sandboxes/pdf',%0A%09%09%09dir: './out/sandboxes',%0A%09%09%09override: %7B%0A%09%09%09%09skipModuleInsertion: true%0A%09%09%09%7D%0A %09%09%7D%0A%09%5D%0A%7D
dc04871bbe659d91fb838fe29c4eb1d40e3e067c
allow images from the headnode
lg_sv/webapps/client/js/pano.js
lg_sv/webapps/client/js/pano.js
var panoClient; function panoRunner() { init(); animate(0); } function getConfig(key, def) { key = key.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + key + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? def : decodeURIComponent(results[1].replace(/\+/g, " ")); } function init() { var container, vertFov, aspectRatio; var yawRads, pitchRads, rollRads, isLeader; var ros = new ROSLIB.Ros({ url: 'ws://localhost:9090' }); container = document.getElementById( 'container' ); vertFov = getConfig('fov', 75) * 1.0; aspectRatio = window.innerWidth / window.innerHeight; yawRads = aspectRatio * toRad(vertFov * getConfig('yawOffset', 0)); pitchRads = toRad(getConfig('pitchOffset', 0) * 1.0); rollRads = toRad(getConfig('rollOffset', 0) * 1.0); isLeader = getConfig('leader', 'false').toLowerCase() == "true"; panoClient = new PanoClient(ros, vertFov, aspectRatio, yawRads, pitchRads, rollRads, isLeader); container.appendChild(panoClient.getDomElement()); window.addEventListener('resize', onWindowResize, false); } function onWindowResize() { panoClient.windowResize(); } function animate(nowMsec) { requestAnimationFrame(animate); panoClient.update(nowMsec); } function toRad(deg) { return THREE.Math.degToRad(deg); } window.onload = panoRunner;
JavaScript
0
@@ -34,16 +34,53 @@ ner() %7B%0A + THREE.ImageUtils.crossOrigin = '';%0A init()
6f47a30b4850f53253cf1457ed4cdb79f62ddada
Make general updates to build script.
build/build.js
build/build.js
#!/usr/bin/env node const hyperquest = require('hyperzip')(require('hyperdirect')) , bl = require('bl') , fs = require('fs') , path = require('path') , cheerio = require('cheerio') , files = require('./files') , testReplace = require('./test-replacements') , docReplace = require('./doc-replacements') , srcurlpfx = `https://raw.githubusercontent.com/nodejs/node/v${process.argv[2]}/` , libsrcurl = srcurlpfx + 'lib/' , testsrcurl = srcurlpfx + 'test/parallel/' , testlisturl = `https://github.com/nodejs/node/tree/v${process.argv[2]}/test/parallel` , libourroot = path.join(__dirname, '../lib/') , testourroot = path.join(__dirname, '../test/parallel/') , docurlpfx = `https://raw.githubusercontent.com/nodejs/node/v${process.argv[2]}/doc/api/` , docourroot = path.join(__dirname, '../doc') if (!/\d\.\d\.\d+/.test(process.argv[2])) { console.error('Usage: build.js xx.yy.zz') return process.exit(1); } function processFile (url, out, replacements) { hyperquest(url).pipe(bl(function (err, data) { if (err) throw err data = data.toString() replacements.forEach(function (replacement) { data = data.replace.apply(data, replacement) }) fs.writeFile(out, data, 'utf8', function (err) { if (err) throw err console.log('Wrote', out) }) })) } function processLibFile (file) { var replacements = files[file] , url = libsrcurl + file , out = path.join(libourroot, file) processFile(url, out, replacements) } function processTestFile (file) { var replacements = testReplace.all , url = testsrcurl + file , out = path.join(testourroot, file) if (testReplace[file]) replacements = replacements.concat(testReplace[file]) processFile(url, out, replacements) } if (!/\d\.\d\.\d+/.test(process.argv[2])) { console.log('Usage: build.js <node version>') return process.exit(-1) } //-------------------------------------------------------------------- // Grab & process files in ../lib/ Object.keys(files).forEach(processLibFile) //-------------------------------------------------------------------- // Discover, grab and process all test-stream* files on nodejs/node hyperquest(testlisturl).pipe(bl(function (err, data) { if (err) throw err var $ = cheerio.load(data.toString()) $('table.files .js-directory-link').each(function () { var file = $(this).text() if (/^test-stream/.test(file) && !/-wrap\.js$/.test(file)) processTestFile(file) }) })) processFile(docurlpfx + 'stream.markdown', path.join(docourroot, 'stream.markdown'), docReplace) //-------------------------------------------------------------------- // Grab the nodejs/node test/common.js processFile( testsrcurl.replace(/parallel\/$/, 'common.js') , path.join(testourroot, '../common.js') , testReplace['common.js'] )
JavaScript
0
@@ -221,16 +221,130 @@ eerio')%0A + , encoding = 'utf8'%0A , nodeVersion = process.argv%5B2%5D%0A , nodeVersionRegexString = '%5C%5Cd+%5C%5C.%5C%5Cd+%5C%5C.%5C%5Cd+' %0A , f @@ -547,31 +547,27 @@ node/v$%7B -process.argv%5B2%5D +nodeVersion %7D/%60%0A @@ -710,31 +710,27 @@ tree/v$%7B -process.argv%5B2%5D +nodeVersion %7D/test/p @@ -922,31 +922,27 @@ node/v$%7B -process.argv%5B2%5D +nodeVersion %7D/doc/ap @@ -1007,42 +1007,67 @@ f (! -/%5Cd%5C.%5Cd%5C.%5Cd+/.test(process.argv%5B2%5D +RegExp('%5E' + nodeVersionRegexString + '$').test(nodeVersion )) %7B @@ -1249,22 +1249,16 @@ if (err) -%0A throw e @@ -1425,22 +1425,24 @@ , data, -'utf8' +encoding , functi @@ -1470,16 +1470,8 @@ err) -%0A thr @@ -2012,131 +2012,8 @@ %0A%7D%0A%0A -%0Aif (!/%5Cd%5C.%5Cd%5C.%5Cd+/.test(process.argv%5B2%5D)) %7B%0A console.log('Usage: build.js %3Cnode version%3E')%0A return process.exit(-1)%0A%7D%0A%0A%0A //--
599681079eefaa888425117038961c0b4a1f284c
corrected the address
YamahaControlInterface.js
YamahaControlInterface.js
{ "name": "refreshButton", "type": "Button", "x": 0, "y": .85, "width": .15, "height": .15, "mode": "momentary", "color": "#000000", "stroke": "#aaaaaa", "ontouchstart": "interfaceManager.refreshInterface()", }, { "name" : "yamahaPower", "type" : "Button", "x" : 0, "y" : 0, "width" : .25, "height" : .25, "mode" : "momentary", "label" : "Power", "min":-1, "max":1, "address" : "yamaha", }
JavaScript
0.999998
@@ -358,19 +358,214 @@ in%22: -- +0, %22max%22: 1, +%0A %22 -max%22:1 +address%22 : %22/yamaha%22,%0A%7D,%0A%0A%7B%0A %22name%22 : %22yamahaVolumeUp%22,%0A %22type%22 : %22Button%22,%0A %22x%22 : 0, %22y%22 : .30,%0A %22width%22 : .25, %22height%22 : .25,%0A %22mode%22 : %22momentary%22,%0A %22label%22 : %22VolumeUp%22,%0A %22min%22:0, %22max%22:2 ,%0A %22 @@ -572,22 +572,23 @@ address%22 : %22 +/ yamaha%22,%0A%7D @@ -567,28 +567,29 @@ 2,%0A %22address%22 : %22/yamaha%22,%0A%7D +,
e855175a5301caf55e3b5d87269e71fd529e0099
Fix build paths for v2 and v3 folders.
build/build.js
build/build.js
/* eslint-env node */ const fs = require('fs'); const zlib = require('zlib'); const rollup = require('rollup'); const uglify = require('uglify-js'); const babel = require('rollup-plugin-babel'); const replace = require('rollup-plugin-replace'); const {name, version, homepage} = require('../package.json'); const banner = `/*!\n * ${name} v${version}\n * ${homepage}\n * Released under the MIT License.\n */\n`; // Dirs const dirs = [ 'dist', 'dist/drivers', 'dist/drivers/auth', 'dist/drivers/http', 'dist/drivers/oauth2', 'dist/drivers/router', 'dist/v2', 'dist/v3' ]; dirs.forEach((dir) => { if (!fs.existsSync(dir)){ fs.mkdirSync(dir); } }); // Files const files = [{ input: 'src/v2.js', name: 'vue-auth', }, { input: 'src/v3.js', name: 'vue-auth', }, { input: 'src/drivers/auth/basic.js', name: 'drivers/auth/basic' }, { input: 'src/drivers/auth/bearer.js', name: 'drivers/auth/bearer' }, { input: 'src/drivers/auth/devise.js', name: 'drivers/auth/devise' }, { input: 'src/drivers/http/axios.1.x.js', name: 'drivers/http/axios.1.x' }, { input: 'src/drivers/http/vue-resource.1.x.js', name: 'drivers/http/vue-resource.1.x' }, { input: 'src/drivers/oauth2/facebook.js', name: 'drivers/oauth2/facebook' }, { input: 'src/drivers/oauth2/google.js', name: 'drivers/oauth2/google' }, { input: 'src/drivers/router/vue-router.2.x.js', name: 'drivers/router/vue-router.2.x' }]; files.forEach((file) => { rollup.rollup({ input: file.input, plugins: [babel(), replace({__VERSION__: version})] }) .then(bundle => bundle.generate({ banner, format: 'umd', name: 'VueAuth' }).then(({code}) => write(`dist/${file.name}.js`, code, bundle)) ) .then(bundle => write(`dist/${file.name}.min.js`, banner + '\n' + uglify.minify(read(`dist/${file.name}.js`)).code, bundle, true) ) .then(bundle => bundle.generate({ banner, format: 'es', }).then(({code}) => write(`dist/${file.name}.esm.js`, code, bundle)) ) .then(bundle => bundle.generate({ banner, format: 'cjs' }).then(({code}) => write(`dist/${file.name}.common.js`, code, bundle)) ) .catch(logError); }); function read(path) { return fs.readFileSync(path, 'utf8'); } function write(dest, code, bundle, zip) { return new Promise((resolve, reject) => { fs.writeFile(dest, code, err => { if (err) return reject(err); if (zip) { zlib.gzip(code, (err, zipped) => { if (err) return reject(err); console.log(blue(dest) + ' ' + getSize(code) + ' (' + getSize(zipped) + ' gzipped)'); }); } else { console.log(blue(dest) + ' ' + getSize(code)); } resolve(bundle); }); }); } function getSize(code) { return (code.length / 1024).toFixed(2) + 'kb'; } function logError(e) { console.log(e); } function blue(str) { return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m'; }
JavaScript
0
@@ -746,32 +746,35 @@ js',%0A name: ' +v2/ vue-auth',%0A%7D, %7B%0A @@ -808,16 +808,19 @@ name: ' +v3/ vue-auth
548d402f91439a63499cedd7e763952eccbde639
Remove uneeded args.
assets/js/components/dashboard-sharing/DashboardSharingSettingsButton.stories.js
assets/js/components/dashboard-sharing/DashboardSharingSettingsButton.stories.js
/** * DashboardSharingSettingsButton Component Stories. * * Site Kit by Google, Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import DashboardSharingSettingsButton from './DashboardSharingSettingsButton'; const Template = ( args ) => <DashboardSharingSettingsButton { ...args } />; export const DefaultDashboardSharingSettingsButton = Template.bind( {} ); DefaultDashboardSharingSettingsButton.storyName = 'Default'; export default { title: 'Components/DashboardSharingSettingsButton', component: DashboardSharingSettingsButton, };
JavaScript
0
@@ -801,14 +801,8 @@ = ( - args ) =%3E @@ -837,20 +837,8 @@ tton - %7B ...args %7D /%3E;
2a1cdfcc0b4a762a2d0b5f12b55addeb0c44a5e3
Use same ticks for search-console graph.
assets/js/modules/search-console/components/module/ModuleOverviewWidget/Stats.js
assets/js/modules/search-console/components/module/ModuleOverviewWidget/Stats.js
/** * Stats component for ModuleOverviewWidget. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; /** * WordPress dependencies */ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ import { getSiteStatsDataForGoogleChart } from '../../../util'; import { Grid, Row, Cell } from '../../../../../material-components'; import GoogleChart from '../../../../../components/GoogleChart'; import { partitionReport } from '../../../../../util/partition-report'; const Stats = ( { data, metrics, selectedStats, dateRangeLength } ) => { const options = { chart: { title: __( 'Search Traffic Summary', 'google-site-kit' ), }, curveType: 'function', height: 270, width: '100%', chartArea: { height: '80%', width: '100%', left: 60, }, legend: { position: 'top', textStyle: { color: '#616161', fontSize: 12, }, }, hAxis: { format: 'M/d/yy', gridlines: { color: '#fff', }, textStyle: { color: '#616161', fontSize: 12, }, }, vAxis: { direction: selectedStats === 3 ? -1 : 1, gridlines: { color: '#eee', }, minorGridlines: { color: '#eee', }, textStyle: { color: '#616161', fontSize: 12, }, titleTextStyle: { color: '#616161', fontSize: 12, italic: false, }, viewWindow: { min: 0, }, }, series: { 0: { color: metrics[ selectedStats ].color, targetAxisIndex: 0, }, 1: { color: metrics[ selectedStats ].color, targetAxisIndex: 0, lineDashStyle: [ 3, 3 ], lineWidth: 1, }, }, tooltip: { isHtml: true, // eslint-disable-line sitekit/acronym-case trigger: 'both', }, focusTarget: 'category', crosshair: { color: 'gray', opacity: 0.1, orientation: 'vertical', trigger: 'both', }, }; const { compareRange, currentRange } = partitionReport( data, { dateRangeLength } ); const googleChartData = getSiteStatsDataForGoogleChart( currentRange, compareRange, metrics[ selectedStats ].label, metrics[ selectedStats ].metric, dateRangeLength, ); return ( <Grid className="googlesitekit-search-console-site-stats"> <Row> <Cell size={ 12 }> <GoogleChart chartType="LineChart" data={ googleChartData } loadingHeight="270px" loadingWidth="100%" options={ options } /> </Cell> </Row> </Grid> ); }; Stats.propTypes = { data: PropTypes.arrayOf( PropTypes.object ).isRequired, dateRangeLength: PropTypes.number.isRequired, metrics: PropTypes.arrayOf( PropTypes.object ).isRequired, selectedStats: PropTypes.number.isRequired, }; export default Stats;
JavaScript
0
@@ -1179,16 +1179,356 @@ ) =%3E %7B%0A +%09const %7B compareRange, currentRange %7D = partitionReport( data, %7B dateRangeLength %7D );%0A%09const googleChartData = getSiteStatsDataForGoogleChart(%0A%09%09currentRange,%0A%09%09compareRange,%0A%09%09metrics%5B selectedStats %5D.label,%0A%09%09metrics%5B selectedStats %5D.metric,%0A%09%09dateRangeLength,%0A%09);%0A%0A%09const dates = googleChartData.slice( 1 ).map( ( %5B date %5D ) =%3E date );%0A%0A %09const o @@ -1538,16 +1538,16 @@ ons = %7B%0A - %09%09chart: @@ -1971,24 +1971,41 @@ : 12,%0A%09%09%09%7D,%0A +%09%09%09ticks: dates,%0A %09%09%7D,%0A%09%09vAxis @@ -2786,281 +2786,13 @@ %09%7D,%0A + %09%7D;%0A%0A -%09const %7B compareRange, currentRange %7D = partitionReport( data, %7B dateRangeLength %7D );%0A%09const googleChartData = getSiteStatsDataForGoogleChart(%0A%09%09currentRange,%0A%09%09compareRange,%0A%09%09metrics%5B selectedStats %5D.label,%0A%09%09metrics%5B selectedStats %5D.metric,%0A%09%09dateRangeLength,%0A%09);%0A%0A %09ret
82d56bade62d79471b16abf3a327d8607bd38a4d
Wrap a method that is guaranteed to be there.
lib/JooseX/DOMBinding/JQuery.js
lib/JooseX/DOMBinding/JQuery.js
Module("JooseX.DOMBinding", function (module) { // Role for meta classes that implement bindings between Joose objects and DOM elements Role("JQueryMetaRole", { requires: ["getAttribute"], // and requires attribute $ that includes a jquery object methods: { handlePropbind: function (props) { var me = this; var names = []; Joose.O.each(props, function (bindingProps, name) { var attr = me.getAttribute(name); if(!attr) { throw new Error("Cant find attribute "+name+" for binding") } names.push(name) var props = { selector: null, accessor: "val", args: [], notifyOn: [], }; Joose.O.extend(props, bindingProps); var selector = props.selector; var accessor = props.accessor; var args = props.args; var notifyOn = props.notifyOn; var getterName = attr.getterName(); var setterName = attr.setterName(); // Update from bound element before get me.wrapMethod(getterName, "before", function () { var n = name; var $ = this.$; if(selector) { $ = this.$.find(selector) } var value = $[accessor].apply($, args) this[name] = value }) // Update bound element after set me.wrapMethod(setterName, "after", function beforeSet () { var value = this[name] var $ = this.$; if(selector) { $ = this.$.find(selector) } var a = []; for(var i = 0; i < args.length; i++) { a.push(args[i]) } a.push(value) $[accessor].apply($, a) }) me.wrapMethod("show", "after", function afterGet () { var me = this; for(var i = 0; i < notifyOn.length; i++) { var eventName = notifyOn[i]; var target = this.$; if(selector) { target = target.find(selector) } target.bind(eventName, function (e) { me.notify(eventName, this, e) }) } }) }); me.addMethod("redraw", function redraw () { for(var i = 0; i < names.length; i++) { var name = names[i]; var setter = this.meta.getAttribute(name).setterName(); var value = this[name]; this[setter](value) } }) } } }) Role("JQuery", { metaRoles: [module.JQueryMetaRole], methods: { // puts object onto page. Override to place somewhere else draw: function () { this.$ = this.create(); this.destination().append(this.$); }, destination: function () { return jQuery(document.body) }, notify: function (eventName, target, eventObject) { } }, after: { initialize: function () { this.draw() } } }) })
JavaScript
0.999999
@@ -1507,32 +1507,42 @@ fore%22, function +beforeGet () %7B%0A @@ -1996,22 +1996,21 @@ unction -before +after Set () %7B @@ -2554,11 +2554,11 @@ od(%22 -sho +dra w%22,
66a24096121e44ac10a9a11567e6e067749c33eb
build file update
build/index.js
build/index.js
(function (global, factory) { if (typeof define === "function" && define.amd) { define(['module'], factory); } else if (typeof exports !== "undefined") { factory(module); } else { var mod = { exports: {} }; factory(mod); global.index = mod.exports; } })(this, function (module) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /** * Get network connection details of device in browser using Expanded Network API. * Currently supported in latest version of chrome. * * More info - https://wicg.github.io/netinfo/ * * Author: Ganapati V S(@ganapativs) * */ var isNetInfoAPISupported = !!(navigator && navigator.connection); var ignoreProperties = ['onchange', 'addEventListener', 'removeEventListener', 'dispatchEvent']; var netInfo = {}; var listeners = []; if (isNetInfoAPISupported) { var _updateNetInfo = function _updateNetInfo(e) { var info = navigator.connection; netInfo = {}; for (var p in info) { // Not checking for hasOwnProperty as it always returns false // for `NetworkInformation` instance if (!ignoreProperties.includes(p)) { netInfo[p] = info[p]; } } // Prevent calling callback on initial update, // only call when there is change event if (e) { listeners.map(function (cb) { return cb(netInfo); }); } return netInfo; }; _updateNetInfo(); navigator.connection.addEventListener('change', _updateNetInfo); } /** * Remove listener * * @function * @param {Function} cb Listener callback to be removed * * @returns {Boolean} Listener remove status */ var removeListener = function removeListener(cb) { var matched = false; listeners = listeners.filter(function (l) { if (l === cb) { matched = true; return false; } return true; }); return matched; }; /** * Store listener * * @function * @param {Function} cb Listener callback to be added * * @returns {Boolean} Listener attach status */ var addListener = function addListener(cb) { if (typeof cb === 'function') { var hasSameListener = listeners.some(function (l) { return l === cb; }); if (!hasSameListener) { listeners.push(cb); } return true; } return false; }; /** * Get current net info * * @function * @returns {Object} Net info object */ var getNetInfo = function getNetInfo() { return _extends({}, netInfo, { addListener: addListener, removeListener: removeListener }); }; module.exports = getNetInfo; });
JavaScript
0.000001
@@ -2847,17 +2847,16 @@ ion') %7B%0A -%0A
e60485352df13a58147df70641d07fa04bf0ae50
add error report
buildServer.js
buildServer.js
const Koa = require('koa'); const cors = require('koa2-cors'); const kjson = require('koa-json') const router = require('koa-router')(); const bodyParser = require('koa-bodyparser'); const JWT = require('jsonwebtoken'); const IO = require('socket.io'); const path = require('path'); const fs = require('fs'); const os = require('os'); const crypto = require('crypto'); const queue = require('queue'); const fsex=require("fs-extra"); const http=require('http'); const log=require('npmlog'); const Git = require('simple-git/promise')(); const uuid=require("uuid/v4"); const exec = require('child-process-promise').exec; var q = queue(); q.autostart=true; q.concurrency=1; q.start(); q.current=false; q.on("start",function(job){ q.current=job; }); q.on("success",function(){ q.current=false; }); q.on("error",function(){ q.current=false; }); var finishedJobs=[]; const app = new Koa(); app.use(cors()); app.use(kjson()); app.use(bodyParser()); const server = http.Server(app.callback()); const io = IO(server); var port=process.env.PORT || 5656; server.listen(port, () => { log.info("WEB",`httpd started at ${port}`); }) router.post('/api/build', async (ctx, next) => { var jwt=ctx.request.body.data; try { var decoded = JWT.verify(jwt, 'gxicon_toki_key'); } catch(err) { ctx.response.body = { code:401 }; return next(); } var localId=addJob({ jobId:ctx.request.body.id, config:decoded.data }); ctx.response.body = { code:0, data:{ localId:localId, status:q.current._gx_info.localId==localId?"current":"pending", queueLength:q.jobs.length } } }); router.get('/api/queue', async (ctx, next) => { var infos=[] for(var i of q.jobs){ infos.push(i._gx_info); } ctx.response.body = {code:0,data:{ status:q.jobs.length==0?"idle":"busy", queue:infos.reverse(), current:q.current._gx_info, finished:[].concat(finishedJobs).reverse().slice(0,10) }}; }); router.get('/', async (ctx, next) => { ctx.response.body = 'GxIcon BuildServer [beta]<br>Current pending jobs:<br>'; }); app.use(router.routes()); function addJob(data){ return (function(){ data.localId=uuid(); data.queueTime=new Date().getTime(); var f=async function () { var data=arguments.callee._gx_info; data.execTime=new Date().getTime(); await resetEnv(); await fxex.writeFile("_autoMake.json",JSON.stringify(data.config, null, 4)); await sleep(10000); data.endTime=new Date().getTime(); finishedJobs.push(data); log.info("JOB","END",{localId:data.localId,jobId:data.jobId}); }; f._gx_info=data; log.info("JOB","ADD",{localId:data.localId,jobId:data.jobId}); q.push(f); return data.localId; })(data); } async function sleep(usec){ return new Promise(function(resolve){ setTimeout(resolve,usec); }); } async function resetEnv(stdout){ var fetch=exec('git fetch'); if(stdout)fetch.childProcess.stdout.pipe(stdout); await fetch; var clean=exec('git clean -xdf -e node_modules -e build/ -e .gradle'); if(stdout)clean.childProcess.stdout.pipe(stdout); await clean; var reset=exec('git reset --hard HEAD'); if(stdout)reset.childProcess.stdout.pipe(stdout); await reset; }
JavaScript
0.000001
@@ -809,34 +809,63 @@ error%22,function( -)%7B +err)%7B%0A log.error(%22JOB%22,err); %0A q.current=f
24b620f987513ef8c6cfda2ee220927011811156
Make sure that we can play YouTube history items
youtube/model.js
youtube/model.js
'use strict'; const YT = require('./client'); const LocalModel = require('../local/models/playlists'); module.exports = class YouTubeModel { static history() { if (Cache.youtube.history) return Cache.youtube.history; return LocalModel.loadPlaylist(Paths.youtube_history).then((history) => { Cache.add('youtube', 'history', history); return history; }); } static addToHistory(record) { return this.history().then((history) => { var last_ten = history.items.slice(0, 9); if (last_ten.map(i => i.id).includes(record.id)) return; history.items.unshift(record); return LocalModel.savePlaylist(history); }); } static playlists(token) { return this.fetch('playlists', token); } static likes(token) { return this.fetch('likes', token); } static playlistItems(id) { return this.fetch('items', id, 'playlist_items', true); } static fetch(action, token_or_id, cache_key, full) { // Early return if we already if (action == 'items' && Cache.youtube.playlist_items[token_or_id]) return Cache.youtube.playlist_items[token_or_id]; else if (Cache.youtube[cache_key || action] && !token_or_id) return Cache.youtube[cache_key || action]; return YT[action](token_or_id, full).then((set) => { return Record.youtube(set); }).then((result) => { // Add the result to cache; we can safely do this // call here as the method would've early returned if no // h-ref was provided. Cache.add('youtube', (cache_key || action), result); return result; }); } static searchResults() { return MetaModel.searchResults().then((hash) => { return hash.youtube; }); } static findById(id, section, playlist) { if (playlist instanceof $) return this.findPlaylist(playlist.data('id')).then((playlist) => { return this.findInPlaylist(id, section, playlist); }); else if (playlist instanceof Record) return this.findInPlaylist(id, section, playlist); else return this.findRecord(id, section); } static findPlaylist(id) { return this.playlists().then((playlists) => { return playlists.collection.find(item => item.id == id); }); } static findInPlaylist(id, section, playlist) { return Promise.resolve({ playlist: playlist, record: playlist.items.find(item => item.id == id) }); } static findRecord(id, section) { return this[section.camel()]().then((cache) => { return cache.collection.find(record => record.id == id); }); } /** * Performs a search directly on YouTube rather than in * the user's collection and allows us to deal with * instances of `Record` rather than JSON hashes. * * @param {String} value - The value to look for. * @return {Promise} */ static netSearch(value) { return new Promise((resolve, reject) => { return YT.search(value).then((results) => { var ids = results.items.map(item => item.id.videoId); return YT.fetch('videos', { id: ids.join(",") }, (data) => { resolve({ collection: data.items.map(result => Record.youtube(result)), next_token: results.next_token, net: true }); }); }); }); } /** * Adds an element to a playlist given its id and updates * the cache accordingly. * * @param {String} id - The playlist's id. * @param {Record} record - The element to add. * @return {Promise} */ static addToPlaylist(id, record) { if (Cache.youtube.playlist_items[id]) Cache.youtube.playlist_items[id].then((cached) => { cached.items.push(record); }); return YT.insert(id, record.id); } /** * Creates a brand new playlist given a title. This methods * delegates to the client and updates the cache accordingly. * * @param {String} title - The playlist's title. * @return {Promise} */ static createPlaylist(title) { return YT.create(title).then((hash) => { var record = Record.youtube(hash); return this.playlists().then((playlists) => { playlists.items.unshift(record); return record; }); }); } }
JavaScript
0
@@ -2527,24 +2527,129 @@ cache) =%3E %7B%0A + if (section == 'history')%0A return cache.items.find(record =%3E record.id == id);%0A else%0A return
18c0e889e3ce0bad44de3844969a623d5d0b4c15
Update wew.js
examples/js/wew.js
examples/js/wew.js
function wew(WEW){ 'use strict'; this.uid = new Date; this.appid = WEW.opts.appID; this.ttl = WEW.opts.ttl; (this.storage = window.localStorage).setItem(this.uid, this.uid); } wew.prototype.getSet = function (setName,callback){ 'use strict'; var storageKey = setName || ""; console.log("setName: "+setName); var cached=this.inCache(storageKey); if(!cached){ this.askCloud('http://ddr.'+this.appid+'.wew.io/cset/',storageKey, callback); }else{ callback(cached); } }, wew.prototype.getCap = function(capabilityName, callback) { 'use strict'; var storageKey = capabilityName; var capability =""; console.log("capabilityName: "+capabilityName); var cached=this.inCache(storageKey); if(!cached){ this.askCloud('http://ddr.'+this.appid+'.wew.io/c/'+capabilityName,storageKey, callback); }else{ callback(cached); } }, wew.prototype.inCache = function(storageKey) { capability =0; if(this.storage && this.storage.getItem(storageKey) && JSON.parse && JSON) { try { capability = JSON.parse(this.storage.getItem(storageKey)); var now = new Date(); var age = new Date(capability.ts); if( (now.getTime() - age.getTime()) > this.ttl) { this.storage.removeItem(storageKey); capability=0; } else { return capability; } } catch(e) { } }else{ return capability; } }, wew.prototype.askCloud = function (url,storageKey,callback) { var http = this.httpObj(); var storage = this.storage; var w=window,d=document, e=d.documentElement,g=d.getElementsByTagName('body')[0], x=w.innerWidth||e.clientWidth||g.clientWidth, y=w.innerHeight||e.clientHeight||g.clientHeight; var orientation = window.orientation || ""; var height = y || ""; var width = x || ""; var pixelratio = window.devicePixelRatio || ""; url = url +"?o="+orientation+"&h="+height+"&w="+width+"&p="+pixelratio; console.log(url); http.open('GET', url, true); http.onreadystatechange = function (){ if (http.readyState == 4 && http.status == 200) { if(storage) { var capability = JSON.parse(http.responseText); var i =0; for (key in capability) { try{ capability['ts'] = new Date(); if(i<1){ storage.setItem(storageKey, JSON.stringify(capability)); } var jsn={}; jsn[key] = capability[key]; jsn['ts'] = capability['ts']; storage.setItem(key, JSON.stringify(jsn)); console.log("stored"); }catch (e){ console.log("Could not store"); console.log(e); } i++; } } callback(JSON.parse(http.responseText)); } }; http.send(); }, wew.prototype.httpObj = function () { var xmlhttpmethod = false, attempts = [ function () { return new XMLHttpRequest(); }, function () { return new ActiveXObject("Microsoft.XMLHTTP"); }, function () { return new XDomainRequest; }, function () { return new ActiveXObject("MSXML2.XMLHTTP.3.0"); } ], al = attempts.length; while (al--) { try { xmlhttpmethod = attempts[al](); } catch (e) { continue; } break; } return xmlhttpmethod; }
JavaScript
0.000001
@@ -1450,196 +1450,8 @@ ge;%0A -%09%09var w=window,d=document,%0A%09%09%09e=d.documentElement,g=d.getElementsByTagName('body')%5B0%5D,%0A%09%09%09x=w.innerWidth%7C%7Ce.clientWidth%7C%7Cg.clientWidth,%0A%09%09%09y=w.innerHeight%7C%7Ce.clientHeight%7C%7Cg.clientHeight;%0A %09%09va @@ -1507,17 +1507,29 @@ eight = -y +screen.height %7C%7C %22%22;%0A @@ -1542,17 +1542,28 @@ width = -x +screen.width %7C%7C %22%22;%0A
9590c0a567dec9a4257db77b61283d76dfa9c488
Update Fixer Node Argument Range (#3755)
eslint/cactbot-response-default-severities.js
eslint/cactbot-response-default-severities.js
module.exports = { meta: { type: 'suggestion', docs: { description: 'prevent explicit overrides where the response default is being used', category: 'Stylistic Issues', recommended: true, url: 'https://github.com/quisquous/cactbot/blob/main/docs/RaidbossGuide.md#trigger-elements', }, fixable: 'code', schema: [], }, create: (context) => { const defaultSeverityResponseMap = { 'info': [ 'tankCleave', 'miniBuster', 'aoe', 'bigAoe', 'spread', 'stackMiddle', 'knockbackOn', 'lookTowards', 'lookAway', 'getUnder', 'outOfMelee', 'getInThenOut', 'getOutThenIn', 'getBackThenFront', 'getFrontThenBack', 'killAdds', 'killExtraAdd', 'moveAway', 'moveAround', 'breakChains', 'moveChainsTogether', ], 'alert': [ 'tankBuster', 'stackMarker', 'getTogether', 'stackMarkerOn', 'doritoStack', 'spreadThenStack', 'stackThenSpread', 'knockback', 'lookAwayFromTarget', 'lookAwayFromSource', 'getBehind', 'goFrontOrSides', 'getIn', 'getOut', 'goMiddle', 'goRight', 'goLeft', 'goWest', 'goEast', 'goFrontBack', 'goSides', 'awayFromFront', 'sleep', 'stun', 'interrupt', 'preyOn', 'awayFrom', 'earthshaker', ], 'alarm': [ 'tankBusterSwap', 'meteorOnYou', 'stopMoving', 'stopEverything', 'wakeUp', ], 'info, info': [ 'knockbackOn', ], 'alert, info': [ 'tankBuster', 'preyOn', ], 'alarm, alert': [ 'tankBusterSwap', ], }; return { 'Property[key.name=\'response\'] > CallExpression[callee.object.name=\'Responses\'][arguments.length!=0]': (node) => { const responseSeverity = node.arguments.map((arg) => arg.value).join(', '); const defaultSeverity = defaultSeverityResponseMap[responseSeverity]; if (defaultSeverity && defaultSeverity.includes(node.callee.property.name)) { context.report({ node, message: 'Use default severity in cases where the severity override matches the response default', fix: (fixer) => { return fixer.replaceTextRange( [node.arguments[0].start, node.arguments[node.arguments.length - 1].end], '', ); }, }); } }, }; }, };
JavaScript
0.000001
@@ -2585,13 +2585,16 @@ %5B0%5D. -start +range%5B0%5D , no @@ -2633,19 +2633,24 @@ th - 1%5D. -end +range%5B1%5D %5D,%0A
8ab7b8567073c9d14c77964d044d2872a015cdc5
Fix type ContextRouter (#820)
definitions/npm/react-router-dom_v4.x.x/flow_v0.38.x-/react-router-dom_v4.x.x.js
definitions/npm/react-router-dom_v4.x.x/flow_v0.38.x-/react-router-dom_v4.x.x.js
declare module 'react-router-dom' { declare export class BrowserRouter extends React$Component { props: { basename?: string, forceRefresh?: boolean, getUserConfirmation?: GetUserConfirmation, keyLength?: number, children?: React$Element<*>, } } declare export class HashRouter extends React$Component { props: { basename?: string, getUserConfirmation?: GetUserConfirmation, hashType?: 'slash' | 'noslash' | 'hashbang', children?: React$Element<*>, } } declare export class Link extends React$Component { props: { to: string | LocationShape, replace?: boolean, children?: React$Element<*>, } } declare export class NavLink extends React$Component { props: { to: string | LocationShape, activeClassName?: string, className?: string, activeStyle?: Object, style?: Object, isActive?: (match: Match, location: Location) => boolean, children?: React$Element<*>, exact?: bool, strict?: bool, } } // NOTE: Below are duplicated from react-router. If updating these, please // update the react-router and react-router-native types as well. declare export type Location = { pathname: string, search: string, hash: string, state?: any, key?: string, } declare export type LocationShape = { pathname?: string, search?: string, hash?: string, state?: any, } declare export type HistoryAction = 'PUSH' | 'REPLACE' | 'POP' declare export type RouterHistory = { length: number, location: Location, action: HistoryAction, listen(callback: (location: Location, action: HistoryAction) => void): () => void, push(path: string | LocationShape, state?: any): void, replace(path: string | LocationShape, state?: any): void, go(n: number): void, goBack(): void, goForward(): void, canGo?: (n: number) => bool, block(callback: (location: Location, action: HistoryAction) => boolean): void, // createMemoryHistory index?: number, entries?: Array<Location>, } declare export type Match = { params: Object, isExact: boolean, path: string, url: string, } declare export type ContextRouter = RouterHistory & { match: Match, } declare export type GetUserConfirmation = (message: string, callback: (confirmed: boolean) => void) => void declare type StaticRouterContext = { url?: string, } declare export class StaticRouter extends React$Component { props: { basename?: string, location?: string | Location, context: StaticRouterContext, children?: React$Element<*>, } } declare export class MemoryRouter extends React$Component { props: { initialEntries?: Array<LocationShape | string>, initialIndex?: number, getUserConfirmation?: GetUserConfirmation, keyLength?: number, children?: React$Element<*>, } } declare export class Router extends React$Component { props: { history: RouterHistory, children?: React$Element<*>, } } declare export class Prompt extends React$Component { props: { message: string | (location: Location) => string | true, when?: boolean, } } declare export class Redirect extends React$Component { props: { to: string | LocationShape, push?: boolean, } } declare export class Route extends React$Component { props: { component?: ReactClass<*>, render?: (router: ContextRouter) => React$Element<*>, children?: (router: ContextRouter) => React$Element<*>, path?: string, exact?: bool, strict?: bool, } } declare export class Switch extends React$Component { props: { children?: Array<React$Element<*>>, } } declare type FunctionComponent<P> = (props: P) => ?React$Element<any>; declare type ClassComponent<D, P, S> = Class<React$Component<D, P, S>>; declare export function withRouter<P, S>(Component: ClassComponent<void, P, S> | FunctionComponent<P>): ClassComponent<void, $Diff<P, ContextRouter>, S>; declare type MatchPathOptions = { path: string, exact?: boolean, strict?: boolean, } declare export function matchPath(pathname: string, options: MatchPathOptions): null | Match }
JavaScript
0.999999
@@ -2273,25 +2273,61 @@ r = -RouterHistory & %7B +%7B%0A history: RouterHistory,%0A location: Location, %0A
561cb895ec70a1d74f4b20ca4cbf3489c866eb2c
make sure to only hydrate on first pass
packages/react/dom.js
packages/react/dom.js
'use strict'; var React = require('react'); var ReactDOM = require('react-dom'); var ReactRouterDOM = require('react-router-dom'); var mixinable = require('mixinable'); var hopsConfig = require('hops-config'); exports.combineContexts = mixinable({ bootstrap: mixinable.parallel, enhanceElement: mixinable.pipe, getMountpoint: mixinable.override }); exports.contextDefinition = { constructor: function (options) { if (!options) { options = {}; } this.mountpoint = options.mountpoint || '#main'; }, bootstrap: function () { return Promise.resolve(); }, enhanceElement: function (reactElement) { return Promise.resolve(React.createElement( ReactRouterDOM.BrowserRouter, { basename: hopsConfig.basePath }, reactElement )); }, getMountpoint: function () { return document.querySelector(this.mountpoint); } }; exports.createContext = exports.combineContexts( exports.contextDefinition ); exports.render = function (reactElement, context) { return function () { var mountpoint = context.getMountpoint(); if (mountpoint.hasAttribute('data-hopsroot')) { ReactDOM.unmountComponentAtNode(mountpoint); } else { mountpoint.setAttribute('data-hopsroot', ''); } return context.bootstrap().then(function () { return context.enhanceElement(reactElement).then( function (enhancedElement) { if (ReactDOM.hydrate) { ReactDOM.hydrate(enhancedElement, mountpoint); } else { ReactDOM.render(enhancedElement, mountpoint); } } ); }); }; }; Object.assign(exports, require('./lib/components'));
JavaScript
0
@@ -1072,20 +1072,32 @@ ();%0A -if ( +var isMounted = mountpoi @@ -1128,16 +1128,35 @@ psroot') +;%0A if (isMounted ) %7B%0A @@ -1446,16 +1446,30 @@ .hydrate + && !isMounted ) %7B%0A
1b9a7eca982b27b395ce4194b71b4416a3db935c
Limit to 25 characters
share/spice/zanran/spice.js
share/spice/zanran/spice.js
/* nr is the prefix for this function space. There's probably a way to do it in YUI that's not so awful, but I only know jQuery... */ function ddg_spice_zanran(zanran_results) { /* IE6 cannot be supported due to lack of max-width / min-width without rewriting everything */ if(YAHOO.env.ua.ie && YAHOO.env.ua.ie < 7) { return; } if(!zanran_results || !zanran_results.results || !zanran_results.results.length) { return; } var results = zanran_results.results; var out = ""; for(var i=0; i<results.length; i++) { var div = d.createElement("div"); var idiv = d.createElement("div"); var link = d.createElement("a"); link.href = results[i].preview_url; link.title = results[i].title; var img = d.createElement('img'); img.src = results[i].preview_image; link.appendChild(img); idiv.appendChild(link); div.appendChild(idiv); var link2 = d.createElement("a"); link2.href = results[i].preview_url; link2.title = results[i].title; link2.appendChild(d.createTextNode(results[i].short_title)); div.appendChild(link2); div.appendChild(d.createElement('br')); YAHOO.util.Dom.addClass(div, 'inline highlight_zero_click1 highlight_zero_click_wrapper'); YAHOO.util.Dom.setStyle(div, "float", "left"); YAHOO.util.Dom.setStyle(div, "max-width", "137px"); YAHOO.util.Dom.setStyle(div, "vertical-align", "bottom"); YAHOO.util.Dom.setStyle(div, "text-align", "center"); YAHOO.util.Dom.setStyle(idiv, 'height', '200px'); YAHOO.util.Dom.setStyle(idiv, "position", "relative"); YAHOO.util.Dom.setStyle(img, "position", "absolute"); YAHOO.util.Dom.setStyle(img, "bottom", "0px"); YAHOO.util.Dom.setStyle(img, "margin", '0 auto 0 auto'); YAHOO.util.Dom.setStyle(img, 'max-width', '137px'); YAHOO.util.Dom.setStyle(img, 'max-height', '194px'); // A4 ratio var container_div = d.createElement("div"); container_div.appendChild(div); out += container_div.innerHTML; } out += '<div class="clear"></div>'; items = [[]]; items[0]['a'] = out; items[0]['h'] = '<h1>Data & Statistics</h1>'; items[0]['s'] = 'Zanran'; items[0]['u'] = zanran_results.more; items[0]['f'] = 1; // items[0]['i'] = 'http://zanran.com/favicon.ico'; nra(items,1,1); };
JavaScript
0.999998
@@ -897,24 +897,401 @@ idiv);%0A %0A + var very_short_title = results%5Bi%5D.short_title;%0A if(very_short_title.length %3E 25) %7B%0A var words = very_short_title.split(/%5Cs+/);%0A very_short_title = %22%22;%0A while(words.length && very_short_title.length + 1 + words%5B0%5D.length %3C 25) %7B%0A very_short_title = very_short_title + %22 %22 + words.shift();%0A %7D%0A very_short_title += %22%5Cu2026%22;%0A %7D%0A %0A %0A var link @@ -1308,32 +1308,32 @@ teElement(%22a%22);%0A - link2.href = @@ -1432,27 +1432,21 @@ extNode( -results%5Bi%5D. +very_ short_ti
458b7ceb9de07176689c5312b7a80ad2894bbd85
fix link
src/pages/boards/index.js
src/pages/boards/index.js
import React from "react"; import R from "ramda"; import { connect } from "react-redux"; import { compose } from "redux"; import { Link } from "react-router-dom"; import { firebaseConnect, isLoaded, isEmpty, dataToJS } from "react-redux-firebase"; class Boards extends React.Component { render() { return ( <div className="box d-col fb-100"> {this.props.boards ? R.map( board => <div key={board.id}> <Link to={"/boards/" + board.id}>{board.title}</Link> </div>, this.getBoards() ) : <div>No boards</div>} </div> ); } getBoards = () => { const { boards } = this.props; if (boards) { return R.map(key => ({ ...boards[key], id: key }), R.keys(boards)); } return []; }; } export default compose( firebaseConnect(["/boards"]), connect(({ firebase }) => ({ boards: dataToJS(firebase, "/boards") })) )(Boards);
JavaScript
0
@@ -509,18 +509,27 @@ + board. -id +public_code %7D%3E%7Bboard
db3605dc7b7c0c013bcc2bbb9c684e56884a318b
Update offline region example to show off pack status method
example/src/components/CreateOfflineRegion.js
example/src/components/CreateOfflineRegion.js
import React from 'react'; import { Text, View, TouchableOpacity, Dimensions, StyleSheet } from 'react-native'; import MapboxGL from '@mapbox/react-native-mapbox-gl'; import geoViewport from '@mapbox/geo-viewport'; import BaseExamplePropTypes from './common/BaseExamplePropTypes'; import Page from './common/Page'; import Bubble from './common/Bubble'; import sheet from '../styles/sheet'; const CENTER_COORD = [-73.970895, 40.723279]; const MAPBOX_VECTOR_TILE_SIZE = 512; const styles = StyleSheet.create({ percentageText: { padding: 8, textAlign: 'center', }, buttonCnt: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', }, button: { flex: 0.4, alignItems: 'center', justifyContent: 'center', borderRadius: 3, backgroundColor: 'blue', padding: 8, }, buttonTxt: { color: 'white', }, }); class CreateOfflineRegion extends React.Component { static propTypes = { ...BaseExamplePropTypes, }; constructor (props) { super(props); this.state = { name: `test-${Date.now()}`, offlineRegionStatus: null, }; this.onDownloadProgress = this.onDownloadProgress.bind(this); this.onDidFinishLoadingStyle = this.onDidFinishLoadingStyle.bind(this); this.onResume = this.onResume.bind(this); this.onPause = this.onPause.bind(this); } componentWillUnmount () { // avoid setState warnings if we back out before we finishing downloading MapboxGL.offlineManager.deletePack(this.state.name); MapboxGL.offlineManager.unsubscribe('test'); } async onDidFinishLoadingStyle () { const { width, height } = Dimensions.get('window'); const bounds = geoViewport.bounds(CENTER_COORD, 12, [width, height], MAPBOX_VECTOR_TILE_SIZE); const options = { name: this.state.name, styleURL: MapboxGL.StyleURL.Street, bounds: [[bounds[0], bounds[1]], [bounds[2], bounds[3]]], minZoom: 10, maxZoom: 20, }; // start download MapboxGL.offlineManager.createPack( options, this.onDownloadProgress, ); } onDownloadProgress (offlineRegion, offlineRegionStatus) { this.setState({ name: offlineRegion.name, offlineRegionStatus: offlineRegionStatus, }); } onResume () { if (this.state.offlineRegion) { this.state.offlineRegion.resume(); } } onPause () { if (this.state.offlineRegion) { this.state.offlineRegion.pause(); } } _formatPercent () { if (!this.state.offlineRegionStatus) { return '0%'; } return Math.round(this.state.offlineRegionStatus.percentage / 10) / 10; } _getRegionDownloadState (downloadState) { switch (downloadState) { case MapboxGL.OfflinePackDownloadState.Active: return 'Active'; case MapboxGL.OfflinePackDownloadState.Complete: return 'Complete'; default: return 'Inactive'; } } render () { const offlineRegionStatus = this.state.offlineRegionStatus; return ( <Page {...this.props}> <MapboxGL.MapView zoomLevel={10} ref={(c) => this._map = c} onPress={this.onPress} onDidFinishLoadingMap={this.onDidFinishLoadingStyle} centerCoordinate={CENTER_COORD} style={sheet.matchParent} /> {offlineRegionStatus !== null ? ( <Bubble> <View style={{ flex : 1 }}> <Text>Download State: {this._getRegionDownloadState(offlineRegionStatus.state)}</Text> <Text>Download Percent: {offlineRegionStatus.percentage}</Text> <Text>Completed Resource Count: {offlineRegionStatus.completedResourceCount}</Text> <Text>Completed Resource Size: {offlineRegionStatus.completedResourceSize}</Text> <Text>Completed Tile Count: {offlineRegionStatus.completedTileCount}</Text> <Text>Required Resource Count: {offlineRegionStatus.requiredResourceCount}</Text> <View style={styles.buttonCnt}> <TouchableOpacity onPress={this.onResume}> <View style={styles.button}> <Text style={styles.buttonTxt}>Resume</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={this.onPause}> <View style={styles.button}> <Text style={styles.buttonTxt}>Pause</Text> </View> </TouchableOpacity> </View> </View> </Bubble> ) : null} </Page> ); } } export default CreateOfflineRegion;
JavaScript
0
@@ -24,16 +24,17 @@ t';%0A +%0A import %7B Tex @@ -33,20 +33,35 @@ rt %7B +%0A Alert,%0A Text, +%0A View, +%0A Tou @@ -74,16 +74,18 @@ Opacity, +%0A Dimensi @@ -88,16 +88,18 @@ ensions, +%0A StyleSh @@ -101,17 +101,18 @@ yleSheet - +,%0A %7D from ' @@ -122,24 +122,25 @@ ct-native';%0A +%0A import Mapbo @@ -1106,16 +1106,43 @@ ow()%7D%60,%0A + offlineRegion: null,%0A of @@ -1407,16 +1407,76 @@ (this);%0A + this.onStatusRequest = this.onStatusRequest.bind(this);%0A %7D%0A%0A c @@ -2313,24 +2313,60 @@ egion.name,%0A + offlineRegion: offlineRegion,%0A offlin @@ -2620,16 +2620,246 @@ %7D%0A %7D%0A%0A + async onStatusRequest () %7B%0A if (this.state.offlineRegion) %7B%0A const offlineRegionStatus = await this.state.offlineRegion.status();%0A Alert.alert('Get Status', JSON.stringify(offlineRegionStatus, null, 2));%0A %7D%0A %7D%0A%0A _forma @@ -4512,32 +4512,32 @@ styles.button%7D%3E%0A - @@ -4648,16 +4648,257 @@ acity%3E%0A%0A + %3CTouchableOpacity onPress=%7Bthis.onStatusRequest%7D%3E%0A %3CView style=%7Bstyles.button%7D%3E%0A %3CText style=%7Bstyles.buttonTxt%7D%3EStatus%3C/Text%3E%0A %3C/View%3E%0A %3C/TouchableOpacity%3E%0A%0A
c9e69e233aaa0c72fae98c74a3226bad75a4a557
handle getting response headers on timeout with better chances of not getting a browser exception (good for debugging with breaking on all exceptions)
packages/util/ajax.js
packages/util/ajax.js
"use import"; import std.uri as URI; var SIMULTANEOUS = 4; var _inflight = 0; var doc; exports.getDoc = function() { if (doc) { return doc; } try { doc = window.ActiveXObject && new ActiveXObject('htmlfile'); if (doc) { doc.open().write('<html></html>'); doc.close(); window.attachEvent('onunload', function() { try { doc.body.innerHTML = ''; } catch(e) {} doc = null; }); } } catch(e) {} if (!doc) { doc = document; } return doc; }; var ctor = function() { var win = window, doc = exports.getDoc(); //if (doc.parentWindow) { win = doc.parentWindow; } return new (ctor = win.XMLHttpRequest ? win.XMLHttpRequest : function() { return win.ActiveXObject && new win.ActiveXObject('Msxml2.XMLHTTP') || null; }); }; exports.createXHR = function() { return new ctor(); } exports.post = function(opts, cb) { return exports.get(merge({method: 'POST'}, opts), cb); } var Request = Class(function() { var _UID = 0; this.init = function(opts, cb) { if (!opts || !opts.url) { logger.error('no url provided'); return; } this.method = (opts.method || 'GET').toUpperCase(); this.url = opts.url; this.type = opts.type; this.async = opts.async; this.timeout = opts.timeout; this.id = ++_UID; this.headers = {}; this.cb = cb; if (opts.headers) { for (var key in opts.headers) if (opts.headers.hasOwnProperty(key)) { var value = opts.headers[key]; this.headers[key] = value; } } var isObject = opts.data && typeof opts.data == 'object'; if (this.method == 'GET' && opts.data) { this.url = new URI(this.url).addQuery(isObject ? opts.data : URI.parseQuery(opts.data)).toString(); } try { this.data = (this.method != 'GET' ? (isObject ? JSON.stringify(opts.data) : opts.data) : null); } catch(e) { cb && cb({invalidData: true}, null, ''); return; } } }); var _pending = []; exports.get = function(opts, cb) { var request = new Request(opts, cb); if (_inflight >= SIMULTANEOUS) { _pending.push(request); } else { _send(request); } } function _sendNext() { //logger.log('====INFLIGHT', _inflight, SIMULTANEOUS, 'might send next?'); if (_inflight < SIMULTANEOUS) { var request = _pending.shift(); if (request) { _send(request); } } } function _send(request) { ++_inflight; //logger.log('====INFLIGHT', _inflight, 'sending request', request.id); var xhr = exports.createXHR(); xhr.open(request.method, request.url, !(request.async == false)); var setContentType = false; for (var key in request.headers) { if (key.toLowerCase() == 'content-type') { setContentType = true; } xhr.setRequestHeader(key, request.headers[key]); } if (!setContentType) { xhr.setRequestHeader('Content-Type', 'text/plain'); } xhr.onreadystatechange = bind(this, onReadyStateChange, request, xhr); if (request.timeout) { request.timeoutRef = setTimeout(bind(this, cancel, xhr, request), request.timeout); //logger.log('==== setting timeout for', request.timeout, request.timeoutRef, '<<'); } request.ts = +new Date(); xhr.send(request.data || null); } function cancel(xhr, request) { --_inflight; // logger.log('====INFLIGHT', _inflight, 'timeout (cancelled)', request.id); if (request.timedOut) { logger.log('already timed out?!'); } xhr.onreadystatechange = null; request.timedOut = true; try { var headers = xhr.getAllResponseHeaders(); } catch (e) {} request.cb && request.cb({timeout: true}, null, headers); } function onReadyStateChange(request, xhr) { if (xhr.readyState != 4) { return; } if (request.timedOut) { throw 'Unexpected?!'; } --_inflight; // logger.log('====INFLIGHT', _inflight, 'received response', request.ts, request.id, (+new Date() - request.ts) / 1000); setTimeout(_sendNext, 0); var cb = request.cb; if ('timeoutRef' in request) { // logger.log('==== AJAX CLEARING TIMEOUT', request.id); clearTimeout(request.timeoutRef); request.timeoutRef = null; } if (!cb) { return; } // .status will be 0 when requests are filled via app cache on at least iOS 4.x if (xhr.status != 200 && xhr.status != 0) { var response = xhr.response; if (xhr.getResponseHeader('Content-Type') == 'application/json') { try { response = JSON.parse(response); } catch(e) { } } cb({status: xhr.status, response: response}, null, xhr.getAllResponseHeaders()); } else { var data = xhr.responseText; if (request.type == 'json') { if (!data) { cb({status: xhr.status, response: xhr.response}, null, xhr.getAllResponseHeaders()); return; } else { try { data = JSON.parse(data); } catch(e) { cb({status: xhr.status, response: xhr.response, parseError: true}, null, xhr.getAllResponseHeaders()); return; } } } cb(null, data, xhr.getAllResponseHeaders()); } }
JavaScript
0
@@ -3330,23 +3330,72 @@ = true;%0A +%09if (xhr.readyState %3E= xhr.HEADERS_RECEIVED) %7B%0A%09 %09try %7B%0A +%09 %09%09var he @@ -3431,16 +3431,17 @@ ders();%0A +%09 %09%7D catch @@ -3448,16 +3448,21 @@ (e) %7B%7D%0A +%09%7D%0A%09%0A %09request
1c066096053a7fe11aa14edad109707c827fad3d
fix pokemon api request
examples/code-splitting/modules/PokemonAPI.js
examples/code-splitting/modules/PokemonAPI.js
class Pokemons { async retrieve(id) { const response = await fetch(`http://pokeapi.co/api/v2/pokemon/${id}/`); return response.json(); } } export default new Pokemons();
JavaScript
0.000002
@@ -71,16 +71,17 @@ ch(%60http +s ://pokea
13b271d3d1f631f4d6b7247e2907e7065cd4fefb
add one more test
test/integration/cloud/profile.js
test/integration/cloud/profile.js
var { CloudContext } = require('./utils'); describe('User profile story', () => { let ctx = new CloudContext(); let aliceData = ctx.userData.alice; let bobData = ctx.userData.bob; let newBobData = { name: bobData.name, hates: bobData.likes, }; describe('When alice gets her account without creating it', () => { ctx.requestShouldError(404, async () => { ctx.response = await ctx.alice.user(ctx.alice.userId).get(); }); }); let checkUserResponse = (userFn, data) => { ctx.responseShouldHaveFields('id', 'created_at', 'updated_at', 'data'); ctx.responseShould('have id and data matching the request', () => { ctx.response.id.should.equal(userFn().id); ctx.response.data.should.eql(data); }); ctx.test('the local user data should be updated', () => { userFn().data.should.eql(data); }); }; let checkProfileResponse = (userFn, data, following, followers) => { ctx.responseShouldHaveFields( 'id', 'created_at', 'updated_at', 'data', 'following_count', 'followers_count', ); ctx.responseShould( 'have id and data matching the previously submitted data', () => { ctx.response.id.should.equal(userFn().id); ctx.response.data.should.eql(data); }, ); ctx.test('the local user data should be updated', () => { userFn().data.should.eql(data); }); ctx.responseShould( 'contain the counts for following and followers for timeline->user feedgroups', () => { ctx.response.following_count.should.equal(following); ctx.response.followers_count.should.equal(followers); }, ); }; describe('When alice creates her account', () => { ctx.requestShouldNotError(async () => { ctx.user = await ctx.alice.currentUser.getOrCreate(aliceData); ctx.response = ctx.user.full; }); checkUserResponse(() => ctx.response, aliceData); }); describe('When alice looks at her own profile', () => { ctx.requestShouldNotError(async () => { let user = await ctx.user.profile(); ctx.response = user.full; }); ctx.responseShouldHaveFields( 'id', 'created_at', 'updated_at', 'data', 'followers_count', 'following_count', ); }); describe('When alice tries to create her account again', () => { ctx.requestShouldError(409, async () => { await ctx.user.create(aliceData); }); }); describe('When bob calls getOrCreate for his user that does not exist yet', () => { ctx.requestShouldNotError(async () => { ctx.user = await ctx.bob.currentUser.getOrCreate(bobData); ctx.response = ctx.user.full; }); checkUserResponse(() => ctx.response, bobData); }); describe('When bob calls getOrCreate for his existing user with new data', () => { ctx.requestShouldNotError(async () => { ctx.prevResponse = ctx.response; ctx.user = await ctx.bob.currentUser.getOrCreate(newBobData); ctx.response = ctx.user.full; }); ctx.responseShould('be the same as the previous response', () => { ctx.response.should.eql(ctx.prevResponse); }); }); describe('When bob updates his existing user', () => { ctx.requestShouldNotError(async () => { ctx.prevResponse = ctx.response; ctx.user = await ctx.user.update(newBobData); ctx.response = ctx.user.full; }); checkUserResponse(() => ctx.user, newBobData); ctx.responseShouldHaveNewUpdatedAt(); }); describe('When creating follow relationships', () => { ctx.requestShouldNotError(async () => { let promises = []; promises.push( ctx.alice .feed('timeline', ctx.alice.userId) .follow('user', ctx.bob.userId), ); promises.push( ctx.alice .feed('user', ctx.alice.userId) .follow('user', ctx.carl.userId), ); promises.push( ctx.alice .feed('timeline', ctx.alice.userId) .follow('timeline', ctx.dave.userId), ); promises.push( ctx.bob .feed('timeline', ctx.bob.userId) .follow('user', ctx.alice.userId), ); promises.push( ctx.bob .feed('notification', ctx.bob.userId) .follow('user', ctx.alice.userId), ); promises.push( ctx.carl .feed('notification', ctx.carl.userId) .follow('user', ctx.alice.userId), ); promises.push( ctx.dave .feed('notification', ctx.dave.userId) .follow('user', ctx.alice.userId), ); await Promise.all(promises); }); }); describe("When alice looks at bob's profile", () => { let bobUser; ctx.requestShouldNotError(async () => { bobUser = await ctx.alice.user(ctx.bob.userId).profile(); ctx.response = await bobUser.full; }); checkProfileResponse(() => ctx.response, newBobData, 1, 1); }); describe('When alice tries to set a string as user data', () => { ctx.requestShouldError(400, async () => { ctx.response = await ctx.alice .user(ctx.alice.userId) .update('some string'); }); }); describe('When alice deletes her profile', () => { ctx.requestShouldNotError(async () => { ctx.response = await ctx.alice.user(ctx.alice.userId).delete(); }); }); describe('When alice tries to delete bob', () => { ctx.requestShouldError(403, async () => { ctx.response = await ctx.alice.user(ctx.bob.userId).delete(); }); }); });
JavaScript
0.000003
@@ -5369,32 +5369,154 @@ elete();%0A %7D); +%0A%0A ctx.requestShouldError(404, async () =%3E %7B%0A ctx.response = await ctx.alice.user(ctx.alice.userId).get();%0A %7D); %0A %7D);%0A%0A descri