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
033ca6db226d5f153f277a5d03f7b9b21056eab1
Simplify CameraComponent ctor camera setup.
src/core/CameraComponent.js
src/core/CameraComponent.js
/*jshint white: false, strict: false, plusplus: false, onevar: false, nomen: false */ /*global define: false, console: false, window: false, setTimeout: false */ define( function ( require ) { var Component = require( './Component' ); function CameraComponent( paladin, options ) { options = options || {}; this.object = new paladin.subsystem.graphics.SceneObject(); this.camera = (options && options.camera) ? options.camera : new paladin.subsystem.graphics.Camera({ targeted: options.targeted }); this.camera.setParent( this.object ); this.entity = null; if (options.position) { this.object.position = options.position; } if (options.rotation) { this.object.rotation = options.rotation; } } CameraComponent.prototype = new Component( { type: 'graphics', subtype: [ 'camera' ], requires: [ 'spatial' ] } ); CameraComponent.prototype.constructor = CameraComponent; CameraComponent.prototype.onAdd = function( entity ) { entity.spatial.sceneObjects.graphics.bindChild( this.object ); this.entity = entity; }; CameraComponent.prototype.onRemove = function( entity ) { /* Note(alan.kligman@gmail.com): * Not implemented. */ }; return CameraComponent; });
JavaScript
0
@@ -403,20 +403,8 @@ ra = - (options && opt @@ -418,28 +418,11 @@ mera -) ? options.camera : + %7C%7C new @@ -458,16 +458,18 @@ amera(%7B%0A +
ba43154c4b57677f095d5b1aa55655671f3b2058
test 08.08.16 v8.88 dangerHtml 1aaa
src/containers/App/App.js
src/containers/App/App.js
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { IndexLink } from 'react-router'; import { LinkContainer } from 'react-router-bootstrap'; import Navbar from 'react-bootstrap/lib/Navbar'; import Nav from 'react-bootstrap/lib/Nav'; import NavItem from 'react-bootstrap/lib/NavItem'; import Helmet from 'react-helmet'; import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info'; import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth'; import { InfoBar } from 'components'; import { push } from 'react-router-redux'; import config from '../../config'; import { asyncConnect } from 'redux-async-connect'; @asyncConnect([{ promise: ({store: {dispatch, getState}}) => { const promises = []; if (!isInfoLoaded(getState())) { promises.push(dispatch(loadInfo())); } if (!isAuthLoaded(getState())) { promises.push(dispatch(loadAuth())); } return Promise.all(promises); } }]) @connect( state => ({user: state.auth.user}), {logout, pushState: push}) export default class App extends Component { static propTypes = { children: PropTypes.object.isRequired, user: PropTypes.object, logout: PropTypes.func.isRequired, pushState: PropTypes.func.isRequired }; static contextTypes = { store: PropTypes.object.isRequired }; state = { navExpanded: false, userName: window.localStorage.getItem('ls_username'), userPw: window.localStorage.getItem('ls_pw'), userUuid: window.localStorage.getItem('ls_uuid') } componentWillReceiveProps(nextProps) { if (!this.props.user && nextProps.user) { // login this.props.pushState('/loginSuccess'); } else if (this.props.user && !nextProps.user) { // logout this.props.pushState('/'); } } onNavItemClick = () => { this.setState({ navExpanded: false }); } onNavbarToggle = () => { console.log('1: ' + this.state.userName + '2: ' + this.state.userPw + '3: ' + this.state.userUuid); this.setState({ navExpanded: ! this.state.navExpanded }); } handleLogout = (event) => { event.preventDefault(); this.props.logout(); }; render() { const {userName, userPw, userUuid} = this.state; const styles = require('./App.scss'); return ( <div className={styles.app}> <Helmet {...config.app.head}/> <Navbar fixedTop expanded={ this.state.navExpanded } onToggle={ this.onNavbarToggle }> <Navbar.Header> <Navbar.Brand> <IndexLink to="/" activeStyle={{color: '#d52b1e'}}> <div className={styles.brand}/> <span>{config.app.title}</span> </IndexLink> </Navbar.Brand> <Navbar.Toggle/> </Navbar.Header> <Navbar.Collapse> <Nav navbar> <LinkContainer to="/community"> <NavItem eventKey={1} onClick={ this.onNavItemClick }>Community</NavItem> </LinkContainer> <LinkContainer to="/registrieren"> <NavItem eventKey={2} onClick={ this.onNavItemClick }>Mitglied werden</NavItem> </LinkContainer> <LinkContainer to="/kontakt"> <NavItem eventKey={3} onClick={ this.onNavItemClick }>Kontakt</NavItem> </LinkContainer> </Nav> </Navbar.Collapse> </Navbar> <div className={styles.appContent}> {this.props.children} </div> <InfoBar/> <div className="well text-center"> Copyright 2016 | Swiss React Community | React, Redux, Flux, React Native | Swiss-react.ch </div> </div> ); } }
JavaScript
0.000001
@@ -1083,18 +1083,16 @@ push%7D)%0A - export d @@ -2291,63 +2291,8 @@ ) %7B%0A - const %7BuserName, userPw, userUuid%7D = this.state;%0A
e8f37342bad5d45e67d4f95ccc4c677fc62f55a4
resolve warnings
src/ContentBlocks/BlockCarouselWithContent/BlockCarouselWithContent.js
src/ContentBlocks/BlockCarouselWithContent/BlockCarouselWithContent.js
// @flow import React from 'react'; import Box from 'grommet/components/Box'; import Carousel from 'grommet/components/Carousel'; import Footer from 'grommet/components/Footer'; import Markdown from 'grommet/components/Markdown'; import unescape from 'unescape'; import ImageWrapper from '../BlockMarquee/BlockMarquee/ImageWrapper'; import ImageBox from '../BlockMarquee/BlockMarquee/ImageBox'; import { BlockButton } from '../BlockButton'; import getAssetType from './getAssetType'; /* eslint-disable react/no-unused-prop-types */ type Slide = { justification: string, color: 'white' | 'black', content: ?string, button: { label: string, path: string, }, image: { path: string, } } /* eslint-enable react/no-unused-prop-types */ type Props = { carousel: Slide[], imageSize: string } // eslint-disable-next-line react/prefer-stateless-function export default class BlockCarouselWithContent extends React.Component { props: Props; render() { const { carousel, imageSize } = this.props; const size = imageSize ? imageSize.toLowerCase() : 'full'; return ( <Carousel autoplay={false}> {carousel.map((slide) => { const content = unescape(slide.content || ''); const contentClassName = slide.color === 'white' ? 'grommetux-background-color-index--dark' : 'grommetux-background-color-index--light'; return ( <Box className="grommet-cms-content-blocks--carousel-slide__content-box"> <ImageWrapper id="grommet-cms-content-blocks--carousel__image-wrapper" size={size} > <ImageBox id="grommet-cms-content-blocks--carousel__image-box" size={size} justification={slide.justification} texture={slide.image.path} /> </ImageWrapper> {slide.content && <Box className={`grommet-cms-content-blocks--carousel-slide__content ${contentClassName}`} align={slide.justification === 'left' ? 'start' : 'end'} justify="center" margin="large" > <Box margin="large" className="grommet-cms-content-blocks--carousel-slide__inner-box" pad="large" size={{ width: 'large' }} > <Markdown content={content} components={{ p: { props: { size: 'large', margin: 'small' } }, }} /> {slide.button && slide.button.label && <Footer pad={{ vertical: 'medium' }}> <BlockButton buttonType="Button" primary="False" assetType={getAssetType(slide.button.path)} {...slide.button} /> </Footer> } </Box> </Box> } </Box> ); })} </Carousel> ); } }
JavaScript
0
@@ -798,16 +798,17 @@ mageSize +? : string
5cf287a747ed5b22ceb7ac09af9b8c9a54de025e
implement stopCheck
lib/core/services_monitor.js
lib/core/services_monitor.js
var async = require('../utils/async_extend.js'); var ServicesMonitor = function(options) { this.events = options.events; this.logger = options.logger; this.checkList = {}; this.checkTimers = {}; this.checkState = {}; }; ServicesMonitor.prototype.addCheck = function(name, checkFn, time) { this.logger.info('add check: ' + name); // TODO: check if a service with the same name already exists this.checkList[name] = {fn: checkFn, interval: time || 5000}; }; ServicesMonitor.prototype.startMonitor = function() { this.logger.info('startMonitor'); var self = this; async.eachObject(this.checkList, function(checkName, check, callback) { self.events.on('check:' + checkName, function(obj) { self.checkState[checkName] = obj.name[obj.status]; self.events.emit("servicesState", self.checkState); }); if (check.interval !== 0) { self.checkTimers[checkName] = setInterval(function() { check.fn.call(check.fn, function(obj) { self.events.emit('check:' + checkName, obj); }); }, check.interval); } check.fn.call(check.fn, function(obj) { self.events.emit('check:' + checkName, obj); }); callback(); }, function(err) { if (err) { self.logger.error("error running service check"); self.logger.error(err.message); } }); }; module.exports = ServicesMonitor;
JavaScript
0.000001
@@ -342,132 +342,264 @@ ;%0A -// TODO: check if a service with the same name already exists%0A this.checkList%5Bname%5D = %7Bfn: checkFn, interval: time %7C%7C 5000%7D +this.checkList%5Bname%5D = %7Bfn: checkFn, interval: time %7C%7C 5000%7D;%0A%7D;%0A%0AServicesMonitor.prototype.stopCheck = function(name) %7B%0A clearInterval(this.checkTimers%5Bname%5D);%0A delete this.checkTimers%5Bname%5D;%0A delete this.checkList%5Bname%5D;%0A delete this.checkState%5Bname%5D ;%0A%7D;
b9167a54c2ff3ff797b7198b7fa5070d9cd54a06
switch deprecated fs.exists for fs.stat
controllers/thumbnails.js
controllers/thumbnails.js
'use strict'; var path = require('path'), fs = require('fs'), sharp = require('sharp'), config = require('../config.json'), Promise = require('bluebird'), restifyErrors = require('restify-errors'), CommonController = require('./common'); class ThumbnailsController extends CommonController { constructor() { super(); function loadAndShowImage(thumbFile, res) { let input = fs.createReadStream(thumbFile); res.setHeader('Content-Type', 'image/jpeg'); return input.pipe(res); } this.coroutines.getResource.main = Promise.coroutine(function* (req, res, next) { let thumbFile = path.join(config.file_storage.path, 'thumbs', `${req.params.uuid}-${req.params.type}-${req.params.size}.jpg`), originalFile = path.join(config.file_storage.path, 'photos', `${req.params.uuid}`), fsExists = Promise.promisify((file, cb) => { fs.exists(file, (exists) => { cb(null, exists); }); }); if (!(yield fsExists(originalFile))) { return next(new restifyErrors.NotFoundError()); } var input; if (!(yield fsExists(thumbFile))) { var size = req.params.size.split('x'), width = Math.min(1000, Math.max(0, parseInt(size[0]))), height = size.length === 2 ? Math.min(1000, Math.max(0, parseInt(size[1]))) : width, imgpipe = sharp(); if (req.params.type === 'square') { imgpipe.resize(width, width || null, { kernel: sharp.kernel.lanczos2, interpolator: sharp.interpolator.nohalo }).crop(sharp.strategy.entropy); } else { imgpipe.resize(width || null, height || null, { kernel: sharp.kernel.lanczos2, interpolator: sharp.interpolator.nohalo }); } imgpipe.clone().jpeg().quality(80).toFile(thumbFile, (err) => { if (err) { throw err; } return loadAndShowImage(thumbFile, res); }); input = fs.createReadStream(originalFile); input.pipe(imgpipe); } else { return loadAndShowImage(thumbFile, res); } }); } } module.exports = ThumbnailsController;
JavaScript
0.000003
@@ -1018,22 +1018,20 @@ fs. -exists +stat (file, ( exis @@ -1030,20 +1030,19 @@ e, ( -exis +sta ts) =%3E %7B cb( @@ -1041,26 +1041,189 @@ =%3E %7B - cb(null, exists); +%0A if (!stats) %7B%0A console.log('FILE NOT FOUND:', file);%0A %7D%0A cb(null, stats);%0A %7D);
e192402a426c24e0733822ea5bc4ce455bbdb416
Add item priorities
js/forum/src/components/HeaderSecondary.js
js/forum/src/components/HeaderSecondary.js
import Component from 'flarum/Component'; import Button from 'flarum/components/Button'; import LogInModal from 'flarum/components/LogInModal'; import SignUpModal from 'flarum/components/SignUpModal'; import SessionDropdown from 'flarum/components/SessionDropdown'; import SelectDropdown from 'flarum/components/SelectDropdown'; import NotificationsDropdown from 'flarum/components/NotificationsDropdown'; import ItemList from 'flarum/utils/ItemList'; import listItems from 'flarum/helpers/listItems'; /** * The `HeaderSecondary` component displays secondary header controls, such as * the search box and the user menu. On the default skin, these are shown on the * right side of the header. */ export default class HeaderSecondary extends Component { view() { return ( <ul className="Header-controls"> {listItems(this.items().toArray())} </ul> ); } /** * Build an item list for the controls. * * @return {ItemList} */ items() { const items = new ItemList(); items.add('search', app.search.render()); if (Object.keys(app.locales).length > 1) { const locales = []; for (const locale in app.locales) { locales.push(Button.component({ active: app.locale === locale, children: app.locales[locale], icon: app.locale === locale ? 'check' : true, onclick: () => { if (app.session.user) { app.session.user.savePreferences({locale}).then(() => window.location.reload()); } else { document.cookie = `locale=${locale}; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT`; window.location.reload(); } } })); } items.add('locale', SelectDropdown.component({ children: locales, buttonClassName: 'Button Button--link' })); } if (app.session.user) { items.add('notifications', NotificationsDropdown.component()); items.add('session', SessionDropdown.component()); } else { if (app.forum.attribute('allowSignUp')) { items.add('signUp', Button.component({ children: app.trans('core.sign_up'), className: 'Button Button--link', onclick: () => app.modal.show(new SignUpModal()) }) ); } items.add('logIn', Button.component({ children: app.trans('core.log_in'), className: 'Button Button--link', onclick: () => app.modal.show(new LogInModal()) }) ); } return items; } }
JavaScript
0.000006
@@ -1054,16 +1054,20 @@ render() +, 30 );%0A%0A @@ -1853,27 +1853,31 @@ nk'%0A %7D) +, 20 );%0A - %7D%0A%0A i @@ -1961,24 +1961,28 @@ .component() +, 10 );%0A ite @@ -2026,16 +2026,19 @@ ponent() +, 0 );%0A %7D @@ -2314,24 +2314,28 @@ %7D) +, 10 %0A );%0A @@ -2535,32 +2535,32 @@ w LogInModal())%0A - %7D)%0A @@ -2553,16 +2553,19 @@ %7D) +, 0 %0A )
6d81e5a8ab8d7d330c75da418b32168d5545356a
Update e2e tests
e2e-tests/scenarios.js
e2e-tests/scenarios.js
'use strict'; /* https://github.com/angular/protractor/blob/master/docs/toc.md */ describe('my app', function() { it('should automatically redirect to /view1 when location hash/fragment is empty', function() { browser.get('index.html'); expect(browser.getLocationAbsUrl()).toMatch("/view1"); }); describe('view1', function() { beforeEach(function() { browser.get('index.html#/view1'); }); it('should render view1 when user navigates to /view1', function() { expect(element.all(by.css('[ng-view] p')).first().getText()). toMatch(/partial for view 1/); }); }); describe('view2', function() { beforeEach(function() { browser.get('index.html#/view2'); }); it('should render view2 when user navigates to /view2', function() { expect(element.all(by.css('[ng-view] p')).first().getText()). toMatch(/partial for view 2/); }); }); });
JavaScript
0
@@ -100,24 +100,25 @@ p', function + () %7B%0A%0A%0A it( @@ -152,21 +152,16 @@ ect to / -view1 when lo @@ -189,16 +189,24 @@ is empty +/invalid ', funct @@ -200,32 +200,33 @@ valid', function + () %7B%0A browser @@ -297,16 +297,106 @@ tch( -%22/view1%22 +'/');%0A%0A browser.get('index.html#/invalid');%0A expect(browser.getLocationAbsUrl()).toMatch('/' );%0A @@ -414,21 +414,20 @@ scribe(' -view1 +home ', funct @@ -421,32 +421,33 @@ 'home', function + () %7B%0A%0A before @@ -451,32 +451,33 @@ oreEach(function + () %7B%0A brows @@ -496,21 +496,16 @@ x.html#/ -view1 ');%0A @@ -532,21 +532,20 @@ render -view1 +home when us @@ -565,13 +565,8 @@ to / -view1 ', f @@ -564,32 +564,33 @@ to /', function + () %7B%0A expec @@ -667,26 +667,89 @@ ch(/ -partial for view 1 +This web shop is full of AngularJS directives, services, controllers and filters. /);%0A @@ -777,21 +777,21 @@ scribe(' -view2 +about ', funct @@ -789,24 +789,25 @@ t', function + () %7B%0A%0A be @@ -815,32 +815,33 @@ oreEach(function + () %7B%0A brows @@ -860,21 +860,21 @@ x.html#/ -view2 +about ');%0A @@ -901,21 +901,21 @@ render -view2 +about when us @@ -935,13 +935,13 @@ to / -view2 +about ', f @@ -947,16 +947,17 @@ function + () %7B%0A @@ -988,33 +988,34 @@ .css('%5Bng-view%5D -p +h1 ')).first().getT @@ -1043,26 +1043,324 @@ ch(/ -partial for view 2 +About this web shop/);%0A %7D);%0A%0A %7D);%0A%0A describe('shop', function () %7B%0A beforeEach(function () %7B%0A browser.get('index.html#/shop');%0A %7D);%0A%0A it('should render shop when user navigates to /shop', function () %7B%0A expect(element.all(by.css('%5Bng-view%5D label')).first().getText())%0A .toMatch(/Filter /);%0A @@ -1363,23 +1363,22 @@ /);%0A %7D);%0A -%0A %7D);%0A%7D);%0A
e75185669f843c7074755315c310c6789ba31c26
fix for bottom border color getting reset (#7114)
src/TextField/TextFieldUnderline.js
src/TextField/TextFieldUnderline.js
import React from 'react'; import PropTypes from 'prop-types'; import transitions from '../styles/transitions'; const propTypes = { /** * True if the parent `TextField` is disabled. */ disabled: PropTypes.bool, /** * Override the inline-styles of the underline when parent `TextField` is disabled. */ disabledStyle: PropTypes.object, /** * True if the parent `TextField` has an error. */ error: PropTypes.bool, /** * Override the inline-styles of the underline when parent `TextField` has an error. */ errorStyle: PropTypes.object, /** * True if the parent `TextField` is focused. */ focus: PropTypes.bool, /** * Override the inline-styles of the underline when parent `TextField` is focused. */ focusStyle: PropTypes.object, /** * @ignore * The material-ui theme applied to this component. */ muiTheme: PropTypes.object.isRequired, /** * Override the inline-styles of the root element. */ style: PropTypes.object, }; const defaultProps = { disabled: false, disabledStyle: {}, error: false, errorStyle: {}, focus: false, focusStyle: {}, style: {}, }; const TextFieldUnderline = (props) => { const { disabled, disabledStyle, error, errorStyle, focus, focusStyle, muiTheme, style, } = props; const { color: errorStyleColor, } = errorStyle; const { prepareStyles, textField: { borderColor, disabledTextColor, errorColor, focusColor, }, } = muiTheme; const styles = { root: { borderTop: 'none', borderLeft: 'none', borderRight: 'none', borderBottom: 'solid 1px', borderColor: borderColor, bottom: 8, boxSizing: 'content-box', margin: 0, position: 'absolute', width: '100%', }, disabled: { borderBottom: 'dotted 2px', borderColor: disabledTextColor, }, focus: { borderBottom: 'solid 2px', borderColor: focusColor, transform: 'scaleX(0)', transition: transitions.easeOut(), }, error: { borderColor: errorStyleColor ? errorStyleColor : errorColor, transform: 'scaleX(1)', }, }; let underline = Object.assign({}, styles.root, style); let focusedUnderline = Object.assign({}, underline, styles.focus, focusStyle); if (disabled) underline = Object.assign({}, underline, styles.disabled, disabledStyle); if (focus) focusedUnderline = Object.assign({}, focusedUnderline, {transform: 'scaleX(1)'}); if (error) focusedUnderline = Object.assign({}, focusedUnderline, styles.error); return ( <div> <hr aria-hidden="true" style={prepareStyles(underline)} /> <hr aria-hidden="true" style={prepareStyles(focusedUnderline)} /> </div> ); }; TextFieldUnderline.propTypes = propTypes; TextFieldUnderline.defaultProps = defaultProps; export default TextFieldUnderline;
JavaScript
0
@@ -1654,24 +1654,29 @@ erBottom +Style : 'solid 1px',%0A @@ -1671,13 +1671,37 @@ olid - 1px' +',%0A borderBottomWidth: 1 ,%0A @@ -1886,16 +1886,21 @@ erBottom +Style : 'dotte @@ -1900,21 +1900,45 @@ 'dotted - 2px' +',%0A borderBottomWidth: 2 ,%0A @@ -2007,24 +2007,29 @@ erBottom +Style : 'solid 2px',%0A @@ -2024,13 +2024,37 @@ olid - 2px' +',%0A borderBottomWidth: 2 ,%0A
abef50a8ff972cf766666e94d5ad97a5545e743b
Update lib/flatiron/plugins/http.js to fix missed https {Object} option
lib/flatiron/plugins/http.js
lib/flatiron/plugins/http.js
/* * http.js: Top-level plugin exposing HTTP features in flatiron * * (C) 2011, Nodejitsu Inc. * MIT LICENSE * */ var director = require('director'), flatiron = require('../../flatiron'), union; try { // // Attempt to require union. // union = require('union'); } catch (ex) { // // Do nothing since this is a progressive enhancement // console.warn('flatiron.plugins.http requires the `union` module from npm'); console.warn('install using `npm install union`.'); console.trace(); process.exit(1); } // // Name this plugin. // exports.name = 'http'; exports.attach = function (options) { var app = this; // // Define the `http` namespace on the app for later use // app.http = app.http || {}; app.http = flatiron.common.mixin({}, app.http, options || {}); app.http.before = app.http.before || []; app.http.after = app.http.after || []; app.http.headers = app.http.headers || { 'x-powered-by': 'flatiron ' + flatiron.version }; app.router = new director.http.Router().configure({ async: true }); app.start = function (port, host, callback) { if (!callback && typeof host === 'function') { callback = host; host = null; } app.init(function (err) { if (err) { if (callback) { return callback(err); } throw err; } app.listen(port, host, callback); }); }; app.createServer = function(){ app.server = union.createServer({ after: app.http.after, before: app.http.before.concat(function (req, res) { if (!app.router.dispatch(req, res, app.http.onError || union.errorHandler)) { if (!app.http.onError) res.emit('next'); } }), headers: app.http.headers, limit: app.http.limit }); }; app.listen = function (port, host, callback) { if (!callback && typeof host === 'function') { callback = host; host = null; } app.createServer(); return host ? app.server.listen(port, host, callback) : app.server.listen(port, callback); }; };
JavaScript
0
@@ -1788,16 +1788,45 @@ tp.limit +,%0A https: app.http.https %0A %7D);
299b3004da77fcbe9230031b127d25515491e748
Fix wrap(). See note
src/core/MeshComponent.js
src/core/MeshComponent.js
import {Mesh} from 'three'; import {Component} from './Component'; import {attributes, copy, mirror} from './prototype/attributes'; import {CompositionError} from './errors'; @attributes( copy('position', 'rotation', 'quaternion', 'scale'), mirror('material', 'geometry') ) class MeshComponent extends Component { static defaults = { ...Component.defaults, build: true, geometry: {}, material: false, shadow: { cast: true, receive: true }, position: {x: 0, y: 0, z: 0}, rotation: {x: 0, y: 0, z: 0}, scale: {x: 1, y: 1, z: 1} }; static instructions = { position: ['x', 'y', 'z'], rotation: ['x', 'y', 'z'], scale: ['x', 'y', 'z'] }; // CUSTOM GEOMETRY HANDLING static custom(geom, constructor = Mesh) { return class extends MeshComponent { build(params = this.params) { const {geometry, material} = this.applyBridge({ geometry: geom, material: params.material }); return this.applyBridge({mesh: new constructor(geometry, material)}).mesh; } }; } static create(geom, params, constructor) { return new (MeshComponent.custom(geom, constructor))(params); } constructor(params, defaults = MeshComponent.defaults, instructions = MeshComponent.instructions) { super(params, defaults, instructions); if (this.params.build) { const build = this.build(this.params); if (!build) { throw new CompositionError( 'MeshComponent', '.build() method should return a THREE.Object3D or a Promise resolved with THREE.Object3D.', this ); } if (build instanceof Promise) { build.then(native => { this.native = native; this.wrap(); }); } else { this.native = build; this.wrap(); } } } // BUILDING & WRAPPING build() { throw new CompositionError( 'MeshComponent', 'Instance should have it\'s own .build().', this ); } wrap() { return new Promise(resolve => { this.defer(() => { const {position, rotation, scale, shadow} = this.params; this.position.set(position.x, position.y, position.z); this.rotation.set(rotation.x, rotation.y, rotation.z); this.scale.set(scale.x, scale.y, scale.z); this.native.castShadow = shadow.cast; this.native.receiveShadow = shadow.receive; this.applyBridge({onWrap: 1}); resolve(this); }); }); } // COPYING & CLONING copy(source) { return super.copy(source, () => { this.position.copy(source.position); this.rotation.copy(source.rotation); this.quaternion.copy(source.quaternion); }); } clone(geometry, material) { const dest = new this.constructor({build: false}).copy(this); if (geometry) dest.geometry = dest.geometry.clone(); if (material) dest.material = dest.material.clone(); return dest; } } export { MeshComponent };
JavaScript
0
@@ -2083,24 +2083,65 @@ e =%3E %7B%0A + // TODO: Fix defer with physics%0A // this.defer( @@ -2144,26 +2144,24 @@ fer(() =%3E %7B%0A - const @@ -2212,18 +2212,16 @@ arams;%0A%0A - th @@ -2275,26 +2275,24 @@ n.z);%0A - this.rotatio @@ -2330,26 +2330,24 @@ otation.z);%0A - this.s @@ -2386,26 +2386,24 @@ .z);%0A%0A - this.native. @@ -2428,18 +2428,16 @@ w.cast;%0A - th @@ -2481,26 +2481,24 @@ ive;%0A%0A - this.applyBr @@ -2523,18 +2523,16 @@ %0A%0A - resolve( @@ -2539,24 +2539,27 @@ this);%0A + // %7D);%0A %7D);
897349c097d0576377ad8ead81e89b3793974078
Update eventManager tests. Remove jest timer
src/__tests__/utils/eventManager.js
src/__tests__/utils/eventManager.js
/* eslint-env jest */ import eventManager from './../../utils/eventManager'; jest.useFakeTimers(); describe('EventManager', () => { it('Should be able to bind an event', () => { eventManager.on('foo', () => {}); expect(eventManager.list.has('foo')).toBe(true); }); it('Should be able to emit event', () => { const cb = jest.fn(); eventManager.on('foo', cb); expect(cb).not.toHaveBeenCalled(); eventManager.emit('foo'); jest.runAllTimers(); expect(cb).toHaveBeenCalled(); }); it('Should return false when trying to call unbound event', () => { const id = eventManager.emit('bar'); jest.runAllTimers(); expect(id).toBe(false); }); it('Should be able to remove event', () => { eventManager.on('foo', () => {}); expect(eventManager.list.size).toBe(1); eventManager.off('foo'); expect(eventManager.list.size).toBe(0); }); });
JavaScript
0
@@ -75,31 +75,8 @@ ';%0A%0A -jest.useFakeTimers();%0A%0A desc @@ -429,33 +429,8 @@ ');%0A - jest.runAllTimers();%0A @@ -582,33 +582,8 @@ ');%0A - jest.runAllTimers();%0A
49caad8bc465a630ae0478f3150a29cbfa55a485
Refactor of through
src/gulp-phantomcss.js
src/gulp-phantomcss.js
var path = require('path'); var through2Concurrent = require('through2-concurrent'); var gutil = require('gulp-util'); var PluginError = gutil.PluginError; var _ = require('lodash'); module.exports.configure = function (config) { this.paths = config.paths; this.phantom = config.phantom; return this; }; module.exports.through = function (args) { if (_.isString(args)) { var screenshotDir = args; args = {}; args.screenshots = screenshotDir; } args = _.extend({ screenshots: 'screenshots', results: 'results', viewportSize: [1280, 800], logLevel: 'error' }, args || {}); args.paths = this.paths; var phantom = this.phantom; var error = 0; function endStream(file, cb) { if (args.breakOnError && error > 0) { return this.emit('error', new PluginError( 'gulp-phantomcss', 'Some tests have failed.' )); } this.emit('end'); } return through2Concurrent.obj( {maxConcurrency: 10}, function (file, enc, cb) { if (file.isStream()) { return this.emit('error', new PluginError( 'gulp-phantomcss', 'Streaming not supported' )); } args.test = path.resolve(file.path); phantom(args.paths.runnerjs, args) .on('exit', function (fail) { if (fail) { error++; } cb(null, file); }); }, endStream); };
JavaScript
0.000001
@@ -701,289 +701,17 @@ ion -endStream(file, cb) %7B%0A if (args.breakOnError && error %3E 0) %7B%0A return this.emit('error', new PluginError(%0A 'gulp-phantomcss', 'Some tests have failed.'%0A ));%0A %7D%0A this.emit('end');%0A %7D%0A%0A return through2Concurrent.obj(%0A %7BmaxConcurrency: 10%7D,%0A function +transform (fil @@ -723,15 +723,19 @@ c, c -b +allback ) %7B%0A - @@ -763,18 +763,16 @@ %7B%0A - return t @@ -806,18 +806,16 @@ nError(%0A - @@ -869,18 +869,16 @@ - - ));%0A %7D%0A @@ -869,30 +869,27 @@ ));%0A - %7D%0A +%7D%0A%0A args.tes @@ -922,18 +922,16 @@ );%0A%0A - phantom( @@ -963,18 +963,16 @@ )%0A - - .on('exi @@ -1001,18 +1001,16 @@ - if (fail @@ -1009,26 +1009,24 @@ if (fail) %7B%0A - er @@ -1040,18 +1040,16 @@ - %7D%0A @@ -1054,12 +1054,16 @@ - cb +callback (nul @@ -1082,30 +1082,295 @@ - %7D);%0A %7D, endStream +%7D);%0A %7D%0A%0A function flush() %7B%0A if (args.breakOnError && error %3E 0) %7B%0A return this.emit('error', new PluginError(%0A 'gulp-phantomcss', 'Some tests have failed.'%0A ));%0A %7D%0A this.emit('end');%0A %7D%0A%0A return through2Concurrent.obj(%7BmaxConcurrency: 10%7D, transform, flush );%0A%7D
2c69c82222a6ba070b1c78a68f5ee10682bd3dc6
Fix purchase confirmation decimal points
src/_common/PurchaseConfirmation.js
src/_common/PurchaseConfirmation.js
import React, { PropTypes } from 'react'; import { FormattedTime } from 'react-intl'; import { epochToDate } from '../_utils/DateUtils'; import { M } from '../_common'; const PurchaseConfirmation = ({ receipt }) => ( <div> <table> <tbody> <tr> <td colSpan="2"> {receipt.longcode} </td> </tr> <tr> <td><M m="Purchase Price" /></td> <td>{receipt.buy_price}</td> </tr> <tr> <td><M m="Purchase Time" /></td> <td> <FormattedTime value={epochToDate(receipt.purchase_time)} format="full" /> </td> </tr> <tr> <td><M m="Balance" /></td> <td>{receipt.balance_after}</td> </tr> </tbody> </table> <br/> <button><M m="Back" /></button> </div> ); PurchaseConfirmation.propTypes = { proposal: PropTypes.object, }; export default PurchaseConfirmation;
JavaScript
0.999999
@@ -140,16 +140,29 @@ port %7B M +, NumberPlain %7D from @@ -241,16 +241,105 @@ %3Ctable%3E%0A +%09%09%09%3Cthead%3E%0A%09%09%09%09%3Cth colSpan=%222%22%3E%7B%60Contract Ref. $%7Breceipt.contract_id%7D%60%7D%3C/th%3E%0A%09%09%09%3C/thead%3E%0A %09%09%09%3Ctbod @@ -708,32 +708,58 @@ %3E%3C/td%3E%0A%09%09%09%09%09%3Ctd%3E +%0A%09%09%09%09%09%09%3CNumberPlain value= %7Breceipt.balance @@ -765,16 +765,25 @@ e_after%7D + /%3E%0A%09%09%09%09%09 %3C/td%3E%0A%09%09
5ea844e19a2e936f9f1520fecc581dcc868c05ca
Use sensible defaults for trace signature and type
lib/instrumentation/trace.js
lib/instrumentation/trace.js
'use strict' var asyncState = require('../async-state') var Trace = module.exports = function (transaction, signature, type) { this.transaction = transaction this.signature = signature this.type = type this.ended = false this._stackPrevStarted = asyncState.lastTransactionTraceStarted asyncState.lastTransactionTraceStarted = this this._client = transaction._client this._start = new Date() this._hrtime = process.hrtime() } Trace.prototype.end = function () { this._diff = process.hrtime(this._hrtime) this.ended = true this.transaction._endTrace(this) } Trace.prototype.duration = function () { if (!this.ended) { this._client.logger.error('Trying to call trace.duration() on un-ended Trace!') return null } var ns = this._diff[0] * 1e9 + this._diff[1] return ns / 1e6 } Trace.prototype.startTime = function () { if (!this.ended || !this.transaction.ended) { this._client.logger.error('Trying to call trace.startTime() for un-ended Trace/Transaction!') return null } var parent = this._parent() if (!parent) return 0 var start = parent._hrtime var ns = (this._hrtime[0] - start[0]) * 1e9 + (this._hrtime[1] - start[1]) return ns / 1e6 } Trace.prototype.ancestors = function () { if (!this.ended || !this.transaction.ended) { this._client.logger.error('Trying to call trace.ancestors() for un-ended Trace/Transaction!') return null } var parent = this._parent() if (!parent) return [] return parent.ancestors().concat(parent.signature) } Trace.prototype._parent = function () { var prev = this._stackPrevStarted while (prev) { if (prev.ended && prev._endOrder > this._endOrder) return prev prev = prev._stackPrevStarted } return null }
JavaScript
0
@@ -183,16 +183,29 @@ ignature + %7C%7C 'unknown' %0A this. @@ -215,16 +215,29 @@ e = type + %7C%7C 'unknown' %0A this.
94d3596f93da57cc03b8612129ae99c74645962a
reset offest properly (scope!)
src/historicBGPData.js
src/historicBGPData.js
/*jslint node:true, bitwise:true */ var Q = require('q'); var fs = require('fs'); var http = require('http'); var chalk = require('chalk'); var readline = require('linebyline'); var spawn = require('child_process').spawn; var moment = require('moment'); // Take a line of the origin RIB file and load it into a hash map. // Map format is {start -> {cidr -> asn}} var offsets = [0, 0], parseASLine, asnRegex = /(\d+) [ie]$/; var parseRIBLine = function (seen, map, line) { 'use strict'; var networkSlash = line.indexOf("/", offsets[0]), networkEnd = line.indexOf(" ", networkSlash), network, asn; if (networkEnd < 0) { return; } network = line.substring(offsets[0], networkEnd); if (seen[network]) { return; } else { seen[network] = true; } network = new Buffer(network.substr(0, networkSlash - offsets[0]).split('.')).readUInt32BE(0); asn = asnRegex.exec(line.substr(offsets[1])); if (asn) { map[network + line.substring(networkSlash, networkEnd)] = parseInt(asn[1], 10); } }; var parseRIBHeader = function (map, line) { 'use strict'; var net = line.indexOf("Network"), path = line.indexOf("Path"); if (net > 0 && path > 0) { offsets = [net, path]; console.log(chalk.blue("Header parameters learned: " + net + ", " + path)); } }; parseASLine = function (s, m, l) { 'use strict'; if (offsets[0] === 0) { parseRIBHeader(m, l); } else { parseRIBLine(s, m, l); } }; // Download IP 2 AS Mapping. var loadIP2ASMap = function (when) { 'use strict'; var roundedTime = moment(when).startOf('hour'), url; roundedTime.hour(roundedTime.hour() - (roundedTime.hour() % 2)); url = roundedTime.format("[http://archive.routeviews.org/oix-route-views/]YYYY.MM/[oix-full-snapshot-]YYYY-MM-DD-HHmm[.bz2]"); console.log(chalk.blue(roundedTime.format("[Downloading IP -> ASN Map for] MMM D, YYYY"))); return Q.Promise(function (resolve, reject) { var download = fs.createWriteStream('rib.bz2'); http.get(url, function (res) { res.pipe(download); res.on('end', function () { if (fs.existsSync('rib')) { fs.unlinkSync('rib'); } console.log(chalk.blue("Decompressing...")); // Note: We download the file and use the external bunzip2 utility // because the node seek-bzip and alternative JS native // implementations are orders of magnitude slower, and make this // a process which can't actually be done in a sane manner. var decompression = spawn('bunzip2', ['rib.bz2']); decompression.on('close', function (code) { if (code !== 0) { console.warn(chalk.red("Decompression failed:" + code)); reject(code); } else { console.log(chalk.green("Done.")); resolve('rib'); } }); }).on('error', function (err) { console.warn(chalk.red("Download Failed:" + err)); reject(err); }); }); }); }; var parseIP2ASMap = function (path) { 'use strict'; var seen = {}, map = {}; console.log(chalk.blue("Parsing IP -> ASN Map")); return Q.promise(function (resolve, reject) { var rl = readline(path); rl.on('line', parseASLine.bind({}, seen, map)) .on('end', function () { console.log(chalk.green("Done.")); resolve(map); }) .on('error', function (err) { console.warn(chalk.red("ASN -> Country Map failed:" + err)); reject(err); }); }); }; exports.loadIP2ASMap = loadIP2ASMap; exports.parseIP2ASMap = parseIP2ASMap;
JavaScript
0
@@ -365,43 +365,8 @@ var -offsets = %5B0, 0%5D,%0A parseASLine,%0A asnR @@ -417,16 +417,25 @@ nction ( +offsets, seen, ma @@ -1035,16 +1035,25 @@ nction ( +offsets, map, lin @@ -1286,16 +1286,21 @@ %0A %7D%0A%7D;%0A +%0Avar parseASL @@ -1315,16 +1315,19 @@ nction ( +c, s, m, l) @@ -1351,23 +1351,17 @@ ;%0A if ( -offsets +c %5B0%5D === @@ -1384,16 +1384,19 @@ BHeader( +c, m, l);%0A @@ -1422,16 +1422,19 @@ RIBLine( +c, s, m, l) @@ -3042,16 +3042,31 @@ ';%0A var + conf = %5B0, 0%5D, seen = @@ -3247,16 +3247,22 @@ bind(%7B%7D, + conf, seen, m
1c95a05ad333791a130ca090be9b0068a05d8085
fix unit test
test/purchasing/unit-receipt-note/validator.js
test/purchasing/unit-receipt-note/validator.js
var helper = require("../../helper"); var validator = require('dl-models').validator.master; var validatorPurchasing = require('dl-models').validator.purchasing; var UnitReceiptNoteManager = require("../../../src/managers/purchasing/unit-receipt-note-manager"); var unitReceiptNoteManager = null; var unitReceiptNote = require("../../data-util/purchasing/unit-receipt-note-data-util"); var StorageManager = require("../../../src/managers/master/storage-manager"); var storageManager = null; var storage = require("../../data-util/master/storage-data-util"); require("should"); before('#00. connect db', function (done) { helper.getDb() .then(db => { unitReceiptNoteManager = new UnitReceiptNoteManager(db, { username: 'unit-test' }); storageManager = new StorageManager(db, { username: 'unit-test' }); done(); }) .catch(e => { done(e); }) }); var storageData; var storageDataId; it('#01. should success when create new data', function (done) { storage.getNewData() .then((data) => storageManager.create(data)) .then((id) => { storageManager.getSingleById(id) .then((data) => { storageData=data; }); id.should.be.Object(); storageDataId = id; done(); }) .catch((e) => { done(e); }); }); var createdData; it('#02. should success when create new data with storage', function (done) { unitReceiptNote.getNewData() .then((data) => { data.storageId=storageDataId; data.unit=storageData.unit; data.isInventory=true; unitReceiptNoteManager.create(data) .then((id) => { id.should.be.Object(); var createdId = id; done(); }) }) .catch((e) => { done(e); }); }); it('#03. should error when create new data isInventory=true without storage', function (done) { unitReceiptNote.getNewData() .then(data => { data.isInventory=true; unitReceiptNoteManager.create(data) .then(id => { done("should error when create new data isInventory=true without storage"); }) .catch(e => { try { e.errors.should.have.property('storage'); done(); } catch (ex) { done(ex); } }); }) .catch(e => { done(e); }); }); it('#04. should error when create new data without deliveryOrderId, unitId, supplierId', function (done) { unitReceiptNote.getNewData() .then(data => { data.deliveryOrder._id=null; data.unit._id=null; data.supplier._id=null; unitReceiptNoteManager.create(data) .then(id => { done("should error when create new data without deliveryOrderId, unitId, supplierId"); }) .catch(e => { try { e.errors.should.have.property('deliveryOrder'); e.errors.should.have.property('unit'); e.errors.should.have.property('supplier'); done(); } catch (ex) { done(ex); } }); }) .catch(e => { done(e); }); }); it('#05. should error when create new data with date < deliveryOrderDate', function (done) { unitReceiptNote.getNewData() .then(data => { var today = new Date(); var yesterday = new Date(today); yesterday.setDate(today.getDate() - 1); data.deliveryOrder.date=today; data.date=yesterday; unitReceiptNoteManager.create(data) .then(id => { done("should error when create new data with date < deliveryOrderDate"); }) .catch(e => { try { e.errors.should.have.property('date'); done(); } catch (ex) { done(ex); } }); }) .catch(e => { done(e); }); }); it('#06. should error when create new data without items', function (done) { unitReceiptNote.getNewData() .then(data => { data.items=[]; unitReceiptNoteManager.create(data) .then(id => { done("should error when create new data without items"); }) .catch(e => { try { e.errors.should.have.property('items'); done(); } catch (ex) { done(ex); } }); }) .catch(e => { done(e); }); }); it('#07. should error when create new data with deliveredQuantity=0', function (done) { unitReceiptNote.getNewData() .then(data => { data.items[0].deliveredQuantity=0; unitReceiptNoteManager.create(data) .then(id => { done("should error when create new data with deliveredQuantity=0"); }) .catch(e => { try { e.errors.should.have.property('items'); done(); } catch (ex) { done(ex); } }); }) .catch(e => { done(e); }); }); it('#08. should error when create new data with storage.unit != data.unit', function (done) { unitReceiptNote.getNewData() .then(data => { data.unit.code="a"; unitReceiptNoteManager.create(data) .then(id => { done("should error when create new data with storage.unit != data.unit"); }) .catch(e => { try { e.errors.should.have.property('storage'); done(); } catch (ex) { done(ex); } }); }) .catch(e => { done(e); }); });
JavaScript
0.000001
@@ -6313,16 +6313,80 @@ +data.storageId=storageDataId;%0A data.isInventory=true; %0A%0A
937e1d9b136ff5adbcbec3406cbd7aa3babb91c6
Fix tests
test/resources/6_setup.js
test/resources/6_setup.js
var fs = require('fs'); var assert = require('assert'); var restify = require('restify'); var client = require('../client'); var settings = require('../../lib/settings.js'); describe('Resource:', function() { describe('Setup:', function() { it('should the database connection', function(done) { client.post('/setup/connection-test/', {uri: 'tcp://shinuza@localhost/shinuza'}, function(err, req, res) { assert.ifError(err); assert.equal(res.statusCode, 200); done(); }); }); it('should create a user', function(done) { client.post('/setup/user-creation', {username: 'foo', password: 'bar'}, function(err, req, res, json) { assert.ifError(err); assert.equal(res.statusCode, 201); done(); }); }); it('should generate the settings-file', function(done) { client.post('/setup/commit', function(err, req, res) { assert.ifError(err); assert.equal(res.statusCode, 201); assert.equal(fs.existsSync(settings.path(settings.DEFAULT_FILENAME)), false); done(); }); }); it('should create the tables', function(done) { var client = restify.createStringClient({ url: 'http://localhost:' + settings.get('PORT') }); client.get('/setup/table-creation', function(err, req, res) { assert.ifError(err); assert.equal(res.headers['content-type'], "text/event-stream; charset=utf-8"); client.close(); done(); }); }); }); });
JavaScript
0.000003
@@ -16,16 +16,44 @@ e('fs'); +%0Avar path = require('path'); %0A%0Avar as @@ -810,32 +810,37 @@ %0A %7D);%0A%0A it +.only ('should generat @@ -1050,22 +1050,33 @@ ync( -settings.path( +path.join(process.cwd(), sett @@ -1104,15 +1104,29 @@ )), -false); +true);%0A assert %0A
1839c7117a226f1dc390d5d6bdcfc6a33dacb195
remove unused variable
lib/model/breakpointModel.js
lib/model/breakpointModel.js
'use strict' 'use babel' const Breakpoint = require('thera-debug-common-types').Breakpoint const {COMMAND} = require('thera-debug-common-types').Payload const {Emitter, Disposable} = require('atom') module.exports = class BreakpointModel { constructor (service) { this.breakpoints = [] this.emitter = new Emitter() this.disposable = new Disposable(service.onPaused(this._serviceHandler.bind(this))) this.service = service this.selectedId = undefined } _serviceHandler (payload) { if (payload.command === COMMAND.RESOLVE_BREAKPOINT) { let breakpoint = payload.breakpoint let breakpointExist = this.getBreakpointById(breakpoint.id) if (!breakpointExist) { this.breakpoints.push(breakpoint) this.emitter.emit('did-change', {command: BreakpointModel.command().ADD, value: breakpoint}) } else { breakpointExist.enable = breakpoint.enable this.emitter.emit('did-change', {command: BreakpointModel.command().ACTIVATE, value: breakpoint}) } } else if (payload.command === COMMAND.REMOVE_BREAKPOINT) { this.removeBreakpointByPath(payload.path, payload.line, true) } } static command () { return Object.freeze({ADD: 0, REMOVE: 1, ACTIVATE: 2, SELECT: 3}) } getBreakpoints () { return this.breakpoints } getBreakpointsByFile (filePath) { return this.breakpoints.filter((ele) => ele.path === filePath) } observeBreakpoints (callback) { if (this.breakpoints.length > 0) { callback(this) } return this.emitter.on('did-change', callback) } addBreakpoint (file, line) { this.service.setBreakpoint(file, line) } removeBreakpointById (id, callByService = false) { if (id === this.selectedId) { this.selectedId = undefined } let tobeRemoved, element this.breakpoints.forEach((ele, index) => { if (ele.id === id) { tobeRemoved = index element = ele } }) if (tobeRemoved !== undefined) { // service correct breakpoint do not need call back to service. if (!callByService) { this.service.removeBreakpoint(element.path, element.line) } var breakpointRemove = this.breakpoints.splice(tobeRemoved, 1)[0] this.emitter.emit('did-change', {command: BreakpointModel.command().REMOVE, value: breakpointRemove}) } } removeBreakpointByPath (path, line, callByService = false) { let breakpoint = this.breakpoints.filter((ele) => ele.path === path && ele.line === line)[0] if (breakpoint) { this.removeBreakpointById(breakpoint.id, callByService) } } setBreakpointActive (id, active) { let breakpoint this.breakpoints.forEach((ele) => { if (ele.id === id) { breakpoint = ele } }) if (breakpoint) { // breakpoint.enable = active // if (active) { // // TODO replace breakpoint // this.service.setBreakpoint(breakpoint.path, breakpoint.line) // } else { // this.service.removeBreakpoint(breakpoint.id) // } this.service.setBreakpoint(breakpoint.path, breakpoint.line, active) // this.emitter.emit('did-change', {command: BreakpointModel.command().ACTIVATE, value: breakpoint}) } } getBreakpointById (id) { let breakpoint = this.breakpoints.filter((ele) => ele.id === id)[0] return breakpoint } getBreakpointsByPath (path, line) { let breakpoints = this.breakpoints .filter((ele) => ele.path === path && ele.line === line) return breakpoints } setSelectedId (id) { this.selectedId = id this.emitter.emit('did-change', {command: BreakpointModel.command().SELECT, value: id}) } destroy () { this.emitter.dispose() this.disposable.dispose() } }
JavaScript
0.00003
@@ -23,74 +23,8 @@ l'%0A%0A -const Breakpoint = require('thera-debug-common-types').Breakpoint%0A cons
ebdd42a863a6a95b7d2cf176401b1c4c6489d6d5
Throw instead of assert.fail
src/create-client.test.js
src/create-client.test.js
import { strict as assert } from 'assert'; import createClient from './create-client.js'; export default { simple: () => { const client = createClient(); const events = []; const onChange = data => events.push(data); client.watch({ onChange }); client.watch({ query: { foo: {} }, onChange }); client.watch({ query: { dne: {} }, onChange: () => assert.fail('Should not have been called') }); client.update({ data: { _type: null, foo: 123 }, query: { _type: {}, foo: {} } }); client.update({ data: { _type: null, foo: 123 }, query: { _type: {}, foo: {} } }); assert.deepEqual(events, [ { _root: { _type: null, foo: 123 } }, { _type: null, foo: 123 } ]); }, 'cancel watching': () => { const client = createClient(); const events = []; const onChange = data => events.push(data); const { unwatch } = client.watch({ onChange }); client.update({ data: { foo: 123 }, query: { foo: {} } }); unwatch(); client.update({ data: { foo: 456 }, query: { foo: {} } }); assert.deepEqual(events, [{ _root: { foo: 123 } }]); }, 'ref changes': () => { const client = createClient({ getKey: ({ _type }) => _type }); const events = []; const onChange = data => events.push(data); client.watch({ query: { foo: { id: {} } }, onChange }); client.watch({ query: { _key: { _args: { arg: 1 }, id: {}, name: {} } }, onChange }); client.update({ data: { _type: 'Root', _key: { _type: 'Foo:1' }, foo: { _type: 'Foo:1', id: 1, name: 'foo' } }, query: { _type: {}, _key: { _args: { arg: 1 }, _type: {} }, foo: { _type: {}, id: {}, name: {} } } }); client.cacheUpdate({ data: { 'Foo:1': { _type: 'Foo:1', id: 2 } } }); client.cacheUpdate({ data: { 'Foo:1': { _type: 'Foo:1', name: 'FOO' } } }); assert.deepEqual(events, [ { _type: 'Root', foo: { _type: 'Foo:1', id: 1 } }, { _type: 'Root', _key: { _type: 'Foo:1', id: 1, name: 'foo' } }, { _type: 'Root', foo: { _type: 'Foo:1', id: 2 } }, { _type: 'Root', _key: { _type: 'Foo:1', id: 2, name: 'foo' } }, { _type: 'Root', _key: { _type: 'Foo:1', id: 2, name: 'FOO' } } ]); }, 'arg ref changes': () => { const client = createClient({ getKey: ({ _type, id }) => _type === 'Root' ? 'Root' : _type && id ? `${_type}:${id}` : null }); const events = []; const onChange = data => events.push(data); client.watch({ query: { foo: { _args: { id: 1 }, _type: {}, id: {}, name: {} } }, onChange }); client.update({ data: { _type: 'Root', foo: { _type: 'Foo', id: 1, name: 'foo' } }, query: { _type: {}, id: {}, foo: { _args: { id: 1 }, _type: {}, id: {}, name: { _type: {}, id: {} } } } }); assert.deepEqual(events, [ { _type: 'Root', foo: { _type: 'Foo', id: 1, name: 'foo' } } ]); } };
JavaScript
0.000438
@@ -381,19 +381,33 @@ =%3E -assert.fail +%7B%0A throw new Error ('Sh @@ -433,16 +433,25 @@ called') +;%0A %7D %0A %7D);
7ef660b4a314b0fd04dbc90e3d2231ece5d1b3e6
Update tests according to the latest breaking changes
src/input-tags.spec.js
src/input-tags.spec.js
describe('Module: angularjs-input-tags -', () => { let $componentController; beforeEach(angular.mock.module('angularjs-input-tags')); beforeEach(angular.mock.inject(_$componentController_ => { $componentController = _$componentController_; })); describe('Component: inputTags -', () => { let ctrl; beforeEach(() => { ctrl = $componentController('inputTags', { $element: angular.element('<div></div>') }, { onTagAdding: jasmine.createSpy('onTagAdding'), onTagRemoving: jasmine.createSpy('onTagRemoving') }); }); describe('Event: onTagAdding', () => { it('should be emit', () => { ctrl.$onInit(); ctrl.addTag({code: 1, text: '1'}); expect(ctrl.onTagAdding).toHaveBeenCalled(); }); it('should be emit with formatted tag value', () => { ctrl.$onInit(); ctrl.addTag({code: 1, text: '1'}); expect(ctrl.onTagAdding).toHaveBeenCalledWith({code: 1, text: '1'}); }); }); it('should add tag on list', () => { ctrl.$onInit(); ctrl.addTag({code: 1, text: '1'}); expect(ctrl.tags).toContain({code: 1, text: '1'}); }); it('should update tag list', () => { ctrl.$onInit(); ctrl.addTag({code: 1, text: '1'}); ctrl.addTag({code: 1, text: '1'}); ctrl.addTag({code: 1, text: '1'}); expect(ctrl.tags.length).toBe(1); }); it('should display autocomplete on focus', () => { ctrl.$onInit(); ctrl.triggerFocus(); expect(ctrl.autocompleteVisible).toBe(true); }); it('should hide autocomplete on blur', () => { ctrl.$onInit(); ctrl.triggerBlur(); expect(ctrl.autocompleteVisible).toBe(false); }); it('should emit `onTagRemoving` event', () => { ctrl.$onInit(); ctrl.tags = ['Demo']; ctrl.removeTag({code: 1, text: '1'}); expect(ctrl.onTagRemoving).toHaveBeenCalled(); expect(ctrl.onTagRemoving).toHaveBeenCalledWith({code: 1, text: '1'}); }); it('should remove matching element by code', () => { ctrl.$onInit(); ctrl.tags.length = 0; ctrl.addTag({code: 1, text: '1'}); ctrl.removeTag({code: 1}); expect(ctrl.tags.length).toBe(0); }); it('should reset the tag list', () => { ctrl.$onInit(); expect(ctrl.path.length).toBe(0); }); it('should go to the selected element in the tree', () => { ctrl.$onInit(); const pathLength = ctrl.path.length; ctrl.next('subLevel'); expect(ctrl.path.length).toBe(pathLength + 1); }); it('should back to the previous element in the tree when on the root', () => { ctrl.$onInit(); ctrl.path = []; ctrl.previous(); expect(ctrl.path.length).toBe(0); }); it('should back to the previous element in the tree when in 2 sublevels', () => { ctrl.$onInit(); ctrl.next('subLevel'); ctrl.next('subSubLevel'); ctrl.previous(); expect(ctrl.path.length).toBe(1); }); }); });
JavaScript
0
@@ -957,32 +957,38 @@ eBeenCalledWith( +%7Btag: %7Bcode: 1, text: @@ -983,32 +983,33 @@ e: 1, text: '1'%7D +%7D );%0A %7D);%0A @@ -1996,16 +1996,22 @@ ledWith( +%7Btag: %7Bcode: 1 @@ -2014,32 +2014,33 @@ e: 1, text: '1'%7D +%7D );%0A %7D);%0A%0A
8289cc5c585b6e816b6a3c95949ec6dc3bb10229
fix test cases
server/test/test.js
server/test/test.js
var assert = require('assert') , jrs = require('jsonrpc-serializer') , Handler = require('../lib/p2p-rpc') , sse = require('../lib/sse'); function CheckRes(fn) { this.json = fn; } function CheckSseRes(fn) { this.send = fn; } function mockPost(jstring) { return { type: 'POST', body: JSON.parse(jstring) }; } function mockGet(jstring) { return { type: 'GET', query: { q: jstring } }; } describe('sse', function() { var cases = [ 'oh my god', 'oh my god\noh my baby', 'oh my god\noh my baby\n' ]; it('#send & #parse', function(done) { var finished = 0; for (var i in cases) { (function(c) { sse.send(c, function(data) { assert.equal(sse.parse(data), c); finished++; if (finished == cases.length) done(); }); })(cases[i]); } }); }); describe('simple-rpc-call', function() { var handler = new Handler().handler; describe('request & response', function() { it('should receive a reponse', function(done) { var resCount = 0; function checkDone() { if (resCount == 5) done(); } // peerId: id2, recv request & send response var longReq = jrs.notification('wait_request', { peerId: 'id2' }); handler(mockGet(longReq), new CheckSseRes(function(data) { var obj = jrs.deserialize(sse.parse(data)); assert.equal(obj.type, 'notification'); assert.equal(obj.payload.method, 'forward_request'); assert.equal(obj.payload.params.peerId, 'id1'); assert.equal(obj.payload.params.remoteId, 'id2'); assert.equal(obj.payload.params.request, 'Hello World!'); resCount++; var res = jrs.notification('response', { peerId: 'id2', remoteId: 'id1', id: obj.payload.params.id, response: 'Hello Sb!' }); handler(mockPost(res), new CheckRes(function(code, data) { assert.equal(code, 200); var obj = jrs.deserializeObject(data); assert.equal(obj.type, 'notification'); assert.equal(obj.payload.method, 'responseSuccess'); resCount++; checkDone(); })); })); // peerId: id3, recv notification var longReq2 = jrs.notification('wait_request', { peerId: 'id3' }); handler(mockGet(longReq2), new CheckSseRes(function(data) { var obj = jrs.deserialize(sse.parse(data)); assert.equal(obj.type, 'notification'); assert.equal(obj.payload.method, 'forward_notification'); assert.equal(obj.payload.params.peerId, 'id1'); assert.equal(obj.payload.params.remoteId, 'id3'); assert.equal(obj.payload.params.notification, 'Admire You'); resCount++; checkDone(); })); // peerId: id1, send request & recv response var req = jrs.request('test_id', 'request', { peerId: 'id1', remoteId: 'id2', request: 'Hello World!' }); handler(mockPost(req), new CheckRes(function(code, data) { assert.equal(code, 200); var obj = jrs.deserializeObject(data); assert.equal(obj.type, 'success'); assert.equal(obj.payload.id, 'test_id'); assert.equal(obj.payload.result.peerId, 'id2'); assert.equal(obj.payload.result.remoteId, 'id1'); assert.equal(obj.payload.result.response, 'Hello Sb!'); resCount++; checkDone(); })); var req2 = jrs.notification('notification', { peerId: 'id1', remoteId: 'id3', notification: 'Admire You' }); handler(mockPost(req2), new CheckRes(function(code, data) { assert.equal(code, 200); var obj = jrs.deserializeObject(data); assert.equal(obj.type, 'notification'); assert.equal(obj.method, 'forwardSuccess'); resCount++; checkDone(); })); }); }); }); describe('invalid_request', function() { var handler = new Handler().handler; var reqs = [ JSON.stringify({ admire: 'Hello World' }), jrs.request('test_id', 'HelloWorld', ['Oh my baby']), jrs.notification('HelloWorld', ['Oh my baby']), jrs.success('test_id', ['Oh my baby']), JSON.stringify(jrs.errorObject('test_id', { code: -32000, message: 'oh my baby' })) ]; var fns = [mockGet, mockPost]; for (var i in reqs) { var req = reqs[i]; for (var j in fns) { var fn = fns[j]; it ('request' + i + ':' + j, function(done) { handler(fn(req), new CheckRes(function(code, data) { assert.notEqual(code, 200); done(); })); }); } } }); describe('auth', function() { var handler = new Handler().auth(function(id, authInfo) { return id == authInfo; }).handler; var reqs = [ jrs.request('test_id', 'request', { peerId: 'id1', remoteId: 'id2', authInfo: 'id001', request: 'Hello World' }), jrs.notification('response', { peerId: 'id1', remoteId: 'id2', authInfo: 'id001', response: 'Hello Sb' }), jrs.notification('wait_request', { peerId: 'id1', authInfo: 'id001' }) ]; var fns = [mockGet, mockPost]; describe('#1', function() { for (var i in reqs) { var req = reqs[i]; for (var j in fns) { var fn = fns[j]; it('should be rejected', function(done) { handler(fn(req), new CheckRes(function(code, data) { assert.equal(code, 401); done(); })); }); }; } }); });
JavaScript
0.000013
@@ -2758,28 +2758,23 @@ .params. -notification +request , 'Admir @@ -3532,28 +3532,23 @@ cation(' -notification +request ', %7B%0A @@ -3600,28 +3600,23 @@ -notification +request : 'Admir @@ -3852,16 +3852,24 @@ ual(obj. +payload. method, @@ -3869,23 +3869,28 @@ ethod, ' -forward +notification Success'
661e3b3c8b021b1a9a4c6f09a61121e55a5d4209
Set model body during a DELETE request. Refs #70.
servers/Route.bones
servers/Route.bones
var path = require('path'); var env = process.env.NODE_ENV || 'development'; var headers = { 'Content-Type': 'application/json' }; server = Bones.Server.extend({}); var options = { type: '.js', wrapper: Bones.utils.wrapClientFile, sort: Bones.utils.sortByLoadOrder }; // TODO: This should be moved to the initialize method! server.prototype.assets = { vendor: new mirror([ require.resolve(path.join(__dirname, '../assets/jquery')), require.resolve('underscore'), require.resolve('backbone') ], { type: '.js' }), core: new mirror([ require.resolve(path.join(__dirname, '../shared/utils')), require.resolve(path.join(__dirname, '../client/utils')), require.resolve(path.join(__dirname, '../shared/backbone')), require.resolve(path.join(__dirname, '../client/backbone')) ], { type: '.js' }), models: new mirror([], options), views: new mirror([], options), routers: new mirror([], options), templates: new mirror([], options) }; if (env === 'development') { server.prototype.assets.core.unshift(require.resolve(path.join(__dirname, '../assets/debug'))); } // TODO: This should be moved to the initialize method! server.prototype.assets.all = new mirror([ server.prototype.assets.vendor, server.prototype.assets.core, server.prototype.assets.routers, server.prototype.assets.models, server.prototype.assets.views, server.prototype.assets.templates ], { type: '.js' }); // Stores models, views served by this server. // TODO: This should be moved to the initialize method! server.prototype.models = {}; server.prototype.views = {}; // Stores instances of routers registered with this server. // TODO: This should be moved to the initialize method! server.prototype.routers = {}; server.prototype.initialize = function(app) { this.registerComponents(app); this.initializeAssets(app); this.initializeModels(app); }; server.prototype.registerComponents = function(app) { var components = ['routers', 'models', 'views', 'templates']; components.forEach(function(kind) { for (var name in app[kind]) { app[kind][name].register(this); } }, this); }; server.prototype.initializeAssets = function(app) { this.get('/assets/bones/vendor.js', this.assets.vendor.handler); this.get('/assets/bones/core.js', this.assets.core.handler); this.get('/assets/bones/routers.js', this.assets.routers.handler); this.get('/assets/bones/models.js', this.assets.models.handler); this.get('/assets/bones/views.js', this.assets.views.handler); this.get('/assets/bones/templates.js', this.assets.templates.handler); this.get('/assets/bones/all.js', this.assets.all.handler); }; server.prototype.initializeModels = function(app) { this.models = app.models; _.bindAll(this, 'loadModel', 'getModel', 'saveModel', 'delModel', 'loadCollection'); this.get('/api/:model/:id', [this.loadModel, this.getModel]); this.post('/api/:model', [this.loadModel, this.saveModel]); this.put('/api/:model/:id', [this.loadModel, this.saveModel]); this.del('/api/:model/:id', [this.loadModel, this.delModel]); this.get('/api/:collection', this.loadCollection.bind(this)); }; server.prototype.loadCollection = function(req, res, next) { var name = Bones.utils.pluralize(req.params.collection); if (name in this.models) { // Pass any querystring paramaters to the collection. req.collection = new this.models[name]([], req.query); req.collection.fetch({ success: function(collection, resp) { res.send(resp, headers); }, error: function(collection, err) { var error = err instanceof Object ? err.message : err; next(new Error.HTTP(error, err && err.status || 500)); } }); } else { next(); } }; server.prototype.loadModel = function(req, res, next) { var name = req.params.model; if (name in this.models) { // Pass any querystring paramaters to the model. req.model = new this.models[name]({ id: req.params.id }, req.query); } next(); }; server.prototype.getModel = function(req, res, next) { if (!req.model) return next(); req.model.fetch({ success: function(model, resp) { res.send(resp, headers); }, error: function(model, err) { var error = err instanceof Object ? err.message : err; next(new Error.HTTP(error, err && err.status || 404)); } }); }; server.prototype.saveModel = function(req, res, next) { if (!req.model) return next(); req.model.save(req.body, { success: function(model, resp) { res.send(resp, headers); }, error: function(model, err) { var error = err instanceof Object ? err.message : err; next(new Error.HTTP(error, err && err.status || 409)); } }); }; server.prototype.delModel = function(req, res, next) { if (!req.model) return next(); req.model.destroy({ success: function(model, resp) { res.send(resp, headers); }, error: function(model, err) { var error = err instanceof Object ? err.message : err; next(new Error.HTTP(error, err && err.status || 409)); } }); };
JavaScript
0
@@ -5088,32 +5088,146 @@ return next();%0A + if (req.body && !req.model.set(req.body, %7B%0A error: function(model, err) %7B next(err); %7D%0A %7D)) return;%0A req.model.de
bd822e6184b0c65f3756081f49e252c5c95d8aba
extract id
client/edit/index.js
client/edit/index.js
/* globals define, ajaxify, socket, app, config, utils, bootbox */ define('forum/client/plugins/custom-fields-edit', [], function () { 'use strict'; var Edit = {}; // TODO User ajaxify.data.theirid ? var idPrefix = 'field_', api = { get : 'plugins.ns-custom-fields.getFields', save: 'plugins.ns-custom-fields.saveFields' }; Edit.init = function () { renderFields($('.custom-fields')); }; Edit.save = function () { var $form = $('.form-horizontal'); var data = $form.serializeArray().map(function (item) { return { name : item.name.replace(idPrefix, ''), value: item.value } }); socket.emit(api.save, {uid: ajaxify.data.theirid, data: data}, function (error) { if (error) { return app.alertError(error.message); } app.alertSuccess('Custom Fields are saved'); }); }; function appendControl($container) { var $row = $('<div></div>').addClass('row'); var $column = $('<div></div>').addClass('col-md-4 col-md-offset-4 form-actions'); var $button = $('<a></a>') .addClass('btn btn-primary btn-block') .attr('href', '#') .text('Save') .on('click', function () { Edit.save(); }); $container.append($row); $row.append($column); $column.append($button); } function appendFields(columns, fields, data) { var i = 0, len = fields.length, fieldKey, fieldEntity, content = data || {}; var j = 0, columnsLen = columns.length, $column; var renderer = { input: function (key, entity) { return $('<input>') .addClass('form-control') .attr('id', key) .attr('name', key) .attr('placeholder', entity.prompt) .val(content[entity.key]); }, select: function (key, entity) { var selectedId = content[entity.key]; var selected = false; var select = $('<select></select>').addClass('form-control').attr('name', key); //Prompt option var promptOption = $('<option></option>') .attr('value', 'default') .attr('disabled', 'disabled') .text(entity.prompt) .appendTo(select); entity.options.forEach(function (item, index) { var option = $('<option></option>') .attr('value', item.id) .text(item.text); if (selectedId == item.id) { selected = true; option.prop('selected', true); } option.appendTo(select); }); if (!selected) { promptOption.prop('selected', true); } return select; } }; for (i; i < len; ++i) { $column = columns[j]; fieldEntity = fields[i]; //Namespace fields to prevent collisions fieldKey = idPrefix + fieldEntity.key; var $group = $('<div></div>').addClass('control-group'); var $label = $('<label></label>').addClass('control-label').text(fieldEntity.name).attr('for', fieldKey); var $wrapper = $('<div></div>').addClass('controls'); var $control = renderer[fieldEntity.type](fieldKey, fieldEntity); $group.append($label); $group.append($wrapper); $wrapper.append($control); $column.append($group); if ((j + 1) % columnsLen == 0) { j = 0; } else { ++j; } } } // Create 3 column layout function renderFields($parent) { var $form = $('<form></form>').addClass('form-horizontal container'); var $row = $('<div></div>').addClass('row'); var columns = [ $('<div></div>').addClass('col-md-4'), $('<div></div>').addClass('col-md-4'), $('<div></div>').addClass('col-md-4') ]; $parent.append($form); $form.append($row); columns.forEach(function ($column) { $row.append($column); }); appendFields(columns, ajaxify.data.customFields.fields, ajaxify.data.customFields.data); appendControl($form); } return Edit; });
JavaScript
0.999697
@@ -784,24 +784,33 @@ jaxify.data. +userData. theirid, dat
06073eea66d2e7900f17e583aacc083db58c17b8
remove space bar testing
client/game_board.js
client/game_board.js
var stage, board, tiles, fleets, scale, sWid, is_dragging; var lastMouse = { x:0, y:0 }; var is_dragging = false; $(document).ready(function() { init_stage(); document.addEventListener('keyup', handleKeyUp, false); document.addEventListener('keydown', handleKeyDown, false); }); /** * Called from createAll in game.js after all assets are loaded. * Clears old game globals, re-sets defaults. */ var setGlobals = function() { stage.removeChild(board); board = new createjs.Container(); tiles = []; fleetshapes = {}; scale = 0.65; }; var handleKeyUp = function( e ) { switch (e.keyCode) { case 189: // dash zoomBoard(-0.05); break; case 187: // equals (plus sign) zoomBoard(0.05); break; default: break; } }; var handleKeyDown = function( e ) { switch (e.keyCode) { case 37: // left arrow moveBoard(-1, 0); break; case 38: // up arrow moveBoard(0, -1); break; case 39: moveBoard(1, 0); break; case 40: moveBoard(0, 1); break; case 32: drawExplosion(500, 300, 1.0); drawShield(800, 300, 1.0); break; default: break; } }; /** * Calls init and draw functions for each tile in game board */ var createBoard = function() { if (stage) { initSelection(); updateCanvasSize(); drawAsteroids(); drawTiles(); drawNoFlyZones(); drawBases(); drawAgents(); drawFleets(); drawSprites(); stage.addChild( board ); scale = 0.75; var boardWidth = 7 * sWid * scale; var boardHeight = 7 * sWid * scale; board.x = (window.innerWidth - boardWidth) / 2.0; board.y = (window.innerHeight - boardHeight) / 2.0; board.scaleX = scale; board.scaleY = scale; fadeIn(board, 1000, false, false); } }; var drawAsteroids = function() { var asteroids = clientGame.game.board.asteroids; for ( var a = 0; a < asteroids.length; a++ ) { drawAsteroid( asteroids[a] ); } }; var drawTiles = function() { var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { initTile(p); drawTile(p); } }; var drawFleets = function() { initFleets(); var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateFleets(p); } }; var drawNoFlyZones = function() { var planets = clientGame.game.board.planets; initNoFlyZones(); updateNoFlyZones(); }; var drawBases = function() { var planets = clientGame.game.board.planets; initBases(); for ( var p = 0; p < planets.length; p++ ) { updateBases(p); } }; var drawAgents = function() { initAgents(); var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateAgents(p); } }; /** * Calls function to turn mouse enablement on/off on different * createJS containers based on what action the user is in. */ var updateBoardInteractivity = function() { var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateTileInteractivity(p); } updateFleetsInteractivity(); updateBasesInteractivity(); updateAgentsInteractivity(); }; /** * Calls update functions on each tile to update appearance, interactivity * based on current pending action or game event */ var updateBoard = function() { var planets = clientGame.game.board.planets; // this sets all bases to invisible. Update function will reveal // and draw any that are on planets. updateRemovedBases(); for ( var p = 0; p < planets.length; p++ ) { updateTileInteractivity(p); updateTileImage(p); updateFleets(p); updateBases(p); updateAgents(p); } updateNoFlyZones(); updateRemovedFleets(); updateDeadAgents(); stage.update(); };
JavaScript
0
@@ -997,92 +997,8 @@ ak;%0A -%09%09case 32:%0A%09%09%09drawExplosion(500, 300, 1.0);%0A%09%09%09drawShield(800, 300, 1.0);%0A%09%09%09break;%0A %09%09de
ea7038a45ac7e70af974463f4e5bd1c442bdf6f1
清理:待发布文件
service/deployer.js
service/deployer.js
'use strict'; const path = require('path'); const fsHelper = require('../utils/fsHelper'); const fs = fsHelper.fsExtra; const backup = require('./backup'); const config = require('../config'); const deployDir = config['deploy.dir']; const clobberOptions = { clobber: true }; module.exports = { /** * 添加发布文件 */ add: function (absUploadFilePath, absFilePath) { const absDeployFilePath = this.getDeployFilePath(absFilePath); const currentDeployDir = this.getCurrentDeployDir(absFilePath); return fs.ensureDirAsync(currentDeployDir) .then(() => fs.moveAsync(absUploadFilePath, absDeployFilePath, clobberOptions)); }, /** * 按目录添加发布文件 */ addByDir: function (absUploadDir, dir) { return this.walk(absUploadDir) .then(items => { items.forEach(item => { let fileName = path.parse(item).base; if (!fsHelper.testName(fileName)) { throw Error(`zip包存在无效文件名:"${fileName}"`); } }); return items; }) .then(items => items.map(item => { let _path = path.relative(absUploadDir, item); let absFilePath = path.join(dir, _path); return this.add(item, absFilePath) })) .then(promises => Promise.all(promises)); }, walk: function (absDir) { return new Promise(function (resolve, reject) { let items = []; fs.walk(absDir) .on('error', error => { reject(error); }) .on('data', item => { if (item.stats.isDirectory()) { return; } items.push(item.path); }) .on('end', () => { resolve(items); }); }); }, /** * 发布 */ deploy: function (absFilePath, absDeployFilePath) { return fs.moveAsync(absDeployFilePath, absFilePath, clobberOptions) .then(() => backup.add(absFilePath)) }, /** * 获取待发布文件列表 */ getDeployFiles: function (absDir) { return fs.readdirAsync(`${absDir}/${deployDir}`); }, /** * 取消发布 */ undeploy: function (absDeployFilePath) { return fs.removeAsync(absDeployFilePath); }, /** * 根据文件获取对应的发布文件 */ getDeployFilePath: function (absFilePath) { const { dir, base } = path.parse(absFilePath); return `${dir}/${deployDir}/${base}`; }, /** * 根据文件获取当前的发布目录 */ getCurrentDeployDir: function (absFilePath) { const { dir } = path.parse(absFilePath); return `${dir}/${deployDir}`; } };
JavaScript
0
@@ -34,24 +34,58 @@ re('path');%0A +const moment = require('moment');%0A const fsHelp @@ -261,16 +261,66 @@ y.dir'%5D; +%0Aconst deployKeeptime = config%5B'deploy.keepTime'%5D; %0A%0Aconst @@ -2537,15 +2537,473 @@ yDir%7D%60;%0A + %7D,%0A%0A /**%0A * %E6%B8%85%E7%90%86%E5%BE%85%E5%8F%91%E5%B8%83%E6%96%87%E4%BB%B6%0A */%0A clean: function (absPath) %7B%0A var absDeployDir = %60$%7BabsPath%7D/$%7BdeployDir%7D%60;%0A%0A return fs.readdirAsync(absDeployDir)%0A .then(files =%3E files.map(file =%3E (%7B%0A file,%0A stat: fs.statSync(%60$%7BabsDeployDir%7D/$%7Bfile%7D%60)%0A %7D)))%0A .then(files =%3E files.forEach(file =%3E %7B%0A if (moment() - moment(file.stat.mtime) %3E deployKeeptime) %7B%0A fs.removeSync(%60$%7BabsDeployDir%7D/$%7Bfile%7D%60);%0A %7D%0A %7D));%0A %7D%0A%0A%7D;
cac3cd583afc05624a3b0c2befdadec84607fe7a
Revert "testing"
api/login/forgot/index.js
api/login/forgot/index.js
'use strict'; exports.init = function(req, res){ if (req.isAuthenticated()) { res.redirect(req.user.defaultReturnUrl()); } else { res.render('login/forgot/index'); } }; exports.send = function(req, res, next){ console.log('in send'); //res.send('test'); /*var workflow = req.app.utility.workflow(req, res); workflow.on('validate', function() { console.log('in validate'); if (!req.body.email) { workflow.outcome.errfor.email = 'required'; return workflow.emit('response'); } workflow.emit('generateToken'); }); workflow.on('generateToken', function() { console.log('in generateToken'); var crypto = require('crypto'); crypto.randomBytes(21, function(err, buf) { if (err) { return next(err); } var token = buf.toString('hex'); console.log('before encryptPW'); req.app.db.models.User.encryptPassword(token, function(err, hash) { if (err) { return next(err); } console.log('after encryptPW'); workflow.emit('patchUser', token, hash); }); }); }); workflow.on('patchUser', function(token, hash) { var starttime = new Date(); starttime.setHours(starttime.getHours() + 4); // Get the iso time (GMT 0 == UTC 0) var isotime = new Date((new Date(starttime)).toISOString() ); //isotime += 10000000; console.log('patchUser: resetPasswordExpires is ' + isotime); var conditions = { email: req.body.email.toLowerCase() }; var fieldsToSet = { resetPasswordToken: hash, resetPasswordExpires: isotime //Date.now() + 10000000 }; req.app.db.models.User.findOne({ where: conditions }) .error(function(err) { // error callback console.log('Couldnt find user: ' + err); return workflow.emit('exception', err); }) .success(function(user) { console.log('User returned.'); //console.dir(user); if (!user) { return workflow.emit('exception', 'couldn\'t find user'); } user.updateAttributes({ resetPasswordToken: fieldsToSet.resetPasswordToken, resetPasswordExpires: fieldsToSet.resetPasswordExpires }).then(function(){ if (err) { return workflow.emit('exception', err); } console.log('Saved user'); workflow.emit('sendEmail', token, user); }); }); }); workflow.on('sendEmail', function(token, user) { console.log('reached sendEmail: '); console.log(req.app.config.smtp.from.name +' <'+ req.app.config.smtp.from.address +'>'); console.log(req.app.config.smtp.credentials.user + ', ' + req.app.config.smtp.credentials.host); req.app.utility.sendmail(req, res, { from: req.app.config.smtp.from.name +' <'+ req.app.config.smtp.from.address +'>', to: user.email, subject: 'Reset your '+ req.app.config.projectName +' password', textPath: 'login/forgot/email-text', htmlPath: 'login/forgot/email-html', locals: { username: user.username, resetLink: req.protocol +'://'+ req.headers.host +'?u=' + user.email + '&t=' + token, ///api/v1/login/reset/'+ user.email +'/'+ token +'/', projectName: req.app.config.projectName }, success: function(message) { workflow.emit('response'); }, error: function(err) { workflow.outcome.errors.push('Error Sending: '+ err); workflow.emit('response'); } }); }); workflow.emit('validate'); */ }; /* */
JavaScript
0
@@ -275,18 +275,16 @@ t');%0A%0A -/* var work @@ -2539,16 +2539,18 @@ %7D); +%0A%0A @@ -2554,22 +2554,392 @@ -%0A %0A%0A + //create Resetpassword record%0A /*var resetPW = req.app.db.models.ResetPassword.build(%7B%0A userId: userId, %0A resetPasswordToken: fieldsToSet.resetPasswordToken, %0A resetPasswordExpires: fieldsToSet.resetPasswordExpires,%0A isUsed: 'N',%0A %7D);*/%0A%0A // persist an instance%0A //user.save()%0A %0A %0A%0A @@ -2938,32 +2938,34 @@ %0A%0A %7D);%0A + %7D);%0A%0A workf @@ -4065,18 +4065,16 @@ e');%0A%0A -*/ %0A %0A%7D;%0A%0A
a9ef57b9b04692d85086e9da188564c56854709e
update LUTShader
shader/LUTShader.js
shader/LUTShader.js
export default class LUTShader { // Adapted from Matt DesLauriers - https://github.com/mattdesl/glsl-lut // FOR LUT of 64x64x64 static computeLUT64() { return ` vec3 computeLUT64(vec3 color, sampler2D lutTexture, vec4 lutRectangle) { float blueColor = color.b * 63.0; vec2 quad1; quad1.y = floor(floor(blueColor) / 8.0); quad1.x = floor(blueColor) - (quad1.y * 8.0); quad1.x += lutRectangle.x; quad1.y += lutRectangle.y; vec2 quad2; quad2.y = floor(ceil(blueColor) / 8.0); quad2.x = ceil(blueColor) - (quad2.y * 8.0); quad2.x += lutRectangle.x; quad2.y += lutRectangle.y; float width = 0.125 * lutRectangle.z; float height = 0.125 * lutRectangle.w; vec2 texPos1; texPos1.x = (quad1.x * width) + 0.5 / 512.0 + ((width - 1.0 / 512.0) * color.r); texPos1.y = (quad1.y * height) + 0.5 / 512.0 + ((height - 1.0 / 512.0) * color.g); vec2 texPos2; texPos2.x = (quad2.x * width) + 0.5 / 512.0 + ((width - 1.0 / 512.0) * color.r); texPos2.y = (quad2.y * height) + 0.5 / 512.0 + ((height - 1.0 / 512.0) * color.g); vec3 newColor1 = texture2D(lutTexture, texPos1).rgb; vec3 newColor2 = texture2D(lutTexture, texPos2).rgb; vec3 newColor = mix(newColor1, newColor2, fract(blueColor)); return newColor; } vec3 computeLUT64(vec3 color, sampler2D lutTexture) { return computeLUT64(color, lutTexture, vec4(0., 0., 1., 1.)); } `; } }
JavaScript
0
@@ -32,130 +32,114 @@ %7B%0A -// Adapted from Matt DesLauriers - https://github.com/mattdesl/glsl-lut%0A // FOR LUT of 64x64x64%0A static computeLUT64() %7B +static computeLUT(%7B%0A lutSize = 64,%0A %7D = %7B%7D) %7B%0A const lutTextureSize = lutSize * Math.sqrt(lutSize); %0A @@ -161,34 +161,32 @@ vec3 computeLUT -64 (vec3 color, sam @@ -245,25 +245,17 @@ float -blueColor +x = color @@ -259,279 +259,261 @@ lor. -b * 63.0;%0A%0A vec2 quad1;%0A quad1.y = floor(floor(blueColor) / 8.0);%0A quad1.x = floor(blueColor) - (quad1.y * 8.0);%0A%0A quad1.x += lutRectangle.x;%0A quad1.y += lutRectangle.y;%0A%0A vec2 quad2;%0A quad2.y = floor(ceil(blueColor) +r * $%7B(lutSize - 1)%7D.;%0A float y = color.g * $%7B(lutSize - 1)%7D.;%0A float z = color.b * $%7B(lutSize - 1)%7D.;%0A%0A float previousZ = floor(z);%0A float nextZ = ceil(z);%0A%0A vec2 quad1 = vec2(mod(previousZ, 8.), floor(previousZ / 8. -0 +) );%0A @@ -523,50 +523,59 @@ +vec2 quad2 -.x = -ceil(blueColor) - (quad2.y * 8.0 +vec2(mod(nextZ, 8.), floor(nextZ / 8.) );%0A%0A @@ -586,365 +586,241 @@ -quad2.x += lutRectangle.x;%0A quad2.y += lutRectangle.y;%0A%0A float width = 0.125 +vec2 previousUV;%0A previousUV.x = lutRectangle.x + ((quad1.x * +$%7B lut -Rectangle.z;%0A float height = 0.125 * lutRectangle.w;%0A%0A vec2 texPos1;%0A texPos1.x = (quad1.x * width) + 0.5 / 512.0 + ((width - 1.0 / 512.0) * color.r);%0A texPos1.y = (quad1.y * height) + 0.5 / 512.0 + ((height - 1.0 / 512.0) * color.g) +Size%7D.) + x) / $%7BlutTextureSize%7D. * lutRectangle.z;%0A previousUV.y = lutRectangle.y + ((quad1.y * $%7BlutSize%7D.) + y) / $%7BlutTextureSize%7D. * lutRectangle.w ;%0A%0A @@ -831,23 +831,22 @@ vec2 -texPos2 +nextUV ;%0A @@ -851,87 +851,103 @@ -texPos2 +nextUV .x = -(quad2.x * width) + 0.5 / 512.0 + ((width - 1.0 / 512.0) * color.r) +lutRectangle.x + ((quad2.x * $%7BlutSize%7D.) + x) / $%7BlutTextureSize%7D. * lutRectangle.z ;%0A @@ -956,89 +956,103 @@ -texPos2 +nextUV .y = -(quad2.y * height) + 0.5 / 512.0 + ((height - 1.0 / 512.0) * color.g) +lutRectangle.y + ((quad2.y * $%7BlutSize%7D.) + y) / $%7BlutTextureSize%7D. * lutRectangle.w ;%0A%0A @@ -1101,15 +1101,18 @@ re, -texPos1 +previousUV ).rg @@ -1165,15 +1165,14 @@ re, -texPos2 +nextUV ).rg @@ -1235,17 +1235,9 @@ act( -blueColor +z ));%0A @@ -1291,18 +1291,16 @@ mputeLUT -64 (vec3 co @@ -1353,18 +1353,16 @@ mputeLUT -64 (color,
95ff97899ca882c39f53789fbf867f127469cdb4
Add custom grouping key based on the message
lib/raygun.messageBuilder.js
lib/raygun.messageBuilder.js
/* * raygun * https://github.com/MindscapeHQ/raygun4node * * Copyright (c) 2015 MindscapeHQ * Licensed under the MIT license. */ 'use strict'; var stackTrace = require('stack-trace'); var os = require('os'); var humanString = require('object-to-human-string'); var packageDetails = require('../package.json'); function filterKeys(obj, filters) { if (!obj || !filters || typeof obj !== 'object') { return obj; } Object.keys(obj).forEach(function (i) { if (filters.indexOf(i) > -1) { delete obj[i]; } else { obj[i] = filterKeys(obj[i], filters); } }); return obj; } var RaygunMessageBuilder = function (options) { options = options || {}; var _filters; if (Array.isArray(options.filters)) { _filters = options.filters; } var message = { occurredOn: new Date(), details: { client: { name: 'raygun-node', version: packageDetails.version } } }; this.build = function () { return message; }; this.setErrorDetails = function (error) { var errorType = Object.prototype.toString.call(error); if (errorType === '[object Object]') { error = humanString(error); } if (typeof error === "string") { message.details.error = { message: error }; return this; } var stack = []; var trace = stackTrace.parse(error); trace.forEach(function (callSite) { stack.push({ lineNumber: callSite.getLineNumber(), className: callSite.getTypeName() || 'unknown', fileName: callSite.getFileName(), methodName: callSite.getFunctionName() || '[anonymous]' }); }); message.details.error = { stackTrace: stack, message: error.message || "NoMessage", className: error.name }; return this; }; this.setEnvironmentDetails = function () { var environment = { osVersion: os.type() + ' ' + os.platform() + ' ' + os.release(), architecture: os.arch(), totalPhysicalMemory: os.totalmem(), availablePhysicalMemory: os.freemem(), utcOffset: new Date().getTimezoneOffset() / -60.0 }; // cpus seems to return undefined on some systems var cpus = os.cpus(); if (cpus && cpus.length && cpus.length > 0) { environment.processorCount = cpus.length; environment.cpu = cpus[0].model; } message.details.environment = environment; return this; }; this.setMachineName = function (machineName) { message.details.machineName = machineName || os.hostname(); return this; }; this.setUserCustomData = function (customData) { message.details.userCustomData = customData; return this; }; this.setTags = function (tags) { if (Array.isArray(tags)) { message.details.tags = tags; } return this; }; this.setRequestDetails = function (request) { if (request) { message.details.request = { hostName: request.hostname || request.host, url: request.path, httpMethod: request.method, ipAddress: request.ip, queryString: filterKeys(request.query, _filters), headers: filterKeys(request.headers, _filters), form: filterKeys(request.body, _filters) }; } return this; }; var extractUserProperties = function(userData) { var data = {}; if(userData.identifier) { data.identifier = userData.identifier; } if(userData.email) { data.email = userData.email; } if(userData.fullName) { data.fullName = userData.fullName; } if(userData.firstName) { data.firstName = userData.firstName; } if(userData.uuid) { data.uuid = userData.uuid; } return data; }; this.setUser = function (user) { var userData = user; if (user instanceof Function) { userData = user(); } if (userData instanceof Object) { message.details.user = extractUserProperties(userData); } else { message.details.user = { 'identifier': userData }; } return this; }; this.setVersion = function (version) { message.details.version = version; return this; }; }; exports = module.exports = RaygunMessageBuilder;
JavaScript
0
@@ -1172,24 +1172,104 @@ ing(error);%0A + message.details.groupingKey = error.replace(/%5CW+/g, %22%22).substring(0, 64);%0A %7D%0A%0A i
b3de618c9370344f9ed385db4f74687ab8dd15b4
Update yawsSocketConnect.js
test/yawsSocketConnect.js
test/yawsSocketConnect.js
var should = require('chai').should(); var expect = require('chai').expect; require('fake-dom'); describe('yaws.socketConnect', function() { window={location:{href:"https://127.0.0.1/example"}}; require('../src/yawsSocketConnect.js'); it('yaws should be an object', function() { window.yaws.should.be.a('object'); }); it('yaws.socketConnect should be a function', function() { window.yaws.socketConnect.should.be.a('function'); }); it('yaws.socketConnect() should throw an error on missing argument', function() { expect(window.yaws.socketConnect).to.throw("The first parameter 'onMessage' is required to be a function accepting a single parameter of type Blob."); }); it('yaws.socketConnect() should throw an error on missing Websocket', function() { expect(function(){window.yaws.socketConnect(function(blob){},{},'/')}).to.throw("No Websocket Implementation found"); }); //basic socket window.Websocket = function(url){ this.url=url; return this; }; Websocket = window.Websocket; it('yaws.socketConnect() should be an object', function() { window.yaws.socketConnect(function(blob){},{},'/').should.be.a('object'); }); it('yaws.socketConnect() should be a Websocket', function() { window.yaws.socketConnect(function(blob){},{},'/').should.be.instanceof(Websocket); }); //check both getURL-options it('yaws.socketConnect().url should be wss://127.0.0.1/example', function() { window.yaws.socketConnect(function(blob){},{},'/').property('url','wss://127.0.0.1/example'); }); window.location={ href: window.location.href, protocol: "http", path: "/ex", domainname: "localhost" }; it('yaws.socketConnect().url should be ws://localhost/ex', function() { window.yaws.socketConnect(function(blob){},{},'/').property('url','ws://localhost/ex'); }); //reconnecting socket window.ReconnectingWebSocket = window.Websocket; ReconnectingWebSocket = window.ReconnectingWebSocket; it('yaws.socketConnect() should be an object', function() { window.yaws.socketConnect(function(blob){},{},'/').should.be.a('object'); }); it('yaws.socketConnect() should be a ReconnectingWebSocket', function() { window.yaws.socketConnect(function(blob){},{},'/').should.be.instanceof(ReconnectingWebSocket); }); //robust socket window.RobustWebSocket = window.Websocket; RobustWebSocket = window.RobustWebSocket; it('yaws.socketConnect() should be an object', function() { window.yaws.socketConnect(function(blob){},{},'/').should.be.a('object'); }); it('yaws.socketConnect() should be a RobustWebSocket', function() { window.yaws.socketConnect(function(blob){},{},'/').should.be.instanceof(RobustWebSocket); }); });
JavaScript
0.000001
@@ -1438,32 +1438,39 @@ unction() %7B%0A +expect( window.yaws.sock @@ -1495,32 +1495,41 @@ (blob)%7B%7D,%7B%7D,'/') +).to.have .property('url', @@ -1756,32 +1756,39 @@ unction() %7B%0A +expect( window.yaws.sock @@ -1821,16 +1821,25 @@ ,%7B%7D,'/') +).to.have .propert
1ff11883a02f0348eaccfb5e400edc466e526b27
Convert MessageList to radio buttons
dev/js/containers/MessageList.js
dev/js/containers/MessageList.js
import React from 'react'; const MessageList = () => ( <ul> <li>Option 1</li> <li>Option 2</li> <li>Option 3</li> </ul> ); export default MessageList;
JavaScript
0.999999
@@ -56,20 +56,68 @@ %0A %3C -ul +div %3E%0A %3C -li%3E +p%3E%3Cinput type=%22radio%22 name=%22message%22 value=%221%22 /%3E Opti @@ -122,28 +122,74 @@ tion 1%3C/ -li +p %3E%0A %3C -li%3E +p%3E%3Cinput type=%22radio%22 name=%22message%22 value=%222%22 /%3E Option 2 @@ -194,20 +194,66 @@ 2%3C/ -li +p %3E%0A %3C -li%3E +p%3E%3Cinput type=%22radio%22 name=%22message%22 value=%223%22 /%3E Opti @@ -262,18 +262,18 @@ 3%3C/ -li +p %3E%0A %3C/ -ul +div %3E%0A);
15acbb145d267ca5268135a417c1e31fcaa60f1b
Implement resetCallback function
src/jquery.seslider.js
src/jquery.seslider.js
(function($) { $.fn.seSlider = function(options) { var defaults = { nextBtn: '.sliderNextBtn', prevBtn: '.sliderPrevBtn', playPauseBtn: '.sliderPlayBtn', resetBtn: '.sliderResetBtn', preventReversedCycle: false, progressBar: null, changeCallback: null, afterChangeCallback: null, playCallback: null, pauseCallback: null, endCallback: null, autoPlay: false, slideshowSoundTrack: null, slideshowSteps: null, slideshowIntervalTime: 1000, transitionSpeed: 200 }; var params = $.extend(defaults, options), changeCallbacks = $.Callbacks(), afterChangeCallbacks = $.Callbacks(); if(typeof params.changeCallback === 'function') changeCallbacks.add(params.changeCallback); if(typeof params.afterChangeCallback === 'function') afterChangeCallbacks.add(params.afterChangeCallback); function moveLeft(slider, slideshow) { if(params.preventReversedCycle === true && slideshow.currStep <= 0) return; changeCallbacks.fire(slideshow.currStep, slideshow.currStep - 1, 'left'); slider.animate({ left: + slider.children('li').width() }, params.transitionSpeed, function() { slideshow.currStep--; slider.find('li').last().prependTo(slider); slider.css('left', ''); if(slideshow.currStep < 0) { if(slideshow.interval !== false) stopSlideShow(slider, slideshow, true, false); slideshow.currStep = slideshow.maxStep; } afterChangeCallbacks.fire(slideshow.currStep); updateElapsedTime(slideshow); updateProgressBar(slideshow.elapsedTime / slideshow.maxTime * 100); updateSoundTrackTime(slideshow.elapsedTime / 1000); }); } function moveRight(slider, slideshow, updateComponents) { changeCallbacks.fire(slideshow.currStep, slideshow.currStep + 1, 'right'); slider.animate({ left: - slider.children('li').width() }, params.transitionSpeed, function() { slideshow.currStep++; slider.find('li').first().appendTo(slider); slider.css('left', ''); if(slideshow.currStep > slideshow.maxStep) { slideshow.currStep = 0; if(slideshow.interval !== false) { stopSlideShow(slider, slideshow, true, false); updateComponents = false; } } afterChangeCallbacks.fire(slideshow.currStep); if(updateComponents === true) { updateElapsedTime(slideshow); updateProgressBar(slideshow.elapsedTime / slideshow.maxTime * 100); updateSoundTrackTime(slideshow.elapsedTime / 1000); } }); } function playSlideShow(slider, slideshow) { slideshow.interval = setInterval(function() { slideshow.elapsedTime += params.slideshowIntervalTime; updateProgressBar(slideshow.elapsedTime / slideshow.maxTime * 100); if(params.slideshowSteps === null || params.slideshowSteps[slideshow.currStep] <= slideshow.elapsedTime) moveRight(slider, slideshow, false); }, params.slideshowIntervalTime); if(params.slideshowSoundTrack !== null) $(params.slideshowSoundTrack).get(0).play(); if(typeof params.playCallback === 'function') params.playCallback(); } function stopSlideShow(slider, slideshow, endReached, reset) { if(slideshow.interval !== false) { clearInterval(slideshow.interval); slideshow.interval = false; if(params.slideshowSoundTrack !== null) $(params.slideshowSoundTrack).get(0).pause(); } if(endReached === true || reset === true) { slider.finish(); if(reset === true && slideshow.currStep !== 0) slider.find('li').slice((slideshow.maxStep + 1) - slideshow.currStep).prependTo(slider); slideshow.currStep = 0; slideshow.elapsedTime = 0; updateProgressBar(0); updateSoundTrackTime(0); if(reset !== true && typeof params.endCallback === 'function') params.endCallback(); } else if(typeof params.pauseCallback === 'function') params.pauseCallback(); } function updateElapsedTime(slideshow) { if(params.slideshowSteps === null) slideshow.elapsedTime = params.slideshowIntervalTime * slideshow.currStep; else slideshow.elapsedTime = params.slideshowSteps[slideshow.currStep - 1] || 0; } function updateProgressBar(size) { if(params.progressBar !== null) $(params.progressBar).children('div').css('width', size + '%'); } function updateSoundTrackTime(time) { if(params.slideshowSoundTrack !== null) $(params.slideshowSoundTrack).get(0).currentTime = time; } return this.each(function() { var obj = $(this).children('ul'); var slideWidth = obj.children('li').width(), slideshow = { interval: false, maxStep: obj.find('li').length - 1, currStep: 0, elapsedTime: 0 }; slideshow.maxTime = params.slideshowSteps !== null ? params.slideshowSteps[slideshow.maxStep] : params.slideshowIntervalTime * (slideshow.maxStep + 1); if(obj.children('li').length === 1) return true; obj.children('li').last().prependTo(obj); if(obj.children('li').length === 2) { var first = obj.children('li').first().clone(), last = obj.children('li').last().clone(); obj.append(first).append(last); } obj.css({width: slideWidth * (slideshow.maxStep + 1), marginLeft: - slideWidth}); if(params.autoPlay === true) playSlideShow(obj, slideshow); //Next button $(params.nextBtn).on('touchstart click', function(e) { e.preventDefault(); if(obj.css('left') !== 'auto') return; moveRight(obj, slideshow, true); }); //Prev button $(params.prevBtn).on('touchstart click', function(e) { e.preventDefault(); if(obj.css('left') !== 'auto') return; moveLeft(obj, slideshow); }); //Reset button $(params.resetBtn).on('touchstart click', function(e) { e.preventDefault(); stopSlideShow(obj, slideshow, false, true); }); //SlideShow play $(params.playPauseBtn).on('touchstart click', function(e) { e.preventDefault(); if(slideshow.interval === false) playSlideShow(obj, slideshow); else stopSlideShow(obj, slideshow, false, false); }); }); }; })(jQuery);
JavaScript
0.000075
@@ -469,32 +469,65 @@ Callback: null,%0A + resetCallback: null,%0A auto @@ -4870,15 +4870,20 @@ if( -reset ! +endReached = == t @@ -4965,32 +4965,162 @@ .endCallback();%0A + else if(reset === true && typeof params.resetCallback === 'function')%0A params.resetCallback();%0A %7D%0A
259e54bb53471164ad844007684c72c8f5ef636a
make Dom accessible in Context for plugins
src/js/base/Context.js
src/js/base/Context.js
define([ 'jquery', 'summernote/base/core/func', 'summernote/base/core/list', 'summernote/base/core/dom' ], function ($, func, list, dom) { /** * @param {jQuery} $note * @param {Object} options * @return {Context} */ var Context = function ($note, options) { var self = this; var ui = $.summernote.ui; this.memos = {}; this.modules = {}; this.layoutInfo = {}; this.options = options; /** * create layout and initialize modules and other resources */ this.initialize = function () { this.layoutInfo = ui.createLayout($note, options); this._initialize(); $note.hide(); return this; }; /** * destroy modules and other resources and remove layout */ this.destroy = function () { this._destroy(); $note.removeData('summernote'); ui.removeLayout($note, this.layoutInfo); }; /** * destory modules and other resources and initialize it again */ this.reset = function () { var disabled = self.isDisabled(); this.code(dom.emptyPara); this._destroy(); this._initialize(); if (disabled) { self.disable(); } }; this._initialize = function () { // add optional buttons var buttons = $.extend({}, this.options.buttons); Object.keys(buttons).forEach(function (key) { self.memo('button.' + key, buttons[key]); }); var modules = $.extend({}, this.options.modules, $.summernote.plugins || {}); // add and initialize modules Object.keys(modules).forEach(function (key) { self.module(key, modules[key], true); }); Object.keys(this.modules).forEach(function (key) { self.initializeModule(key); }); }; this._destroy = function () { // destroy modules with reversed order Object.keys(this.modules).reverse().forEach(function (key) { self.removeModule(key); }); Object.keys(this.memos).forEach(function (key) { self.removeMemo(key); }); }; this.code = function (html) { var isActivated = this.invoke('codeview.isActivated'); if (html === undefined) { this.invoke('codeview.sync'); return isActivated ? this.layoutInfo.codable.val() : this.layoutInfo.editable.html(); } else { if (isActivated) { this.layoutInfo.codable.val(html); } else { this.layoutInfo.editable.html(html); } $note.val(html); this.triggerEvent('change', html); } }; this.isDisabled = function () { return this.layoutInfo.editable.attr('contenteditable') === 'false'; }; this.enable = function () { this.layoutInfo.editable.attr('contenteditable', true); this.invoke('toolbar.activate', true); }; this.disable = function () { // close codeview if codeview is opend if (this.invoke('codeview.isActivated')) { this.invoke('codeview.deactivate'); } this.layoutInfo.editable.attr('contenteditable', false); this.invoke('toolbar.deactivate', true); }; this.triggerEvent = function () { var namespace = list.head(arguments); var args = list.tail(list.from(arguments)); var callback = this.options.callbacks[func.namespaceToCamel(namespace, 'on')]; if (callback) { callback.apply($note[0], args); } $note.trigger('summernote.' + namespace, args); }; this.initializeModule = function (key) { var module = this.modules[key]; module.shouldInitialize = module.shouldInitialize || func.ok; if (!module.shouldInitialize()) { return; } // initialize module if (module.initialize) { module.initialize(); } // attach events if (module.events) { dom.attachEvents($note, module.events); } }; this.module = function (key, ModuleClass, withoutIntialize) { if (arguments.length === 1) { return this.modules[key]; } this.modules[key] = new ModuleClass(this); if (!withoutIntialize) { this.initializeModule(key); } }; this.removeModule = function (key) { var module = this.modules[key]; if (module.shouldInitialize()) { if (module.events) { dom.detachEvents($note, module.events); } if (module.destroy) { module.destroy(); } } delete this.modules[key]; }; this.memo = function (key, obj) { if (arguments.length === 1) { return this.memos[key]; } this.memos[key] = obj; }; this.removeMemo = function (key) { if (this.memos[key] && this.memos[key].destroy) { this.memos[key].destroy(); } delete this.memos[key]; }; this.createInvokeHandler = function (namespace, value) { return function (event) { event.preventDefault(); self.invoke(namespace, value || $(event.target).closest('[data-value]').data('value')); }; }; this.invoke = function () { var namespace = list.head(arguments); var args = list.tail(list.from(arguments)); var splits = namespace.split('.'); var hasSeparator = splits.length > 1; var moduleName = hasSeparator && list.head(splits); var methodName = hasSeparator ? list.last(splits) : list.head(splits); var module = this.modules[moduleName || 'editor']; if (!moduleName && this[methodName]) { return this[methodName].apply(this, args); } else if (module && module[methodName] && module.shouldInitialize()) { return module[methodName].apply(module, args); } }; return this.initialize(); }; return Context; });
JavaScript
0
@@ -424,16 +424,36 @@ options; +%0A this.dom = dom; %0A%0A /*
657700925ba8042025d3942e32d5d31790082c9a
Fix delete card copy.
app/account/views/card.js
app/account/views/card.js
module.exports = Zeppelin.ModelView.extend({ tagName: 'li', attributes: function() { return { 'title': this.model.get('name'), 'data-type': this.model.get('type') }; }, className: function() { var className = 'card is-item'; if (this.model.get('featured')) className += ' is-featured'; return className; }, events: { 'click': 'onClick', 'click [data-action=delete]': 'delete', 'click [data-action=highlight]': 'toggleHighlight' }, elements: { 'name': 'span.card-name' }, bindings: { model: { 'change:name': 'onNameChange', 'change:featured': 'onFeaturedChange' } }, delete: function(event) { event.stopPropagation(); if (window.confirm('Are you sure you want to delete card?')) { this.model.destroy(); this.broadcast('cardsList:layout'); } }, updateName: function(value) { this.getElement('name').text(value); return this; }, toggleHighlight: function(event) { event.stopPropagation(); this.model.save({featured: !this.model.get('featured')}); return this; }, onClick: function(event) { if (!event.metaKey) { event.preventDefault(); this.model.select(); } }, onFeaturedChange: function(card, isFeatured) { this.$el.data('width', ''); this.$el.data('height', ''); this.$el.removeAttr('style'); this.$el.removeAttr('data-width'); this.$el.removeAttr('data-height'); this.$el.toggleClass('is-featured', isFeatured); this.broadcast('cardsList:layout'); }, onNameChange: function(card, value) { this.updateName(value); } });
JavaScript
0
@@ -769,16 +769,21 @@ delete +this card?'))
4063b4e83c5db06e187c2c0be73c64a71d02e857
return callback function.
testcube/static/common.js
testcube/static/common.js
"use strict"; let my = {}; my.defaultToolTip = "Loading ..."; my.debugLog = true; function disableConsoleLog() { my.logMethod = console.log; console.log = function () { } } function enableConsoleLog() { console.log = my.logMethod; } function doSetup() { } function getColor(value) { // value from 0 to 1 => red to green, if value is not good, let it red if (value < 0.9) { value -= 0.3; } let hue = (value * 120).toString(10); return ["hsl(", hue, ",100%,35%)"].join(""); } function hmsToSeconds(str) { // e.g. '02:04:33' to seconds let p = str.split(':'), s = 0, m = 1; while (p.length > 0) { s += m * parseInt(p.pop(), 10); m *= 60; } return s; } function startLogHighlight(callback) { $(function () { $.getScript('/static/libs/rainbow/rainbow.min.js', function () { $.getScript('/static/libs/rainbow/language/generic.js', function () { $.getScript('/static/libs/rainbow/language/python.js', function () { $.getScript('/static/libs/rainbow/language/log-zen.js', function () { Rainbow.color(); if (callback) callback(); }); }); }); }); }); }
JavaScript
0.000001
@@ -1207,16 +1207,23 @@ allback) + return callbac
0bf0256337755d880901b57ba327d866b962903e
Use similar assetstorage scanning mechanism in the qmlui menu as well. Check asset suffixes properly.
bin/scenes/Avatar/avatarmenu.js
bin/scenes/Avatar/avatarmenu.js
var avatarMenu = null; function MenuActionHandler(assetRef, index) { this.assetName = assetRef; } MenuActionHandler.prototype.triggered = function() { var avatarEntity = scene.GetEntity("Avatar" + client.GetConnectionID()); if (avatarEntity == null) return; var r = avatarEntity.avatar.appearanceRef; r.ref = this.assetName; avatarEntity.avatar.appearanceRef = r; } if (!framework.IsHeadless()) { engine.ImportExtension("qt.core"); engine.ImportExtension("qt.gui"); // Connect to asset refs ready signal of existing storages (+ refresh them now) var assetStorages = asset.GetAssetStorages(); for (var i = 0; i < assetStorages.length; ++i) { assetStorages[i].AssetRefsChanged.connect(PopulateAvatarUiMenu); assetStorages[i].RefreshAssetRefs(); } // Connect to adding new storages asset.AssetStorageAdded.connect(OnAssetStorageAdded); } function OnAssetStorageAdded(storage) { storage.AssetRefsChanged.connect(PopulateAvatarUiMenu); storage.RefreshAssetRefs(); } function PopulateAvatarUiMenu() { var menu = ui.MainWindow().menuBar(); if (avatarMenu == null) avatarMenu = menu.addMenu("&Avatar"); avatarMenu.clear(); var assetStorages = asset.GetAssetStorages(); for (var i = 0; i < assetStorages.length; ++i) { var assetList = assetStorages[i].GetAllAssetRefs(); for (var j = 0; j < assetList.length; ++j) { var assetNameLower = assetList[j].toLowerCase(); // Can not check the actual asset type from the ref only. But for now assume xml = avatar xml if ((assetNameLower.indexOf(".xml") != -1) || (assetNameLower.indexOf(".avatar") != -1)) { var assetName = assetList[j]; var handler = new MenuActionHandler(assetName); avatarMenu.addAction(assetName).triggered.connect(handler, handler.triggered); } } } }
JavaScript
0
@@ -1048,24 +1048,124 @@ tRefs();%0A%7D%0A%0A +function EndsWith(str, suffix)%0A%7B%0A return str.indexOf(suffix) == (str.length - suffix.length);%0A%7D%0A%0A function Pop @@ -1740,16 +1740,25 @@ if (( +EndsWith( assetNam @@ -1767,35 +1767,31 @@ ower -.indexOf(%22.xml%22) != -1) %7C%7C +, %22.xml%22)) %7C%7C (EndsWith (ass @@ -1801,25 +1801,18 @@ ameLower -.indexOf( +, %22.avatar @@ -1817,14 +1817,8 @@ ar%22) - != -1 ))%0A
95fa66c2bacd1fd98a4ec8ee7fbb58b9e51361f5
Remove renderValue from FieldHelper
client/src/components/FieldHelper.js
client/src/components/FieldHelper.js
import React from "react" import { Col, ControlLabel, FormControl, FormGroup, HelpBlock, InputGroup, ToggleButton, ToggleButtonGroup } from "react-bootstrap" import utils from "utils" const getFieldId = field => field.id || field.name // name property is required const getHumanValue = (field, humanValue) => { if (typeof humanValue === "function") { return humanValue(field.value) } else if (humanValue !== undefined) { return humanValue } else { return field.value } } const getFormGroupValidationState = (field, form) => { const { touched, errors } = form const fieldTouched = touched[field.name] const fieldError = errors[field.name] return (fieldTouched && (fieldError ? "error" : null)) || null } const getHelpBlock = (field, form) => { const { touched, errors } = form const fieldTouched = touched[field.name] const fieldError = errors[field.name] return fieldTouched && fieldError && <HelpBlock>{fieldError}</HelpBlock> } const renderFieldNoLabel = (field, form, widgetElem, children) => { const id = getFieldId(field) const validationState = getFormGroupValidationState(field, form) return ( <FormGroup controlId={id} validationState={validationState}> {widgetElem} {getHelpBlock(field, form)} {children} </FormGroup> ) } const renderField = ( field, label, form, widgetElem, children, extraColElem, addon, vertical, extraAddon ) => { if (label === undefined) { label = utils.sentenceCase(field.name) // name is a required prop of field } vertical = vertical || false // default direction of label and input = vertical let widget if (!addon) { widget = widgetElem } else { // allows passing a url for an image if (addon.indexOf(".") !== -1) { addon = <img src={addon} height={20} alt="" /> } const focusElement = () => { const element = document.getElementById(id) if (element && element.focus) { element.focus() } } widget = ( <InputGroup> {widgetElem} {extraAddon && <InputGroup.Addon>{extraAddon}</InputGroup.Addon>} <InputGroup.Addon onClick={focusElement}>{addon}</InputGroup.Addon> </InputGroup> ) } const id = getFieldId(field) const validationState = getFormGroupValidationState(field, form) // setting label or extraColElem explicitly to null will completely remove these columns! const widgetWidth = 12 - (label === null ? 0 : 2) - (extraColElem === null ? 0 : 3) // controlId prop of the FormGroup sets the id of the control element return ( <FormGroup controlId={id} validationState={validationState}> {vertical ? ( <React.Fragment> {label !== null && <ControlLabel>{label}</ControlLabel>} {widget} {getHelpBlock(field, form)} {children} </React.Fragment> ) : ( <React.Fragment> {label !== null && ( <Col sm={2} componentClass={ControlLabel}> {label} </Col> )} <Col sm={widgetWidth}> <div> {widget} {getHelpBlock(field, form)} {children} </div> </Col> </React.Fragment> )} {extraColElem && <Col sm={3} {...extraColElem.props} />} </FormGroup> ) } export const renderInputField = ({ field, // { name, value, onChange, onBlur } form, // contains, touched, errors, values, setXXXX, handleXXXX, dirty, isValid, status, etc. ...props }) => { const { label, children, extraColElem, addon, vertical, innerRef, extraAddon, ...otherProps } = props const widgetElem = ( <FormControl {...Object.without(field, "value")} value={field.value === null ? "" : field.value} ref={innerRef} {...otherProps} /> ) return renderField( field, label, form, widgetElem, children, extraColElem, addon, vertical, extraAddon ) } export const renderInputFieldNoLabel = ({ field, // { name, value, onChange, onBlur } form, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc. ...props }) => { const { children, ...otherProps } = props const widgetElem = ( <FormControl {...Object.without(field, "value")} value={field.value === null ? "" : field.value} {...otherProps} /> ) return renderFieldNoLabel(field, form, widgetElem, children) } export const renderReadonlyField = ({ field, // { name, value, onChange, onBlur } form, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc. ...props }) => { const { label, children, extraColElem, addon, vertical, humanValue, ...otherProps } = props const widgetElem = ( <FormControl.Static componentClass={"div"} {...field} {...otherProps}> {getHumanValue(field, humanValue)} </FormControl.Static> ) return renderField( field, label, form, widgetElem, children, extraColElem, addon, vertical ) } export const renderValue = ({ field, // { name, value, onChange, onBlur } form, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc. ...props }) => { const id = field.id || field.name return ( <FormControl.Static componentClass={"span"} id={id}> {getHumanValue(field)} </FormControl.Static> ) } export const renderSpecialField = ({ field, // { name, value, onChange, onBlur } form, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc. ...props }) => { const { label, children, extraColElem, addon, vertical, widget, ...otherProps } = props const widgetElem = React.cloneElement(widget, { ...field, ...otherProps }) return renderField( field, label, form, widgetElem, children, extraColElem, addon, vertical ) } export const renderButtonToggleGroup = ({ field, // { name, value, onChange, onBlur } form, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc. ...props }) => { const { label, children, extraColElem, addon, vertical, buttons, ...otherProps } = props const widgetElem = ( <ToggleButtonGroup type="radio" defaultValue={field.value} {...field} {...otherProps} > {buttons.map((button, index) => { if (!button) { return null } const { label, ...props } = button return ( <ToggleButton {...props} key={button.value} value={button.value}> {label} </ToggleButton> ) })} </ToggleButtonGroup> ) return renderField( field, label, form, widgetElem, children, extraColElem, addon, vertical ) } export default renderField
JavaScript
0
@@ -5097,343 +5097,8 @@ %0A%7D%0A%0A -export const renderValue = (%7B%0A field, // %7B name, value, onChange, onBlur %7D%0A form, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.%0A ...props%0A%7D) =%3E %7B%0A const id = field.id %7C%7C field.name%0A return (%0A %3CFormControl.Static componentClass=%7B%22span%22%7D id=%7Bid%7D%3E%0A %7BgetHumanValue(field)%7D%0A %3C/FormControl.Static%3E%0A )%0A%7D%0A%0A expo
1ace0f6d5438d459debdffe2ac80a298f594dbf0
remove hard-coded list of unary keywords in space-unary-ops rule (fixes #2696)
lib/rules/space-unary-ops.js
lib/rules/space-unary-ops.js
/** * @fileoverview This rule shoud require or disallow spaces before or after unary operations. * @author Marcin Kumorek * @copyright 2014 Marcin Kumorek. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { var options = context.options && Array.isArray(context.options) && context.options[0] || { words: true, nonwords: false }; //-------------------------------------------------------------------------- // Helpers //-------------------------------------------------------------------------- /** * Check if the parent unary operator is "!" in order to know if it's "!!" convert to Boolean or just "!" negation * @param {ASTnode} node AST node * @returns {boolean} Whether or not the parent is unary "!" operator */ function isParentUnaryBangExpression(node) { return node && node.parent && node.parent.type === "UnaryExpression" && node.parent.operator === "!"; } /** * Checks if the type is a unary word expression * @param {string} type value of AST token * @returns {boolean} Whether the word is in the list of known words */ function isWordExpression(type) { return ["delete", "new", "typeof", "void"].indexOf(type) !== -1; } /** * Check if the node's child argument is an "ObjectExpression" * @param {ASTnode} node AST node * @returns {boolean} Whether or not the argument's type is "ObjectExpression" */ function isArgumentObjectExpression(node) { return node.argument && node.argument.type && node.argument.type === "ObjectExpression"; } /** * Check Unary Word Operators for spaces after the word operator * @param {ASTnode} node AST node * @param {object} firstToken first token from the AST node * @param {object} secondToken second token from the AST node * @returns {void} */ function checkUnaryWordOperatorForSpaces(node, firstToken, secondToken) { if (options.words) { if (secondToken.range[0] === firstToken.range[1]) { context.report(node, "Unary word operator \"" + firstToken.value + "\" must be followed by whitespace."); } } if (!options.words && isArgumentObjectExpression(node)) { if (secondToken.range[0] > firstToken.range[1]) { context.report(node, "Unexpected space after unary word operator \"" + firstToken.value + "\"."); } } } /** * Checks UnaryExpression, UpdateExpression and NewExpression for spaces before and after the operator * @param {ASTnode} node AST node * @returns {void} */ function checkForSpaces(node) { var tokens = context.getFirstTokens(node, 2), firstToken = tokens[0], secondToken = tokens[1]; if (isWordExpression(firstToken.value)) { checkUnaryWordOperatorForSpaces(node, firstToken, secondToken); return void 0; } if (options.nonwords) { if (node.prefix) { if (isParentUnaryBangExpression(node)) { return void 0; } if (firstToken.range[1] === secondToken.range[0]) { context.report(node, "Unary operator \"" + firstToken.value + "\" must be followed by whitespace."); } } else { if (firstToken.range[1] === secondToken.range[0]) { context.report(node, "Space is required before unary expressions \"" + secondToken.value + "\"."); } } } else { if (node.prefix) { if (secondToken.range[0] > firstToken.range[1]) { context.report(node, "Unexpected space after unary operator \"" + firstToken.value + "\"."); } } else { if (secondToken.range[0] > firstToken.range[1]) { context.report(node, "Unexpected space before unary operator \"" + secondToken.value + "\"."); } } } } //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- return { "UnaryExpression": checkForSpaces, "UpdateExpression": checkForSpaces, "NewExpression": checkForSpaces }; }; module.exports.schema = [ { "type": "object", "properties": { "words": { "type": "boolean" }, "nonwords": { "type": "boolean" } }, "additionalProperties": false } ];
JavaScript
0
@@ -1130,311 +1130,8 @@ %7D%0A%0A - /**%0A * Checks if the type is a unary word expression%0A * @param %7Bstring%7D type value of AST token%0A * @returns %7Bboolean%7D Whether the word is in the list of known words%0A */%0A function isWordExpression(type) %7B%0A return %5B%22delete%22, %22new%22, %22typeof%22, %22void%22%5D.indexOf(type) !== -1;%0A %7D%0A%0A @@ -2699,42 +2699,37 @@ if ( -isWordExpression(firstToken.value) +firstToken.type === %22Keyword%22 ) %7B%0A
7e629a4aa50ff8323a58d333ad2a0701969c5db8
Stop comment polling on route change
client/src/js/controllers/comment.js
client/src/js/controllers/comment.js
angular.module('gokibitz.controllers') .controller('CommentController', [ '$rootScope', '$scope', '$http', '$routeParams', 'Comment', 'pathFilter', function ($rootScope, $scope, $http, $routeParams, Comment, pathFilter) { //console.log('Comment Controller'); //console.log('scope', $scope); $scope.$watch('kifu', function () { //console.log('KIFU', $scope.kifu); if ($scope.kifu) { $scope.formData = {}; $scope.listComments = function () { //console.log('checking $scope.comments', $scope.comments); //console.log('$scope.loading', $scope.loading); //console.log('list comments itself, checking path', $scope.kifu.path); var path; if ($scope.kifu.path.m === 0) { path = ''; } else { path = pathFilter($scope.kifu.path, 'string'); } //console.log('path', path); $http.get('/api/kifu/' + $scope.kifu._id + '/comments/' + path ) .success(function (data) { data.forEach(function (comment) { comment.path = pathFilter(comment.path, 'object'); }); $scope.comments = data; setTimeout(function () { $scope.loading = false; }, 0); }) .error(function (data) { console.log('Error: ' + data); }); }; $scope.addComment = function () { var data = $scope.formData; data._id = $scope.kifu._id; data.path = pathFilter($scope.kifu.path, 'string'); //console.log('checking data', data); var newComment = new Comment(data); newComment.$save(function (response) { $scope.formData = {}; $scope.listComments(); }); }; $scope.updateComment = function (comment) { var self = this; $http.put('/api/comment/' + comment._id, comment) .success(function (data) { angular.extend(comment, data.comment); delete self.edit; }) .error(function (data) { console.log('Error: ' + data); }); }; $scope.cancelEdit = function (comment) { var self = this; $http.get('/api/comment/' + comment._id) .success(function (data) { angular.extend(comment, data); delete self.edit; }) .error(function (data) { console.log('Error: ' + data); }); }; $scope.deleteComment = function (comment) { $http.delete('/api/comment/' + comment._id) .success(function () { $scope.listComments(); }) .error(function (data) { console.log('Error: ' + data); }); }; // Load Comments $scope.loading = true; $scope.listComments(); setInterval(function () { $scope.listComments(); }, 3000); $scope.$watch('kifu.path', function () { $scope.loading = true; $scope.comments = null; $scope.listComments(); // Resize the iframe //console.log('resize from comments controller'); //resize(); }, true); $scope.$on('edit', function (event, edit) { //console.log('edit has changed', edit); }); } }); } ]);
JavaScript
0
@@ -69,96 +69,8 @@ er', - %5B%0A%09%09'$rootScope',%0A%09%09'$scope',%0A%09%09'$http',%0A%09%09'$routeParams',%0A%09%09'Comment',%0A%09%09'pathFilter', %0A%09%09f @@ -2595,16 +2595,35 @@ ;%0A%0A%09%09%09%09%09 +var pollComments = setInter @@ -2681,24 +2681,133 @@ %09%7D, 3000);%0A%0A +%09%09%09%09%09$scope.$on('$routeChangeStart', function (next, current) %7B%0A%09%09%09%09%09%09clearInterval(pollComments);%0A%09%09%09%09%09%7D);%0A%0A %09%09%09%09%09$scope. @@ -3173,8 +3173,7 @@ %09%7D%0A%09 -%5D );%0A
0eb98c637bb0e4e882a20c95189cac56341a311f
Handle local execution with the Lambda callback model
lib/run/execution-wrapper.js
lib/run/execution-wrapper.js
// Wrapper for a Lambda function executing in a different process "use strict"; function sendError(pid, err, callback) { const message = err.message || err; console.error(message); if (err.stack) { console.error(err.stack); } process.send({ result: message, type: 'error' }, null, callback); } function sendResult(pid, result, callback) { process.send({ result: JSON.stringify(result), type: 'result' }, null, callback); } function exit(error, result) { if (error) { sendError(process.pid, error, function() { process.exit(1); }); return; } sendResult(process.pid, result, function() { process.exit(0); }); } function parseArgs(args) { return args.reduce(function(ret, val, id) { if (id === 2) { ret.path = val; } else if (id === 3) { ret.handler = val; } else if (id === 4) { ret.event = JSON.parse(val); } else if (id === 5) { ret.timeout = val; } return ret; }, { }); } function wrapper(path, handler, evt, timeout) { timeout = parseInt(timeout || 6000, 10); handler = handler || 'handler'; evt = evt || {}; // Timeout monitoring const now = new Date().getTime(); const deadline = now + timeout; let context = {}; const watchdog = setTimeout(function() { context.fail(new Error('Operation timed out')); }, timeout); // Listen to premature exits process.on('beforeExit', function() { context.fail(new Error('Process exited without completing request')); }); // Create a context object to pass along to the Lambda function context = { done: function(error, result) { clearTimeout(watchdog); exit(error, result); }, succeed: function(result) { clearTimeout(watchdog); exit(null, result); }, fail: function(error) { clearTimeout(watchdog); exit(error, null); }, getRemainingTimeInMillis: function() { return deadline - (new Date()).getTime(); } }; try { require(path)[handler](evt, context); } catch(err) { sendError(process.pid, err, function() { process.exit(1); }); } } const args = parseArgs(process.argv); wrapper(args.path, args.handler, args.event, args.timeout);
JavaScript
0
@@ -1221,16 +1221,42 @@ t %7C%7C %7B%7D; +%0A let finished = false; %0A%0A // @@ -1558,32 +1558,61 @@ ', function() %7B%0A + if (!finished) %7B%0A context. @@ -1669,24 +1669,34 @@ request'));%0A + %7D%0A %7D);%0A%0A @@ -2230,24 +2230,71 @@ );%0A %7D +,%0A%0A callbackWaitsForEmptyEventLoop: true %0A %7D;%0A%0A @@ -2307,16 +2307,27 @@ %0A + const fn = require @@ -2345,23 +2345,885 @@ ler%5D -(evt, context); +;%0A%0A // Detect if it uses the callback pattern or not%0A if (fn.length === 3) %7B%0A // Callback is used, in our case we will just send out%0A // the result and stop the watchdog, but we will not forcefully%0A // exit the process. This should be similar to how Lambda does it,%0A // where it naturally then let's the process terminate%0A fn(evt, context, function(err, data) %7B%0A clearTimeout(watchdog);%0A finished = true;%0A%0A if (!context.callbackWaitsForEmptyEventLoop) %7B%0A // Exit the process as well%0A exit(err, data);%0A %7D else %7B%0A if (err) sendError(process.pid, err);%0A sendResult(process.pid, data);%0A %7D%0A %7D);%0A %7D else %7B%0A fn(evt, context);%0A %7D %0A
a750bcf87327c0e413ad6019e991aaa0a88d072e
Update fichas.js
app/controllers/fichas.js
app/controllers/fichas.js
//PdfModule var fichaReme = require('../pdf/fichaReme'); // Config var config = require('../config/config'); // Models Ficha = require('../models/').Ficha; Users = require('../models/').User; // CRUD Operations for Ficha Model module.exports = { index(req, res) { Ficha.findAll() .then(function (Fichas) { Fichas.forEach(function(ficha){ var areaYObjetivoPorSeccion = config.areaYObjetivoPorSeccion(ficha.seccion, ficha.areadedesarrollo); ficha.dataValues.area = areaYObjetivoPorSeccion.area; ficha.dataValues.nombrearea = areaYObjetivoPorSeccion.nombrearea; }) console.log(Fichas); res.status(200).json(Fichas); }) .catch(function (error) { console.log(error); res.status(500).json(error); }); }, show(req, res) { Ficha.findAll({ where: { id: req.params.id }, include: [{ model: Users }] }) .then(function (Ficha) { console.log(Ficha); var areaYObjetivoPorSeccion = config.areaYObjetivoPorSeccion(Ficha.seccion, Ficha.areadedesarrollo); Ficha.dataValues.area = areaYObjetivoPorSeccion.area; Ficha.dataValues.nombrearea = areaYObjetivoPorSeccion.nombrearea; res.status(200).json(Ficha); }) .catch(function (error) { console.log(error); res.status(500).json(error); }); }, create(req, res) { // res.status(200).json(req.body); Ficha.create(req.body) .then(function (newFicha) { res.status(200).json(newFicha); }) .catch(function (error) { res.status(500).json(error); }); }, update(req, res) { Ficha.update(req.body, { where: { id: req.body.id } }) .then(function (updatedRecords) { res.status(200).json(updatedRecords); }) .catch(function (error) { console.log(error); res.status(500).json(error); }); }, delete(req, res) { console.log(req.params) Ficha.destroy({ where: { id: req.params.id } }) .then(function (deletedRecords) { res.status(200).json(deletedRecords); }) .catch(function (error) { console.log(error); res.status(500).json(error); }); }, print(req, res) { Ficha.findAll({ where: { id: req.params.id }, include: [{ model: Users }] }) .then(function (Ficha) { var doc = fichaReme.pdf(Ficha[0].dataValues); doc.pipe(res); doc.end(); // req.body }) .catch(function (error) { console.log(error); res.status(500).json(error); }); } };
JavaScript
0
@@ -675,45 +675,8 @@ %7D)%0A - console.log(Fichas);%0A @@ -1098,28 +1098,43 @@ -console.log(Ficha);%0A +Ficha.forEach(function(ficha)%7B%0A @@ -1206,17 +1206,17 @@ Seccion( -F +f icha.sec @@ -1221,17 +1221,17 @@ eccion, -F +f icha.are @@ -1254,33 +1254,37 @@ -F + f icha.dataValues. @@ -1332,25 +1332,29 @@ -F + f icha.dataVal @@ -1398,32 +1398,51 @@ ion.nombrearea;%0A + %7D)%0A
0e96b4f59abd87c4b74b4e97bdf419bbf00e9516
Debounce the search query task
app/controllers/search.js
app/controllers/search.js
import Controller from '@ember/controller'; import { computed } from '@ember/object'; import { alias, bool, readOnly } from '@ember/object/computed'; import { inject as service } from '@ember/service'; import { task } from 'ember-concurrency'; import PaginationMixin from '../mixins/pagination'; export default Controller.extend(PaginationMixin, { search: service(), queryParams: ['q', 'page', 'per_page', 'sort'], q: alias('search.q'), page: '1', per_page: 10, sort: null, model: readOnly('dataTask.lastSuccessful.value'), hasData: computed('dataTask.lastSuccessful', 'dataTask.isRunning', function() { return this.get('dataTask.lastSuccessful') || !this.get('dataTask.isRunning'); }), firstResultPending: computed('dataTask.lastSuccessful', 'dataTask.isRunning', function() { return !this.get('dataTask.lastSuccessful') && this.get('dataTask.isRunning'); }), totalItems: readOnly('model.meta.total'), currentSortBy: computed('sort', function() { if (this.get('sort') === 'downloads') { return 'All-Time Downloads'; } else if (this.get('sort') === 'recent-downloads') { return 'Recent Downloads'; } else { return 'Relevance'; } }), hasItems: bool('totalItems'), dataTask: task(function* (params) { if (params.q !== null) { params.q = params.q.trim(); } return yield this.store.query('crate', params); }).drop(), });
JavaScript
0.999998
@@ -209,16 +209,25 @@ t %7B task +, timeout %7D from @@ -301,16 +301,42 @@ tion';%0A%0A +const DEBOUNCE_MS = 250;%0A%0A export d @@ -1381,24 +1381,98 @@ (params) %7B%0A + // debounce the search query%0A yield timeout(DEBOUNCE_MS);%0A%0A if ( @@ -1610,12 +1610,19 @@ %7D). -drop +restartable (),%0A
d1cbff7110f4c139d2993327b81a002413b769c5
Add person information if available and http headers
lib/server/rollbar-server.js
lib/server/rollbar-server.js
rollbar = Npm.require("rollbar"); var environmentVarsRequired = [ 'ROLLBAR_SERVER_ACCESS_TOKEN', 'ROLLBAR_CLIENT_ACCESS_TOKEN' ]; rollbarServerAccessToken = null; rollbarClientAccessToken = null; var allNecessaryKeysAvailable = function() { return _.reduce(_.map(environmentVarsRequired, function(envVar) { return !_.isUndefined(process.env[envVar]); }), function(memo, item) { return memo && item; }, true); }; var reportAPIConnectionNotPossible = function() { var message = ''; message = "Cannot connect to Rollbar API as the following environment variables are not available: [ " + environmentVarsRequired.join(', ') + " ]"; console.log(message); }; throwErrorIfNotInitialised = function() { if (!allNecessaryKeysAvailable()) { throw new Meteor.Error(403, "Cannot connect to Rollbar API as the following environment variables are not available: [ " + environmentVarsRequired.join(', ') + " ]"); } }; throwError = function(message) { check(message, String); throwErrorIfNotInitialised(); var exceptionDetails = arguments.length > 1 ? arguments[1] : {}; var logLevel = arguments.length > 2 ? arguments[2] : 'error'; check(exceptionDetails, Object); check(logLevel, String); rollbar.reportMessageWithPayloadData(message, { level: logLevel, custom: exceptionDetails }, {}, function(err) { if (err) { console.log("saucecode:rollbar: failed to throw error to rollbar."); console.log(err); } }); }; handleError = function(error) { var payloadData = arguments.length > 1 ? arguments[1] : {}; var logLevel = arguments.length > 2 ? arguments[2] : 'error'; check(payloadData, Object); check(logLevel, String); throwErrorIfNotInitialised(); rollbar.handleErrorWithPayloadData(error, { level: logLevel, custom: payloadData }, function(err) { if (err) { console.log("saucecode:rollbar: failed to post error to rollbar."); console.log(err); } }); }; var methods = { logClientError: function(method, arguments) { var fn = rollbar[method] if (fn) fn.apply(this, arguments); }, getRollbarClientConfig: function() { return { accessToken: rollbarClientAccessToken, captureUncaught: true, payload: { environment: rollbarEnvironment || "production" } }; }, throwError: function() { check(arguments, [Match.Any]); throwError.apply(this, arguments); // Using apply to use array of args }, handleError: function() { check(arguments, [Match.Any]); handleError.apply(this, arguments); } }; Meteor.startup(function() { if (allNecessaryKeysAvailable()) { rollbarServerAccessToken = process.env["ROLLBAR_SERVER_ACCESS_TOKEN"]; rollbarClientAccessToken = process.env["ROLLBAR_CLIENT_ACCESS_TOKEN"]; rollbarEnvironment = process.env["ROLLBAR_ENVIRONMENT"] || 'development'; rollbar.init(rollbarServerAccessToken, { environment: rollbarEnvironment }); Inject.rawHead('rollbar', Assets.getText('lib/private/client-head.html'). replace("POST_CLIENT_ITEM_ACCESS_TOKEN", rollbarClientAccessToken). replace("ENVIRONMENT", rollbarEnvironment) ); rollbar.handleUncaughtExceptions(rollbarServerAccessToken, { exitOnUncaughtException: true }); Meteor.methods(methods); } else { reportAPIConnectionNotPossible(); } });
JavaScript
0
@@ -196,16 +196,307 @@ null;%0A%0A +var getUserPayload = function(userId) %7B%0A var userPayload = %7B%7D;%0A if(userId) %7B%0A var user = Meteor.users.findOne(%7B_id: userId%7D);%0A userPayload = %7B%0A id: userId,%0A username: user.profile && user.profile.name%0A %7D;%0A %7D else %7B%0A userPayload = null;%0A %7D%0A return userPayload;%0A%7D;%0A%0A var allN @@ -1589,16 +1589,99 @@ gLevel,%0A + person: getUserPayload(this.userId),%0A headers: this.connection.httpHeaders,%0A cust @@ -2171,16 +2171,99 @@ Level, %0A + person: getUserPayload(this.userId),%0A headers: this.connection.httpHeaders,%0A cust
9fbce034009fe669358f70e5440aab93073287a0
Remove the strange `isFalse` and `isTrue`.
katas/es6/language/number-api/isinteger.js
katas/es6/language/number-api/isinteger.js
// 55: Number - isInteger // To do: make all tests pass, leave the assert lines unchanged! // Follow the hints of the failure messages! describe('`Number.isInteger()` determines if a value is an integer', function(){ const isTrue = (what) => assert.equal(what, true); const isFalse = (what) => assert.equal(what, false); it('`isInteger` is a static function on `Number`', function() { //// const whatType = 'method'; const whatType = 'function'; assert.equal(typeof Number.isInteger, whatType); }); describe('zero in different ways', function() { it('0 is an integer', function() { //// const zero = null; const zero = 0; isTrue(Number.isInteger(zero)); }); it('0.000', function() { //// const veryZero = 0.000001; const veryZero = 0.00000; isTrue(Number.isInteger(veryZero)); }); it('the string "0" is NOT an integer', function() { //// const stringZero = 0; const stringZero = '0'; isFalse(Number.isInteger(stringZero)); }); }); describe('one in different ways', function() { it('0.111 + 0.889', function() { //// const rest = 0.88; const rest = 0.889; isTrue(Number.isInteger(0.111 + rest)); }); it('0.5 + 0.2 + 0.2 + 0.1 = 1 ... isn`t it?', function() { //// const oneOrNot = 0.5 + 0.2 + 0.3; const oneOrNot = 0.5 + 0.2 + 0.4; isFalse(Number.isInteger(oneOrNot)); }); it('parseInt`ed "1" is an integer', function() { //// const convertedToInt = Number.parse('1.01'); const convertedToInt = Number.parseInt('1.01'); isTrue(Number.isInteger(convertedToInt)); }); }); describe('what is not an integer', function() { it('`Number()` is an integer', function() { //// const numberOne = Number; const numberOne = Number(); isTrue(Number.isInteger(numberOne)); }); it('`{}` is NOT an integer', function() { //// const isit = Number.isWhat({}); const isit = Number.isInteger({}); isFalse(isit); }); it('`0.1` is not an integer', function() { //// const isit = Number(0.1); const isit = Number.isInteger(0.1); isFalse(isit); }); it('`Number.Infinity` is not an integer', function() { //// const isit = Number.isInteger(Number.MAX_VALUE); const isit = Number.isInteger(Number.Infinity); isFalse(isit); }); it('`NaN` is not an integer', function() { //// const isit = Number.isFloat(NaN); const isit = Number.isInteger(NaN); isFalse(isit); }); }); });
JavaScript
0.99947
@@ -215,116 +215,8 @@ ()%7B%0A - const isTrue = (what) =%3E assert.equal(what, true);%0A const isFalse = (what) =%3E assert.equal(what, false);%0A it @@ -273,24 +273,24 @@ unction() %7B%0A + //// con @@ -544,38 +544,38 @@ zero = 0;%0A -isTrue +assert (Number.isIntege @@ -689,38 +689,38 @@ 0.00000;%0A -isTrue +assert (Number.isIntege @@ -858,39 +858,38 @@ ro = '0';%0A -isFalse +assert (Number.isIntege @@ -897,24 +897,34 @@ (stringZero) + === false );%0A %7D);%0A @@ -1068,38 +1068,38 @@ = 0.889;%0A -isTrue +assert (Number.isIntege @@ -1278,23 +1278,22 @@ ;%0A -isFalse +assert (Number. @@ -1311,16 +1311,26 @@ neOrNot) + === false );%0A %7D @@ -1493,38 +1493,38 @@ ('1.01');%0A -isTrue +assert (Number.isIntege @@ -1736,14 +1736,14 @@ -isTrue +assert (Num @@ -1909,36 +1909,45 @@ (%7B%7D);%0A -isFalse(isit +assert(isit === false );%0A %7D);%0A @@ -2073,36 +2073,45 @@ 0.1);%0A -isFalse(isit +assert(isit === false );%0A %7D);%0A @@ -2284,36 +2284,45 @@ ity);%0A -isFalse(isit +assert(isit === false );%0A %7D);%0A @@ -2464,20 +2464,29 @@ -isFalse(isit +assert(isit === false );%0A
18c6d8cb2ebeafef2efeb9c447e87733f3cd1095
Fix hiding the blinking cursor on Firefox
tests/acceptance/setup.js
tests/acceptance/setup.js
import { remote } from 'webdriverio'; import Mugshot from 'mugshot'; import WebdriverIOAdapter from 'mugshot-webdriverio'; import path from 'path'; const { BROWSER } = process.env; let mugshot; before(function() { this.timeout(10 * 1000); const options = { host: 'selenium', desiredCapabilities: { browserName: BROWSER } }; global.browser = remote(options).init(); const adapter = new WebdriverIOAdapter(global.browser); mugshot = new Mugshot(adapter, { rootDirectory: path.join(__dirname, 'screenshots', BROWSER), acceptFirstBaseline: false }); return global.browser; }); function checkForVisualChanges(test, name, selector = '.todoapp') { return new Promise(resolve => { try { mugshot.test({ name, selector }, (err, result) => { if (err) { test.error(err); resolve(); return; } if (!result.isEqual) { // If we reject the promise Mocha will halt the suite. Workaround from // https://github.com/mochajs/mocha/issues/1635#issuecomment-191019928 test.error(new Error('Visual changes detected. Check screenshots')); } resolve(); }); } catch (e) { test.error(e); resolve(); } }); } beforeEach(function() { return global.browser.url('http://app:3000/') // Wait for webpack to build the app. .then(() => global.browser.waitForVisible('.todoapp', 5 * 1000)); }); afterEach(function() { return checkForVisualChanges(this.test, this.currentTest.fullTitle()); }); after(function() { return global.browser.end(); });
JavaScript
0
@@ -606,16 +606,22 @@ r;%0A%7D);%0A%0A +async function @@ -682,22 +682,256 @@ p') %7B%0A -return +// TODO: defocus the add todo field because the _blinking_ caret is causing%0A // the tests to be flaky; remove when Firefox 53 is released and leave it to%0A // caret-color: transparent.%0A return global.browser.click('.header h1').then(() =%3E new Pro @@ -1490,16 +1490,17 @@ %7D%0A %7D) +) ;%0A%7D%0A%0Abef
3048a7d2f00dc9897181eee1f650157c8dd49da1
Update play button selector for Hype Machine test.
tests/connectors/hypem.js
tests/connectors/hypem.js
'use strict'; module.exports = function(driver, connectorSpec) { connectorSpec.shouldBehaveLikeMusicSite(driver, { url: 'http://hypem.com/artist/Violet+Days+x+Win+and+Woo', playButtonSelector: '.tools .playdiv' }); };
JavaScript
0
@@ -197,23 +197,19 @@ r: ' -.tools .playdiv +#playerPlay '%0A%09%7D
00d812479fe791c7b0921d72ae0eb108c35486a4
Use proper placeholders for future functionalities
plugins/core-cloud/src/components/detailstab.js
plugins/core-cloud/src/components/detailstab.js
const {i18n, React} = Serverboards import Details from '../containers/details' class DetailsTab extends React.Component{ constructor(props){ super(props) this.state={ tab: "details" } } render(){ let Section = () => null const section = this.state.tab switch(section){ case "details": Section=Details break; } return ( <div className="ui expand with right side menu"> <Section {...this.props}/> <div className="ui side menu"> <a className={`item ${section == "details" ? "active" : ""}`} data-tooltip={i18n("Details")} data-position="left center" onClick={() => this.setState({tab:"details"})} > <i className="file text outline icon"></i> </a> <a className={`item ${section == "edit" ? "active" : ""}`} data-tooltip={i18n("Edit")} data-position="left center" onClick={() => this.setState({tab:"edit"})} > <i className="code icon"></i> </a> <a className={`item ${section == "logs" ? "active" : ""}`} data-tooltip={i18n("Logs")} data-position="left center" onClick={() => this.setState({tab:"logs"})} > <i className="desktop icon"></i> </a> </div> </div> ) } } export default DetailsTab
JavaScript
0
@@ -858,20 +858,19 @@ ion == %22 -edit +ssh %22 ? %22act @@ -919,12 +919,27 @@ 8n(%22 -Edit +SSH Remote Terminal %22)%7D%0A @@ -1031,12 +1031,11 @@ ab:%22 -edit +ssh %22%7D)%7D @@ -1151,20 +1151,30 @@ ion == %22 -logs +remote_desktop %22 ? %22act @@ -1223,12 +1223,22 @@ 8n(%22 -Logs +Remote Desktop %22)%7D%0A @@ -1330,12 +1330,22 @@ ab:%22 -logs +remote_desktop %22%7D)%7D
7ac1c53a91ed0598ecf09c0f310ea599b2daa201
Fix the compressor output connection
src/youmix.js
src/youmix.js
$(document).ready(function() { var player = $("video.html5-main-video")[0]; if (!player) { return; } function makeDistortionCurve(amount) { var k = typeof amount === 'number' ? amount : 50, samples = 44100, curve = new Float32Array(samples), deg = Math.PI / 180, i = 0, x; for ( ; i < samples; ++i ) { x = i * 2 / samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) ); } return curve; } var context = new AudioContext(); var source = context.createMediaElementSource(player); source.connect(context.destination); // Set up the different audio nodes we will use for the app var analyser = context.createAnalyser(); var distortion = context.createWaveShaper(); var gainNode = context.createGain(); var biquadFilter = context.createBiquadFilter(); var convolver = context.createConvolver(); var oscillator = context.createOscillator(); var compressor = context.createDynamicsCompressor(); $.get(chrome.extension.getURL("templates/body.html"), function(data) { $('#watch-header').after(data); }); $('body').on('change', "#ym-presets", function() { var preset = $(this).val(); console.log(preset); presets(preset); }); function presets(preset) { source.disconnect(); switch (preset) { case 'normal': source.connect(context.destination); break; case 'underwater': break; case 'lowpass': break; case 'compressor': // Connect the source node to the destination source.connect(compressor); compressor.threshold.value = -50; compressor.knee.value = 40; compressor.ratio.value = 12; compressor.reduction.value = -20; compressor.attack.value = 0; compressor.release.value = 0.25; // Connect to output gainNode.connect(context.destination); break; case 'hallway': source.connect(biquadFilter); biquadFilter.connect(gainNode); biquadFilter.type = "highpass"; biquadFilter.frequency.value = 1000; biquadFilter.gain.value = 688; // Connect to output gainNode.connect(context.destination); break; } } });
JavaScript
0.000058
@@ -1840,16 +1840,17 @@ = 0.25;%0A +%0A @@ -1874,32 +1874,34 @@ put%0A -gainNode +compressor .connect(con
9d43907c856fc053f764543cbbd441719b55b5e5
Include rescue list in rat
api/models/rat.js
api/models/rat.js
'use strict' let mongoose = require('mongoose') mongoose.Promise = global.Promise let Schema = mongoose.Schema let RatSchema = new Schema({ archive: { default: false, type: Boolean }, CMDRname: { type: String }, createdAt: { type: Date }, data: { default: {}, type: Schema.Types.Mixed }, drilled: { default: { dispatch: false, rescue: false }, type: { dispatch: { type: Boolean }, rescue: { type: Boolean } } }, lastModified: { type: Date }, joined: { default: Date.now(), type: Date }, nicknames: { default: [], type: [{ type: String }] }, platform: { default: 'pc', enum: [ 'pc', 'xb' ], type: String }, rescues: { type: [{ type: Schema.Types.ObjectId, ref: 'Rescue' }] }, rescueCount: { default: 0, index: true, type: Number }, user: { type: Schema.Types.ObjectId, ref: 'User' } }, { versionKey: false }) RatSchema.index({ CMDRname: 'text' }) let linkRescues = function (next) { var rat rat = this rat.rescues = rat.rescues || [] mongoose.models.Rescue.update({ $text: { $search: rat.CMDRname.replace(/cmdr /i, '').replace(/\s\s+/g, ' ').trim(), $caseSensitive: false, $diacriticSensitive: false } }, { $set: { platform: rat.platform }, $pull: { unidentifiedRats: rat.CMDRname.replace(/cmdr /i, '').replace(/\s\s+/g, ' ').trim() }, $push: { rats: rat._id } }) .then(function () { mongoose.models.Rescue.find({ rats: rat._id }).then(function (rescues) { rescues.forEach(function (rescue) { //this.rescues.push( rescue._id ) }) if (this.rescues) { this.rescueCount = this.rescues.length } else { this.rescueCount = 0 } next() }).catch(next) }) } let normalizePlatform = function (next) { this.platform = this.platform.toLowerCase().replace(/^xb\s*1|xbox|xbox1|xbone|xbox\s*one$/g, 'xb') next() } let updateTimestamps = function (next) { let timestamp = new Date() if (!this.open) { this.active = false } if (this.isNew) { this.createdAt = this.createdAt || timestamp } this.lastModified = timestamp next() } let sanitizeInput = function (next) { let rat = this if (rat && rat.CMDRname) { rat.CMDRname = rat.CMDRname.replace(/cmdr /i, '').replace(/\s\s+/g, ' ').trim() } next() } RatSchema.pre('save', sanitizeInput) RatSchema.pre('save', updateTimestamps) RatSchema.pre('save', normalizePlatform) RatSchema.pre('save', linkRescues) RatSchema.pre('update', sanitizeInput) RatSchema.pre('update', updateTimestamps) RatSchema.set('toJSON', { virtuals: true }) RatSchema.plugin(require('mongoosastic')) if (mongoose.models.Rat) { module.exports = mongoose.model('Rat') } else { module.exports = mongoose.model('Rat', RatSchema) }
JavaScript
0.000001
@@ -1756,10 +1756,8 @@ -// this @@ -1770,17 +1770,16 @@ es.push( - rescue._ @@ -1780,17 +1780,16 @@ scue._id - )%0A
0e97b90e355cb69b7b9b59952ed335ffef38eb8d
add (probably)complete elements with [src] list
recliner.js
recliner.js
/** * Recliner.js * A super lightweight production ready jQuery plugin * for lazy loading images and other dynamic content. * * Licensed under the MIT license. * Copyright 2014 Kam Low * http://sourcey.com */ ;(function($) { $.fn.recliner = function(options) { var $w = $(window), elements = this, selector = this.selector, loaded, timer, options = $.extend({ attrib: "data-src", // selector for attribute containing the media src throttle: 300, // millisecond interval at which to process events threshold: 100, // scroll distance from element before its loaded printable: true, // be printer friendly and show all elements on document print live: true, // auto bind lazy loading to ajax loaded elements getScript: false // load content with `getScript` rather than `ajax` }, options); // load the element source function load(e) { var $e = $(e), source = $e.attr(options.attrib), type = $e.prop('tagName'); if (source) { $e.addClass('lazy-loading'); if (type == 'IMG' || type == 'IFRAME') { $e.attr('src', source); $e[0].onload = function(ev) { onload($e); }; } else if (options.getScript === true) { $.getScript(source, function(ev) { onload($e); }); } else { // ajax load non image and iframe elements $e.load(source, function(ev) { onload($e); }); } } else { onload($e); // set as loaded if no action taken } } // handle element load complete function onload(e) { // remove loading and add loaded class to all elements e.removeClass('lazy-loading'); e.addClass('lazy-loaded'); // handle lazyshow event for custom processing e.trigger('lazyshow'); } // process the next elements in the queue function process() { var inview = elements.filter(function() { var $e = $(this); if ($e.css('display') == 'none') return; // If no Doctype is declared jquery's $(window).height() does not work properly // See http://stackoverflow.com/a/25274520/322253 // Therefore use innerHeight instead (if it's available) var viewportHeight = (typeof window.innerHeight !== 'undefined') ? window.innerHeight : $w.height(); var wt = $w.scrollTop(), wb = wt + viewportHeight, et = $e.offset().top, eb = et + $e.height(); return eb >= wt - options.threshold && et <= wb + options.threshold; }); loaded = inview.trigger("lazyload"); elements = elements.not(loaded); } // initialize elements for lazy loading function init(els) { // bind the lazyload event for loading elements els.one("lazyload", function() { load(this); }); process(); } // bind lazy loading events $w.on("scroll.lazy resize.lazy lookup.lazy", function(ev) { if (timer) clearTimeout(timer); // throttle events for best performance timer = setTimeout(function() { $w.trigger("lazyupdate"); }, options.throttle); }); $w.on("lazyupdate", function(ev) { process(); }); // handle elements loaded into the dom via ajax if (options.live) { $(document).ajaxSuccess(function(ev, xhr, settings) { var $e = $(selector).not('.lazy-loaded').not('.lazy-loading'); elements = elements.add($e); init($e); }); } // be printer friendly and show all elements on document print if (options.printable && window.matchMedia) { window .matchMedia('print') .addListener(function (mql) { if (mql.matches) { $(selector).trigger('lazyload'); } }); } init(this); return this; }; })(window.jQuery);
JavaScript
0
@@ -1110,24 +1110,25 @@ ding');%0A +%0A if (type @@ -1123,45 +1123,326 @@ -if (type == 'IMG' %7C%7C type == 'IFRAME' +// elements with %5Bsrc%5D attribute: %3Caudio%3E, %3Cembed%3E, %3Ciframe%3E, %3Cimg%3E, %3Cinput%3E, %3Cscript%3E, %3Csource%3E, %3Ctrack%3E, %3Cvideo%3E (https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes)%0A // excepts: %3Cinput%3E, %3Cscript%3E (use options.getScript instead)%0A if (/%5E(IMG%7CIFRAME%7CAUDIO%7CEMBED%7CSOURCE%7CTRACK%7CVIDEO)$/.test(type) ) %7B%0A @@ -4204,23 +4204,16 @@ %7D;%0A%0A%7D)( -window. jQuery);
cf4dac1b49177ebb73fd59d35641ef00ee5a1a04
Update paramour.js
Paramour/paramour/paramour.js
Paramour/paramour/paramour.js
CodeMirror.defineSimpleMode("paramour", { // The start state contains the rules that are intially used start: [ // Strings { regex: /(["'])(?:[^\\]|\\.)*?\1/, token: "string" }, { regex: /(\B\/(?:[^\\]|\\.)+?\/)([imguy]*)/, token: ["string", "variable-2"] }, // Comments { regex: /###/, token: "comment", next: "comment" }, { regex: /(#\s*)(\$[a-z\$][\w\$]*)(\s*[\-\=]>\s*)(.*)/i, token: ["comment", "variable", "operator", null] }, { regex: /(#\s*)(@)([\d\.]+)/i, token: ["comment", null, "number"] }, { regex: /(#\s*)([\d\.]+)(\?[\!\*]?)/i, token: ["operator", "number", "operator"] }, { regex: /#\?/, token: "operator" }, { regex: /#.*/, token: "comment" }, // Docstrings { regex: /\/\*/, token: "string", next: "docstring" }, // Quasi Strings { regex: /`/, token: "string", next: "quasi" }, { regex: /(["'`]{3})(?:[^\\]:\\.)*?\1/, token: "string" }, // Get and Set { regex: /([gs]et\b\??)\s*([a-zA-Z\$_][\w\$]*)/, token: ["keyword-2", "variable"] }, // Custom Operators { // Prefix Operator regex: /(\[\s*)([!\~\*\/%\+\-<>\&\^\|\?\:\=;]+)(\s*[a-z\$_][\w\$]*)(\s*\])/i, token: [null, "variable-2", "variable", null] }, { // Media operator regex: /(\[\s*)([a-z\$_][\w\$]*\s*)([!\~\*\/%\+\-<>\&\^\|\?\:\=;]+)(\s*[a-z\$_][\w\$]*)(\s*\])/i, token: [null, "variable", "variable-2", "variable", null] }, { // Suffix Operator regex: /(\[\s*)([a-z\$_][\w\$]*\s*)([!\~\*\/%\+\-<>\&\^\|\?\:\=;]+)(\s*\])/i, token: [null, "variable", "variable-2", null] }, // Paramour Operators { regex: /((?:un)defined\s+)([a-zA-Z\$_][\w\$]*)/, token: ["keyword", "variable"] }, // Atoms and Atom-like { regex: /(\b(true|false|null|undefined|defined)\b|(\!+[01]))/, token: "keyword" }, // Keywords { regex: /\b(abstract|boolean|break|byte|case|catch|char|class|const|continue|debugger|default|delete|do|double|else|enum|eval|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|let|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|var|void|volatile|while|with|yield|[gs]et)\b/, token: "keyword" }, { regex: /[^\-\+][\-\+\~\&]>|@/, token: "keyword" }, // Variable names { regex: /(\.[a-z\$_][\w\$]*|\.{3}|<init>)/i, token: "variable-2" }, { regex: /([a-z\$_][\w\$]*)/i, token: "variable" }, // Numbers { regex: /\b(0b[01]+|0o[1-7]+|0x[a-f\d]+|[-+]?(?:\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?)\b/i, token: "number" }, // Operators { regex: /[!\~\*\/%\+\-<>\&\^\|\?\:\=]+/, token: "operator" }, // N. Literals { regex: /[\{\[\(\?]/, indent: true }, { regex: /[\)\]\}]/, dedent: true } ], // Quasi Strings quasi: [ { regex: /`/, token: "string", next: "start" }, { regex: /\$\{(?:[^\{\}]*?)\}/, mode: "start" }, { regex: /^(?:[^\\]|\\.)*?$/, token: "string" } ], // Docstrings docstring: [ { regex: /\*\//, token: "string", next: "start" }, { regex: /^(?:[^\*]|\*[^\/])*?$/, token: "string" } ], // Comments comment: [ { regex: /###/, token: "comment", next: "start" }, { regex: /^(?:[^#]|#[^#]|##[^#])*?$/, token: "comment" } ], // "The meta property contains global information about the mode. It // can contain properties like lineComment, which are supported by // all modes, and also directives like dontIndentStates, which are // specific to simple modes" - CodeMirror. meta: { dontIndentStates: ["comment"], blockCommentStart: "###", blockCommentEnd: "###", lineComment: "#", fold: "brace", closeBrackets: "( ) [ ] { } ' ' \" \" ` ` \"\"\" \"\"\" ''' ''' ``` ```".split(" ") } });
JavaScript
0
@@ -225,10 +225,8 @@ /(%5C -B%5C /(?: @@ -235,17 +235,17 @@ %5C%5C%5D%7C%5C%5C.) -+ +* ?%5C/)(%5Bim
aade0c7b62c53fbcada89610610d4d3e704964ef
Use put
src/decorator/validation.js
src/decorator/validation.js
import {OrmMetadata} from '../orm-metadata'; export function validation () { return function (target) { OrmMetadata.forTarget(target).addTo('validation', true); } }
JavaScript
0
@@ -138,13 +138,11 @@ et). -addTo +put ('va
95910172775ef59ccefcbbde3d3d6028f3140528
Add @fileoverview to control.js
src/directives/control.js
src/directives/control.js
goog.provide('ngeo.CreateControl'); goog.provide('ngeo.controlDirective'); goog.require('goog.asserts'); goog.require('ngeo'); /** * @typedef {function(Element): ol.control.Control} */ ngeo.CreateControl; /** * This directive can be used to add a control to a DOM element of * the HTML page. The user of the directive is responsible for * providing a function that returns the control instance. That * function should be defined in the parent scope. * * Example #1: * <div ngeo-control="createScaleLineControl"></div> * * Example #2: * <div ngeo-control="createScaleLineControl" ngeo-control-map="map1"></div> * * @return {angular.Directive} The directive specs. * @ngInject */ ngeo.controlDirective = function() { return { restrict: 'A', link: /** * @param {angular.Scope} scope Scope. * @param {angular.JQLite} element Element. * @param {angular.Attributes} attrs Attributes. */ function(scope, element, attrs) { var attr; attr = 'ngeoControl'; var createControl = /** @type {ngeo.CreateControl} */ (scope.$eval(attrs[attr])); var control = createControl(element[0]); attr = 'ngeoControlMap'; var map = /** @type {ol.Map} */ (scope.$eval(attrs[attr])); goog.asserts.assertInstanceof(map, ol.Map); map.addControl(control); } }; }; ngeoModule.directive('ngeoControl', ngeo.controlDirective);
JavaScript
0
@@ -1,227 +1,35 @@ -goog.provide('ngeo.CreateControl');%0Agoog.provide('ngeo.controlDirective');%0A%0Agoog.require('goog.asserts');%0Agoog.require('ngeo');%0A%0A%0A/**%0A * @typedef %7Bfunction(Element): ol.control.Control%7D%0A */%0Angeo.CreateControl;%0A%0A%0A/**%0A * This +/**%0A * @fileoverview Provides a dir @@ -72,16 +72,19 @@ to a DOM +%0A * element @@ -86,19 +86,16 @@ ement of -%0A * the HTM @@ -210,19 +210,16 @@ ce. That -%0A * functio @@ -226,16 +226,19 @@ n should +%0A * be defi @@ -426,24 +426,242 @@ 1%22%3E%3C/div%3E%0A * +/%0A%0Agoog.provide('ngeo.CreateControl');%0Agoog.provide('ngeo.controlDirective');%0A%0Agoog.require('goog.asserts');%0Agoog.require('ngeo');%0A%0A%0A/**%0A * @typedef %7Bfunction(Element): ol.control.Control%7D%0A */%0Angeo.CreateControl;%0A%0A%0A/** %0A * @return
5edfb9eef5941eda4f9c5dbfc57e0a5c87228988
use _.cancellable in component
src/directives/component.js
src/directives/component.js
var _ = require('../util') var templateParser = require('../parsers/template') module.exports = { isLiteral: true, /** * Setup. Two possible usages: * * - static: * v-component="comp" * * - dynamic: * v-component="{{currentView}}" */ bind: function () { if (!this.el.__vue__) { // create a ref anchor this.anchor = _.createAnchor('v-component') _.replace(this.el, this.anchor) // check keep-alive options. // If yes, instead of destroying the active vm when // hiding (v-if) or switching (dynamic literal) it, // we simply remove it from the DOM and save it in a // cache object, with its constructor id as the key. this.keepAlive = this._checkParam('keep-alive') != null // check ref this.refID = _.attr(this.el, 'ref') if (this.keepAlive) { this.cache = {} } // check inline-template if (this._checkParam('inline-template') !== null) { // extract inline template as a DocumentFragment this.template = _.extractContent(this.el, true) } // component resolution related state this._pendingCb = this.ctorId = this.Ctor = null // if static, build right now. if (!this._isDynamicLiteral) { this.resolveCtor(this.expression, _.bind(function () { var child = this.build() child.$before(this.anchor) this.setCurrent(child) }, this)) } else { // check dynamic component params this.readyEvent = this._checkParam('wait-for') this.transMode = this._checkParam('transition-mode') } } else { _.warn( 'v-component="' + this.expression + '" cannot be ' + 'used on an already mounted instance.' ) } }, /** * Public update, called by the watcher in the dynamic * literal scenario, e.g. v-component="{{view}}" */ update: function (value) { this.realUpdate(value) }, /** * Switch dynamic components. May resolve the component * asynchronously, and perform transition based on * specified transition mode. Accepts an async callback * which is called when the transition ends. (This is * exposed for vue-router) * * @param {String} value * @param {Function} [cb] */ realUpdate: function (value, cb) { this.invalidatePending() if (!value) { // just remove current this.unbuild() this.remove(this.childVM, cb) this.unsetCurrent() } else { this.resolveCtor(value, _.bind(function () { this.unbuild() var newComponent = this.build() var self = this if (this.readyEvent) { newComponent.$once(this.readyEvent, function () { self.swapTo(newComponent, cb) }) } else { this.swapTo(newComponent, cb) } }, this)) } }, /** * Resolve the component constructor to use when creating * the child vm. */ resolveCtor: function (id, cb) { var self = this var pendingCb = this._pendingCb = function (ctor) { if (!pendingCb.invalidated) { self.ctorId = id self.Ctor = ctor cb() } } this.vm._resolveComponent(id, pendingCb) }, /** * When the component changes or unbinds before an async * constructor is resolved, we need to invalidate its * pending callback. */ invalidatePending: function () { if (this._pendingCb) { this._pendingCb.invalidated = true this._pendingCb = null } }, /** * Instantiate/insert a new child vm. * If keep alive and has cached instance, insert that * instance; otherwise build a new one and cache it. * * @return {Vue} - the created instance */ build: function () { if (this.keepAlive) { var cached = this.cache[this.ctorId] if (cached) { return cached } } var vm = this.vm var el = templateParser.clone(this.el) if (this.Ctor) { var child = vm.$addChild({ el: el, template: this.template, _asComponent: true, _host: this._host }, this.Ctor) if (this.keepAlive) { this.cache[this.ctorId] = child } return child } }, /** * Teardown the current child, but defers cleanup so * that we can separate the destroy and removal steps. */ unbuild: function () { var child = this.childVM if (!child || this.keepAlive) { return } // the sole purpose of `deferCleanup` is so that we can // "deactivate" the vm right now and perform DOM removal // later. child.$destroy(false, true) }, /** * Remove current destroyed child and manually do * the cleanup after removal. * * @param {Function} cb */ remove: function (child, cb) { var keepAlive = this.keepAlive if (child) { child.$remove(function () { if (!keepAlive) child._cleanup() if (cb) cb() }) } else if (cb) { cb() } }, /** * Actually swap the components, depending on the * transition mode. Defaults to simultaneous. * * @param {Vue} target * @param {Function} [cb] */ swapTo: function (target, cb) { var self = this var current = this.childVM this.unsetCurrent() this.setCurrent(target) switch (self.transMode) { case 'in-out': target.$before(self.anchor, function () { self.remove(current, cb) }) break case 'out-in': self.remove(current, function () { target.$before(self.anchor, cb) }) break default: self.remove(current) target.$before(self.anchor, cb) } }, /** * Set childVM and parent ref */ setCurrent: function (child) { this.childVM = child var refID = child._refID || this.refID if (refID) { this.vm.$[refID] = child } }, /** * Unset childVM and parent ref */ unsetCurrent: function () { var child = this.childVM this.childVM = null var refID = (child && child._refID) || this.refID if (refID) { this.vm.$[refID] = null } }, /** * Unbind. */ unbind: function () { this.invalidatePending() this.unbuild() // destroy all keep-alive cached instances if (this.cache) { for (var key in this.cache) { this.cache[key].$destroy() } this.cache = null } } }
JavaScript
0.000196
@@ -3051,24 +3051,8 @@ %0A - var pendingCb = thi @@ -3066,16 +3066,30 @@ ingCb = +_.cancellable( function @@ -3102,46 +3102,8 @@ ) %7B%0A - if (!pendingCb.invalidated) %7B%0A @@ -3121,18 +3121,16 @@ Id = id%0A - se @@ -3144,18 +3144,16 @@ = ctor%0A - cb @@ -3155,33 +3155,26 @@ cb()%0A - %7D%0A %7D +) %0A this.vm @@ -3196,16 +3196,22 @@ ent(id, +this._ pendingC @@ -3458,26 +3458,16 @@ gCb. -invalidated = true +cancel() %0A
f1f5e2fbf7876050fcac018cf08bdbe73752c613
use will-change in animations to improve performance
src/element.visibility.js
src/element.visibility.js
import _ from "./utils"; import $Element from "./element"; import styleAccessor from "./styleaccessor"; /** * Changing of element visibility support * @module visibility */ var parseTimeValue = (value) => { var endIndex = value.length - 1; return value.lastIndexOf("ms") === endIndex - 1 || value.lastIndexOf("s") !== endIndex ? parseFloat(value) : parseFloat(value) * 1000; }, calcDuration = (style, animation) => { var prefix = animation ? "animation-" : "transition-", delay = styleAccessor.get[prefix + "delay"](style).split(","), duration = styleAccessor.get[prefix + "duration"](style).split(","), iterationCount = animation ? styleAccessor.get[prefix + "iteration-count"](style).split(",") : []; return Math.max.apply(Math, duration.map((value, index) => { var it = iterationCount[index] || "1"; // initial or empty value equals to 1 return (it === "initial" ? 1 : parseFloat(it)) * parseTimeValue(value) + (parseTimeValue(delay[index]) || 0); })); }, transitionProps = ["timing-function", "property", "duration", "delay"].map((p) => "transition-" + p), eventType = _.WEBKIT_PREFIX ? "webkitTransitionEnd" : "transitionend", absentStrategy = !_.LEGACY_ANDROID && _.CSS3_ANIMATIONS ? ["position", "absolute"] : ["display", "none"], changeVisibility = (el, fn, callback) => () => el.legacy((node, el, index, ref) => { var style = node.style, compStyle = _.computeStyle(node), isHidden = typeof fn === "function" ? fn(node) : fn, isDetached = !_.docEl.contains(node), completeVisibilityChange = () => { if (style.visibility === "hidden") { style[absentStrategy[0]] = absentStrategy[1]; } else { style.pointerEvents = ""; } if (callback) callback(el, index, ref); }, processVisibilityChange = () => { var duration, index, transition, absentance; // Android Browser is too slow and has a lot of bugs in // the implementation, so disable animations for them if (!_.LEGACY_ANDROID && _.CSS3_ANIMATIONS && !isDetached) { duration = Math.max(calcDuration(compStyle), calcDuration(compStyle, true)); } if (duration) { // make sure that the visibility property will be changed // to trigger the completeAnimation callback if (!style.visibility) style.visibility = isHidden ? "visible" : "hidden"; transition = transitionProps.map((prop, index) => { // have to use regexp to split transition-timing-function value return styleAccessor.get[prop](compStyle).split(index ? ", " : /, (?!\d)/); }); // try to find existing or use 0s length or make a new visibility transition index = transition[1].indexOf("visibility"); if (index < 0) index = transition[2].indexOf("0s"); if (index < 0) index = transition[0].length; transition[0][index] = "linear"; transition[1][index] = "visibility"; transition[isHidden ? 2 : 3][index] = "0s"; transition[isHidden ? 3 : 2][index] = duration + "ms"; transition.forEach((value, index) => { styleAccessor.set[transitionProps[index]](style, value.join(", ")); }); node.addEventListener(eventType, function completeAnimation(e) { if (e.propertyName === "visibility") { e.stopPropagation(); // this is an internal event node.removeEventListener(eventType, completeAnimation, false); completeVisibilityChange(); } }, false); } if (isHidden) { absentance = style[absentStrategy[0]]; // store current inline value in a internal property if (absentance !== "none") el.set("__visibility", absentance); // prevent accidental user actions during animation style.pointerEvents = "none"; } else { // restore initial property value if it exists style[absentStrategy[0]] = el.get("__visibility") || ""; } style.visibility = isHidden ? "hidden" : "visible"; // trigger native CSS animation el.set("aria-hidden", String(isHidden)); // must be AFTER changing the aria-hidden attribute if (!duration) completeVisibilityChange(); }; // if element is not detached use requestAnimationFrame that fixes several issues: // 1) animation of new added elements (http://christianheilmann.com/2013/09/19/quicky-fading-in-a-newly-created-element-using-css/) // 2) firefox-specific animations sync quirks (because of the getComputedStyle call) // 3) power consuption: show/hide do almost nothing if page is not active if (isDetached) { processVisibilityChange(); } else { _.raf(processVisibilityChange); } }), makeVisibilityMethod = (name, fn) => function(delay, callback) { var len = arguments.length, delayType = typeof delay; if (len === 1 && delayType === "function") { callback = delay; delay = 0; } if (delay && (delayType !== "number" || delay < 0) || callback && typeof callback !== "function") { throw _.makeError(name); } callback = changeVisibility(this, fn, callback); if (delay) { setTimeout(callback, delay); } else { callback(); } return this; }; /** * Show element with optional callback and delay * @memberOf module:visibility * @param {Number} [delay=0] time in miliseconds to wait * @param {Function} [callback] function that executes when animation is done * @return {$Element} * @function */ $Element.prototype.show = makeVisibilityMethod("show", false); /** * Hide element with optional callback and delay * @memberOf module:visibility * @param {Number} [delay=0] time in miliseconds to wait * @param {Function} [callback] function that executes when animation is done * @return {$Element} * @function */ $Element.prototype.hide = makeVisibilityMethod("hide", true); /** * Toggle element visibility with optional callback and delay * @memberOf module:visibility * @param {Number} [delay=0] time in miliseconds to wait * @param {Function} [callback] function that executes when animation is done * @return {$Element} * @function */ $Element.prototype.toggle = makeVisibilityMethod("toggle", function(node) { return node.getAttribute("aria-hidden") !== "true"; });
JavaScript
0
@@ -1895,39 +1895,141 @@ -style.pointerEvents = %22 +// remove temporary properties%0A style.pointerEvents = %22auto%22;%0A style.willChange = %22auto %22;%0A @@ -3830,32 +3830,239 @@ %7D);%0A%0A + // use willChange to improve performance:%0A // http://dev.opera.com/articles/css-will-change-property/%0A style.willChange = transition%5B1%5D.join(%22, %22);%0A%0A @@ -4640,17 +4640,19 @@ alue in -a +the interna @@ -5726,16 +5726,23 @@ suption: + looped show/hi @@ -5746,16 +5746,18 @@ /hide do +es almost
b2d928c0c63f75f9da9531b538c41fb78d3f477a
Fix logic of mirobot-service which would close the connection before the last acknowledgement would have been received.
app/js/mirobot-service.js
app/js/mirobot-service.js
// Jean-Daniel Michaud - 2015 // // This service offers API for mirobot communication back and forth define(function () { 'use strict'; // First, the error codes var eErrCode = { CONN_CLOSED: 1 }; // We return this object to anything injecting our service var Service = {}; // Keep all pending requests here until they get responses var _callbacks = {}; // Create a unique callback ID to map requests to responses var currentCallbackId = 0; // Hold our WebSocket object. Will be initialized on call to connect. var _ws; // State of the mirobot. The mirobot server does not have a message queue so // we can't send more than 1 request at once. So we need to keep track of the // mirobot state. // false: idle // true: busy var _mirobotState = false; // Message queue to buffer messages to be sent to the mirobot var _msgQueue = []; // Position this flag to close the websocket connection upon last message // answered var _closeRequestPending = false; // Upon reception of a message through the WebSocker interface, parse the json // and call the listener function _onmessage(message) { //console.log(message); listener(JSON.parse(message.data)); } // Get the data on message reception and notify the appropriate Promise function listener(message) { console.log('--> ', message); // Mirobot just answered, to is not busy anymore _mirobotState = false; // If an object exists with callback_id in our _callbacks object, resolve it if (_callbacks.hasOwnProperty(message.id.toString())) { var callback = _callbacks[message.id.toString()]; if (message.status === 'complete') { delete _callbacks[message.id.toString()]; // Process the next message as soon as possible processMessage(); // Call back the client code callback.resolve(); } else if (message.status === 'error') { console.log('Error: id: ', message.id, 'message: ', message.msg); callback.reject(); } else { // Just ignore accepted status } } else { // Else call the default callback Service.messageHandler(message); } // If no more message to be processed and close requested if (_msgQueue.length === 0 && _closeRequestPending) { forceClose(); } } // Prepare a callback object associated to the request containing a callbackId // and a promise object. function sendRequest(request) { //console.log('Sending request', request); if (_ws.readyState === _ws.OPEN) { _mirobotState = true; console.log('<-- ', request); _ws.send(JSON.stringify(request)); } else { var callback = _callbacks[request.id.toString()]; delete _callbacks[request.id.toString()]; // Signal the client code that the promise has failed callback.reject({ errno: eErrCode.CONN_CLOSED, err: 'Websocket connection is closed' }); } } // This creates a new callback ID for a request function getCallbackId() { currentCallbackId += 1; if(currentCallbackId > 10000) { currentCallbackId = 0; } return currentCallbackId; } // Check the mirobot status and send the next message is available function processMessage() { // If there are messages to be sent and mirobot is ready to receive if (_msgQueue.length > 0 && _mirobotState === false) { // send the older message sendRequest(_msgQueue.shift()); } } function forceClose () { _ws.terminate(); } function reinit () { // Clear the mirobot state _mirobotState = false; // Clear the message queue _msgQueue = []; // Clear the callback map _callbacks = {}; currentCallbackId = 0; } // Default message handler for message without registered callback Service.messageHandler = function (messageObj) { console.log('WARNING! message received without a valid callback ID: ', messageObj); console.log('Pensing request:'); console.log(_callbacks); }; // Send a request to mirobot Service.send = function(request) { // Storing in a variable for clarity on what sendRequest returns var promise = new Promise(function (resolve, error) { var callbackId = getCallbackId(); _callbacks[callbackId] = { time: new Date(), resolve: resolve, reject: error }; request.id = callbackId; }); // Push the message on the queue _msgQueue.push(request); // Process the message is the mirobot is idle processMessage(); // Return the promise to the client code return promise; }; // Connect to the mirobot Service.connect = function(ip, port, onopen, onclose, onerror, suffix) { if (suffix === undefined) { suffix = ''; } // Reinit the module state reinit(); // Connect to the server _ws = new WebSocket('ws://' + ip + ':' + port + '/' + suffix); // Initialize the callback handlers _ws.onopen = onopen; _ws.onclose = onclose; _ws.onerror = onerror; _ws.onmessage = _onmessage; }; Service.close = function (waitForServer) { if (waitForServer) { // Wait for all the command to be processed _closeRequestPending = true; } else { forceClose(); } }; return Service; });
JavaScript
0
@@ -2192,23 +2192,25 @@ no more -message +callbacks to be p @@ -2242,33 +2242,47 @@ ted%0A if ( -_msgQueue +Object.keys(_callbacks) .length ===
025aaa369b3f31ae294ec377fed77edd5fd0f215
trim unused lasso.js regexes
src/languages/lasso.js
src/languages/lasso.js
/* Language: Lasso Author: Eric Knibbe <eric@lassosoft.com> Description: Lasso is a language and server platform for database-driven web applications. This definition handles Lasso 9 syntax and LassoScript for Lasso 8.6 and earlier. */ function(hljs) { var LASSO_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_.]*'; var LASSO_ANGLE_RE = '<\\?(lasso(script)?|=)'; var LASSO_CLOSE_RE = '\\]|\\?>'; var LASSO_KEYWORDS = { literal: 'true false none minimal full all void and or not ' + 'bw nbw ew new cn ncn lt lte gt gte eq neq rx nrx ft', built_in: 'array date decimal duration integer map pair string tag xml null ' + 'boolean bytes keyword list locale queue set stack staticarray ' + 'local var variable global data self inherited currentcapture givenblock', keyword: 'cache database_names database_schemanames database_tablenames ' + 'define_tag define_type email_batch encode_set html_comment handle ' + 'handle_error header if inline iterate ljax_target link ' + 'link_currentaction link_currentgroup link_currentrecord link_detail ' + 'link_firstgroup link_firstrecord link_lastgroup link_lastrecord ' + 'link_nextgroup link_nextrecord link_prevgroup link_prevrecord log ' + 'loop namespace_using output_none portal private protect records ' + 'referer referrer repeating resultset rows search_args ' + 'search_arguments select sort_args sort_arguments thread_atomic ' + 'value_list while abort case else fail_if fail_ifnot fail if_empty ' + 'if_false if_null if_true loop_abort loop_continue loop_count params ' + 'params_up return return_value run_children soap_definetag ' + 'soap_lastrequest soap_lastresponse tag_name ascending average by ' + 'define descending do equals frozen group handle_failure import in ' + 'into join let match max min on order parent protected provide public ' + 'require returnhome skip split_thread sum take thread to trait type ' + 'where with yield yieldhome' }; var HTML_COMMENT = hljs.COMMENT( '<!--', '-->', { relevance: 0 } ); var LASSO_NOPROCESS = { className: 'meta', begin: '\\[noprocess\\]', starts: { end: '\\[/noprocess\\]', returnEnd: true, contains: [HTML_COMMENT] } }; var LASSO_START = { className: 'meta', begin: '\\[/noprocess|' + LASSO_ANGLE_RE }; var LASSO_DATAMEMBER = { className: 'symbol', begin: '\'' + LASSO_IDENT_RE + '\'' }; var LASSO_CODE = [ hljs.COMMENT( '/\\*\\*!', '\\*/' ), hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, hljs.inherit(hljs.C_NUMBER_MODE, {begin: hljs.C_NUMBER_RE + '|(-?infinity|NaN)\\b'}), hljs.inherit(hljs.APOS_STRING_MODE, {illegal: null}), hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}), { className: 'string', begin: '`', end: '`' }, { // variables variants: [ { begin: '[#$]' + LASSO_IDENT_RE }, { begin: '#', end: '\\d+', illegal: '\\W' } ] }, { className: 'type', begin: '::\\s*', end: LASSO_IDENT_RE, illegal: '\\W' }, { className: 'params', variants: [ { begin: '-(?!infinity)' + LASSO_IDENT_RE, relevance: 0 }, { begin: '(\\.\\.\\.)' } ] }, { begin: /(->|\.\.?)\s*/, relevance: 0, contains: [LASSO_DATAMEMBER] }, { className: 'class', beginKeywords: 'define', returnEnd: true, end: '\\(|=>', contains: [ hljs.inherit(hljs.TITLE_MODE, {begin: LASSO_IDENT_RE + '(=(?!>))?|[-+*/%](?!>)'}) ] } ]; return { aliases: ['ls', 'lassoscript'], case_insensitive: true, lexemes: LASSO_IDENT_RE + '|&[lg]t;', keywords: LASSO_KEYWORDS, contains: [ { className: 'meta', begin: LASSO_CLOSE_RE, relevance: 0, starts: { // markup end: '\\[|' + LASSO_ANGLE_RE, returnEnd: true, relevance: 0, contains: [HTML_COMMENT] } }, LASSO_NOPROCESS, LASSO_START, { className: 'meta', begin: '\\[no_square_brackets', starts: { end: '\\[/no_square_brackets\\]', // not implemented in the language lexemes: LASSO_IDENT_RE + '|&[lg]t;', keywords: LASSO_KEYWORDS, contains: [ { className: 'meta', begin: LASSO_CLOSE_RE, relevance: 0, starts: { end: '\\[noprocess\\]|' + LASSO_ANGLE_RE, returnEnd: true, contains: [HTML_COMMENT] } }, LASSO_NOPROCESS, LASSO_START ].concat(LASSO_CODE) } }, { className: 'meta', begin: '\\[', relevance: 0 }, { className: 'meta', begin: '^#!.+lasso9\\b', relevance: 10 } ].concat(LASSO_CODE) }; }
JavaScript
0.000001
@@ -285,18 +285,11 @@ Z_%5D%5B -a-zA-Z0-9_ +%5C%5Cw .%5D*' @@ -2527,64 +2527,8 @@ = %5B%0A - hljs.COMMENT(%0A '/%5C%5C*%5C%5C*!',%0A '%5C%5C*/'%0A ),%0A @@ -3397,11 +3397,8 @@ %3E%7C%5C. -%5C.? )%5Cs* @@ -4981,19 +4981,23 @@ '%5E#! -.+ +', end:' lasso9 -%5C%5Cb +$ ',%0A
a579048995e9b5fd913aba639232f6210bc6ccc4
fix after dogstack-agents update
app/components/Navigation.js
app/components/Navigation.js
import React from 'react' import { connect as connectFela } from 'react-fela' import { not, pipe, map, values, isNil } from 'ramda' import AppBar from 'material-ui/AppBar' import Drawer from 'material-ui/Drawer' import MenuItem from 'material-ui/MenuItem' import Divider from 'material-ui/Divider' import { withState, withHandlers, compose } from 'recompose' import { NavLink } from 'react-router-dom' import styles from '../styles/Navigation' import { FormattedMessage } from '../../lib/Intl' import LogOut from '../../agents/containers/LogOut' function Navigation (props) { const { styles, isDrawerOpen, toggleDrawer, navigationRoutes } = props const mapRouteItems = pipe( map(route => { const { path, name = path, navigation } = route const { Component, title = name, icon } = navigation if (Component) { return ( <Component key={name} as={MenuItem} leftIcon={ <i className={icon} aria-hidden="true" /> } /> ) } return ( <NavLink to={path} key={name}> <MenuItem leftIcon={ <i className={icon} aria-hidden="true" /> } > <FormattedMessage id={title} className={styles.labelText} /> </MenuItem> </NavLink> ) }), values ) return ( <div> <AppBar title={ <FormattedMessage id='app.name' className={styles.labelText} /> } onLeftIconButtonTouchTap={toggleDrawer} /> <Drawer open={isDrawerOpen}> <MenuItem leftIcon={ <i className="fa fa-bars" aria-hidden="true"/> } onTouchTap={toggleDrawer} > <FormattedMessage id='app.closeMenu' className={styles.labelText} /> </MenuItem> <Divider /> {mapRouteItems(navigationRoutes)} <Divider /> </Drawer> </div> ) } export default compose( connectFela(styles), withState('isDrawerOpen', 'setDrawerOpen', false), withHandlers({ toggleDrawer: ({ setDrawerOpen }) => () => setDrawerOpen(not) }) )(Navigation)
JavaScript
0
@@ -394,16 +394,68 @@ ter-dom' +%0Aimport %7B LogOut %7D from 'dogstack-agents/components' %0A%0Aimport @@ -543,60 +543,8 @@ ntl' -%0Aimport LogOut from '../../agents/containers/LogOut' %0A%0Afu
126e36bd8dc17d92d3e02912359f04513b7f2d37
Support for more than one extended class in same file.
src/lexers/PHPLexer.js
src/lexers/PHPLexer.js
define(function (require, exports, module) { "use strict"; var Lexer = require("thirdparty/lexer"); /** @const {string} Placeholder for unnamed functions. */ var UNNAMED_PLACEHOLDER = "function"; /** * Parse the source and extract the code structure. * @param {string} source the source code. * @returns {object[]} the code structure. */ function parse(source) { var line = 0; // line number. var ns = []; // the namespace array. var literal = true; // check if it's in literal area. var comment = false; // the comment flag. var state = []; // the state array. var modifier = null; // the modifier. var isStatic = false; // static flag. var isAbstract = false; // abstract flag. // helper function to peek an item from an array. var peek = function (array) { if (array.length > 0) { return array[array.length - 1]; } return null; }; var results = []; var ignored = function () { /* noop */ }; var lexer = new Lexer(); lexer // when it encounters `<?php` structure, turn off literal mode. .addRule(/<\?(php)?/, function () { literal = false; }) // when it encounters `?>` structure, turn on literal mode. .addRule(/\?>/, function () { literal = true; }) // toggle comment if necessary. .addRule(/\/\*/, function () { comment = true; }) .addRule(/\*\//, function () { comment = false; }) // ignore the comments. .addRule(/\/\/[^\n]*/, ignored) // detect abstract modifier, but treat it apart from the visibility modifiers .addRule(/public|protected|private|abstract/, function (w) { if (w === "abstract") { isAbstract = true; } else { modifier = w; } }) .addRule(/static/, function () { isStatic = true; }) // when it encounters `function` and literal mode is off, // 1. push 'function' into state array; // 2. push a function structure in result. .addRule(/function/, function () { if (!literal && !comment) { state.push("function"); results.push({ type: "function", name: ns.join("::"), args: [], modifier: "unnamed", isStatic: isStatic, // static functions did not appear in cursive (flag always false) line: line }); } }) // when it encounters `class` and literal mode is off. // 1. push "class" into state array. // 2. create a class structure into results array. .addRule(/class/, function () { if (!literal && !comment && ns.length === 0) { state.push("class"); results.push({ type: "class", name: ns.join("::"), args: [], modifier: "public", isStatic: isStatic, line: line }); } }) // added support for extended classes .addRule(/extends/, function () { if (!literal && !comment) { if (peek(state) === "class") { state.pop(); } } }) // if it's a variable and it's in function args semantics, push it into args array. .addRule(/\$[0-9a-zA-Z_]+/, function (w) { // PHP variables can contain numbers if (!literal && !comment) { if (peek(state) === "args") { peek(results).args.push(w); } // reset modifiers when variable is parsed. modifier = null; isStatic = false; } }) // check if it's an identity term. .addRule(/[0-9a-zA-Z_]+/, function (w) { // PHP classes and functions can contain numbers var ref; if (!literal && !comment) { switch (peek(state)) { case "function": ns.push(w); ref = peek(results); // if it's in name space scope. if (ns.length > 1) { ref.name += "::" + w; } else { ref.name = w; } ref.modifier = modifier || "public"; break; case "class": ns.push(w); ref = peek(results); ref.name += "::" + w; break; default: break; } // reset modifier when identity term is parsed. modifier = null; isStatic = false; } }) // check if it's in function definition, turn on args mode. .addRule(/\(/, function () { if (!literal && !comment) { if (peek(state) === "function") { var ref = peek(results); if (!ref || ref.type !== "function") { ns.push(UNNAMED_PLACEHOLDER); results.push({ type: "function", name: ns.join("::"), args: [], modifier: "unnamed", isStatic: false, line: line }); } state.push("args"); } } }) // turn off args mode. .addRule(/\)/, function () { if (!literal && !comment) { if (peek(state) === "args") { state.pop(); } } }) // start function/class body definition or scoped code structure. .addRule(/{/, function () { if (!literal && !comment) { var ref; if ((ref = peek(state)) === "function" || ref === "class") { var prefix = state.pop(); state.push(prefix + ":start"); } else { state.push("start"); } } }) // pop name from namespace array if it's in a namespace. .addRule(/}/, function () { if (!literal && !comment && state.length > 0) { var s = state.pop().split(":")[0]; if (s === "class") { ns.pop(); } // support for anonymous functions within other functions if (s === "function") { if (peek(results).modifier === "unnamed") { state.pop(); } else { ns.pop(); } } } }) .addRule(/;/, function () { if (!literal && !comment) { if(peek(state) === "function" && isAbstract) { ns.pop(); isAbstract = false; } else if (peek(state) === "class") { ns.pop(); } } }) // other terms are ignored. .addRule(/./, ignored) // line number increases. .addRule(/\r?\n/, function () { line += 1; }); lexer.setInput(source); // parse the code to the end of the source. while (lexer.index < source.length - 1) { lexer.lex(); } return results; } module.exports = { parse: parse }; });
JavaScript
0
@@ -780,32 +780,65 @@ abstract flag.%0A + var lastExtended = null;%0A // helpe @@ -3825,34 +3825,99 @@ -state.pop( +lastExtended = results.pop();%0A state.push(%22extended%22 );%0A @@ -5461,32 +5461,312 @@ break;%0A + case %22extended%22:%0A state.push(%22class%22);%0A results.push(lastExtended);%0A ref = peek(results);%0A ref.name += %22::%22 + w;%0A break;%0A
cc174405dac4d565afb474ebe3fb580197338f50
remove debugging
src/lib/LazyBuilder.js
src/lib/LazyBuilder.js
import Immutable from 'immutable'; import Promise, {coroutine} from 'bluebird'; import PairTable from 'pair-table'; import {isString, isPlainObject} from 'lodash'; import path from 'path'; import getChanges from './getChanges'; const privates = new WeakMap(); const build = coroutine(function* _build(input) { const priv = privates.get(this); // prohibit calling twice in parallel if (priv.building) throw new Error('You must wait for previous build() to finish before calling build() again.'); priv.building = true; // validate input if (!Immutable.Map.isMap(input)) { throw new TypeError('Input must be an immutable map!'); } for (const contents of input.values()) { if (!Buffer.isBuffer(contents)) { throw new TypeError('input values must all be buffers'); } } // unpack private members const { fn, input: oldInput, importations: oldImportations, causations: oldCausations, } = priv; // start new mappings tables for this build const newImportations = new PairTable(); // <L: buildPath, R: importPath> const newCausations = new PairTable(); // <L: buildPath, R: outputPath> // determine which input files have changed since last time const changedInput = oldInput ? getChanges(oldInput, input) : input; // decide which files we need to build const filesToBuild = changedInput.withMutations(map => { // add any files that are known to import any of these files for (const [buildPath, importPath] of oldImportations) { if (changedInput.has(importPath)) { map.set(buildPath, input.get(buildPath) || null); } } }); // debug // console.log('\n\nfiles to build'); // for (const [file, contents] of filesToBuild.entries()) { // console.log(' ' + file, contents ? JSON.stringify(String(contents)) : contents); // } // console.log('\n\n'); // build everything const results = yield Promise.props( filesToBuild .filter(contents => contents) .map((contents, buildPath) => { // make a context for the fn, to enable this.importFile() const context = { importFile: importee => { console.assert(!path.isAbsolute(importee)); newImportations.add(buildPath, importee); return input.get(importee) || null; }, }; return Promise.resolve().then(() => fn.call(context, buildPath, contents)); }) .toObject() ); // note all output paths, to prevent fn output errors going unchallenged const allOutputPaths = {}; // {[outputPath]: buildPath} // process the results to determine output const outputWrites = {}; for (const buildPath of filesToBuild.keys()) { let result = results[buildPath]; if (!result) continue; // start preparing some info about this atomic build job, to emit later // const info = {buildPath}; // normalise the structure of the result { // if it's a single buffer/string, this is an instruction // to output to the exact same path if (Buffer.isBuffer(result) || isString(result)) { const newContents = result; result = {[buildPath]: newContents}; } // otherwise it's got to be a POJO else if (!isPlainObject(result)) { throw new TypeError( `LazyBuilder callback's return value is of invalid type ` + `(${typeof result}) when building "${buildPath}"` ); } } // note what was imported by this file // info.imported = newImportations.getRightsFor(buildPath); // and see what was output const outputPaths = Object.keys(result); // info.output = outputPaths; // process the result for this file for (let outputPath of outputPaths) { // first ensure this output path is uniquely output by a single input path // (because if we were to just pick one, results might be undeterministic) { const otherInputFile = allOutputPaths[outputPath]; if (otherInputFile) { throw new Error( `LazyBuilder: when building "${buildPath}"` + `the fn tried to output to "${outputPath}", but this has already ` + `been output by "${otherInputFile}"` ); } allOutputPaths[outputPath] = buildPath; } // make sure it's a buffer let contents = result[outputPath]; if (isString(contents)) contents = new Buffer(contents); else if (!Buffer.isBuffer(contents)) { throw new TypeError( `LazyBuilder: Expected value for output file "${outputPath}" ` + `to be string or buffer; got ${typeof contents}.` ); } // make sure the path is normal (should be relative, with no "./" or "../") if (path.isAbsolute(outputPath)) { throw new Error(`LazyBuilder: Expected a relative path, got: ${outputPath}`); } outputPath = path.normalize(outputPath); console.assert(outputPath.charAt(0) !== '.', 'should not start with a dot: ' + outputPath); // add it to the output outputWrites[outputPath] = contents; // and note the new causation newCausations.add(buildPath, outputPath); } } // status: the output now contains everything that got written on this build // - but we also need to return all other *unaffected* files at the end. // fill in the gaps in the new mappings (causations and importations) with // those from the previous build - i.e. any where the build path was not // rebuilt this time { // carry over output mappings for (const [oldBuildPath, oldOutputPath] of oldCausations) { if (!filesToBuild.has(oldBuildPath)) newCausations.add(oldBuildPath, oldOutputPath); } // carry over import mappings for (const [oldBuildPath, oldResolvedImportPath] of oldImportations) { if (!filesToBuild.has(oldBuildPath)) { newImportations.add(oldBuildPath, oldResolvedImportPath); } } } // see what needs deleting - anything that was output last build, but // was *not* output on this build const toDelete = new Set(); { const oldOutputPaths = oldCausations.getAllRights(); const newOutputPaths = newCausations.getAllRights(); for (const file of oldOutputPaths) { if (!newOutputPaths.has(file)) toDelete.add(file); } } // augment the output with output from last time - carry over anything that // wasn't output this time and isn't in toDelete if (priv.output) { priv.output.forEach((contents, file) => { console.assert(Buffer.isBuffer(contents)); if (!outputWrites[file] && !toDelete.has(file)) { outputWrites[file] = contents; } }); } // finalise the output const output = Immutable.Map(outputWrites); // debugging console.assert([...output.values()].every(Buffer.isBuffer), 'bug..?'); // finish up and resolve with the output priv.importations = newImportations; priv.causations = newCausations; priv.input = input; priv.output = output; priv.building = false; return Immutable.Map(output); }); export default class LazyBuilder { constructor(fn) { if (fn.constructor.name === 'GeneratorFunction') fn = coroutine(fn); privates.set(this, { fn, importations: new PairTable(), causations: new PairTable(), }); this.build = build.bind(this); } }
JavaScript
0.000065
@@ -1629,244 +1629,8 @@ );%0A%0A - // debug%0A // console.log('%5Cn%5Cnfiles to build');%0A // for (const %5Bfile, contents%5D of filesToBuild.entries()) %7B%0A // console.log(' ' + file, contents ? JSON.stringify(String(contents)) : contents);%0A // %7D%0A // console.log('%5Cn%5Cn');%0A%0A // @@ -6537,97 +6537,8 @@ );%0A%0A - // debugging%0A console.assert(%5B...output.values()%5D.every(Buffer.isBuffer), 'bug..?');%0A%0A //
5e5d9ba7acee8f8c9ce0fc407b0c4c57e1ae1bee
Corrige une typo dans la nationalité (#1700)
src/lib/Nationality.js
src/lib/Nationality.js
let ZONE_LABEL = { fr: "française", ue: "UE", autre: "hors UE", } let EEE_COUNTRY_CODES = [ "AT", "BE", "BG", "CY", "CZ", "DE", "DK", "EE", "ES", "FI", "FR", "GR", "HR", "HU", "IE", "IS", "IT", "LI", "LU", "LV", "MT", "NL", "NO", "PL", "PT", "RO", "SE", "SI", "SK", "UK", ] function getNationalityFromCountryCode(countryCode) { switch (countryCode) { case "DE": return "Européenne" case "FR": return "Français" case "AF": return "Non européenne" } } function getZone(countryCode) { if (!countryCode) { return "" } countryCode = countryCode.toUpperCase() if (countryCode === "FR") { return "fr" } if (EEE_COUNTRY_CODES.includes(countryCode) || countryCode === "CH") { return "ue" } if (countryCode === "AF") { return "autre" } return "" } const Nationality = { getLabel: function (nationality) { return ZONE_LABEL[getZone(nationality)] }, getNationalityFromCountryCode: getNationalityFromCountryCode, getZone: getZone, getCountryCodeByNationality: function (nationality) { switch (nationality) { case "ue": return "DE" case "autre": return "AF" } return "FR" }, } export default Nationality
JavaScript
0.000107
@@ -492,16 +492,17 @@ Fran%C3%A7ais +e %22%0A ca
f6d41fc87dd92474e2a2006a5139b6863a88b1e4
Add auth.register-confirm state
app/app.module.js
app/app.module.js
// Written by Joshua Paul A. Chan (function() { "use strict"; // Import variables if present (from env.js) (thanks @jvandemo) var env = {}; if (window) { env = window.__env; } // Initialize app angular.module('wr', ['ui.router', 'textAngular', 'angularModalService', 'wr.controllers', 'wr.services', 'wr.directives', 'wr.components']) .constant('__env', env) .constant('__token', 'SECRET-YEET') // FIXME: switch token to true php session token .config(function($logProvider, $locationProvider, $stateProvider, $urlRouterProvider, $httpProvider, $urlMatcherFactoryProvider, __env, __token) { // enable/disable angular debug $logProvider.debugEnabled(__env.enableDebug); // FIXME locationProvider // $locationProvider.html5Mode(true); // make trailing slashes optional $urlMatcherFactoryProvider.strictMode(false); $stateProvider .state('app', { url: "/", abstract: true, }) .state('auth', { url: "", templateUrl: "client/app/templates/bare.html", abstract: true, }) .state('auth.login', { url: "/login", template: "<login />", }) .state('auth.register', { url: "/register", template: "<register />", }) .state('convos', { url: "/conversations", templateUrl: "client/app/templates/conversations.html", deepStateRedirect: true }) .state('convos.convo', { url: "/{convoId}", views: { convo: { template: "<convo/>" } } }) // TODO: Settings page .state('settings', { url: "/settings", templateUrl: "client/app/templates/bare.html", deepStateRedirect: true }); $urlRouterProvider.when('/', '/login'); // automatically attach token to outgoing requests $httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = __token; }); // Initialize modules angular.module('wr.controllers', []); angular.module('wr.services', []); angular.module('wr.directives', []); angular.module('wr.components', []); }());
JavaScript
0.000001
@@ -1292,32 +1292,215 @@ /%3E%22,%0A %7D)%0A + .state('auth.register-confirm', %7B%0A url: %22/register-confirm%22,%0A templateUrl: %22client/app/components/registerConfirm/registerConfirm.view.html%22,%0A %7D)%0A .state('
435470b44d03ef670e10bbf2ef01a9e3a3000461
Remove default parameter value from RuleFinder
src/lib/rule-finder.js
src/lib/rule-finder.js
const path = require('path'); const eslint = require('eslint'); const isAbsolute = require('path-is-absolute'); const difference = require('./array-diff'); const getSortedRules = require('./sort-rules'); function _getConfigFile(specifiedFile) { if (specifiedFile) { if (isAbsolute(specifiedFile)) { return specifiedFile; } return path.join(process.cwd(), specifiedFile); // eslint-disable-line import/no-dynamic-require } // This is not being called with an arg. Use the package.json `main` return require(path.join(process.cwd(), 'package.json')).main; // eslint-disable-line import/no-dynamic-require } function _getConfig(configFile) { const cliEngine = new eslint.CLIEngine({ // Ignore any config applicable depending on the location on the filesystem useEslintrc: false, // Point to the particular config configFile }); return cliEngine.getConfigForFile(); } function _getCurrentRules(config) { return Object.keys(config.rules); } function _normalizePluginName(name) { const scopedRegex = /(@[^/]+)\/(.+)/; const match = scopedRegex.exec(name); if (match) { return { module: `${match[1]}/eslint-plugin-${match[2]}`, prefix: match[2] }; } return { module: `eslint-plugin-${name}`, prefix: name }; } function _isDeprecated(rule) { return rule.meta && rule.meta.deprecated; } function _getPluginRules(config, {includeDeprecated}) { let pluginRules = []; const plugins = config.plugins; if (plugins) { plugins.forEach(plugin => { const normalized = _normalizePluginName(plugin); const pluginConfig = require(normalized.module); // eslint-disable-line import/no-dynamic-require const rules = pluginConfig.rules === undefined ? {} : pluginConfig.rules; pluginRules = pluginRules.concat( Object.keys(rules) .filter(rule => includeDeprecated || !_isDeprecated(rules[rule])) .map(rule => `${normalized.prefix}/${rule}`) ); }); } return pluginRules; } function _getCoreRules({includeDeprecated}) { const rules = eslint.linter.getRules(); return Array.from(rules.keys()) .filter(rule => includeDeprecated || !_isDeprecated(rules.get(rule))); } function _isNotCore(rule) { return rule.indexOf('/') !== '-1'; } function RuleFinder(specifiedFile, options = {}) { const {omitCore, includeDeprecated} = options; const configFile = _getConfigFile(specifiedFile); const config = _getConfig(configFile); let currentRules = _getCurrentRules(config); const pluginRules = _getPluginRules(config, {includeDeprecated}); const coreRules = _getCoreRules({includeDeprecated}); const allRules = omitCore ? pluginRules : [...coreRules, ...pluginRules]; if (omitCore) { currentRules = currentRules.filter(_isNotCore); } const unusedRules = difference(allRules, currentRules); // eslint-disable-line vars-on-top // Get all the current rules instead of referring the extended files or documentation this.getCurrentRules = () => getSortedRules(currentRules); // Get all the current rules' particular configuration this.getCurrentRulesDetailed = () => config.rules; // Get all the plugin rules instead of referring the extended files or documentation this.getPluginRules = () => getSortedRules(pluginRules); // Get all the available rules instead of referring eslint and plugin packages or documentation this.getAllAvailableRules = () => getSortedRules(allRules); this.getUnusedRules = () => getSortedRules(unusedRules); } module.exports = function (specifiedFile, options = {}) { return new RuleFinder(specifiedFile, options); };
JavaScript
0
@@ -2326,29 +2326,24 @@ ile, options - = %7B%7D ) %7B%0A const
275f7df1fc1c69f33362b5ff114d645013fe1584
Add pageChange event for tracking virtual page changes
app/public/sa-tracking.js
app/public/sa-tracking.js
'use strict'; var events = []; var requestInterval = 5000; window.addEventListener('click', function(e) { e = event || window.event; events.push(processEvent(e)); }); var processEvent = function(e) { // Event attributes var eventProps = ['type', 'timeStamp']; // Event target attributes var targetProps = ['nodeName', 'innerHTML']; // Trimmed event var result = {}; eventProps.forEach(function(prop) { if (e[prop]) { result[prop] = e[prop]; } }); if(e.target) { targetProps.forEach(function(prop) { if(e.target[prop]) { result[prop] = e.target[prop]; } }); } console.log('event result: ' + JSON.stringify(result)); return result; }; var ajax = {}; ajax.postUrl ='http://sextant-ng-b.herokuapp.com/api/0_0_1/data'; ajax.createXHR = function() { try { return new XMLHttpRequest(); } catch(e) { throw new Error('No XHR object.'); } }; ajax.post = function(data) { var xhr = this.createXHR(); xhr.open('POST', this.postUrl, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(data); }; var sendEvents = setInterval(function() { if (!events.length) return; ajax.post(JSON.stringify(events)); events = []; }, requestInterval); window.addEventListener('load', function() { if(!window.angular) return; // HTML element where ng-app is defined var ngAppNode = document.getElementsByClassName('ng-scope')[0]; // Convert element to an Angular element in order to access the $rootScope var ngApp = angular.element(ngAppNode); // Listen to route changes on the $routeProvider ngApp.scope().$on('$routeChangeSuccess', function(e, current, previous) { if (previous) { // Navigation between two angular routes if(previous.originalPath && current.originalPath) { console.log('from %s to %s', previous.originalPath, current.originalPath); } } // Initial page load else { console.log('initial load'); } }); });
JavaScript
0
@@ -1844,80 +1844,241 @@ -console.log('from %25s to %25s', previous.originalPath, current.originalPath +var pageChange = %7B%7D;%0A%0A pageChange.from = previous.originalPath;%0A pageChange.to = current.originalPath;%0A pageChange.timeStamp = new Date().getTime();%0A%0A events.push(pageChange );%0A
2dfbcd853df7d83a295fbcf3a3166c62cb3e1e6a
Validate localStorage in server
src/extra/auth/reducer.js
src/extra/auth/reducer.js
import { LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE, } from './actions'; function reducer(state = { token: localStorage.getItem('token') || '', }, action) { switch (action.type) { case LOGIN_REQUEST: return Object.assign({}, state, { creds: action.payload, }); case LOGIN_SUCCESS: return Object.assign({}, state, { token: action.payload.access_token, user: action.payload.user, }); case LOGIN_FAILURE: return Object.assign({}, state, { error: 'Error en el login', }); default: return state; } } export default reducer;
JavaScript
0.000004
@@ -78,43 +78,97 @@ ';%0A%0A -function reducer(state = %7B%0A +const isNode = typeof localStorage === 'undefined';%0Alet token = '';%0A%0Aif (!isNode) token -: + = loc @@ -199,18 +199,52 @@ ') %7C%7C '' -,%0A +;%0A%0Afunction reducer(state = %7B token %7D, actio
356f2ed7a4a23421cce3aebd1811e458054aa69f
add task list update mutation and action
app/renderer/src/store.js
app/renderer/src/store.js
import Vue from 'vue' import Vuex from 'vuex' import io from 'socket.io-client' Vue.use(Vuex) const state = { is_connected: false, port: null, current_protocol_name: "No File Selected", errors: "No errors" } const mutations = { UPDATE_ROBOT_CONNECTION (state, payload) { state.is_connected = payload.is_connected state.port = payload.port }, UPDATE_CURRENT_PROTOCOL (state, payload) { state.current_protocol_name = payload.current_protocol_name state.errors = payload.errors } } const actions = { connect_robot ({ commit }, port) { const payload = {is_connected: true, 'port': port} let options = {params: {'port': port}} Vue.http .get('http://localhost:5000/robot/serial/connect', options) .then((response) => { console.log('successfully connected...') console.log('committing with payload:', payload) commit('UPDATE_ROBOT_CONNECTION', payload) }, (response) => { console.log('failed to connect', response) }) }, disconnect_robot ({ commit }) { Vue.http .get('http://localhost:5000/robot/serial/disconnect') .then((response) => { console.log(response) if (response.data.is_connected === true){ console.log('successfully connected...') } else { console.log('Failed to connect', response.data) } commit('UPDATE_ROBOT_CONNECTION', {'is_connected': false, 'port': null}) }, (response) => { console.log('Failed to communicate to backend server. Failed to connect', response) }) }, uploadProtocol ({commit}, target) { Vue.http .post('http://localhost:5000/upload', {file: target.result, filename: target.fileName}) .then((response) => { console.log(response) commit('UPDATE_CURRENT_PROTOCOL', {'current_protocol_name': target.fileName, 'errors': response.body.data}) }, (response) => { console.log('failed to upload', response) }) } } function createWebSocketPlugin(socket) { return store => { socket.on('event', data => { console.log(data) if (data.type === 'connection_status') { if (data.is_connected === false) { store.commit('UPDATE_ROBOT_CONNECTION', {'is_connected': false, 'port': null}) } } }) } } const socket = io.connect('ws://localhost:5000') socket.on('connect', function(){ console.log('WebSocket has connected.') socket.emit('connected') }); socket.on('disconnect', function(){ console.log('WebSocket has disconnected') }) const websocketplugin = createWebSocketPlugin(socket) export default new Vuex.Store({ state, actions, mutations, plugins: [websocketplugin] })
JavaScript
0.000001
@@ -216,16 +216,31 @@ errors%22 +,%0A tasks: %5B%5D %0A%7D%0A%0A%0Acon @@ -543,16 +543,97 @@ .errors%0A + %7D,%0A UPDATE_TASK_LIST (state, payload) %7B%0A state.tasks = payload.tasks%0A %7D%0A%7D%0A @@ -2292,24 +2292,391 @@ %0A %7D)%0A + %7D,%0A updateTasks (%7Bcommit%7D, target) %7B%0A Vue.http%0A .get('http://localhost:5000/instruments/placeables', %7Bprotocol: target.result%7D)%0A .then((response) =%3E %7B%0A console.log(response)%0A commit('UPDATE_TASK_LIST', %7B'tasks': response.body.data%7D)%0A %7D, (response) =%3E %7B%0A console.log('failed to upload', response)%0A %7D)%0A %7D%0A%7D%0A%0Afun
3f818d6f3b29bd19a10cd48b6219a7a8b0767394
Add token event listeners in text
app/js/arethusa.text/text.js
app/js/arethusa.text/text.js
'use strict'; angular.module('arethusa.text').service('text', [ 'state', 'configurator', function (state, configurator) { var self = this; function configure() { configurator.getConfAndDelegate('text', self); self.hideArtificialTokens = false; } configure(); function selectRealTokens() { return arethusaUtil.inject({}, state.tokens, function(memo, id, token) { if (!token.artificial) { memo[id] = token; } }); } function setTokens() { self.tokens = self.hideArtificialTokens ? selectRealTokens() : state.tokens; } this.init = function() { setTokens(); }; } ]);
JavaScript
0.000014
@@ -306,219 +306,862 @@ ion -selectRealTokens() %7B%0A return arethusaUtil.inject(%7B%7D, state.tokens, function(memo, id, token) %7B%0A if (!token.artificial) %7B%0A memo%5Bid%5D = +addRealToken(container, id, token) %7B%0A if (!token.artificial) %7B%0A container%5Bid%5D = token;%0A %7D%0A %7D%0A%0A function removeRealToken(container, id, token) %7B%0A if (!token.artificial) %7B%0A delete container%5Bid%5D;%0A %7D%0A %7D%0A%0A function selectRealTokens() %7B%0A return arethusaUtil.inject(%7B%7D, state.tokens, addRealToken);%0A %7D%0A%0A this.setTokens = function() %7B%0A self.tokens = self.hideArtificialTokens ? selectRealTokens() : state.tokens;%0A %7D;%0A%0A // tokenAdded and tokenRemoved only have to do something, when%0A // artificial tokens are hidden. Otherwise self.tokens is the%0A // same as state.tokens anyway.%0A state.on('tokenAdded', function(event, token -; +) %7B %0A - %7D%0A %7D);%0A %7D%0A%0A function setT +if (self.hideArtificialTokens) %7B%0A addRealToken(self.tokens, token.id, token);%0A %7D%0A %7D);%0A%0A state.on('tokenRemoved', function(event, t oken -s( ) %7B%0A @@ -1162,38 +1162,28 @@ en) %7B%0A -self.tokens = +if ( self.hideArt @@ -1199,51 +1199,82 @@ kens - ? selectRealTokens() : state. +) %7B%0A removeRealToken(self.tokens, token.id, token -s +) ;%0A -%7D + %7D%0A %7D); %0A%0A @@ -1306,16 +1306,40 @@ %7B%0A +configure();%0A self. setToken
8df7bcc622f5cc32ddbc6954d5da7564de34c7d2
Update style templates
app/feed/types.js
app/feed/types.js
let types = { 'photo': { title: 'PHOTO', colorDark: 'black', colorLight: 'white', }, 'question': { title: 'QUESTION', colorDark: '#00301B', colorLight: '#00AA4E', }, 'deadline': { title: 'DEADLINE', colorDark: '#A91400', colorLight: '#FF5505', }, 'update': { title: 'UPDATE', colorDark: '#032269', colorLight: '#27AFFF', } }; module.exports = types;
JavaScript
0
@@ -89,21 +89,39 @@ white',%0A + reaction: '%F0%9F%93%B7'%0A %7D,%0A - 'quest @@ -204,16 +204,34 @@ 0AA4E',%0A + reaction: '%F0%9F%A4%93'%0A %7D,%0A ' @@ -319,16 +319,34 @@ F5505',%0A + reaction: '%F0%9F%98%B1'%0A %7D,%0A ' @@ -403,16 +403,16 @@ 32269',%0A - colo @@ -430,16 +430,34 @@ 7AFFF',%0A + reaction: '%F0%9F%91%8F'%0A %7D%0A%7D;%0A%0A
2b26198fd2868fe64edb4cc3372e39aac65be70a
update application to use updated WebPush implementation (#146)
app/js/lib/foxbox/webpush.js
app/js/lib/foxbox/webpush.js
'use strict'; import EventDispatcher from './common/event-dispatcher'; // Private members const p = Object.freeze({ // Properties, api: Symbol('api'), settings: Symbol('settings'), // Methods: listenForMessages: Symbol('listenForMessages'), }); export default class WebPush extends EventDispatcher { constructor(api, settings) { super(['message']); this[p.api] = api; this[p.settings] = settings; Object.seal(this); } subscribeToNotifications(resubscribe = false) { if (!navigator.serviceWorker) { return Promise.reject('No service worker supported'); } navigator.serviceWorker.addEventListener('message', this[p.listenForMessages].bind(this)); const settings = this[p.settings]; if (settings.pushEndpoint && settings.pushPubKey && !resubscribe) { return Promise.resolve(); } return navigator.serviceWorker.ready .then((reg) => { reg.pushManager.subscribe({userVisibleOnly: true}) .then((subscription) => { const endpoint = subscription.endpoint; const key = subscription.getKey ? subscription.getKey('p256dh') : ''; settings.pushEndpoint = endpoint; settings.pushPubKey = btoa(String.fromCharCode.apply(null, new Uint8Array(key))); // Send push information to the server // @todo We will need some library to write taxonomy messages const pushConfigurationMsg = [[ [{ id: 'setter:subscribe.webpush@link.mozilla.org', }], { Json: { subscriptions: [{ public_key: settings.pushPubKey, push_uri: settings.pushEndpoint, }], }, }, ]]; return this[p.api].put( 'channels/set', pushConfigurationMsg ) .then(() => { // Setup some common push resources const pushResourcesMsg = [[ [{ id: 'setter:resource.webpush@link.mozilla.org', }], { Json: { resources: ['res1'], }, }, ]]; return this[p.api].put('channels/set', pushResourcesMsg); }); }) .catch((error) => { if (Notification.permission === 'denied') { throw new Error('Permission request was denied.'); } else { console.error('Error while saving subscription ', error); throw new Error(`Subscription error: ${error}`); } }); }); } [p.listenForMessages](evt) { const msg = evt.data || {}; if (!msg.action) { return; } this.emit('message', msg); } }
JavaScript
0
@@ -1134,16 +1134,93 @@ ) : '';%0A + const auth = subscription.getKey ? subscription.getKey('auth') : '';%0A @@ -1352,16 +1352,115 @@ (key))); +%0A settings.pushAuth = btoa(String.fromCharCode.apply(null,%0A new Uint8Array(auth))); %0A%0A @@ -1864,16 +1864,59 @@ dpoint,%0A + auth: settings.pushAuth,%0A
99be04da487e5f7a840fec40f9740e2b47a344cf
Revert "fix removeChild error"
app/routes/application.js
app/routes/application.js
import Ember from 'ember'; import AjaxPromise from '../utils/ajax-promise'; import config from '../config/environment'; import preloadDataMixin from '../mixins/preload_data'; const { getOwner } = Ember; export default Ember.Route.extend(preloadDataMixin, { cordova: Ember.inject.service(), i18n: Ember.inject.service(), isErrPopUpAlreadyShown: false, isOfflineErrAlreadyShown: false, logger: Ember.inject.service(), messageBox: Ember.inject.service(), _loadDataStore: function(){ return this.preloadData(true).catch(error => { if (error.status === 0 || (error.errors && error.errors[0].status === "0")) { this.transitionTo("offline"); } else { this.handleError(error); } }).finally(() => { // don't know why but placing this before preloadData on iPhone 6 causes register_device request to fail with status 0 if (this.session.get('isLoggedIn')) { this.get("cordova").appLoad(); } }); }, init() { var _this = this; var storageHandler = function (object) { var authToken = window.localStorage.getItem('authToken'); if(authToken !== null && authToken.length === 0) { window.location.reload(); } }; window.addEventListener("storage", function() { storageHandler(_this); }, false); }, beforeModel(transition = []) { var language; try { window.localStorage.test = "isSafariPrivateBrowser"; } catch (e) { this.get("messageBox").alert(this.get("i18n").t("QuotaExceededError")); } window.localStorage.removeItem('test'); if (transition.queryParams.ln) { language = transition.queryParams.ln === "zh-tw" ? "zh-tw" : "en"; this.set('session.language', language); } language = this.session.get("language") || "en"; moment.locale(language); this.set("i18n.locale", language); Ember.onerror = window.onerror = error => this.handleError(error); return this._loadDataStore(); }, afterModel() { if(this.get("session.isAdminApp")) { this.loadStaticData(true).catch(error => { if (error.status === 0 || (error.errors && error.errors[0].status === "0")) { this.transitionTo("offline"); } else { this.handleError(error); } }); } }, renderTemplate() { this.render(); // default template this.render('notifications', { // the template to render into: 'application', // the template to render into outlet: 'notifications', // the name of the outlet in that template controller: 'notifications' // the controller to use for the template }); if(this.get("session.isAdminApp")){ this.render('notification_link', { into: 'application', outlet: 'notification_link', controller: 'notification_link' }); this.render('internet_call_status', { into: 'application', outlet: 'internet_call_status', controller: 'internet_call_status' }); } }, offlineError(reason){ if(!this.get('isOfflineErrAlreadyShown')) { this.set('isOfflineErrAlreadyShown', true); this.get("messageBox").alert(this.get("i18n").t("offline_error"), () => { this.set('isOfflineErrAlreadyShown', false); }); if(!reason.isAdapterError){ this.get("logger").error(reason); } } }, quotaExceededError(reason){ this.get("logger").error(reason); this.get("messageBox").alert(this.get("i18n").t("QuotaExceededError")); }, somethingWentWrong(reason) { this.get("logger").error(reason); if(!this.get('isErrPopUpAlreadyShown')) { this.set('isErrPopUpAlreadyShown', true); this.get("messageBox").alert(this.get("i18n").t("unexpected_error"), () => { this.set('isErrPopUpAlreadyShown', false); }); } }, notFoundError(reason) { this.get("logger").error(reason); this.get("messageBox").alert(this.get("i18n").t(status+"_error")); }, unauthorizedError() { if (this.session.get('isLoggedIn')) { this.controllerFor("application").send('logMeOut'); } }, handleError: function(reason) { try { var status; try { status = parseInt(reason.errors[0].status, 10); } catch (err) { status = reason.status; } if(!window.navigator.onLine){ this.offlineError(reason); } else if(reason.name === "QuotaExceededError") { this.quotaExceededError(reason); } else if (reason.name === "NotFoundError" && reason.code === 8) { return false; }else if (status === 401) { this.unauthorizedError(); } else if ([403, 404].indexOf(status) >= 0) { this.notFoundError(reason); } else if (status === 0) { // status 0 means request was aborted, this could be due to connection failure // but can also mean request was manually cancelled this.get("messageBox").alert(this.get("i18n").t("offline_error")); } else { this.somethingWentWrong(reason); } } catch (err) { console.log(err); } }, actions: { setLang(language) { this.session.set("language", language); window.location.reload(); }, loading() { Ember.$(".loading-indicator").remove(); var view = getOwner(this).lookup('component:loading').append(); this.router.one('didTransition', view, 'destroy'); }, // this is hopefully only triggered from promises from routes // so in this scenario redirect to home for 404 error(reason) { try { var errorStatus = parseInt(reason.status || reason.errors && reason.errors[0].status, 10) if ([403, 404].indexOf(errorStatus) >= 0) { this.get("messageBox").alert(this.get("i18n").t(errorStatus+"_error"), () => this.transitionTo("/")); } else { this.handleError(reason); } } catch (err) { console.log(err); } }, willTransition(transition) { Ember.run.next(function() { // before transitioning close all foundation-dialog box Ember.$(".reveal-modal").foundation("reveal", "close"); // remove joyride-popup if not assigned for page if($(".joyride-list").length === 0) { Ember.$('.joyride-tip-guide').remove(); } }); } } });
JavaScript
0
@@ -4498,102 +4498,8 @@ if -(reason.name === %22NotFoundError%22 && reason.code === 8) %7B%0A return false;%0A %7Delse if (sta
ec16ab7b7eed0bdf8e9d583a24127665732b048e
Use bind for a concise invocation of generateCouchdbResponse().
lib/unexpectedMockCouchdb.js
lib/unexpectedMockCouchdb.js
var BufferedStream = require('bufferedstream'); var expect = require('unexpected'); var http = require('http'); var mockCouch = require('mock-couch'); var url = require('url'); function generateCouchdbResponse(databases, request) { var responseObject = null; function createMockReq(requestProperties) { var requestStream = new BufferedStream(); requestStream.destroy = function () { responseProperties.requestDestroyed = true; }; setImmediate(function () { requestStream.emit('end'); req.emit('end'); }); var req = new http.IncomingMessage(requestStream); req.url = request.path; req.method = request.method; return req; } function createMockRes() { var hasSeenResponse = false; var res = { setHeader: function () { if (hasSeenResponse) { return; } }, send: function (statusCode, body) { if (hasSeenResponse) { return; } responseObject = { statusCode: statusCode, body: body }; hasSeenResponse = true; } }; return res; } var req = createMockReq(request); var res = createMockRes(); var couchdb = mockCouch.express(); Object.keys(databases).forEach(function (databaseName) { couchdb.addDB(databaseName, databases[databaseName].docs || []); }); // run the handler couchdb(req, res, function () {}); return responseObject; } module.exports = { name: 'unexpected-mock-couchdb', installInto: function () { expect.installPlugin(require('unexpected-mitm')); expect.addAssertion('with couchdb mocked out', function (expect, subject, couchdb) { this.errorMode = 'nested'; var nextAssertionArgs = this.args.slice(1); var args = [subject, 'with http mocked out', { response: function (requestProperties) { return generateCouchdbResponse(couchdb, requestProperties); } }].concat(nextAssertionArgs); return expect.apply(expect, args); }); } };
JavaScript
0
@@ -2093,136 +2093,51 @@ se: -function (requestProperties) %7B%0A return generateCouchdbResponse(couchdb, requestProperties);%0A %7D +generateCouchdbResponse.bind(null, couchdb) %0A
b9abcf6ffff61c98a1e40b00607e51d33c38e303
Remove unnecessary destructuring
app/routes/team/canvas.js
app/routes/team/canvas.js
import Ember from 'ember'; import preload from 'canvas-web/lib/preload'; export default Ember.Route.extend({ model({ id }) { return this.get('store').findRecord('canvas', id, { adapterOptions: { team: this.modelFor('team') } }); }, afterModel() { if (this.modelFor('team').get('isInTeam')) { return preload(this.modelFor('team'), ['channels']); } return null; }, titleToken({ canvas }) { return canvas.get('title'); } });
JavaScript
0.000484
@@ -413,18 +413,14 @@ ken( -%7B canvas - %7D ) %7B%0A
beb4d3bd70c8443c545d40955c51152f7b3ac89c
Change content type check to check for 'application/json' not 'json'
lib/utils/responseHandler.js
lib/utils/responseHandler.js
var Promise = require("bluebird"); module.exports = (response, body) => { var outResponse = { statusCode: response.statusCode, headers: response.headers, body: body }; if (response.statusCode != 200) { var errorResponse = outResponse; if (/\bjson\b/.test(response.headers['content-type'])) { var responseBody = JSON.parse(body); errorResponse.errorCode = responseBody.errorCode; errorResponse.message = responseBody.message; errorResponse.refId = responseBody.refId; if (responseBody.detail !== undefined) { errorResponse.detail = responseBody.detail; } } else { errorResponse.message = body; } return new Promise.reject(errorResponse); } else if (response.headers['content-type'] === 'application/json;charset=UTF-8') { outResponse.content = JSON.parse(body); return outResponse; } else { outResponse.content = body; return outResponse; } };
JavaScript
0.000541
@@ -263,16 +263,29 @@ if (/%5Cb +application%5C/ json%5Cb/.
860a082bb1b024d1e76f081957b08dd215a72147
Troubleshoot script for displaying getting the counts of tickets assigned to each user.
app/scripts/getTickets.js
app/scripts/getTickets.js
/* global SW:true */ $(document).ready(function(){ 'use strict'; console.log( 'Doing SW things!' ); var card = new SW.Card(); var helpdesk = card.services('helpdesk'); helpdesk .request('tickets') .then( function(data){ console.log( 'got data!' ); var ticketCount = {}; $.each(data.tickets, function(index, ticket){ console.log( index ); if (ticketCount[ticket.assignee.id]){ ticketCount[ticket.assignee.id] += 1; } else { ticketCount[ticket.assignee.id] = 1; } console.log( 'ticketCount object' ); console.log( ticketCount ); }); }); });
JavaScript
0
@@ -172,16 +172,44 @@ desk');%0A + var assignmentCount = %7B%7D;%0A helpde @@ -300,36 +300,8 @@ );%0A - var ticketCount = %7B%7D;%0A @@ -369,21 +369,34 @@ le.log( -index +ticket.assignee.id );%0A @@ -403,21 +403,25 @@ if ( -ticke +assignmen tCount%5Bt @@ -443,37 +443,41 @@ id%5D)%7B%0A -ticke +assignmen tCount%5Bticket.as @@ -520,21 +520,25 @@ -ticke +assignmen tCount%5Bt @@ -593,21 +593,25 @@ e.log( ' -ticke +assignmen tCount o @@ -645,30 +645,359 @@ og( -ticketCount );%0A %7D +assignmentCount );%0A %7D);%0A%0A console.log( assignmentCount + 'final' );%0A var ticketTotal = 0;%0A for (var property in assignmentCount) %7B%0A ticketTotal += assignmentCount%5Bproperty%5D;%0A %7D%0A var unassignedTickets = data.tickets.length - ticketTotal;%0A console.log('unassignedTickets');%0A console.log(unassignedTickets );%0A @@ -1003,11 +1003,12 @@ %7D);%0A +%0A %7D);
cedba3c6b47495115ec845efb3e9e486907a53e9
Fix calc
lib/views/permission-view.js
lib/views/permission-view.js
'use babel'; import { $, View, TextEditorView } from 'atom-space-pen-views'; import { CompositeDisposable } from 'atom'; class PermissionView extends View { static content() { return this.div({ class: 'permission-view remote-ftp', }, () => { this.div({ class: 'permissions-wrapper', }, () => { // Owner this.div({ class: 'permission-user block', outlet: 'permissionUser', }, () => { this.h5('Owner Permissions'); // Read this.label('Read', { class: 'input-label inline-block', }, () => { this.input({ class: 'input-checkbox', type: 'checkbox', id: 'permission-user-read', 'data-perm': 'r', }); }); // Write this.label('Write', { class: 'input-label inline-block', }, () => { this.input({ class: 'input-checkbox', type: 'checkbox', id: 'permission-user-write', 'data-perm': 'w', }); }); // Execute this.label('Execute', { class: 'input-label inline-block', }, () => { this.input({ class: 'input-checkbox', type: 'checkbox', id: 'permission-user-execute', 'data-perm': 'e', }); }); }); // Group this.div({ class: 'permission-group block', outlet: 'permissionGroup', }, () => { this.h5('Group Permissions'); // Read this.label('Read', { class: 'input-label inline-block', }, () => { this.input({ class: 'input-checkbox', type: 'checkbox', id: 'permission-group-read', 'data-perm': 'r', }); }); // Write this.label('Write', { class: 'input-label inline-block', }, () => { this.input({ class: 'input-checkbox', type: 'checkbox', id: 'permission-group-write', 'data-perm': 'w', }); }); // Execute this.label('Execute', { class: 'input-label inline-block', }, () => { this.input({ class: 'input-checkbox', type: 'checkbox', id: 'permission-group-execute', 'data-perm': 'e', }); }); }); // Public this.div({ class: 'permission-other block', outlet: 'permissionOther', }, () => { this.h5('Public (other) Permissions'); // Read this.label('Read', { class: 'input-label inline-block', }, () => { this.input({ class: 'input-checkbox', type: 'checkbox', id: 'permission-other-read', 'data-perm': 'r', }); }); // Write this.label('Write', { class: 'input-label inline-block', }, () => { this.input({ class: 'input-checkbox', type: 'checkbox', id: 'permission-other-write', 'data-perm': 'w', }); }); // Execute this.label('Execute', { class: 'input-label inline-block', }, () => { this.input({ class: 'input-checkbox', type: 'checkbox', id: 'permission-other-execute', 'data-perm': 'e', }); }); }); this.div({ class: 'permission-chown block', }, () => { this.b('Group: '); this.label('', { outlet: 'chownGroup', }); this.b('Owner: '); this.label('', { outlet: 'chownOwner', }); }); }); this.div({ class: 'permissions-wrapper-block', }, () => { this.div({ class: 'permissions-chmod block', }, () => { this.label('Chmod'); this.subview('chmodInput', new TextEditorView({ mini: true, placeholderText: 600, })); }); }); this.div({ class: 'block clearfix', outlet: 'buttonBlock', }, () => { this.button({ class: 'inline-block btn pull-right icon icon-x inline-block-tight', outlet: 'cancelButton', click: 'cancel', }, 'Cancel'); this.button({ class: 'inline-block btn btn-primary pull-right icon icon-sync inline-block-tight', outlet: 'saveButton', click: 'confirm', }, 'Save'); }); }); } initialize(params) { this.chmod = { user: 0, group: 0, other: 0, get toString() { return `${this.user}${this.group}${this.other}`; }, }; this.disposables = new CompositeDisposable(); this.disposables.add(atom.commands.add('atom-workspace', { 'core:confirm': () => { this.confirm(); }, 'core:cancel': (event) => { this.cancel(); event.stopPropagation(); }, })); Object.keys(params.rights).forEach((right) => { const perms = right.split(''); const $perm = $(this).find(`.permission-${right}`); for (let i = 0; i < perms.length; i++) { $perm.find(`input[data-perm="${perms[i]}"]`).attr('checked', true); } }); this.chownGroup.html(params.group); this.chownOwner.html(params.owner); this.checkPermissions(); this.show(); } checkPermissions() { const right = { r: 4, w: 2, e: 1 }; const chmods = { user: this.permissionUser, group: this.permissionGroup, other: this.permissionOther, }; Object.keys(chmods).forEach((cKey) => { const cItem = chmods[cKey]; const $inputs = $(cItem).find('input'); const list = {}; for (let x = 0; x < $inputs.length; x++) { const $this = $($inputs[x]); list[$this.attr('data-perm')] = ($this.attr('checked') === 'checked'); } Object.keys(list).filter(key => list[key]).forEach((key) => { this.chmod[cKey] += right[key]; }); }); this.chmodInput.setText(this.chmod.toString); } confirm() { this.hide(); this.checkPermissions(); this.destroy(); } cancel() { this.hide(); this.destroy(); } show() { this.panel = atom.workspace.addModalPanel({ item: this }); this.panel.show(); } hide() { if (this.panel) { this.panel.hide(); } } destroy() { this.remove(); } } export default PermissionView;
JavaScript
0.000309
@@ -5503,21 +5503,36 @@ perms = -right +params.rights%5Bright%5D .split('
24e2c29df3e7adb9126401863803939be2ed1a21
fix can view all articles acceptance test
tests/acceptance/can-view-all-articles-test.js
tests/acceptance/can-view-all-articles-test.js
import Ember from 'ember'; import { test } from 'qunit'; import moduleForAcceptance from 'adlet/tests/helpers/module-for-acceptance'; let s3Mock = Ember.Service.extend({ listAll(){ return [ {Key: "Article1", Body: [77,121,32,83,101,120,121,32,66,101,97,99,104,32,66,111,100,121,33,33,33,33]}, {Key: "Article2", Body: [77,121,32,83,101,120,121,32,66,101,97,99,104,32,66,111,100,121,33,33,33,33]} ]; } }); moduleForAcceptance('Acceptance | can view all articles', { beforeEach() { this.application.register('service:s3Mock', s3Mock); this.application.inject('adapter', 's3', 'service:s3Mock'); } }); test('visiting /', function(assert) { visit('/'); andThen(function() { assert.equal(currentURL(), '/'); var body = find(".application__content").text(); assert.equal(body.includes("Article1"), true, "The page should display Article 1"); assert.equal(body.includes("Article2"), true, "The page should display Article 2"); }); });
JavaScript
0
@@ -808,38 +808,37 @@ rt.equal(body.in -cludes +dexOf (%22Article1%22), tr @@ -833,16 +833,23 @@ ticle1%22) + !== -1 , true, @@ -914,14 +914,13 @@ y.in -cludes +dexOf (%22Ar @@ -927,16 +927,23 @@ ticle2%22) + !== -1 , true,
bac79c1a18a369c81a560de29d790a671f3dc836
add support for chart tooltip
app/public/js/chart_donut.js
app/public/js/chart_donut.js
var Donut = function(args) { var element = args.element; var dataset = args.dataset; var width = args.width || 100; var height = args.height || 100; var radius = Math.min(width, height) / 2; var colors = args.colors; if (typeof colors == 'undefined') { var color = d3.scale.category20(); } else { var color = d3.scale.ordinal().range(colors); } var pie = d3.layout.pie().sort(null); var arc = d3.svg.arc().innerRadius(radius - (width / 3)).outerRadius(radius - width / 6); var svg = d3.select(element).append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); var path = svg.selectAll("path") .data(pie(dataset)) .enter().append("path") .attr("fill", function(d, i) { return color(i); }) .attr("d", arc); };
JavaScript
0
@@ -223,16 +223,42 @@ .colors; +%0A var title = args.title; %0A%0A if ( @@ -715,24 +715,103 @@ 2 + %22)%22);%0A%0A + if (typeof title != 'undefined') %7B%0A svg.append(%22title%22).text(title);%0A %7D%0A%0A var path =
e9f68c5dd05e4bd52909882ae21dcfb959935d61
remove Crag planet. only need 1 planet per faction
app/js/objects.js
app/js/objects.js
var Planet = require('./classes/Planet'); var BattleGroup = require('./classes/BattleGroup'); var Tatooine = new Planet({ id: "Tatooine", type: "Planet", radius: 100, color: 0x000000, texture: 'assets/mars.jpg', homePosition: new THREE.Vector3(-300, 100, 0), autoRotationSpeed: -0.005, videoId: 'video', moons: { count: 2 } }); var Hoth = new Planet({ id: "Hoth", type: "Planet", radius: 70, color: 0x000000, texture: 'assets/planet_hoth.png', homePosition: new THREE.Vector3(300, 100, 0), autoRotationSpeed: -0.005, videoId: 'video', moons: { count: 4 } }); var Crag = new Planet({ id: "Crag", type: "Planet", radius: 50, color: 0x000000, texture: 'assets/planet_crag.jpg', homePosition: new THREE.Vector3(0, 200, 0), autoRotationSpeed: -0.005, videoId: 'video', moons: { count: 1 } }); var RebelAllianceBattleGroup = new BattleGroup({ id: "Rebal Alliance Battle Group", type: "BattleGroup", laserColor: 0x3FFF00, obj: 'assets/star-wars/ARC170-2/Arc170.obj', mtl: 'assets/star-wars/ARC170-2/Arc170.mtl', homePosition: new THREE.Vector3(200, -100, 0), radius: 40, shipPositions: [ new THREE.Vector3(0, 40, 0), new THREE.Vector3(20, 20, 0), new THREE.Vector3(-20, 20, 0), new THREE.Vector3(0, 0, 30), new THREE.Vector3(0, 0, -30), ], autoRotationSpeed: -0.004, scale: 0.02, videoId: 'video' }); var RepublicBattleGroup = new BattleGroup({ id: "Republic Battle Group", type: "BattleGroup", laserColor: 0xDC143C, obj: 'assets/star-wars/ARC170-2/Arc170.obj', mtl: 'assets/star-wars/ARC170-2/Arc170.mtl', homePosition: new THREE.Vector3(-200, -100, 0), radius: 40, shipPositions: [ new THREE.Vector3(0, 40, 0), new THREE.Vector3(20, 20, 0), new THREE.Vector3(-20, 20, 0), new THREE.Vector3(0, 0, 30), new THREE.Vector3(0, 0, -30), ], autoRotationSpeed: -0.004, scale: 0.02, videoId: 'video' }); var sun = new THREE.Mesh( new THREE.SphereGeometry(50, 64, 64), new THREE.MeshBasicMaterial({ map: THREE.ImageUtils.loadTexture("assets/texture_sun.jpg") }) ); module.exports = { objects: [ Hoth, Tatooine, Crag, RebelAllianceBattleGroup, RepublicBattleGroup ], sun: sun };
JavaScript
0.000151
@@ -607,264 +607,8 @@ );%0A%0A -%0Avar Crag = new Planet(%7B%0A id: %22Crag%22,%0A type: %22Planet%22,%0A radius: 50,%0A color: 0x000000,%0A texture: 'assets/planet_crag.jpg',%0A homePosition: new THREE.Vector3(0, 200, 0),%0A autoRotationSpeed: -0.005,%0A videoId: 'video',%0A moons: %7B%0A count: 1%0A %7D%0A%7D);%0A%0A%0A var @@ -1924,14 +1924,8 @@ ine, - Crag, Reb
194719649978a99c73b1801e1d6c7abae7969dc2
Set tracking/crash reporting to true by default
app/lib/config.js
app/lib/config.js
import { app, remote, ipcRenderer } from 'electron' import fs from 'fs' import { memoize } from 'cerebro-tools' import { trackEvent } from './trackEvent' import loadThemes from './loadThemes' const electronApp = remote ? remote.app : app // initiate portable mode // set data directory to ./userdata process.argv.forEach((arg) => { if (arg.toLowerCase() === '-p' || arg.toLowerCase() === '--portable') { electronApp.setPath('userData', `${process.cwd()}/userdata`) } }) const CONFIG_FILE = `${electronApp.getPath('userData')}/config.json` const defaultSettings = memoize(() => { const locale = electronApp.getLocale() || 'en-US' const [lang, country] = locale.split('-') return { locale, lang, country, // use first theme from loadThemes by default theme: loadThemes()[0].value, hotkey: 'Control+Space', showInTray: true, firstStart: true, developerMode: false, cleanOnHide: true, skipDonateDialog: false, lastShownDonateDialog: null, plugins: {}, isMigratedPlugins: false, trackingEnabled: false, crashreportingEnabled: false, openAtLogin: true } }) const readConfig = () => { try { return JSON.parse(fs.readFileSync(CONFIG_FILE).toString()) } catch (err) { return defaultSettings() } } /** * Get a value from global configuration * @param {String} key * @return {Any} */ const get = (key) => { let config if (!fs.existsSync(CONFIG_FILE)) { // Save default config to local storage config = defaultSettings() fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2)) } else { config = readConfig() } return config[key] } /** * Write a value to global config. It immedately rewrites global config * and notifies all listeners about changes * * @param {String} key * @param {Any} value */ const set = (key, value) => { const config = { // If after app update some keys were added to config // we use default values for that keys ...defaultSettings(), ...readConfig() } config[key] = value fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2)) // Track settings changes trackEvent({ category: 'Settings', event: `Change ${key}`, label: value }) if (ipcRenderer) { console.log('notify main process', key, value) // Notify main process about settings changes ipcRenderer.send('updateSettings', key, value) } } export default { get, set }
JavaScript
0.000001
@@ -1058,28 +1058,27 @@ ingEnabled: -fals +tru e,%0A crash @@ -1095,20 +1095,19 @@ nabled: -fals +tru e,%0A o
e27995027a8ae5bfa5c68de32b49e11cd9b6f4c9
Add ISO-639-2 code to Albanian locale
src/locale/sq/index.js
src/locale/sq/index.js
import formatDistance from './_lib/formatDistance/index' import formatLong from './_lib/formatLong/index' import formatRelative from './_lib/formatRelative/index' import localize from './_lib/localize/index' import match from './_lib/match/index' /** * @type {Locale} * @category Locales * @summary Albanian locale. * @language Shqip * @author Ardit Dine [@arditdine]{@link https://github.com/arditdine} */ var locale = { code: 'sq', formatDistance: formatDistance, formatLong: formatLong, formatRelative: formatRelative, localize: localize, match: match, options: { weekStartsOn: 1 /* Monday */, firstWeekContainsDate: 1 } } export default locale
JavaScript
0.999226
@@ -332,16 +332,34 @@ e Shqip%0A + * @iso-639-2 sqi%0A * @auth @@ -665,12 +665,14 @@ e: 1 +, %0A %7D +, %0A%7D%0A%0A
c12baf05a552d6f49f2b4effa7ec9e250779cce7
Fix jscs warning.
app/lib/helper.js
app/lib/helper.js
module.exports = (function () { 'use strict'; /** * Return lodash extended with custom methods. */ var lodashExtended = function () { var _ = require('lodash'); /** * Return an UUID */ function uuid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; /** * Merge properties as private attributes in obj. * ie: {id: 42} => obj._id = 42 */ function privateMerge(obj, properties) { _.forEach(properties, function (value, key) { if (key.substr(0, 1) !== '_') { key = '_' + key; } obj[key] = value; }); return obj; } /** * Return an object with the public/private attributes of obj. * The lodash character of private properties is removed. */ function publicProperties(obj) { var properties = {}; _.forIn(obj, function (value, key) { if (!_.isFunction(obj[key])) { key = key.replace(/^_/, ''); properties[key] = value; } }); return properties; } _.mixin({ uuid: uuid, privateMerge: privateMerge, publicProperties: publicProperties }); return _; }; return { _: lodashExtended() }; })();
JavaScript
0
@@ -496,17 +496,16 @@ );%0A %7D -; %0A%0A /*
c3ae981e9d825d2244a50a131ba175ae005564ba
Change position of all the food
games/hungrydog.js
games/hungrydog.js
var puppy = { x: 550, y: 490, alive: true, won: false, canMove: true, }; var bone1 = { x: 560, y: 80, alive: true, }; var bone2 = { x: 560, y: 200, alive: true, }; var bacon = { x: 560, y: 320, alive: true, }; document.getElementById("up").onclick = function() {move(38);}; document.getElementById("down").onclick = function() {move(40);}; document.getElementById("right").onclick = function() {move(39);}; document.getElementById("left").onclick = function() {move(37);}; var puppyImg = document.getElementById("puppy"); var boneImg1 = document.getElementById("bone1"); var boneImg2 = document.getElementById("bone2"); var baconImg = document.getElementById("bacon"); var boneCount = 3; function move(direction){ if (puppy.canMove){ console.log('moving'); food_move(bone1, boneImg1); food_move(bone2, boneImg2); food_move(bacon, baconImg); if (puppy.canMove){ console.log('moving'); if (direction.keyCode === 38 || direction === 38){ // move up if (puppy.y > 50){ puppy.y = (puppy.y - 10); puppyImg.style.top = (puppy.y + "px"); } }else if (direction.keyCode === 40 || direction === 40){ // move down if (puppy.y < 490){ puppy.y = (puppy.y + 10); puppyImg.style.top = (puppy.y + "px"); } }else if (direction.keyCode === 39 || direction == 39){ // move right if (puppy.x < 1200){ puppy.x = (puppy.x + 10); puppyImg.style.left = (puppy.x + "px"); } }else if (direction.keyCode === 37 || direction == 37){ // move left if (puppy.x > 550){ puppy.x = (puppy.x - 10); puppyImg.style.left = (puppy.x + "px"); } } } } function food_move(player, playerImg){ var random = Math.floor((Math.random() * 4) + 1); // move up if (random === 1){ if (player.y > 0){ player.y = (player.y - 40); playerImg.style.top = (player.y + "px"); } }else if (random === 2){ // move down if (player.y < 440){ player.y = (player.y + 40); playerImg.style.top = (player.y + "px"); } }else if (random === 3){ // move right if (player.x < 600){ player.x = (player.x + 40); playerImg.style.left = (player.x + "px"); } }else{ //move left if (player.x > 0){ player.x = (player.x - 40); playerImg.style.left = (player.x + "px"); } } } document.onkeydown = move;
JavaScript
0.000106
@@ -1697,16 +1697,18 @@ %7D%0A %7D%0A%7D +%0A%7D %0A%0Afuncti @@ -1967,25 +1967,8 @@ 2)%7B%0A - // move down%0A @@ -2106,26 +2106,8 @@ 3)%7B%0A - // move right%0A @@ -2219,16 +2219,17 @@ %7D%0A + %7Delse%7B%0A @@ -2228,24 +2228,8 @@ se%7B%0A - //move left%0A
0e10e0317455cd9f16c7386e9043bf594fb00827
Change injectHTML, add getOptions, add done
core/src/bg/injecthtml.js
core/src/bg/injecthtml.js
// RegExp test cases here: http://regexr.com/3gqin function injectHTML() { // select everything in the body except <script>, <style>, <a>, <code>, <pre> const elements = document.querySelectorAll('body *:not(script):not(style):not(a):not(code):not(pre)'); const userLowerLimit = 10; const userUpperLimit = 100; // eslint-disable-next-line no-useless-escape const generatedRegexTest = `(\\()([A-Z .,!?:"'\`\\\/&-]{${userLowerLimit},${userUpperLimit}})\\w*(\\))`; // generatedRegexTest = /(\()([A-Z .,!?:"'`\\\/&-]{num,num})\w*(\))/gi const inBracketsRegex = new RegExp(generatedRegexTest, 'gi'); for (let i = 0; i < elements.length; i += 1) { if (elements[i].hasChildNodes()) { elements[i].childNodes.forEach((el) => { if (el.nodeType === Node.TEXT_NODE && el.nodeValue.match(inBracketsRegex)) { const text = el.nodeValue.substring(el.nodeValue.indexOf('(') + 1, el.nodeValue.indexOf(')')); // escape allowed characters and "(", ")" to make it RegExp safe const matchedTextRegex = new RegExp(text.replace(/[.,!?:"'`\\/&-()]/g, '\\$&')); // replace symbols that break html layout: data-bracketless=""this" breaks" const htmlSafeText = text.replace(/&/g, '&amp;').replace(/"/g, "'"); // eslint-disable-next-line no-param-reassign el.parentNode.innerHTML = el.parentNode.innerHTML .replace(matchedTextRegex, `<bracket-less data-bracketless="${htmlSafeText}">${text}</bracket-less>`); } }); } } // so that script will be injected once return true; } injectHTML(); // RegExp BUGS // ignores text: "... (i.e., $99.99), ... (plus taxes) to buy it." // @ https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch1.md#values--types // (see Chapter 2). Loops (see "Loops") // incorrectly grabs text: "see Chapter 2", and "). Loops (" // @ https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch1.md#loops and go up
JavaScript
0.000002
@@ -65,16 +65,23 @@ ectHTML( +options ) %7B%0A // @@ -261,25 +261,24 @@ pre)');%0A -%0A const userLowe @@ -273,58 +273,134 @@ nst -userLowerLimit = 10;%0A const userUpperLimit = 100; +%7B%0A lowerRegexLimit, upperRegexLimit,%0A %7D = options;%0A%0A // generate regex using with custom upper and lower character limits %0A / @@ -455,31 +455,24 @@ onst gen -erated Regex -Test +Str = %60(%5C%5C( @@ -501,17 +501,18 @@ %5D%7B$%7B -userLower +lowerRegex Limi @@ -521,16 +521,17 @@ ,$%7Bu -serU pper +Regex Limi @@ -550,82 +550,8 @@ )%60;%0A - // generatedRegexTest = /(%5C()(%5BA-Z .,!?:%22'%60%5C%5C%5C/&-%5D%7Bnum,num%7D)%5Cw*(%5C))/gi%0A co @@ -590,23 +590,16 @@ (gen -erated Regex -Test +Str , 'g @@ -1528,460 +1528,275 @@ %7D%0A - // so that script will be injected once%0A return true;%0A%7D%0AinjectHTML();%0A%0A// RegExp BUGS%0A// ignores text: %22... (i.e., $99.99), ... (plus taxes) to buy it.%22%0A// @ https://github.com/getify/You-Dont-Know-JS/blob/master/up%2520%2526%2520going/ch1.md#values--types%0A%0A// (see Chapter 2). Loops (see %22Loops%22)%0A// incorrectly grabs text: %22see Chapter 2%22, and %22). Loops (%22%0A// @ https://github.com/getify/You-Dont-Know-JS/blob/master/up%2520%2526%2520going/ch1.md#loops and go up +%7D%0A%0A// default values%0Afunction getOptions() %7B%0A chrome.storage.sync.get(%7B%0A lowerRegexLimit: 10,%0A upperRegexLimit: 100,%0A autoActivate: false,%0A autoPlay: false,%0A %7D, options =%3E injectHTML(options));%0A%7D%0A%0Afunction done() %7B%0A getOptions();%0A return true;%0A%7D%0A%0Adone(); %0A
eaff275ec10c30e06ca0e31cd82ee91060aae23d
hide swiper if events count is 0
app/static/script/myjs.js
app/static/script/myjs.js
// Use '[[' and ']]' tags since Django using Mustache's default template tags. Mustache.tags = ['[[', ']]']; $(function(){ var swiper = new Swiper('.swiper-container', { loop : true, pagination: '.swiper-pagination', nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', slidesPerView: 'auto', centeredSlides: true, paginationClickable: true, spaceBetween: 30 }); $('#top-tabs').tabs({ selected: 0 }); }); (function (window) { var $ = window.jQuery; var moment = window.moment; $('.dropdown-toggle').dropdown(); $(function () { webshim.activeLang('ja'); $.webshims.setOptions('extendNative', true); $.webshims.polyfill('forms'); }); moment.locale('ja', {week: {dow: 1}}); var DateFormat = 'YYYY-MM-DD'; $(function () { $('#searchform-date').datetimepicker({ inline: true, locale: moment.locale('ja'), format: DateFormat }); $('#result-number').change(function() { var url = window.location.href; var num = this.value; var regex = /\b(numperpage=)[^&]*/; var newUrl; if (regex.test(url)) { newUrl = url.replace(regex, '$1' + num); } else { newUrl = url + "&numperpage=" + num; } window.location.replace(newUrl); }); }); })(this); /** * bootstrap-confirmation2 */ (function (global) { global.jQuery(function ($) { $('[data-toggle=confirmation]').confirmation({ rootSelector: '[data-toggle=confirmation]', title: '本当によろしいですか?', btnOkLabel: 'はい', btnCancelLabel: 'いいえ' }); }); })(this); /** * croppie-upload - use croppie.js to crop uploaded images */ (function (global) { var $ = global.jQuery; var Blob = global.Blob; var alert = global.alert; var FileReader = global.FileReader; var FormData = global.FormData; var base64ToBlob = function (src) { var chunkSize = 1024; var srcList = src.split(/[:;,]/); var mime = srcList[1]; var byteChars = global.atob(srcList[3]); var byteArrays = []; for (var c = 0, len = byteChars.length; c < len; c += chunkSize) { var slice = byteChars.slice(c, c + chunkSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } return new Blob(byteArrays, {type: mime}); }; $.fn.extend({ croppieUpload: function (opt) { var self = this; var div; // read file self.on('change', function () { $('.croppie-upload-ready').remove(); div = $('<div>') .addClass('croppie-upload-ready') .croppie( $.extend({ enableExif: true, viewport: { width: 200, height: 200, type: 'square' }, boundary: { width: 300, height: 300 } }, opt) ); if (!this.files || !this.files[0]) { alert("Sorry - your browser doesn't support the FileReader API"); return false; } var reader = new FileReader(); reader.onload = function (e) { div.croppie('bind', { url: e.target.result }); }; reader.readAsDataURL(this.files[0]); self.after(div); }); self.closest('form').submit(function () { var form = $(this); var formData = new FormData(form.get(0)); var name = self.attr('name'); div .croppie('result', { type: 'canvas', size: 'viewport' }) .then(function (resp) { formData.append(name, base64ToBlob(resp), 'cropped'); $.ajax({ cache: true, async: false, url: form.attr('action'), type: form.attr('method'), cache: false, processData: false, contentType: false, data: formData }) .done(function () { global.location.reload(); }); }); return false; }); } }); })(this);
JavaScript
0.998986
@@ -117,16 +117,96 @@ tion()%7B%0A + var count = $('.swiper-container .swiper-slide').length;%0A if (count %3E 0) %7B%0A var sw @@ -250,16 +250,18 @@ , %7B%0A + loop : t @@ -257,32 +257,34 @@ loop : true,%0A + pagination: @@ -309,16 +309,18 @@ n',%0A + nextButt @@ -350,16 +350,18 @@ t',%0A + + prevButt @@ -391,16 +391,18 @@ v',%0A + + slidesPe @@ -420,16 +420,18 @@ o',%0A + centered @@ -444,24 +444,26 @@ : true,%0A + + paginationCl @@ -481,16 +481,18 @@ ue,%0A + spaceBet @@ -500,22 +500,74 @@ een: 30%0A + %7D);%0A + %7D else %7B%0A $('.swiper-container').hide();%0A %7D%0A $('#to
55a19445c3799cbb0681c1c67ad498d11aff5b8c
add handling the hash in the url
lessons/misc/webdev-intro/app/slideshow.js
lessons/misc/webdev-intro/app/slideshow.js
'use strict' var contents = ''; console.log('this is a slideshow'); console.log(marked('# test\nof *marked*')); function splitContents(text) { // split the slides apart var slides = text.split('\n#'); // handle the special cases of starting with a newline or whitespace if (text.startsWith('\n')) slides = slides.slice(1); else slides[0] = slides[0].slice(1); // add the # character back to the start of each bit of text for (let i in slides) slides[i] = '#'.concat(slides[i]); return slides; } function addParentSection(slides) { var prev = ''; var result = []; for (let i in slides) { if (slides[i].startsWith('##')) result[i] = prev.concat('\n', slides[i]); else { prev = slides[i].split('\n')[0].slice(1).trim(); result[i] = slides[i]; } } return result; } function makeSlideElements(text, addParent) { var slides = splitContents(text); if (addParent) slides = addParentSection(slides); var elms = []; for (let sl of slides) { let elm = document.createElement('section'); elm.innerHTML = marked(sl); elm.classList.add('slide'); elms.push(elm); } return elms; } var cElm, nElm; function startSlides(contentElm, navElm, url) { cElm = contentElm; nElm = navElm; var xlr = new XMLHttpRequest(); xlr.open('GET', url, true); xlr.send(); xlr.addEventListener('readystatechange', function() { contents = this.responseText; if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { window.setTimeout(setup.bind(this, contentElm, navElm), 1000); } }); function setup(contentElm, navElm) { renderContents(contentElm, this.responseText); genNavbar(navElm, contentElm); } function renderContents(rootElm, contents) { rootElm.innerHTML = ''; for (let elm of makeSlideElements(contents, true)) rootElm.appendChild(elm); rootElm.children[0].classList.add('shown'); } window.addEventListener('keyup', function(keyEvent) { switch(keyEvent.key) { case 'h': prevSlide(); break; case 'l': case ' ': nextSlide(); break; case 'j': selectSlide(cElm.lastElementChild); break; case 'k': selectSlide(cElm.firstElementChild); break; case 's': toggleShowAll(cElm); break; case 'v': toggleHorizontal(cElm); } }) } function toggleShowAll(cElm) { cElm.classList.toggle('show-all'); } function toggleHorizontal(cElm) { cElm.classList.toggle('horizontal'); } function prevSlide() { var current = cElm.getElementsByClassName('shown')[0]; if (current.previousElementSibling) { selectSlide(current.previousElementSibling); } } function nextSlide() { var current = cElm.getElementsByClassName('shown')[0]; if (current.nextElementSibling) { selectSlide(current.nextElementSibling); } } function selectSlide(slideElm) { var contentElm = slideElm.parentElement; // update the classes of slides for (let slide of contentElm.children) slide.classList.remove('shown'); slideElm.classList.add('shown'); // update the nav bar var slideIndex = Array.from(contentElm.children).indexOf(slideElm); // nElm is from the outer context (bad) for (let b of nElm.children) b.classList.remove('shown'); nElm.children[1+slideIndex].classList.add('shown'); } function genNavbar(navElm, contentElm) { var prevButton, nextButton; prevButton = document.createElement('button'); prevButton.innerText = '<-'; prevButton.onclick = prevSlide; navElm.appendChild(prevButton); // Note that using var here would break functionality due to scoping rules for (let sl of contentElm.children) { let marker = document.createElement('button'); marker.classList.add('dot'); marker.onclick = function() { selectSlide(sl); }; marker.innerText = ' '; navElm.appendChild(marker); } nextButton = document.createElement('button'); nextButton.innerText = '->'; nextButton.onclick = nextSlide; navElm.appendChild(nextButton); }
JavaScript
0.000012
@@ -1860,24 +1860,293 @@ ontentElm);%0A + // This sets the hash in the url%0A var h = location.hash;%0A if (h === '')%0A selectSlide(cElm.children%5B0%5D);%0A else %7B%0A let slideIndex = parseInt(h.slice(1)) - 1;%0A selectSlide(cElm.children%5BslideIndex%5D);%0A %7D%0A %7D%0A%0A f @@ -2373,24 +2373,71 @@ n');%0A %7D%0A%0A + // Handle the hotkeys for switching slides%0A window.a @@ -2890,160 +2890,567 @@ - case 's':%0A toggleShowAll(cElm);%0A break;%0A case 'v':%0A toggleHorizontal(cElm);%0A %7D%0A %7D) +%7D%0A %7D)%0A // Handle hotkeys for changing the layout%0A // notice that the event listeners are both run%0A window.addEventListener('keyup', function(keyEvent) %7B%0A switch(keyEvent.key) %7B%0A case 's':%0A toggleShowAll(cElm);%0A break;%0A case 'v':%0A toggleHorizontal(cElm);%0A %7D%0A %7D)%0A%0A // This handles the user changing the hash on the url%0A window.onpopstate = function () %7B%0A var slideIndex = location.hash.slice(1)-1;%0A selectSlide(cElm.children%5BslideIndex%5D);%0A %7D%0A %0A%7D%0A%0A @@ -4462,24 +4462,179 @@ d('shown');%0A + updateUrl(slideIndex);%0A%7D%0A%0Afunction updateUrl(slideIndex) %7B%0A window.history.replaceState(%7Bslide: slideIndex%7D, 'Slide change', './#'+(slideIndex+1));%0A %7D%0A%0Afunction
91e63e57862249383d88f1374024d255a888a6f1
Make comments more clear
src/main_unresolved.js
src/main_unresolved.js
define([ "./main", "./item/lookup", "./item/get_resolved", "./util/json/merge" ], function( Cldr, itemLookup, itemGetResolved, jsonMerge ) { var getSuper; Cldr._raw = {}; // Load resolved or unresolved cldr data // @json [JSON] // // Overwrite Cldr.load(). Cldr.load = function( json ) { if ( typeof json !== "object" ) { throw new Error( "invalid json" ); } Cldr._raw = jsonMerge( Cldr._raw, json ); }; // Overload Cldr.prototype.get(). getSuper = Cldr.prototype.get; Cldr.prototype.get = function( path ) { // Simplify locale using languageId (there are no other resource bundles) // 1: during init(), get is called, but languageId is not defined. Use "" as a workaround in this very specific scenario. var locale = this.attributes && this.attributes.languageId || "" /* 1 */; return getSuper.apply( this, arguments ) || itemLookup( Cldr, locale, path, this.attributes ); }; return Cldr; });
JavaScript
0.000002
@@ -539,85 +539,159 @@ %09// -Simplify locale using languageId (there are no other resource bundles) +1: use languageId as locale on item lookup for simplification purposes, because no other extended subtag is used anyway on bundle parent lookup. %0A%09%09// -1 +2 : du @@ -703,19 +703,27 @@ init(), -get +this method is call @@ -744,16 +744,20 @@ geId is +yet not defi @@ -822,156 +822,140 @@ .%0A%09%09 -var locale = this.attributes && this.attributes.languageId %7C%7C %22%22 /* 1 */;%0A%0A%09%09return getSuper.apply( this, arguments ) %7C%7C%0A%09%09%09itemLookup( Cldr, locale +return getSuper.apply( this, arguments ) %7C%7C%0A%09%09%09itemLookup( Cldr, this.attributes && this.attributes.languageId /* 1 */ %7C%7C %22%22 /* 2 */ , pa
536203b9121d6cac460fcee5b2bafbef27d80b63
Update current-user service to findRecord by id
app/services/current-user.js
app/services/current-user.js
import Service, { inject as service } from '@ember/service'; import { isEmpty } from '@ember/utils'; import RSVP from 'rsvp'; import Sentry from '../sentry'; export default Service.extend({ session: service(), store: service(), load() { let username = this.get('session.data.authenticated.profile.sub'); if (!isEmpty(username)) { return this.store.query('user', { 'username': username, }).then(users => { return users.get('firstObject'); }).catch(err => { alert(err.errors[0].detail) return RSVP.resolve() }).then((user) => { Sentry.configureScope(scope => { scope.setUser({ id: user.id, name: user.name, username: user.username, email: user.email, }); }); return this.set('user', user); }); } else { return RSVP.resolve(); } } });
JavaScript
0
@@ -246,24 +246,18 @@ let -username +id = this. @@ -320,24 +320,18 @@ isEmpty( -username +id )) %7B%0A @@ -355,61 +355,45 @@ ore. -query('user', %7B%0A 'username': username, +findRecord(%0A 'user', id %0A -%7D ).th @@ -399,17 +399,16 @@ hen(user -s =%3E %7B%0A @@ -428,28 +428,8 @@ user -s.get('firstObject') ;%0A
3d099f2003199e201bbf1ad70673e5b148c2e01e
fix validator of unit payment order item
src/purchasing/unit-payment-order-item-validator.js
src/purchasing/unit-payment-order-item-validator.js
require("should"); var validateUnitReceiptNote = require('./unit-receipt-note-validator'); var validateProduct = require('../master/product-validator'); var validateUom = require('../master/uom-validator'); module.exports = function (data) { data.should.have.property('unitReceiptNoteId'); data.unitReceiptNoteId.should.instanceof(Object); data.should.have.property('unitReceiptNote'); data.unitReceiptNote.should.instanceof(Object); validateUnitReceiptNote(data.unit); };
JavaScript
0
@@ -487,16 +487,27 @@ ata.unit +ReceiptNote ); %0A %0A
210e6ab8a7b3071f46abe75ca1de7ecfd8b82fb8
fix jshint warning
corejs/core/webstorage.js
corejs/core/webstorage.js
define([ "core/assert", "core/config" ], function (ASSERT, CONFIG) { "use strict"; var MStorage = function (collectionname) { var storage = {}; var load = function (key, callback) { setTimeout(function () { var data = storage[key]; if( data ) { callback(null, data); } else { callback(new Error("not found")); } }, 0); }; var save = function (node, callback) { setTimeout(function () { storage[node._id] = node; callback(null); }, 0); }; var remove = function (key, callback) { setTimeout(function () { delete storage[key]; callback(null); }, 0); }; var dumpAll = function (callback) { setTimeout(function () { for( var i in storage ) { console.log(JSON.stringify(storage[i])); } callback(null); }, 0); }; var removeAll = function (callback) { setTimeout(function () { storage = {}; callback(null); }, 0); }; var searchId = function (beginning, callback) { setTimeout(function () { var count = 0; var lastmatch = ""; for( var i in storage ) { if( i.indexOf(beginning) === 0 ) { lastmatch = i; count++; } if( count > 1 ) { break; } } if( count === 1 ) { callback(null, storage[lastmatch]); } else { callback(new Error(count > 1 ? "not unique" : "not found")); } }, 0); }; return { load: load, save: save, remove: remove, dumpAll: dumpAll, removeAll: removeAll, searchId: searchId }; }; var LStorage = function (collectionname, type) { var storage = type === "session" ? window.sessionStorage : window.localStorage; var load = function (key, callback) { setTimeout(function () { var data = JSON.parse(storage.getItem(collectionname + key)); if( data ) { callback(null, data); } else { callback(new Error("not found")); } }, 0); }; var save = function (node, callback) { setTimeout(function () { storage.setItem(collectionname + node._id, JSON.stringify(node)); callback(null); }, 0); }; var remove = function (key, callback) { setTimeout(function () { storage.removeItem(collectionname + key); callback(null); }, 0); }; var dumpAll = function (callback) { setTimeout(function () { for( var i = 0; i <= storage.length - 1; i++ ) { var key = storage.key(i); if( key.indexOf(collectionname) === 0 ) { console.log(storage.getItem(key)); } } callback(null); }, 0); }; var removeAll = function (callback) { setTimeout(function () { var ids = []; for( var i = 0; i < storage.length - 1; i++ ) { var key = storage.key(i); if( key.indexOf(collectionname) === 0 ) { ids.push(key); } } for( i = 0; i < ids.length; i++ ) { storage.removeItem(ids[i]); } callback(null); }, 0); }; var searchId = function (beginning, callback) { setTimeout(function () { var count = 0; var lastmatch = ""; for( var i = 0; i <= storage.length - 1; i++ ) { var key = storage.key(i); if( key.indexOf(collectionname + beginning) === 0 ) { lastmatch = key; count++; } if( count > 1 ) { break; } } if( count === 1 ) { callback(null, storage.getItem(lastmatch)); } else { callback(new Error(count > 1 ? "not unique" : "not found")); } }, 0); }; return { load: load, save: save, remove: remove, dumpAll: dumpAll, removeAll: removeAll, searchId: searchId }; }; var Mongo = function (options) { var _storage = null; options = CONFIG.copyOptions(CONFIG.mongodb, options); var open = function (callback) { setTimeout(function () { switch( options.database ) { case "local": _storage = new LStorage(options.collection, "local"); break; case "session": _storage = new LStorage(options.collection, "session"); break; default: _storage = new MStorage(options.collection); } callback(null); }, 0); }; var opened = function () { return _storage !== null; }; var close = function (callback) { _storage = null; if( callback ) { callback(null); } }; var load = function (key, callback) { ASSERT(_storage); _storage.load(key, callback); }; var save = function (node, callback) { ASSERT(_storage); _storage.save(node, callback); }; var remove = function (key, callback) { ASSERT(_storage); _storage.remove(key, callback); }; var dumpAll = function (callback) { ASSERT(_storage); _storage.dumpAll(callback); }; var removeAll = function (callback) { ASSERT(_storage); _storage.removeAll(callback); }; var searchId = function (beggining, callback) { ASSERT(_storage); _storage.searchId(beggining, callback); }; return { open: open, opened: opened, close: close, KEYNAME: "_id", load: load, save: save, remove: remove, dumpAll: dumpAll, removeAll: removeAll, searchId: searchId }; }; return Mongo; });
JavaScript
0.000001
@@ -1681,23 +1681,16 @@ sion%22 ? -window. sessionS @@ -1702,15 +1702,8 @@ e : -window. loca
19fec4fee9bf92c2e576f132d7ffe69c59826d42
Affinity names are internationalized
src/main/js/utils/dbxBuilder.js
src/main/js/utils/dbxBuilder.js
import abilityMessages from '../i18n/ability'; import roleMessages from '../i18n/role'; import unitNameMessages from '../i18n/unitName'; export const transformSponsorAffinityGroupAvailabilitiesJson = (json, intl) => { var result = []; var entry; var mapped; for (var i=0; i<json.length; i++) { entry = json[i]; mapped = transformAffinityGroupsJson(entry.affinityGroups); result.push(mapped); }; return result; } export const transformAffinityGroupsJson = (json, intl) => { var result = []; var entry; var mapped; for (var i=0; i<json.length; i++) { entry = json[i]; mapped = { value : entry.name, label : entry.name } result.push(mapped); }; return result; }
JavaScript
0.997631
@@ -88,24 +88,24 @@ %0Aimport -unitName +affinity Messages @@ -123,16 +123,16 @@ 18n/ -unitName +affinity ';%0A%0A @@ -390,16 +390,22 @@ tyGroups +, intl );%0A @@ -463,23 +463,17 @@ sult;%0A%7D%0A -export +%0A const tr @@ -663,16 +663,52 @@ -value : +label : intl.formatMessage(affinityMessages%5B entr @@ -713,16 +713,18 @@ try.name +%5D) ,%0A @@ -726,21 +726,21 @@ -label +value : entry
47d5f23fee02cfe7b7e28b9824c0694767078d1a
Remove chai truncation to read error messages on spec failure
app/templates/_helpers.js
app/templates/_helpers.js
var chai = require('chai'); var sinonChai = require('sinon-chai'); var sdk = require('flowxo-sdk'); chai.use(sinonChai); chai.use(sdk.Chai); chai.should(); chai.config.includeStack = true; global.expect = chai.expect; global.AssertionError = chai.AssertionError; global.Assertion = chai.Assertion; global.assert = chai.assert; global.sinon = require('sinon');
JavaScript
0
@@ -150,16 +150,190 @@ hould(); +%0A%0A// Don't truncate assertion display:%0A// allows us to view the full error message%0A// when a spec fails%0Achai.config.truncateThreshold = 0;%0A%0A// Show error stack on failed spec %0Achai.co
e83f04b286adcf8068d124bbf83c1beb93911fed
Fix lint
packages/pack/cli/initProtonApp.js
packages/pack/cli/initProtonApp.js
const path = require('path'); const fs = require('fs').promises; const execa = require('execa'); const chalk = require('chalk'); const dedent = require('dedent'); const { success } = require('./log'); const bash = (cli) => execa.shell(cli, { shell: '/bin/bash' }); const TEMPLATE = path.resolve(__dirname, '..', 'template'); const PATH_APP_PKG = path.join(process.cwd(), 'package.json'); /** * Copy the template boilerplate into the root app * - type: default (default) a boilerplate with everything but the auth * - type: auth a boilerplate + private routes * @param {String} type type of boilerplate you want to setup */ async function main(type = 'default') { // Make a copy of the whole src repo await bash(`cp -r ${TEMPLATE}/${type} src`); // Copy basic i18n setup await bash(`cp -r ${TEMPLATE}/po po`); // Copy hidden config files await bash(`cp -r ${TEMPLATE}/.{editorconfig,eslintrc.json,prettierrc} .`); // Copy config tmp await bash(`cp -r ${TEMPLATE}/circle.yml .`); // Copy custom gitignore as during the npm install .gitignore is removed... wtf await bash(`cp -r ${TEMPLATE}/_gitignore .gitignore`); await bash(`cp ${TEMPLATE}/Readme.md Readme.md`); await bash('echo {} > appConfig.json'); const pkgTpl = require('../template/package.json'); const pkgApp = require(PATH_APP_PKG); // Extend the config with the boilerplate's one const pkg = { ...pkgApp, ...pkgTpl, devDependencies: { ...pkgApp.devDependencies, ...pkgTpl.devDependencies } }; // Prout await fs.writeFile(PATH_APP_PKG, JSON.stringify(pkg, null, 4)); console.log(dedent` 🎉 ${chalk.green('Your app is ready')} Here is what's available for this setup: - EditorConfig - Eslint - Prettier - Circle.ci config (lint js + i18n) - Husky + lint-staged - React - Deploy ready, you will need to create an empty branch: deploy-x - npm scripts - ${chalk.yellow('start')}: dev server - ${chalk.yellow('deploy')}: deploy - ${chalk.yellow('pretty')}: run prettier - ${chalk.yellow('i18n:getlatest')}: upgrade translations inside your app - Hook postversion for pushing git tag ➙ Now you can run ${chalk.yellow('npm i')} ➙ Once it's done: ${chalk.yellow('npm start')} `); console.log(); success('Setup done, do not forget about the appConfig.json'); } module.exports = main;
JavaScript
0.000032
@@ -191,24 +191,25 @@ e('./log');%0A +%0A const bash =
9c4840ff0669996a643747f768f38ec776f0cd34
Update initialState
src/client/reducers/initialState.js
src/client/reducers/initialState.js
export default { status: { isScrolling: false, // app scroll currentPage: "home", // currentPage isHeaderVisible: false, // if currentPage == "content" statusMessage: null, // reveal status to user providers: ["4chan", "reddit"], provider: "4chan", boardID: "g", threadID: null, }, boardList: { // obj for each provider: {4chan: [], reddit: []} didInvalidate: false, favourites: [] // [{id:'4chan', board: 'g'}, ...] }, board: { requestWhenOlderThan: 1200, // in seconds receivedAt: 0, // unix timestamp isFetching: false, didInvalidate: false, filterWord: null, history: {}, posts: [], watch: [], limit: 30 // infinite scroll }, thread: { requestWhenOlderThan: 15, // in seconds receivedAt: 0, // unix timestamp isActive: false, isFetching: false, didInvalidate: false, history: {}, posts: [], }, post: { isAuthenticated: false, type: null, // thread/comment references: [], content: null, // user input upload: null // canReply }, settings: { // TODO: all settings here in a flat structure userStoragePath: "./", customStyleSheet: null, filterKeywords: [] // filter board // boardPostMax: 30 // TODO: Add boardpost limit to state } }
JavaScript
0.000001
@@ -157,22 +157,21 @@ tent%22%0A%09%09 -status +alert Message: @@ -203,17 +203,16 @@ to user%0A -%0A %09%09provid @@ -273,11 +273,12 @@ ID: -%22g%22 +null ,%0A%09%09 @@ -461,53 +461,8 @@ : %7B%0A -%09%09requestWhenOlderThan: 1200, // in seconds%0A %09%09re @@ -538,16 +538,36 @@ false,%0A +%09%09searchWord: null,%0A %09%09filter @@ -566,30 +566,29 @@ %09%09filterWord +s : -null +%5B%5D ,%0A%09%09history: @@ -670,51 +670,8 @@ : %7B%0A -%09%09requestWhenOlderThan: 15, // in seconds%0A %09%09re @@ -794,17 +794,16 @@ ts: %5B%5D,%0A -%0A %09%7D,%0A%0A%09po @@ -887,23 +887,23 @@ : %5B%5D,%0A%09%09 -content +message : null, @@ -1070,26 +1070,28 @@ ,%0A%09%09 -f +boardF ilter -Keyw +W ords: %5B%5D // @@ -1090,26 +1090,64 @@ : %5B%5D - // filter board +,%0A%09%09boardUpdateInterval: 30,%0A%09%09threadUpdateInterval: 15, %0A%09%09/
fe8def6a2602b30c9d4a24cba36a28d1406f08a1
Enable InlineWrappers.
packages/scientist/JATSImporter.js
packages/scientist/JATSImporter.js
'use strict'; var isString = require('lodash/isString'); var isArray = require('lodash/isArray'); var last = require('lodash/last'); var DOMImporter = require('substance/model/DOMImporter'); var XMLImporter = require('substance/model/XMLImporter'); var DefaultDOMElement = require('substance/ui/DefaultDOMElement'); var UnsupportedNodeJATSConverter = require('../unsupported/UnsupportedNodeJATSConverter'); var inBrowser = require('substance/util/inBrowser'); function JATSImporter(config) { JATSImporter.super.call(this, config); this.state = new JATSImporter.State(); } JATSImporter.Prototype = function() { this.importDocument = function(xmlString) { this.reset(); var xmlDoc = DefaultDOMElement.parseXML(xmlString, 'fullDoc'); // HACK: server side impl gives an array var articleEl; if (inBrowser) { articleEl = xmlDoc.find('article'); } else { // HACK: this should be more convenient for (var idx = 0; idx < xmlDoc.length; idx++) { if (xmlDoc[idx].tagName === 'article') { articleEl = xmlDoc[idx]; } } } this.convertDocument(articleEl); var doc = this.generateDocument(); return doc; }; this.convertDocument = function(articleElement) { this.convertElement(articleElement); }; this.convertElements = function(elements, startIdx, endIdx) { if (arguments.length < 2) { startIdx = 0; } if(arguments.length < 3) { endIdx = elements.length; } var nodes = []; for (var i = startIdx; i < endIdx; i++) { nodes.push(this.convertElement(elements[i])); } return nodes; }; this._converterCanBeApplied = function(converter, el) { var currentContext = this.state.getCurrentElementContext(); var allowedContext = converter.allowedContext; var matches = converter.matchElement(el); if (matches && currentContext && allowedContext) { var parentTagName = currentContext.tagName; if (isString(allowedContext)) { return (allowedContext === parentTagName); } else if (isArray(allowedContext)) { return (allowedContext.indexOf(parentTagName) > -1); } } return matches; }; this._convertContainerElement = function(el, startPos) { var state = this.state; var nodes = []; state.pushContainer(nodes); var children = el.getChildren(); startPos = startPos || 0; for (var i = startPos; i < children.length; i++) { state.lastContainer = null; var child = this.convertElement(children[i]); nodes.push(child.id); if (state.lastContainer) { Array.prototype.push.apply(nodes, state.lastContainer); } state.lastContainer = null; } state.popContainer(); return nodes; }; this._getUnsupportedNodeConverter = function() { return UnsupportedNodeJATSConverter; }; }; XMLImporter.extend(JATSImporter); JATSImporter.State = function() { JATSImporter.State.super.call(this); }; JATSImporter.State.Prototype = function() { var _super = JATSImporter.State.super.prototype; this.reset = function() { _super.reset.call(this); // stack for containers (body or sections) this.sectionLevel = 1; this.containers = []; // stack for list types this.lists = []; this.listItemLevel = 1; }; this.getCurrentContainer = function() { return last(this.containers); }; this.pushContainer = function(node) { return this.containers.push(node); }; this.popContainer = function() { this.lastContainer = this.containers.pop(); }; this.getCurrentListItemLevel = function() { return this.listItemLevel; }; this.increaseListItemLevel = function() { return this.listItemLevel++; }; this.decreaseListItemLevel = function() { return this.listItemLevel--; }; this.getCurrentList = function() { return last(this.lists); }; }; DOMImporter.State.extend(JATSImporter.State); module.exports = JATSImporter;
JavaScript
0
@@ -483,24 +483,61 @@ r(config) %7B%0A + config.enableInlineWrapper = true;%0A JATSImport
1e010a992cc5ab5874a2cdcbbf1687bc81146fec
Use Promise instead of callback
src/modules/florins.js
src/modules/florins.js
import assign from 'object-assign' import Promise from 'bluebird' const debug = require('debug')('wololobot:florins') export default function (opts) { opts = assign({ delay: 4000 , gain: 5 // 5 florins per 10 minutes , subGain: 10 // 10 florins per 10 minutes , gainInterval: 10 * 60 * 1000 // 10 minutes , excludeMods: false }, opts) const { db } = opts db.schema.hasTable('transactions', exists => { if (exists) return debug('`transactions` table exists') db.schema.createTable('transactions', t => { t.increments('id').primary() t.string('username', 50).index() t.integer('amount').index() t.timestamp('time').defaultTo(db.raw('CURRENT_TIMESTAMP')) t.text('description') }) .then(() => debug('created table')) .catch(e => { throw e }) }) function florinsOf(user) { debug('florinsOf', user) return db('transactions') .select(db.raw('lower(username) as lname')) .sum('amount as florins') .where('lname', '=', user.toLowerCase()) .then(arr => arr[0]) } function florinsOfMany(users) { let lusers = users.map(u => u.toLowerCase()) // maps lower case names to the original capitalised names let nameMap = users.reduce((map, user, i) => assign(map, { [lusers[i]]: user }), {}) return db('transactions') .select(db.raw('lower(username) as lname')).sum('amount as wallet') .whereIn('lname', lusers) .groupBy('lname') .reduce((o, t) => assign(o, { [nameMap[t.lname] || t.lname]: t.wallet }), {}) // add default 0 florins for unrecorded users .then(o => { users.forEach(u => o[u] || (o[u] = 0)) return o }) } function transaction(username, amount, description = '') { return db('transactions').insert({ username: username.toLowerCase() , amount: amount , description: description }) } function transactions(list) { const inserts = list.map(t => ({ username: t.username.toLowerCase() , amount: t.amount , description: t.description || '' })) return db('transactions').insert(inserts) } return function (bot) { let florinsTimeout = null let florinsChecks = [] function respondFlorins() { florinsOfMany(florinsChecks) .then(o => { return Object.keys(o).map(name => { let extra = [] let bet = bot.bet && bot.bet.entryValue(name) || 0 let raffle = bot.raffle && bot.raffle.entryValue(name) || 0 if (bet) extra.push(`bet:${bet}`) if (raffle) extra.push(`raffle:${raffle}`) // user - 352[bet:20,raffle:70] return `${name} - ${o[name] - bet - raffle}` + (extra.length ? `[${extra.join(' / ')}]` : '') }).join(', ') }) .tap(bot.send.bind(bot)) florinsChecks = [] florinsTimeout = null } function gain() { let users = bot.users() transactions(users.map(u => { let sub = bot.isSubscriber && bot.isSubscriber(u.name) return { username: u.name , amount: sub ? opts.subGain : opts.gain , description: 'florins gain' } })) } setInterval(() => { if (bot.isLive) gain() }, opts.gainInterval) assign(bot, { florinsOf, florinsOfMany, transaction, transactions }) bot.command('!forcegain', { rank: 'mod' }, message => { gain() }) bot.command('!florins', (message, ...usernames) => { if (!usernames.length) { usernames = [ message.user ] } usernames.forEach(username => { if (florinsChecks.indexOf(username) === -1) { florinsChecks.push(username) } }) if (!florinsTimeout) { florinsTimeout = setTimeout(respondFlorins, opts.delay) } }) bot.command('!transaction' , { rank: 'mod' } , (message, username, amount, description = '') => { const mname = message.user if (!/^-?\d+$/.test(amount)) { bot.send(`@${mname}, "${amount}" doesn't look like an integer`) } else { amount = parseInt(amount, 10) transaction(username, amount, description) .then(() => bot.send(amount < 0? `@${mname} Removed ${-amount} florins from ${username}.` : /* _ */ `@${mname} Gave ${amount} florins to ${username}.`)) .catch(e => bot.send(`@${mname} ${e.message}`)) } }) const topCommand = opts => (message, n = 3) => { if (n > 15) n = 15 let q = db('transactions') .select('username', db.raw('lower(username) as lname')) .sum('amount as wallet') if (opts.excludeMods && bot.moderators) { q = q.whereNotIn('lname', [ bot.channel.slice(1), ...bot.moderators ] .map(name => name.toLowerCase())) } q .groupBy('lname') .orderBy('wallet', 'desc') .limit(n) .reduce((list, u, i) => list.concat([ `#${i + 1}) ${u.username} - ${u.wallet}` ]), []) .then(list => bot.send(`@${message.user} Top florins: ` + list.join(', '))) } bot.command('!top', topCommand({ excludeMods: opts.excludeMods })) bot.command('!topwithmods', topCommand({ excludeMods: false })) } }
JavaScript
0
@@ -405,18 +405,23 @@ actions' -, +).then( exists =
0f2718149b4394665b6ecaf9dc0c717936e8a0fd
Add asset thumbnail to Assets table
app/views/Assets/index.js
app/views/Assets/index.js
import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; import { formatDate, formatBytes } from '../../utils/helpers'; import DeleteIcon from '../../components/DeleteIcon'; import Page from '../../containers/Page'; import Table from '../../components/Table'; import Button from '../../components/Button'; import TitleBar from '../../components/TitleBar'; import { deleteAsset, indexAssets } from '../../actions/assetActions'; export default class Assets extends Component { static propTypes = { assets: PropTypes.object, dispatch: PropTypes.func, } static defaultProps = { assets: null, dispatch: null, } indexAssets() { this.props.dispatch(indexAssets()); } render() { const { assets, dispatch } = this.props; const reduced = assets.assets.map(props => ({ key: props._id, title: { value: props.title, component: <a href={`/public/assets/${props.filename}`} rel="noopener noreferrer" target="_blank">{props.title}</a>, }, filename: props.filename, size: formatBytes(props.size, 0), dateCreated: { value: new Date(props.dateCreated).getTime(), component: formatDate(props.dateCreated), }, delete: { sortBy: false, component: <DeleteIcon dispatch={dispatch} onClick={() => dispatch(deleteAsset(props._id))} message="Are you sure you want to delete this asset?" />, }, })); return ( <Page name="assets"> <TitleBar title="Assets"> <Button onClick={() => this.indexAssets()} small>Index Asset</Button> <Link to="/admin/settings/assets/new" className="btn btn--small">New Asset</Link> </TitleBar> <div className="content"> <div className="page__inner"> {reduced.length > 0 ? <Table data={reduced} /> : <h3>No assets!</h3>} </div> </div> </Page> ); } }
JavaScript
0
@@ -853,16 +853,244 @@ ps._id,%0A + image: %7B%0A sortBy: false,%0A component: %3Ca href=%7B%60/public/assets/$%7Bprops.filename%7D%60%7D rel=%22noopener noreferrer%22 target=%22_blank%22%3E%3Cimg src=%7B%60/public/assets/$%7Bprops.filename%7D%60%7D alt=%7Bprops.filename%7D /%3E%3C/a%3E,%0A %7D,%0A ti
d3834bb200c9f1b1c6ae64e370985029e83cc7e6
Fix broken modal close
app/assets/javascripts/modal.js
app/assets/javascripts/modal.js
$('#overlay, .modal-close, .navigation-overlay').click(function() { $('#overlay, #modal').fadeOut('fast'); }); $('.navigation-modal-open').click(function() { $('.navigation-overlay, .navigation-modal').fadeTo('slow', 1) });
JavaScript
0.00005
@@ -78,24 +78,64 @@ rlay, #modal +, .navigation-overlay, .navigation-modal ').fadeOut(' @@ -233,24 +233,39 @@ gation-modal +, i.icon-remove ').fadeTo('s
18262016f553ef53c91495d91dbe645d90a423ff
Fix for repeating years under premium calculator
app/assets/javascripts/plans.js
app/assets/javascripts/plans.js
$(document).ready(function() { $('#plan-years').prop('disabled', true); $('#plans').prop('disabled', true); $('#carriers').change(function(e) { $('#plans').prop('disabled', true); $('#plan-years').prop('disabled', false); var id = $('#carriers').val(); $.getJSON('/carriers/'+ id +'/plan_years', function(data) { $.each(data, function(key, value) { $('#plan-years').append($('<option/>').attr("value", value).text(value)); }); get_carrier_plans(); $("#plan-years").select2({dropdownCssClass: 'show-select-search'}); }); }) $('#plan-years').change(function(e) { get_carrier_plans(); }); var get_carrier_plans = function() { var carrier_id = $('#carriers').val(); var year = $('#plan-years').val(); $('#plans').prop('disabled', false); $( "option[value|='']" ).remove(); $(".btn[value='Calculate']").attr('class','btn btn-primary'); $.getJSON('/carriers/'+ carrier_id +'/show_plans',{plan_year: year}, function(data) { $('#plans').empty(); $.each(data, function(key, value) { $('#plans').append($('<option/>').attr("value", value._id).text(value.name).append(" : " + value.hios_plan_id)); }); if($('#plans').is(':empty')) { $('#plans').prop('disabled', true); } $("#plans").select2({dropdownCssClass: 'show-select-search'}); }); }; $('#plans').change(function() { $(".btn[value='Calculate']").attr('class','btn btn-primary'); }); $('.date_picker').change(function() { $(".btn[value='Calculate']").attr('class','btn btn-primary'); }); $('.btn[value="Calculate"]').click(function() { $(this).attr('class','btn btn-default'); }); });
JavaScript
0
@@ -230,24 +230,79 @@ d', false);%0A + $('#plans').empty();%0A $('#plan-years').empty();%0A var id =
0b21266af15b88090e192d8bf1d66c3809bef690
change bullshit index
app/components/VotingButtons.js
app/components/VotingButtons.js
import React, { PropTypes, Component } from 'react'; import { connect } from 'react-redux'; import Button from 'muicss/lib/react/button'; import Container from 'muicss/lib/react/container'; import Dropdown from 'muicss/lib/react/dropdown'; import DropdownItem from 'muicss/lib/react/dropdown-item'; import { getGoogleToken } from '../actions/user'; import { compose, withHandlers, } from 'recompose'; const VotingButton = ({ color, text, onClick }) => (<div> <Button color={color} onClick={onClick} > {text} </Button> </div>); VotingButton.propTypes = { color: PropTypes.string.isRequired, text: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired, }; const enhance = compose( withHandlers({ onClickCreator: props => decision => () => props.onClick(decision) }) ); class VotingButtons extends Component { static propTypes = { userId: PropTypes.string, authToken: PropTypes.string, getGoogleToken: PropTypes.func.isRequired, } votingButtons = () => ( <div> <Container fluid> <Dropdown color="primary" label="Rate this article" alignMenu="left"> <DropdownItem> <VotingButton color="danger" text="Bullshit" onClick={this.props.onClickCreator(0)} /> </DropdownItem> <DropdownItem> <VotingButton color="primary" text="Neutral" onClick={this.props.onClickCreator(0.5)} /> </DropdownItem> <DropdownItem> <VotingButton color="accent" text="Legit" onClick={this.props.onClickCreator(1)} /> </DropdownItem> </Dropdown> </Container> </div>); loginButton = () => ( <div> <Container fluid> <Button color="primary" onClick={() => this.props.getGoogleToken()} > Login to change the world </Button> </Container> </div> ); render() { const { userId, authToken } = this.props; return (userId && authToken) ? this.votingButtons() : this.loginButton(); } } VotingButtons.propTypes = { onClickCreator: PropTypes.func.isRequired, }; const structuredSelector = state => ({ userId: state.user.id, authToken: state.user.authentication_token, }); export default connect(structuredSelector, { getGoogleToken, })(enhance(VotingButtons));
JavaScript
0.000001
@@ -1296,17 +1296,17 @@ Creator( -0 +1 )%7D%0A @@ -1695,33 +1695,33 @@ .onClickCreator( -1 +0 )%7D%0A /
24eddfc7954f24b78b665b33beac55d420c23ccd
fix slider layout in form
app/components/gui/iftttForm.js
app/components/gui/iftttForm.js
"use strict"; var React = require('react'); var Col = require('react-bootstrap').Col; var Row = require('react-bootstrap').Row; var Modal = require('react-bootstrap').Modal; var Input = require('react-bootstrap').Input; var Button = require('react-bootstrap').Button; var LinkedStateMixin = require('react-addons-linked-state-mixin'); var Switch = require('react-bootstrap-switch'); var Blink1SerialOption = require('./blink1SerialOption'); var IftttForm = React.createClass({ mixins: [LinkedStateMixin], propTypes: { rule: React.PropTypes.object.isRequired, allowMultiBlink1: React.PropTypes.bool, patterns: React.PropTypes.array, onSave: React.PropTypes.func, onCancel: React.PropTypes.func, onDelete: React.PropTypes.func, onCopy: React.PropTypes.func }, getInitialState: function() { return { // name: rule.name, // patternId: rule.patternId }; }, // FIXME: why am I doing this? componentWillReceiveProps: function(nextProps) { var rule = nextProps.rule; this.setState({ type: 'ifttt', enabled: rule.enabled, name: rule.name, actionType: 'play-pattern', patternId: rule.patternId || nextProps.patterns[0].id, blink1Id: rule.blink1Id || "0" }); // FIXME: why }, handleClose: function() { this.props.onSave(this.state); }, handleBlink1SerialChange: function(blink1Id) { this.setState({blink1Id: blink1Id}); }, render: function() { var self = this; var createPatternOption = function(item, idx) { return ( <option key={idx} value={item.id}>{item.name}</option> ); }; return ( <div> <Modal show={this.props.show} onHide={this.close} > <Modal.Header> <Modal.Title>IFTTT Settings</Modal.Title> </Modal.Header> <Modal.Body> <p style={{color: "#f00"}}>{this.state.errormsg}</p> <form className="form-horizontal" > <Input labelClassName="col-xs-3" wrapperClassName="col-xs-8" type="text" label="Rule Name" placeholder="Name of rule on IFTTT" valueLink={this.linkState('name')} /> <Input labelClassName="col-xs-3" wrapperClassName="col-xs-5" type="select" label="Pattern" valueLink={this.linkState('patternId')} > {this.props.patterns.map( createPatternOption, this )} </Input> {!this.props.allowMultiBlink1 ? null : <Blink1SerialOption label="blink(1) to use" defaultText="-use default-" labelClassName="col-xs-3" wrapperClassName="col-xs-4" serial={this.state.blink1Id} onChange={this.handleBlink1SerialChange}/>} </form> </Modal.Body> <Modal.Footer> <Row> <Col xs={5}> <Button bsSize="small" bsStyle="danger" onClick={this.props.onDelete} style={{float:'left'}}>Delete</Button> <Button bsSize="small" onClick={this.props.onCopy} style={{float:'left'}}>Copy</Button> </Col> <Col xs={3}> <Switch labelText="Enable" size="small" state={this.state.enabled} onChange={function(s){self.setState({enabled:s});}} /> </Col> <Col xs={4}> <Button bsSize="small" onClick={this.props.onCancel}>Cancel</Button> <Button bsSize="small" onClick={this.handleClose}>OK</Button> </Col> </Row> </Modal.Footer> </Modal> </div> ); } }); module.exports = IftttForm;
JavaScript
0
@@ -3678,16 +3678,31 @@ %3CSwitch + bsSize=%22small%22 labelTe @@ -3716,21 +3716,8 @@ ble%22 - size=%22small%22 %0A
72f1271c33ef8a6a21e0b1fa99ae0b419cdecc9d
Remove particle debug logging.
src/graphics/particles.js
src/graphics/particles.js
var Particles = { emit: function (usrConfig) { var config = { srcX: 0, srcY: 0, minAmount: 10, maxAmount: 20, color: '#ff0000', lifetime: 60, minSize: 2, maxSize: 5 }; for (var prop in usrConfig) { config[prop] = usrConfig[prop]; } var amount = chance.integer({ min: config.minAmount, max: config.maxAmount }); for (var i = 0; i < amount; i++) { var size = chance.integer({ min: config.minSize, max: config.maxSize }); var particle = new Particle(config.color, size); particle.posX = config.srcX; particle.posY = config.srcY; World.add(particle); console.log('add particle', particle); } } }; var Particle = Entity.extend({ color: '#00ff00', size: 0, init: function (color, size) { this.velocityX = chance.floating({min: -10, max: 10}); this.velocityY = chance.floating({min: -10, max: 10}); this.alpha = 1.0; this.color = color; this.size = size; }, getWidth: function () { return this.size; }, getHeight: function () { return this.size; }, update: function () { this.velocityX *= 0.9; this.velocityY += World.gravity * 2; this.posX += this.velocityX; this.posY += this.velocityY; if (this.velocityY >= Canvas.canvas.height + this.size) { World.remove(this); return; } }, draw: function (ctx) { ctx.beginPath(); ctx.rect(this.posX, this.posY, this.size, this.size); ctx.fillStyle = this.color; ctx.fill(); ctx.closePath(); } });
JavaScript
0
@@ -843,60 +843,8 @@ le); -%0A%0A console.log('add particle', particle); %0A