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
7b767bea3a6cfef220abd94d995c22addcb52653
remove _courseData when displaying <SemesterDetail/>
src/screens/semester-detail.js
src/screens/semester-detail.js
import React, {PropTypes} from 'react' import cx from 'classnames' import {State} from 'react-router' import Immutable from 'immutable' import {isCurrentSemester} from 'sto-helpers' import Student from '../models/student' let SemesterDetail = React.createClass({ propTypes: { className: PropTypes.string, student: PropTypes.instanceOf(Student).isRequired, }, mixins: [State], getInitialState() { return { year: null, semester: null, schedules: Immutable.List(), } }, render() { // console.log('SemesterDetail#render') const {year, semester} = this.getParams() const schedules = this.props.student.schedules .filter(isCurrentSemester(year, semester)) .toJS() return ( <div className={cx('semester-detail', this.props.className)}> <pre> {this.getPath()}{'\n'} {JSON.stringify(schedules, null, 2)} </pre> </div> ) }, }) export default SemesterDetail
JavaScript
0
@@ -680,16 +680,94 @@ ester))%0A +%09%09%09.map(sched =%3E sched.toMap())%0A%09%09%09.map(sched =%3E sched.delete('_courseData'))%0A %09%09%09.toJS
2ab23d51e34f3792f3fa2a22c843c477c607390f
improve code
src/search/search-bar/scope.js
src/search/search-bar/scope.js
// Dependencies const React = require('react'); const ReactDOM = require('react-dom'); const builder = require('focus-core').component.builder; const type = require('focus-core').component.types; const uuid = require('uuid'); const find = require('lodash/collection/find'); const {uniqueId} = require('lodash/utility'); // Components const Icon = require('../../common/icon').component; const Dropdown = require('../../common/select-action').component; const {componentHandler} = window; // Mixins const i18nMixin = require('../../common/i18n/mixin'); const scopeMixin = { /** * Component tag name. * @type {String} */ displayName: 'Scope', mixins: [i18nMixin], /** * Component default properties. * @return {Object} the default props. */ getDefaultProps() { return { list: [] }; }, /** * Scope property validation. * @type {Object} */ propTypes: { list: type('array'), value: type(['string', 'number']) }, /** * Called when component will mount. */ componentWillMount() { this.scopesId = uniqueId('scopes_'); }, /** * Called when component is mounted. */ componentDidMount() { if (ReactDOM.findDOMNode(this.refs.scopeDropdown)) { componentHandler.upgradeElement(ReactDOM.findDOMNode(this.refs.scopeDropdown)); } }, /** * Component will receive props. * @param {Object} nextProps the next props */ componentWillReceiveProps(nextProps) { if (ReactDOM.findDOMNode(this.refs.scopeDropdown)) { componentHandler.upgradeElement(ReactDOM.findDOMNode(this.refs.scopeDropdown)); } }, /** * Called before component is unmounted. */ componentWillUnmount() { if (ReactDOM.findDOMNode(this.refs.scopeDropdown)) { componentHandler.downgradeElements(ReactDOM.findDOMNode(this.refs.scopeDropdown)); } }, /** * Get the scope click handler, based on the scope given as an argument. * @param {String} code the clicked scope's code * @return {Function} the scope click handler */ _getScopeClickHandler({code}) { const {onScopeSelection} = this.props; return () => { if (onScopeSelection) { onScopeSelection(code); } }; }, _getActiveScope() { const {list, value} = this.props; const activeScope = find(list, {code: value}); return activeScope || {}; }, /** * Render the scope list if it is deployed * @return {HTML} the rendered scope list */ _renderScopeList() { const {scopesId} = this; const {list: scopeList, value} = this.props; return ( <ul className={`mdl-menu mdl-menu--bottom-left mdl-js-menu mdl-js-ripple-effect`} data-focus='search-bar-scopes' htmlFor={scopesId} ref='scopeDropdown'> {0 < scopeList.length && scopeList.map(scope => { const {code, label, ...otherScopeProps} = scope; const icon = scope.icon ? scope.icon : code; //legacy const scopeId = uniqueId('scopes_'); const isActive = value === code; return ( <li className='mdl-menu__item' data-active={isActive} key={scope.code || scopeId} data-scope={scope.code || scopeId} onClick={this._getScopeClickHandler(scope)}> {scope.code && <Icon name={icon} {...otherScopeProps}/> } <span>{this.i18n(label)}</span> </li> ); })} {0 === scopeList.length && <li className='mdl-menu__item'> {this.i18n('scopes.empty')} </li> } </ul> ); }, /** * Render the complete scope element. * @return {object} - The jsx element. */ render() { const {scopesId} = this; const activeScope = this._getActiveScope(); const {code, label, ...otherScopeProps} = activeScope; const icon = activeScope.icon ? activeScope.icon : code; //legacy return ( <div data-focus='search-bar-scope'> <button className='mdl-button mdl-js-button' id={scopesId} data-scope={code}> <Icon name={icon} {...otherScopeProps}/> <span>{this.i18n(label)}</span> </button> {this._renderScopeList()} </div> ); } }; module.exports = builder(scopeMixin);
JavaScript
0.000689
@@ -3038,32 +3038,38 @@ const %7Bcode, + icon, label, ...other @@ -3093,82 +3093,8 @@ pe;%0A - const icon = scope.icon ? scope.icon : code; //legacy%0A @@ -3497,32 +3497,40 @@ %3CIcon name=%7Bicon + %7C%7C code %7D %7B...otherScope @@ -4146,16 +4146,22 @@ t %7Bcode, + icon, label, @@ -4199,82 +4199,8 @@ pe;%0A - const icon = activeScope.icon ? activeScope.icon : code; //legacy%0A @@ -4354,16 +4354,16 @@ %7Bcode%7D%3E%0A - @@ -4390,16 +4390,24 @@ me=%7Bicon + %7C%7C code %7D %7B...ot
2956f8f7ea53cd1b6d0c86b6108dde07798fdf78
Update Unit.js
src/foam/core/Unit.js
src/foam/core/Unit.js
/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.core', name: 'Unit', documentation: `The abstract model for fungible digitized assets`, ids: [ 'alphabeticCode' ], javaImports: [ 'foam.util.SafetyUtil' ], properties: [ { class: 'String', name: 'name', documentation: 'Name of the asset.', required: true }, { class: 'String', name: 'alphabeticCode', label: 'Code', documentation: 'The alphabetic code associated with the asset. Used as an ID.', required: true, aliases: [ 'id' ] }, { class: 'Int', name: 'precision', documentation: 'Defines the number of digits that come after the decimal point. ', required: true } ] });
JavaScript
0.000001
@@ -282,58 +282,8 @@ %5D,%0A%0A - javaImports: %5B%0A 'foam.util.SafetyUtil'%0A %5D,%0A%0A pr
8453b61cfd398fe53387439056315304bc22ea4f
Fix for integration test Gremlin Server connection.
gremlin-javascript/src/main/javascript/gremlin-javascript/test/helper.js
gremlin-javascript/src/main/javascript/gremlin-javascript/test/helper.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author Jorge Bay Gondra */ 'use strict'; const os = require('os'); const DriverRemoteConnection = require('../lib/driver/driver-remote-connection'); const SaslAuthenticator = require('../lib/driver/sasl-authenticator'); const SaslMechanismPlain = require('../lib/driver/auth/mechanisms/sasl-mechanism-plain'); exports.getConnection = function getConnection(traversalSource) { return new DriverRemoteConnection('ws://localhost:45940/gremlin', { traversalSource: traversalSource }); }; exports.getSecureConnectionWithAuthenticator = function getConnection(traversalSource) { const authenticator = new SaslAuthenticator({ mechanism: new SaslMechanismPlain(), username: 'stephen', password: 'password', authId: os.hostname() }); return new DriverRemoteConnection('wss://localhost:45941/gremlin', { traversalSource: traversalSource, authenticator: authenticator, rejectUnauthorized: false }); };
JavaScript
0
@@ -1594,17 +1594,16 @@ tion('ws -s ://local
d3af031a502a765cfd9dcd4657a6746e3157329a
rewrite queen lesson
ui/learn/src/lesson/queen.js
ui/learn/src/lesson/queen.js
var util = require('../util'); var arrow = util.arrow; module.exports = { title: 'The queen', subtitle: 'Queen = rook + bishop.', image: util.assetUrl + 'images/learn/pieces/Q.svg', stages: [{ goal: 'Use the queen like a rook!', fen: '8/8/8/8/8/8/8/3Q4 w - - 0 1', items: { d8: 'apple', h8: 'flower' }, nbMoves: 1, shapes: [arrow('d1d8'), arrow('d8h8')] }, { goal: 'Use the queen like a bishop!', fen: '8/8/8/8/8/8/8/3Q4 w - - 0 1', items: { h5: 'apple', e8: 'flower' }, nbMoves: 1, shapes: [arrow('d1h5'), arrow('h5e8')] }, { goal: 'Grab the stars,<br>then go to the castle!', fen: '8/8/8/8/8/2Q5/8/8 w - - 0 1', items: { b2: 'apple', b7: 'apple', e7: 'apple', b7: 'apple', g5: 'apple', g8: 'apple', h8: 'apple', g2: 'flower' }, nbMoves: 7 }, { goal: 'The queen is the strong!', fen: '8/8/8/8/8/8/8/7Q w - - 0 1', items: { a3: 'apple', b2: 'apple', b3: 'apple', b7: 'apple', c3: 'apple', c6: 'apple', c7: 'apple', d7: 'apple', e5: 'apple', f4: 'apple', f5: 'apple', g5: 'apple', f8: 'flower' }, nbMoves: 13 }, { goal: 'Grab the stars,<br>then go to the castle!', fen: '8/8/8/8/8/8/8/Q7 w - - 0 1', items: { a5: 'apple', b3: 'apple', c1: 'apple', d7: 'apple', e2: 'apple', f8: 'apple', g6: 'apple', h4: 'apple', h8: 'flower' }, nbMoves: 16 }].map(util.toStage), complete: 'Congratulations! Queens have no secrets for you.' };
JavaScript
0.000001
@@ -210,33 +210,26 @@ l: ' -Use the queen like a rook +Grab all the stars !',%0A @@ -242,37 +242,37 @@ n: '8/8/8/8/8/8/ -8/3Q4 +4Q3/8 w - - 0 1',%0A @@ -276,60 +276,23 @@ -items: %7B%0A d8: 'apple',%0A h8: 'flower'%0A %7D +apples: 'e5 b8' ,%0A @@ -294,33 +294,33 @@ ',%0A nbMoves: -1 +2 ,%0A shapes: %5Ba @@ -329,12 +329,12 @@ ow(' -d1d8 +e2e5 '), @@ -344,11 +344,11 @@ ow(' -d8h +e5b 8')%5D @@ -370,35 +370,26 @@ l: ' -Use the queen like a bishop +Grab all the stars !',%0A @@ -410,17 +410,17 @@ 8/8/ -8 +3Q4 /8/8/ -3Q4 +8 w - @@ -436,120 +436,45 @@ -items: %7B%0A h5: 'apple',%0A e8: 'flower'%0A %7D,%0A nbMoves: 1,%0A shapes: %5Barrow('d1h5'), arrow('h5e8')%5D +apples: 'a3 f2 f8 h3',%0A nbMoves: 4 %0A %7D @@ -485,32 +485,36 @@ goal: 'Grab +all the stars,%3Cbr%3Eth @@ -510,34 +510,8 @@ tars -,%3Cbr%3Ethen go to the castle !',%0A @@ -532,17 +532,17 @@ 8/8/ -8/ 2Q5/8/8 +/8 w - @@ -558,174 +558,35 @@ -items: %7B%0A b2: 'apple',%0A b7: 'apple',%0A e7: 'apple',%0A b7: 'apple',%0A g5: 'apple',%0A g8: 'apple',%0A h8: 'apple',%0A g2: 'flower'%0A %7D +apples: 'a3 d6 f1 f8 g3 h6' ,%0A @@ -596,17 +596,17 @@ bMoves: -7 +6 %0A %7D, %7B%0A @@ -620,31 +620,26 @@ l: ' -The queen is +Grab all the st -rong +ars !',%0A @@ -642,32 +642,36 @@ !',%0A fen: '8/ +6q1/ 8/8/8/8/8/8/7Q w @@ -669,13 +669,10 @@ /8/8 -/7Q w + b - - @@ -686,269 +686,38 @@ -items: %7B%0A a3: 'apple',%0A b2: 'apple',%0A b3: 'apple',%0A b7: 'apple',%0A c3: 'apple',%0A c6: 'apple',%0A c7: 'apple',%0A d7: 'apple',%0A e5: 'apple',%0A f4: 'apple',%0A f5: 'apple',%0A g5: 'apple',%0A f8: 'flower'%0A %7D +apples: 'a2 b5 d3 g1 g8 h2 h5' ,%0A @@ -731,10 +731,9 @@ es: -13 +7 %0A %7D @@ -751,48 +751,31 @@ l: ' -Grab the stars,%3Cbr%3Ethen go to the castle +The queen is the strong !',%0A @@ -802,12 +802,13 @@ 8/8/ -Q7 w +4q3 b - - @@ -822,193 +822,41 @@ -items: %7B%0A a5: 'apple',%0A b3: 'apple',%0A c1: 'apple',%0A d7: 'apple',%0A e2: 'apple',%0A f8: 'apple',%0A g6: 'apple',%0A h4: 'apple',%0A h8: 'flower'%0A %7D +apples: 'a6 d1 f2 f6 g6 g8 h1 h4' ,%0A @@ -870,10 +870,9 @@ es: -16 +9 %0A %7D
4b91100c683e7af93b6d457634e439521dd25ec8
add configurations for AST_Toplevel
upgrade/lib/util/analyzer.js
upgrade/lib/util/analyzer.js
var neuron = require('../../../lib/neuron'), UglifyJS = require('uglify-js'), RELATED_PROP = { 'AST_Function' : ['name', 'argnames', 'body'], 'AST_SymbolFunarg' : ['name'], 'AST_Dot' : ['expression', 'property'], 'AST_Call' : ['args', 'expression', 'body'], 'AST_Defun' : ['argnames', 'name', 'body'], 'AST_Var' : ['definitions'], 'AST_VarDef' : ['name', 'value'], //, 'AST_Return' : ['value'], 'AST_Assign' : ['left', 'operator', 'right'] // 'AST_SymbolVar' : ['name'] }; var fn_arg_def, ref_def; function write(msg, stack){ // process.stdout.write(msg); stack.push(msg); }; function walk(ast, stack, space, extra, is_final){ space = space || ''; write(space, stack); write(extra ? extra + ': ' : '', stack); if(neuron.isString(ast)){ write('string ' + ast + '\r\n', stack); return; } var constructor = ast.CTOR, type = constructor.name; write(type + ' ', stack); write('\r\n', stack); var props = RELATED_PROP[type] || ['body', 'name']; props.forEach(function(prop){ var sub = ast[prop]; if(neuron.isArray(sub) && sub.length === 0){ write(space + ' ', stack); write(prop + ': ' + type + ' []', stack); write('\r\n', stack); }else{ neuron.makeArray(ast[prop]).forEach(function(node){ walk(node, stack, space + ' ', prop); }); } }); }; module.exports = function(ast){ var stack = []; walk(ast, stack); return stack.join(''); };
JavaScript
0
@@ -91,16 +91,52 @@ ROP = %7B%0A + 'AST_Toplevel' : %5B'body'%5D,%0A 'AST
d3b90c66aa2b2aa12265759e05142d46d98703e8
Rename `BaseStore` into `Store` in `Offline` namespace
addon/index.js
addon/index.js
/** * Addon that extends ember-data with ember-flexberry-projections to support work in offline mode. * * @module ember-flexberry-offline * @main ember-flexberry-offline */ import Model from './models/model'; import OfflineModel from './mixins/offline-model'; import BaseStore from './stores/base-store'; /** * This namespace contains classes and methods to support work in offline mode. * * @class Offline * @static * @public */ let Offline = { BaseStore: BaseStore, Model: Model, OfflineModel: OfflineModel }; export default Offline;
JavaScript
0.000004
@@ -454,20 +454,16 @@ e = %7B%0A -Base Store: B
8e0ec68d3bee238f1e4af145c25c8f7803124a19
Clean up index.js to rely on `Ember.getOwner` polyfill.
addon/index.js
addon/index.js
import Ember from 'ember'; import FakeOwner from './fake-owner'; let hasGetOwner = !!Ember.getOwner; Ember.deprecate("ember-getowner-polyfill is now a true polyfill. Use Ember.getOwner directly instead of importing from ember-getowner-polyfill", false, { id: "ember-getowner-polyfill.import" }); export default function(object) { let owner; if (hasGetOwner) { owner = Ember.getOwner(object); } if (!owner && object.container) { owner = new FakeOwner(object); } return owner; }
JavaScript
0
@@ -23,83 +23,8 @@ er'; -%0Aimport FakeOwner from './fake-owner';%0A%0Alet hasGetOwner = !!Ember.getOwner; %0A%0AEm @@ -238,193 +238,20 @@ ult -function(object) %7B%0A let owner;%0A%0A if (hasGetOwner) %7B%0A owner = Ember.getOwner(object);%0A %7D%0A%0A if (!owner && object.container) %7B%0A owner = new FakeOwner(object);%0A %7D%0A%0A return owner;%0A%7D +Ember.getOwner; %0A
4f5557e2e96ac9d0caac3d0f9c0b263b679c6671
Update production.js
config/env/production.js
config/env/production.js
'use strict'; module.exports = { db: 'mongodb://naveen:naveen@kahana.mongohq.com:10077/testmeanapp', app: { name: 'Naveen Gogineni'+'+ 's Modern Stack Website' }, facebook: { clientID: '1452371921688100', clientSecret: '4fe108e43136768857c03aafcae1b433', callbackURL: 'http://navinmeanapp.herokuapp.com/auth/facebook/callback' }, twitter: { clientID: 'CONSUMER_KEY', clientSecret: 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, github: { clientID: 'APP_ID', clientSecret: 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/github/callback' }, google: { clientID: '938514532632-5gjceoo8is66j67rd8kb01im3v7rcnia.apps.googleusercontent.com', clientSecret: '8ZfDd8Yba-EITasxsEXSjwpZ', callbackURL: 'http://navinmeanapp.herokuapp.com/auth/google/callback' }, linkedin: { clientID: 'API_KEY', clientSecret: 'SECRET_KEY', callbackURL: 'http://localhost:3000/auth/linkedin/callback' }, emailFrom : 'navinhai83@gmail.com', // sender address like ABC <abc@example.com> mailer: { service: 'https://mail.google.com', auth: { user: 'navinhai83@gmail.com', pass: 'nav!n123' } } };
JavaScript
0.000001
@@ -144,14 +144,8 @@ neni -'+'+ ' s Mo
d1e727e1262b512ed32f7e8bf2a6c7240eda49e7
Update production scraper config
config/env/production.js
config/env/production.js
/** * Production environment settings * * This file can include shared settings for a production environment, * such as API keys or remote database passwords. If you're using * a version control solution for your Sails app, this file will * be committed to your repository unless you add it to your .gitignore * file. If your repository will be publicly viewable, don't add * any private information to this file! * */ module.exports = { grunt: { _hookTimeout: 100000 }, application_auth: { enableLocalAuth: true, // Get your keys from https://developers.facebook.com/apps/ enableFacebookAuth: true, facebookClientID: '1267766483237355', facebookClientSecret: 'a2f5e3a27b74a64bc0d1ecc2d3a9ec31', facebookCallbackURL: 'https://mastersigma-jaggerfly.rhcloud.com/auth/facebook/callback', facebookAppURL: 'https://apps.facebook.com/master-sigma/' }, /*************************************************************************** * Set the default database connection for models in the production * * environment (see config/connections.js and config/models.js ) * ***************************************************************************/ connections: { // Heroku Deploy // sigmaDv: { // adapter: 'sails-mysql', // host: 'us-cdbr-iron-east-03.cleardb.net', // user: 'bad812654b4b13', // password: 'eed57ee2', // database: 'heroku_1014650bcf2946e' // }, sigmaPrd: { adapter: 'sails-mysql', host: process.env.OPENSHIFT_MYSQL_DB_HOST , port: process.env.OPENSHIFT_MYSQL_DB_PORT, // Openshift Deploy user: 'admin2gbmiNI', password:'lJPfcp7n6ViH' , database: 'mastersigma' } }, models: { schema: true, connection: 'sigmaPrd', migrate: 'safe' }, session: { adapter: 'redis', host: process.env.REDISCLOUD_URL || 'pub-redis-12873.us-east-1-1.2.ec2.garantiadata.com', port: process.env.REDISCLOUD_PORT || 12873, ttl: 1200, pass: process.env.REDISCLOUD_PASSWORD || 'mastersigma92' }, /*************************************************************************** * Set the port in the production environment to 80 * ***************************************************************************/ host: process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1', port: process.env.OPENSHIFT_NODEJS_PORT || 8080, // port: process.env.PORT || 1337, environment: process.env.NODE_ENV || 'development', scraper : { url: 'https://'+ process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1' +':'+3100 }, /*************************************************************************** * Set the log level in production environment to 'silent' * ***************************************************************************/ log: { level: 'verbose' } };
JavaScript
0
@@ -2556,17 +2556,16 @@ l: 'http -s ://'+ pr
56307511a3f960bf4bedf9e8868ad70d5e918358
Use `Ember.ComputedProperty` instead of private modules. (#90)
addon/utils.js
addon/utils.js
import Ember from 'ember'; export function isGeneratorIterator(iter) { return (iter && typeof iter.next === 'function' && typeof iter['return'] === 'function' && typeof iter['throw'] === 'function'); } export function Arguments(args, defer) { this.args = args; this.defer = defer; } Arguments.prototype.resolve = function(value) { if (this.defer) { this.defer.resolve(value); } }; export let objectAssign = Object.assign || function objectAssign(target) { 'use strict'; if (target == null) { throw new TypeError('Cannot convert undefined or null to object'); } target = Object(target); for (var index = 1; index < arguments.length; index++) { var source = arguments[index]; if (source != null) { for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } } return target; }; export function createObservable(fn) { return { subscribe(onNext, onError, onCompleted) { let isDisposed = false; let isComplete = false; let publish = (v) => { if (isDisposed || isComplete) { return; } joinAndSchedule(null, onNext, v); }; publish.error = (e) => { if (isDisposed || isComplete) { return; } joinAndSchedule(() => { if (onError) { onError(e); } if (onCompleted) { onCompleted(); } }); }; publish.complete = () => { if (isDisposed || isComplete) { return; } isComplete = true; joinAndSchedule(() => { if (onCompleted) { onCompleted(); } }); }; // TODO: publish.complete? let maybeDisposer = fn(publish); let disposer = typeof maybeDisposer === 'function' ? maybeDisposer : Ember.K; return { dispose() { if (isDisposed) { return; } isDisposed = true; disposer(); }, }; }, }; } function joinAndSchedule(...args) { Ember.run.join(() => { Ember.run.schedule('actions', ...args); }); } export function _cleanupOnDestroy(owner, object, cleanupMethodName) { // TODO: find a non-mutate-y, hacky way of doing this. if (!owner.willDestroy) { // we're running in non Ember object (possibly in a test mock) return; } if (!owner.willDestroy.__ember_processes_destroyers__) { let oldWillDestroy = owner.willDestroy; let disposers = []; owner.willDestroy = function() { for (let i = 0, l = disposers.length; i < l; i ++) { disposers[i](); } oldWillDestroy.apply(owner, arguments); }; owner.willDestroy.__ember_processes_destroyers__ = disposers; } owner.willDestroy.__ember_processes_destroyers__.push(() => { object[cleanupMethodName](); }); } export let INVOKE = "__invoke_symbol__"; let locations = [ 'ember-glimmer/helpers/action', 'ember-routing-htmlbars/keywords/closure-action', 'ember-routing/keywords/closure-action' ]; for (let i = 0; i < locations.length; i++) { if (locations[i] in Ember.__loader.registry) { INVOKE = Ember.__loader.require(locations[i])['INVOKE']; break; } } // TODO: Symbol polyfill? export const yieldableSymbol = "__ec_yieldable__"; export const _ComputedProperty = Ember.__loader.require("ember-metal/computed").ComputedProperty;
JavaScript
0
@@ -3310,49 +3310,8 @@ ber. -__loader.require(%22ember-metal/computed%22). Comp
8266c6e11661fc9b4e53bdcbf60cacf6062d0e5b
add vk oauth test
config/env/production.js
config/env/production.js
'use strict'; module.exports = { db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/freelook', assets: { lib: { css: [], js: [ '//vk.com/js/api/openapi.js?115' ] }, css: ['app/dist/freelook.min.css'], js: ['app/dist/freelook.min.js'] }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } }, vkontakte: { clientID: process.env.VK_ID || 'VK_ID', clientSecret: process.env.VK_SECRET || 'VK_SECRET', callbackURL: 'http://test.freelook.info/auth/vkontakte/callback', proxy: 'test.freelook.info' } };
JavaScript
0
@@ -941,29 +941,24 @@ proxy: ' -test. freelook .info'%0A @@ -949,21 +949,34 @@ freelook -. info +.herokuapp.com '%0A %7D%0A
e154fb07ef165aa8020c14c4bd5269fdee4fb044
Fix image duplicate clearing
admin/index.js
admin/index.js
/* Core server-side administration module */ let caps = require('../server/caps'), check = require('../server/msgcheck'), common = require('../common'), config = require('../config'), db = require('../db'), events = require('events'), okyaku = require('../server/okyaku'), mnemonics = require('./mnemonic/mnemonics'), Muggle = require('../util/etc').Muggle, winston = require('winston'); let mnemonizer = new mnemonics.mnemonizer(config.SECURE_SALT); function genMnemonic(ip) { return ip && mnemonizer.Apply_mnemonic(ip); } exports.genMnemonic = genMnemonic; let dispatcher = okyaku.dispatcher, redis = global.redis; function modHandler(method, errMsg) { return function (nums, client) { return caps.checkAuth('janitor', client.ident) && check('id...', nums) && client.db.modHandler(method, nums, function (err) { if (err) client.kotowaru(Muggle(errMsg, err)); }); }; } dispatcher[common.SPOILER_IMAGES] = modHandler('spoilerImages', 'Couldn\'t spoiler images.' ); dispatcher[common.DELETE_IMAGES] = modHandler('deleteImages', 'Couldn\'t delete images.' ); // Non-persistent global live admin notifications dispatcher[common.NOTIFICATION] = function (msg, client) { msg = msg[0]; if (!caps.checkAuth('admin', client.ident) || !check('string', msg)) return false; okyaku.push([0, common.NOTIFICATION, common.escape_html(msg)]); return true; }; dispatcher[common.MOD_LOG] = function (msg, client) { if (!caps.checkAuth('janitor', client.ident)) return false; redis.zrange('modLog', 0, -1, function (err, log) { if (err) return winston.error('Moderation log fetch error:', err); client.send([0, common.MOD_LOG, db.destrigifyList(log)]); }); return true; }; // Clean up moderation log entries older than one week function cleanLog() { redis.zremrangebyscore('imageDups', 0, Date.now() + 1000*60*60*24*7, function (err) { if (err) winston.error('Error cleaning up moderation log:', err); } ); } setInterval(cleanLog, 60000);
JavaScript
0.000013
@@ -1826,17 +1826,14 @@ re(' -imageDups +modLog ', 0
72a3dd725d752bab06cafcbbb8cf502d17c819e1
Fix delete user error
server/routes/profile-edit.route.js
server/routes/profile-edit.route.js
//----------------------------------------------------------------------------// var express = require('express'); var router = express.Router(); var pg = require('pg'); var connectionString = require('../modules/db-config.module'); //----------------------------------------------------------------------------// // Edit user profile info ----------------------------------------------------// router.put('/update/:id', function(req, res) { var userData = req.body.userData; // var userId = req.userStatus.userId; var userId = assignUserId(req); var queryObject = profileEditQueryBuilder(userData, userId); if (queryObject.queryString !== 'UPDATE mentors SE WHERE id = $1') { pg.connect(connectionString, function(error, client, done) { connectionErrorCheck(error); // Update the database client.query(queryObject.queryString, queryObject.propertyArray, function(error, result) { done(); // Close connection to the database if(error) { console.log('Unable to update user information: ', error); res.sendStatus(500); } else { res.sendStatus(200); } } ); }); } }); //----------------------------------------------------------------------------// // Create a new FAQ entry ----------------------------------------------------// router.post('/new-faq', function(req, res) { var userId = req.userStatus.userId; var question = req.body.faqData.question; var answer = req.body.faqData.answer; console.log("FAQ OBJECT:", req.body.faqData); pg.connect(connectionString, function(error, client, done) { connectionErrorCheck(error); client.query( 'INSERT INTO faq (mentor_id, question, answer) VALUES ($1, $2, $3)', [userId, question, answer], function(error, result) { done(); // Close connection to the database if(error) { console.log('Error when creating new FAQ: ', error); res.sendStatus(500); } else { res.sendStatus(201); } } ); }); }); //----------------------------------------------------------------------------// // Edit an existing FAQ entry ------------------------------------------------// router.put('/edit-faq/:id', function(req, res) { var userId; var faqArray = req.body.faqArray; var queryObject = faqEditQueryBuilder(faqArray, userId); userId = assignUserId(req); pg.connect(connectionString, function(error, client, done) { connectionErrorCheck(error); client.query(queryObject.queryString, queryObject.propertyArray, function(error, result) { done(); // Close connection to the database if(error) { console.log('Error when updating FAQ: ', error); res.sendStatus(500); } else { res.sendStatus(201); } } ); }); }); //----------------------------------------------------------------------------// // Delete a user and all related messages and FAQs from the database ---------// router.delete('/delete-user/:id', function(req, res) { var isAdmin = req.userStatus.isAdmin; var userId = req.userStatus.userId; var userToDelete = req.params.id; if (isAdmin === true || userToDelete === userId){ pg.connect(connectionString, function(error, client, done) { connectionErrorCheck(error); client.query( 'DELETE FROM mentors WHERE id = $1', [userToDelete], function(error, result) { done(); // Close connection to the database if(error) { console.log('Error when deleting user: ', error); res.sendStatus(500); } else { res.sendStatus(201); } } ); }); } }); //----------------------------------------------------------------------------// // Assigns userId based on isAdmin -------------------------------------------// function assignUserId(req){ if(req.userStatus.isAdmin){ return req.params.id; } else { return req.userStatus.userId; } } //----------------------------------------------------------------------------// // Checks for errors connecting to the database ------------------------------// function connectionErrorCheck(error) { if (error) { console.log('Database connection error: ', error); res.sendStatus(500); } } //----------------------------------------------------------------------------// // Cunstructs SQL query based off of the profile fields ----------------------// function profileEditQueryBuilder(object, userId) { var query = 'UPDATE mentors SET '; var array = []; var index = 0; for (var property in object) { if (object[property]) { index++; query += property + ' = $' + index + ', '; array.push(object[property]); } } index++; query = query.slice(0, -2); query += ' WHERE id = $' + index; array.push(userId); return { queryString: query, propertyArray: array }; } //----------------------------------------------------------------------------// // Constructs SQL query based off of updated FAQ info ------------------------// function faqEditQueryBuilder(faqArray, userId) { // console.log('ARRAY IN QUERY BUILDER', array); var queryString = ''; var propertyArray = []; var questionString = ''; var answerString = ''; var loopTracker = 0; for (var index = 0; index < faqArray.length; index++) { loopTracker++; questionString += ' WHEN $' + loopTracker; loopTracker++; questionString += ' THEN $' + loopTracker; } for (index = 0; index < faqArray.length; index++) { loopTracker++; answerString += ' WHEN $' + loopTracker; loopTracker++; answerString += ' THEN $' + loopTracker; } queryString += 'UPDATE faq ' + 'SET question = CASE id' + questionString + ' END, ' + 'answer = CASE id' + answerString + ' END'; for (index = 0; index < faqArray.length; index++) { propertyArray.push(faqArray[index].faq_id, faqArray[index].question); } for (index = 0; index < faqArray.length; index++) { propertyArray.push(faqArray[index].faq_id, faqArray[index].answer); } return { queryString: queryString, propertyArray: propertyArray }; } //----------------------------------------------------------------------------// module.exports = router;
JavaScript
0.000005
@@ -3697,33 +3697,33 @@ es.sendStatus(20 -1 +0 );%0A %7D%0A
70a8a1ac722ea0070b1bda91bb8040a3c68fe3bf
Update example
lib/node_modules/@stdlib/assert/is-enumerable-property/examples/index.js
lib/node_modules/@stdlib/assert/is-enumerable-property/examples/index.js
/* eslint-disable object-curly-newline, object-curly-spacing */ 'use strict'; var isEnumerableProperty = require( './../lib' ); var bool = isEnumerableProperty( {'a': 'b'}, 'a' ); console.log( bool ); // => true bool = isEnumerableProperty( [ 'a' ], 0 ); console.log( bool ); // => true bool = isEnumerableProperty( [ 'a' ], 'length' ); console.log( bool ); // => false bool = isEnumerableProperty( {}, 'prototype' ); console.log( bool ); // => false bool = isEnumerableProperty( {}, 'hasOwnProperty' ); console.log( bool ); // => false bool = isEnumerableProperty( null, 'a' ); console.log( bool ); // => false bool = isEnumerableProperty( void 0, 'a' ); console.log( bool ); // => false bool = isEnumerableProperty( {'null': false}, null ); console.log( bool ); // => true bool = isEnumerableProperty( {'[object Object]': false}, {} ); console.log( bool ); // => true
JavaScript
0.000001
@@ -35,30 +35,8 @@ line -, object-curly-spacing */%0A @@ -139,16 +139,17 @@ y( %7B + 'a': 'b' %7D, ' @@ -144,16 +144,17 @@ 'a': 'b' + %7D, 'a' ) @@ -701,16 +701,17 @@ perty( %7B + 'null': @@ -715,16 +715,17 @@ ': false + %7D, null @@ -790,16 +790,17 @@ perty( %7B + '%5Bobject @@ -815,16 +815,17 @@ ': false + %7D, %7B%7D );
758c406273a939630f19ce5b733d8ce9429fc7df
clear both community and user cache when creating a seed
src/js/app/controllers/SeedEditCtrl.js
src/js/app/controllers/SeedEditCtrl.js
var filepickerUpload = require('../services/filepickerUpload'), format = require('util').format; var directive = function($scope, currentUser, community, Seed, growl, $analytics, UserMentions, seed, $state, onboarding, $rootScope, Cache) { $scope.onboarding = onboarding; // onboarding mode is not the same as the presence of the onboarding object -- // it should not be enabled, e.g., when someone is still in onboarding but is // editing the seed they just created or creating a 2nd one $scope.onboardingMode = (onboarding && onboarding.currentStep() === 'newSeed'); var prefixes = { intention: "I'd like to create", offer: "I'd like to share", request: "I'm looking for" }; // TODO get multiple placeholders to work var placeholders = { intention: "Add more detail about this intention. What help do you need to make it happen?", offer: 'Add more detail about this offer. Is it in limited supply? Do you wish to be compensated?', request: 'Add more detail about what you need. Is it urgent? What can you offer in exchange?' }; $scope.switchSeedType = function(seedType) { $scope.seedType = seedType; $scope.title = prefixes[seedType] + ' '; $scope.descriptionPlaceholder = placeholders[seedType]; }; $scope.close = function() { $rootScope.seedEditProgress = null; $state.go('community.seeds', {community: community.slug}); }; $scope.addImage = function() { $scope.addingImage = true; function finish() { $scope.addingImage = false; $scope.$apply(); } filepickerUpload({ path: format('user/%s/seeds', currentUser.id), success: function(url) { $scope.imageUrl = url; $scope.imageRemoved = false; finish(); }, failure: function(err) { finish(); } }) }; $scope.removeImage = function() { delete $scope.imageUrl; $scope.imageRemoved = true; }; var validate = function() { var invalidTitle = _.contains(_.values(prefixes), $scope.title.trim()); // TODO show errors in UI if (invalidTitle) alert('Please fill in a title'); return !invalidTitle; } var update = function(data) { seed.update(data, function() { $analytics.eventTrack('Edit Post', {has_mention: $scope.hasMention, community_name: community.name, community_id: community.id}); Cache.drop('community.seeds:' + community.id); $state.go('seed', {community: community.slug, seedId: seed.id}); growl.addSuccessMessage('Seed updated.'); }, function(err) { $scope.saving = false; growl.addErrorMessage(err.data); $analytics.eventTrack('Edit Post Failed'); }); }; var create = function(data) { new Seed(data).$save(function() { $analytics.eventTrack('Add Post', {has_mention: $scope.hasMention, community_name: community.name, community_id: community.id}); Cache.drop('community.seeds:' + community.id); if ($scope.onboardingMode) { onboarding.markSeedCreated(data.type); } else { $scope.close(); growl.addSuccessMessage('Seed created!'); } }, function(err) { $scope.saving = false; growl.addErrorMessage(err.data); $analytics.eventTrack('Add Post Failed'); }); }; $scope.save = function() { if (!validate()) return; $scope.saving = true; var data = { name: $scope.title, description: $scope.description, type: $scope.seedType, communityId: community.id, imageUrl: $scope.imageUrl, imageRemoved: $scope.imageRemoved }; $scope.editing ? update(data) : create(data); }; $scope.searchPeople = function(query) { UserMentions.searchPeople(query, community).$promise.then(function(items) { $scope.people = items; }); }; $scope.getPeopleTextRaw = function(user) { $analytics.eventTrack('Post: Add New: @-mention: Lookup', {query: user.name} ); $scope.hasMention = true; return UserMentions.userTextRaw(user); }; $scope.storeProgress = function() { $rootScope.seedEditProgress = { title: $scope.title, description: $scope.description, type: $scope.seedType }; }; if (seed) { $scope.editing = true; $scope.switchSeedType(seed.type); $scope.title = seed.name; if (seed.media[0]) { $scope.imageUrl = seed.media[0].url; } if (seed.description.substring(0, 3) === '<p>') { $scope.description = seed.description; } else { $scope.description = format('<p>%s</p>', seed.description); } } else if ($rootScope.seedEditProgress) { $scope.switchSeedType($rootScope.seedEditProgress.type); $scope.title = $rootScope.seedEditProgress.title; $scope.description = $rootScope.seedEditProgress.description; } else { var defaultType = (onboarding ? 'offer' : 'intention'); $scope.switchSeedType(defaultType); } }; module.exports = function(angularModule) { angularModule.controller('SeedEditCtrl', directive); }
JavaScript
0
@@ -2152,16 +2152,157 @@ tle;%0A %7D +;%0A%0A var clearCache = function() %7B%0A Cache.drop('community.seeds:' + community.id);%0A Cache.drop('profile.seeds:' + currentUser.id);%0A %7D; %0A%0A var @@ -2508,52 +2508,19 @@ -Cache.drop('community.seeds:' + community.id +clearCache( );%0A @@ -3006,52 +3006,19 @@ -Cache.drop('community.seeds:' + community.id +clearCache( );%0A
b87c6dc3c1e1f94b823384b5f98365259bda1bb7
Remove decimals
lib/node_modules/@stdlib/math/base/dist/binomial/quantile/lib/factory.js
lib/node_modules/@stdlib/math/base/dist/binomial/quantile/lib/factory.js
'use strict'; // MODULES // var isNonNegativeInteger = require( '@stdlib/math/base/utils/is-nonnegative-integer' ); var degenerate = require( '@stdlib/math/base/dist/degenerate/quantile' ).factory; var erfcinv = require( '@stdlib/math/base/special/erfcinv' ); var isnan = require( '@stdlib/math/base/utils/is-nan' ); var round = require( '@stdlib/math/base/special/round' ); var sqrt = require( '@stdlib/math/base/special/sqrt' ); var cdf = require( '@stdlib/math/base/dist/binomial/cdf' ); var SQRT2 = require( '@stdlib/math/constants/float64-sqrt-two' ); var PINF = require( '@stdlib/math/constants/float64-pinf' ); var search = require( './search.js' ); var nan = require( './nan.js' ); // MAIN // /** * Returns a function for evaluating the quantile function for a binomial distribution with number of trials `n` and success probability `p`. * * @param {NonNegativeInteger} n - number of trials * @param {Probability} p - success probability * @returns {Function} quantile function * * @example * var quantile = factory( 10, 0.5 ); * var y = quantile( 0.1 ); * // returns 3.0 * * y = quantile( 0.9 ); * // returns 7.0 */ function factory( n, p ) { var sigmaInv; var sigma; var mu; if ( isnan( n ) || isnan( p ) || !isNonNegativeInteger( n ) || n === PINF || p < 0.0 || p > 1.0 ) { return nan; } if ( p === 0.0 || n === 0.0 ) { return degenerate( 0.0 ); } if ( p === 1.0 ) { return degenerate( n ); } mu = n * p; sigma = sqrt( n * p * ( 1.0-p ) ); sigmaInv = 1.0 / sigma; return quantile; /** * Evaluates the quantile function for a binomial distribution. * * @private * @param {Probability} r - input value * @returns {NonNegativeInteger} evaluated quantile function * * @example * var y = quantile( 0.3 ); * // returns <number> */ function quantile( r ) { var guess; var corr; var x2; var x; if ( isnan( r ) || r < 0.0 || r > 1.0 ) { return NaN; } if ( r === 0.0 ) { return 0; } if ( r === 1.0 ) { return n; } // Cornish-Fisher expansion: if ( r < 0.5 ) { x = -erfcinv( 2.0 * r ) * SQRT2; } else { x = erfcinv( 2.0 * ( 1.0-r ) ) * SQRT2; } x2 = x * x; // Skewness correction: corr = x + ( sigmaInv * ( x2-1.0 ) / 6.0 ); guess = round( mu + (sigma * corr) ); if ( cdf( guess, n, p ) >= r ) { return search.left( guess, r, n, p ); } return search.right( guess, r, n, p ); } // end FUNCTION quantile() } // end FUNCTION factory() // EXPORTS // module.exports = factory;
JavaScript
0.999988
@@ -1075,18 +1075,16 @@ eturns 3 -.0 %0A*%0A* y = @@ -1115,18 +1115,16 @@ eturns 7 -.0 %0A*/%0Afunc
cf2476c1e810a5ed318ab9e688448f1ec57d575f
fixed broken test
test/unit/NewReleaseNotification.test.js
test/unit/NewReleaseNotification.test.js
import { shallowMount } from '@vue/test-utils'; import { createTestingPinia } from '@pinia/testing'; import NewReleaseNotification from '~/components/NewReleaseNotification'; import { createClient } from '~/util/awclient'; describe('hasNewRelease method', () => { createClient(); const wrapper = shallowMount(NewReleaseNotification, { global: { plugins: [createTestingPinia()], }, }); const vm = wrapper.vm; test('should clean and compare version tags properly', () => { vm.currentVersion = vm.cleanVersionTag('v0.8.0'); vm.latestVersion = vm.cleanVersionTag('v0.9.2'); expect(vm.getHasNewRelease()).toBe(true); vm.currentVersion = vm.cleanVersionTag('v0.8.0 (rust)'); vm.latestVersion = vm.cleanVersionTag('v0.9.2'); expect(vm.getHasNewRelease()).toBe(true); vm.currentVersion = vm.cleanVersionTag(' v0.8.0 (rust)'); vm.latestVersion = vm.cleanVersionTag('v0.9.2'); expect(vm.getHasNewRelease()).toBe(true); vm.currentVersion = vm.cleanVersionTag('v0.9.1 (rust)'); vm.latestVersion = vm.cleanVersionTag('v0.9.2'); expect(vm.getHasNewRelease()).toBe(true); vm.currentVersion = vm.cleanVersionTag('v0.9.2 (rust)'); vm.latestVersion = vm.cleanVersionTag('v0.9.2'); expect(vm.getHasNewRelease()).toBe(false); // vm.currentVersion = vm.cleanVersionTag('v0.8.dev+c6433ea'); // vm.latestVersion = vm.cleanVersionTag('v0.9.2'); // expect(vm.getHasNewRelease()).toBe(true); // vm.currentVersion = vm.cleanVersionTag('v0.8.0b1'); // vm.latestVersion = vm.cleanVersionTag('v0.9.2'); // expect(vm.getHasNewRelease()).toBe(true); }); });
JavaScript
0.999512
@@ -262,26 +262,8 @@ %3E %7B%0A - createClient();%0A co @@ -405,16 +405,34 @@ pper.vm; +%0A createClient(); %0A%0A test
18763861ebc55d797556ccd22a1e9a10a9943f6a
refactor test
test/unit/handleUserMessage/isInScope.js
test/unit/handleUserMessage/isInScope.js
var test = require('tape') require('rewire-global').enable() const handleUserMessage = require('../../../messages/handleUserMessage') const isInScope = handleUserMessage.__get__('isInScope') test('affiliation: student should be in scope', t => { const msg = { affiliation:['student'] } t.plan(1) const result = isInScope(msg) t.ok(result) }) test('affiliation: employee should be in scope', t => { const msg = { affiliation:['employee'] } t.plan(1) const result = isInScope(msg) t.ok(result) }) test('affiliation: member should be in scope', t => { const msg = { affiliation:['member'] } t.plan(1) const result = isInScope(msg) t.ok(result) }) test('affiliation: other should not be in scope', t => { const msg = { affiliation:['other'] } t.plan(1) const result = isInScope(msg) t.notOk(result) })
JavaScript
0.000033
@@ -715,19 +715,19 @@ should -not +NOT be in s
c2e0514881a66f19ba4e06caceabaecb416cc759
change let
Admin-CSNet/routes/propertyManagement.js
Admin-CSNet/routes/propertyManagement.js
var Property = require('../model/property'); var User = require('../model/user'); var ObjectId = require('mongodb').ObjectId; var mongoose = require('mongoose'); exports.getAllProperties = function (req, res, next) { "use strict"; var response = []; Property .find({isApproved: true, isAvailable: true}) .populate('hostId') .exec(function (err, results) { if (err) { console.log(err); } else { for (let i = 0; i < results.length; i++) { if (results[i].hostId.isApproved) { response.push(results[i]); } } } res.send(response); }); }; exports.getProperty = function (req, res) { var propertyId = req.param("_id"); var conditions = {_id: new ObjectId(propertyId)}; Property.find({_id: conditions}, function (err, results) { if (err) { throw err; } else { console.log("here is the property " + results); res.send(results); } }) }; exports.getPendingProperty = function (req, res) { var propertyId = req.param("_id"); var conditions = {_id: new ObjectId(propertyId)}; Property.find({_id: conditions}, function (err, results) { if (err) { throw err; } else { console.log("here is the propegetPendingPropertyrty " + results); res.send(results); } }) }; exports.unapprovedProperty = function (req, res) { console.log("Call came here in unapprovedProperty"); Property.find({isApproved: false, isAvailable: true}, function (err, results) { if (err) { throw err; } else { console.log(results); res.send(results); } }) }; exports.approveProperty = function (req, res, next) { var response = {}; var propertyId = req.param("_id"); var conditions = {_id: new ObjectId(propertyId)}; var update = { 'isApproved': true }; Property.update(conditions, update, function (err, results) { if (err) { throw err; } else { response.code = 200; response.message = "updated"; res.render('admin_pendingProperty'); } }); }; exports.admin_pendingProperty = function (req, res) { res.render('admin_pendingProperty'); }; exports.admin_activePropertyManagement = function (req, res) { res.render('admin_activePropertyManagement'); };
JavaScript
0.000003
@@ -215,25 +215,8 @@ ) %7B%0A - %22use strict%22; %0A @@ -484,11 +484,11 @@ or ( -let +var i =
ffd1d3ca19717cee782a081b71ca9cf5cd06a25e
allow all special chars listed in #29
app/scripts/query.js
app/scripts/query.js
var Query = function () { 'use strict'; var queryExpressions = []; var regexTerm = /([\w:!\*]+)/g; var regexNonTerm = /[^\w:!\*]+/g; var glue = function (term, type, field) { var rv = ''; switch (type) { case enumGlueTypes.or: rv += term.replace(regexTerm, field + ':$1'); rv = rv.replace(regexNonTerm, ' OR '); break; case enumGlueTypes.and: rv += term.replace(regexTerm, field + ':$1'); rv = rv.replace(regexNonTerm, ' AND '); break; case enumGlueTypes.phrase: rv += field + ':"' + term + '"'; break; case enumGlueTypes.not: rv += term.replace(regexTerm, '!' + field + ':$1'); rv = rv.replace(regexNonTerm, ' AND '); break; } return rv; }; var enumGlueTypes = { or: 1, and: 2, phrase: 3, not: 4 }; this.enumGlueTypes = enumGlueTypes; this.setQueryExpression = function (index, settings) { var defaults = { term: '*', field: 'er', glueType: enumGlueTypes.or, glueTypeNextTerm: enumGlueTypes.or }; settings = settings || defaults; var me = queryExpressions[index] || defaults; me.term = settings.term || me.term; me.field = settings.field || me.field; me.glueType = settings.glueType || me.glueType; me.glueTypeNextTerm = settings.glueTypeNextTerm || me.glueTypeNextTerm; queryExpressions[index] = me; }; this.deleteQueryExpression = function (index) { delete queryExpressions[index]; }; this.getQueryString = function () { var prevJoiner; return queryExpressions.reduce(function(prev, cur) { var rv = prev; if (cur) { var gluedTerm = glue(cur.term, cur.glueType, cur.field); switch (prevJoiner) { case enumGlueTypes.or: rv += ' OR '; break; case enumGlueTypes.and: rv += ' AND '; break; case enumGlueTypes.not: rv += ' AND NOT '; break; } prevJoiner = cur.glueTypeNextTerm; rv += '(' + gluedTerm + ')'; } return rv; }, ''); }; }; module.exports = Query;
JavaScript
0
@@ -91,19 +91,47 @@ erm + = /(%5B%5Cw -:!%5C* +%5C+%5C-&%5C%7C!%5C(%5C)%7B%7D%5C%5B%5C%5D%5C%5E%22~%5C*%5C?:%5C%5C %5D+)/ @@ -165,12 +165,37 @@ %5B%5E%5Cw -:!%5C* +%5C+%5C-&%5C%7C!%5C(%5C)%7B%7D%5C%5B%5C%5D%5C%5E%22~%5C*%5C?:%5C%5C %5D+/g
44c4da62d4208a08dfb253bb744852de93d08b2a
Remove useless logs and fix req pause stream in auth middleware
core/cb.server/main.js
core/cb.server/main.js
// Requires var http = require('http'); var express = require('express'); var _ = require('underscore'); function setup(options, imports, register) { var workspace = imports.workspace; var logger = imports.logger.namespace("web"); // Expres app var app = express(); if (options.dev) { app.use(function(req, res, next) { logger.log("["+req.method+"]", req.url); next(); }); } // Apply middlewares app.use(express.cookieParser()); app.use(express.cookieSession({ 'key': ['sess', workspace.id].join('.'), 'secret': workspace.secret, })); // Error handling app.use(function(err, req, res, next) { if(!err) return next(); logger.error("Error:"); res.send({ 'error': err.message }, 500); logger.error(err.stack); }); // Get User and set it to res object app.use(function getUser(req, res, next) { // Pause request stream var uid = req.session.userId; if(uid) { req.pause(); return workspace.getUser(uid) .then(function(user) { // Set user res.user = user; // Activate user res.user.activate(); }) .fail(function(err) { res.user = null; }).fin(function() { req.resume(); next(); }); } return next(); }); // Client-side app.get('/', function(req, res, next) { var doRedirect = false; var baseToken = options.defaultToken; var baseEmail = options.defaultEmail; console.log("check auth settings", req.query); if (req.query.email && req.query.token) { // Auth credential: save as cookies and redirect to clean url baseEmail = req.query.email; baseToken = req.query.token; doRedirect = true; } if (baseEmail) { res.cookie('email', baseEmail, { httpOnly: false }); } if (baseToken) { res.cookie('token', baseToken, { httpOnly: false }) } console.log(baseEmail, baseToken, doRedirect); if (doRedirect) { return res.redirect("/"); } return next(); }); app.use('/', express.static(__dirname + '/../../client/build')); app.use('/docs', express.static(__dirname + '/../../docs')); // Block queries for unAuthenticated users // var authorizedPaths = []; app.use(function(req, res, next) { if(needAuth(req.path) || res.user) { return next(); } // Unauthorized return res.send(403, { ok: false, data: {}, error: "Could not run API request because user has not authenticated", method: req.path, }); }); // Check if a path need auth var needAuth = function(path) { return _.find(authorizedPaths, function(authPath) { return path.indexOf(authPath) == 0; }) != null; }; // Disable auth for a path var disableAuth = function(path) { logger.log("disable auth for", path); authorizedPaths.push(path); }; // Http Server var server = http.createServer(app); // Register register(null, { "server": { "app": app, "http": server, 'disableAuth': disableAuth, 'port': options.port, } }); } // Exports module.exports = setup;
JavaScript
0
@@ -964,40 +964,8 @@ ) %7B%0A - // Pause request stream%0A @@ -1012,24 +1012,60 @@ if(uid) %7B%0A + // Pause request stream%0A @@ -1304,28 +1304,10 @@ %7D -)%0A .fail( +, func @@ -1366,19 +1366,20 @@ %7D). -fin +done (functio @@ -1689,64 +1689,8 @@ l;%0A%0A - console.log(%22check auth settings%22, req.query);%0A%0A
9fbd76d6da15cd7a03ef36bd7a75be77c55feef8
Move activeChanged call from create to rendered
source/IconButton.js
source/IconButton.js
(function (enyo, scope) { /** * _moon.IconButton_ is an icon that acts like a button. Specify the icon image * by setting the {@link moon.Icon#src} property to a URL indicating the image file's location. * * ``` * {kind: 'moon.IconButton', src: 'images/search.png'} * ``` * * If you want to combine an icon with text inside of a button, use a * [moon.Icon]{@link moon.Icon} inside a [moon.Button]{@link moon.Button}. * * Moonstone supports two methods for displaying icons; in addition to using * traditional image assets specified in {@link moon.Icon#src}, you may use icons that are * stored as single characters in a special symbol font. To do this, set the * value of the _icon_ property to a string representing an icon name, e.g.: * * ``` * {kind: 'moon.IconButton', icon: 'closex'} * ``` * * The name-to-character mappings for font-based icons are stored in * _css/moonstone-icons.less_. Each mapping associates an icon name with the icon * font's corresponding character or symbol. * * See [moon.Icon]{@link moon.Icon} for more information on the available font-based * icons, as well as specifications for icon image assets. * * @ui * @class moon.IconButton * @extends moon.Icon * @public */ enyo.kind( /** @lends moon.IconButton.prototype */ { /** * @private */ name: 'moon.IconButton', /** * @private */ kind: 'moon.Icon', /** * @private */ published: /** @lends moon.IconButton.prototype */ { /** * Used when the IconButton is part of an [enyo.Group]{@link enyo.Group}. * A value of true indicates that this is the active button of the group; * false, that it is not the active button. * * @type {Boolean} * @default false * @public */ active: false, /** * A boolean parameter affecting the size of the button. * If true, the button will have a diameter of 60px. * However, the button's tap target will still have a diameter of 78px, with * invisible DOM wrapping the small button to provide the larger tap zone. * * @type {Boolean} * @default true * @public */ small: true, /** * When true, the button will have no rounded background color/border * * @type {Boolean} * @default true * @public */ noBackground: false }, /** * @private */ classes: 'moon-icon-button', /** * @private */ spotlight: true, /** * @private */ handlers: { /** * onSpotlightSelect simulates mousedown */ onSpotlightKeyDown: 'depress', /** * onSpotlightKeyUp simulates mouseup */ onSpotlightKeyUp: 'undepress', /** * used to request it is in view in scrollers */ onSpotlightFocused: 'spotlightFocused', onSpotlightBlur: 'undepress' }, /** * @private */ create: function () { this.inherited(arguments); if (this.hasOwnProperty("active")) { this.activeChanged(); } this.noBackgroundChanged(); }, /** * @private */ noBackgroundChanged: function () { this.addRemoveClass('no-background', this.noBackground); }, /** * @private */ tap: function () { if (this.disabled) { return true; } this.setActive(true); }, /** * @fires enyo.GroupItem#event:onActivate * @private */ activeChanged: function () { this.bubble('onActivate'); }, /** * Adds _pressed_ CSS class. * @private */ depress: function (inSender, inEvent) { if (inEvent.keyCode === 13) { this.addClass('pressed'); } }, /** * Removes _pressed_ CSS class. * @private */ undepress: function () { this.removeClass('pressed'); }, /** * @fires moon.Scroller#event:onRequestScrollIntoView * @private */ spotlightFocused: function (inSender, inEvent) { if (inEvent.originator === this) { this.bubble('onRequestScrollIntoView'); } } }); })(enyo, this);
JavaScript
0
@@ -2819,16 +2819,133 @@ ments);%0A +%09%09%09this.noBackgroundChanged();%0A%09%09%7D,%0A%0A%09%09/**%0A%09%09* @private%0A%09%09*/%0A%09%09rendered: function () %7B%0A%09%09%09this.inherited(arguments);%0A %09%09%09if (t @@ -3011,39 +3011,8 @@ %09%09%7D%0A -%09%09%09this.noBackgroundChanged();%0A %09%09%7D,
31a5059dc4ee8996db4a83ab92028afc81e5ab2d
Fix authorizer
lib/middleware/apiGatewayAuthorizerEvent/apiGatewayAuthorizerEvent.js
lib/middleware/apiGatewayAuthorizerEvent/apiGatewayAuthorizerEvent.js
const smash = require("../../../smash.js"); const logger = smash.logger(); const errorUtil = smash.errorUtil(); const EventType = require("./lib/eventType.js"); const Event = require("./lib/event.js"); class ApiGatewayAuthorizerEvent { constructor() { this.events = []; } _matchEvents(eventToMatch) { return this.events.filter(event => event.match(eventToMatch)); } async handleEvent(rawEvent, context, callback) { if (typeof callback !== 'function') { throw new errorUtil.TypeError("Third parameter of handleEvent() must be a function, ", callback); } this._callback = callback; const event = new Event(rawEvent, context, this); const matchedEvent = this._matchEvents(event); if (matchedEvent) { if (event.requestId) { logger.info("RequestId: ", event.requestId); } logger.info("Match event in env: " + smash.getEnv("ENV")); smash.setCurrentEvent(event); try { await matchedEvent.callback.call(smash, event); } catch (error) { event.handleError(error); } } else { logger.info("No event found"); this.terminate(new Error("No event found")); } return this; } terminate(error, data) { if (error) { logger.info("Result => Failure", error); } else { logger.info("Result => Success"); } this._callback(error, data); return this; } isEvent(event) { if (event.type === "REQUEST") { return true; } return false; } event(route, callback) { this.events.push(new EventType(route, callback)); return this; } getHandlers() { return this.events; } expose() { return [ { "functionName": "apiGatewayAuthorizerEvent", "function": "event", }, ]; } } module.exports = ApiGatewayAuthorizerEvent;
JavaScript
0.000001
@@ -1412,23 +1412,16 @@ %0A%09event( -route, callback @@ -1461,15 +1461,8 @@ ype( -route, call
4ed2c1e09aeddf02614c4163260eb4e6fc12a5a0
Print test filename
lib/node_modules/@stdlib/math/base/utils/float64-signbit/test/test.js
lib/node_modules/@stdlib/math/base/utils/float64-signbit/test/test.js
'use strict'; // MODULES // var tape = require( 'tape' ); var round = require( '@stdlib/math/base/special/round' ); var pow = require( '@stdlib/math/base/special/pow' ); var signbit = require( './../lib' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( typeof signbit === 'function', 'main export is a function' ); t.end(); }); tape( 'the function returns a boolean', function test( t ) { t.equal( typeof signbit(5), 'boolean', 'returns a boolean' ); t.end(); }); tape( 'the function returns a boolean indicating if a sign bit is on (true) or off (false)', function test( t ) { var bool; var sign; var frac; var exp; var x; var i; for ( i = 0; i < 1e4; i++ ) { if ( Math.random() < 0.5 ) { sign = -1; } else { sign = 1; } frac = Math.random() * 10; exp = round( Math.random()*646 ) - 323; x = sign * frac * pow( 10, exp ); bool = signbit( x ); if ( sign < 0 ) { t.equal( bool, true, 'returns true for ' + x ); } else { t.equal( bool, false, 'returns false for ' + x ); } } t.end(); });
JavaScript
0.000005
@@ -273,16 +273,43 @@ ( t ) %7B%0A +%09t.ok( true, __filename );%0A %09t.ok( t
f02fbc5bf30bbaec360bd0c7665929e4c0c6c43e
Add small packet request/response benchmark
examples/bench/bench_client.js
examples/bench/bench_client.js
const promiseImpl = require('bluebird'); global.Promise = promiseImpl; const FastMQ = require('../../lib/index.js'); const ParallelBenchmark = require('./ParallelBenchmark'); const parseArgs = require('minimist'); const options = parseArgs(process.argv.slice(2)); const Parallel = options.p || 10; const Requests = options.n || 1000; const bench1 = new ParallelBenchmark('test_cmd_json', { parallel: Parallel, requests: Requests, setup: function() { this.number = 1; return FastMQ.Client.connect('client1', 'master').then((ch) => { this.channel = ch; }); }, fn: function() { // console.log(`this.number: ${this.number}`); const reqData = { num: this.number++, data: 'test' }; return this.channel.request('master', 'test_cmd_json', reqData, 'json'); }, verify: function(data) { // console.log(data); }, onStart: function(target) { console.log(`# Run ${target.name}, parallel: ${target.parallel} requests: ${target.requests}`); }, onComplete: function(stat) { console.log(`# Benchmark ${stat.name}: ${stat.ops} operation per sec., elapsed: ${stat.elapsed} ms`); this.channel.disconnect(); }, }); const bench2 = new ParallelBenchmark('test_cmd_raw_1k', { parallel: Parallel, requests: Requests, setup: function() { this.rawData = Buffer.allocUnsafe(1024); return FastMQ.Client.connect('client1', 'master').then((ch) => { this.channel = ch; }); }, fn: function() { // console.log(`this.number: ${this.number}`); // let reqData = {num: this.number++, data: 'test'}; return this.channel.request('master', 'test_cmd_raw', this.rawData, 'raw'); }, verify: function(data) { // console.log(data); }, onStart: function(target) { console.log(`# Run ${target.name}, parallel: ${target.parallel} requests: ${target.requests}`); }, onComplete: function(stat) { console.log(`# Benchmark ${stat.name}: ${stat.ops} operation per sec., elapsed: ${stat.elapsed} ms`); this.channel.disconnect(); }, }); bench1.run().then(() => { bench2.run(); });
JavaScript
0.000001
@@ -2163,27 +2163,251 @@ );%0A%0A -bench1.run( +const bench3 = new ParallelBenchmark('test_cmd_raw_64kb', %7B%0A parallel: Parallel,%0A requests: Requests,%0A setup: function() %7B%0A this.rawData = Buffer.allocUnsafe(64);%0A return FastMQ.Client.connect('client2', 'master' ).then(( ) =%3E @@ -2402,16 +2402,18 @@ ).then(( +ch ) =%3E %7B%0A @@ -2419,22 +2419,743 @@ + -bench2.run();%0A%7D + this.channel = ch;%0A %7D);%0A %7D,%0A fn: function() %7B%0A // console.log(%60this.number: $%7Bthis.number%7D%60);%0A // let reqData = %7Bnum: this.number++, data: 'test'%7D;%0A return this.channel.request('master', 'test_cmd_raw', this.rawData, 'raw');%0A %7D,%0A verify: function(data) %7B%0A // console.log(data);%0A %7D,%0A onStart: function(target) %7B%0A console.log(%60# Run $%7Btarget.name%7D, parallel: $%7Btarget.parallel%7D requests: $%7Btarget.requests%7D%60);%0A %7D,%0A onComplete: function(stat) %7B%0A console.log(%60# Benchmark $%7Bstat.name%7D: $%7Bstat.ops%7D operation per sec., elapsed: $%7Bstat.elapsed%7D ms%60);%0A this.channel.disconnect();%0A %7D,%0A%7D);%0A%0Abench1.run()%0A.then(() =%3E bench2.run())%0A.then(() =%3E bench3.run() );%0A
f7cf209613627fdfc965a9eb797a50b858102a8e
Add debug message for failed lambda invocations
packages/target-chrome-aws-lambda/src/create-chrome-aws-lambda-target.js
packages/target-chrome-aws-lambda/src/create-chrome-aws-lambda-target.js
const debug = require('debug')('loki:chrome:aws-lambda'); const AWS = require('aws-sdk'); const { parseError, withRetries } = require('@loki/core'); function createChromeAWSLambdaTarget({ baseUrl = 'http://localhost:6006', chromeAwsLambdaFunctionName, chromeAwsLambdaRetries = 0, }) { const invoke = withRetries(chromeAwsLambdaRetries, 1000)(async payload => { const lambda = new AWS.Lambda(); const params = { FunctionName: chromeAwsLambdaFunctionName, Payload: JSON.stringify(payload), }; debug(`Invoking ${params.FunctionName} with ${params.Payload}`); const data = await lambda.invoke(params).promise(); const response = JSON.parse(data.Payload); if (response.errorMessage) { throw parseError(response.errorMessage); } return response; }); const start = () => {}; const stop = () => {}; const getStorybook = () => invoke({ command: 'getStorybook', baseUrl, }); const captureScreenshotForStory = async ( kind, story, options, configuration ) => { const screenshot = await invoke({ command: 'captureScreenshotForStory', baseUrl, kind, story, options, configuration, }); return Buffer.from(screenshot, 'base64'); }; const captureScreenshotsForStories = async (stories, options) => { const screenshots = await invoke({ command: 'captureScreenshotsForStories', baseUrl, stories, options, }); return screenshots.map(screenshot => { if (screenshot.errorMessage) { return parseError(screenshot.errorMessage); } return Buffer.from(screenshot, 'base64'); }); }; return { start, stop, getStorybook, captureScreenshotForStory, captureScreenshotsForStories, }; } module.exports = createChromeAWSLambdaTarget;
JavaScript
0
@@ -720,24 +720,143 @@ rMessage) %7B%0A + debug(%0A %60Invocation failed due to $%7Bresponse.errorType%7D with message %22$%7Bresponse.errorMessage%7D%22%60%0A );%0A throw
6ba1e59b73e1ab72542f797d73bcfd75626a3090
handle errors in graphql response
packages/veritone-widgets/src/redux/modules/filePicker/filePickerSaga.js
packages/veritone-widgets/src/redux/modules/filePicker/filePickerSaga.js
import { fork, all, call, put, take, takeEvery, select } from 'redux-saga/effects'; import { delay } from 'redux-saga'; import { isArray } from 'lodash'; import { modules } from 'veritone-redux-common'; const { user: userModule, config: configModule } = modules; import callGraphQLApi from '../../../shared/callGraphQLApi'; import uploadFilesChannel from '../../../shared/uploadFilesChannel'; import { UPLOAD_REQUEST, uploadProgress, uploadComplete, endPick } from '.'; export function* uploadFileSaga(fileOrFiles) { const files = isArray(fileOrFiles) ? fileOrFiles : [fileOrFiles]; const getUrlQuery = `query urls($name: String!){ getSignedWritableUrl(key: $name) { url key bucket } }`; const config = yield select(configModule.getConfig); const { apiRoot, graphQLEndpoint } = config; const graphQLUrl = `${apiRoot}/${graphQLEndpoint}`; const token = yield select(userModule.selectSessionToken); // get a signed URL for each object to be uploaded let signedWritableUrlResponses; try { signedWritableUrlResponses = yield all( files.map(({ name }) => call(callGraphQLApi, { endpoint: graphQLUrl, query: getUrlQuery, // todo: add uuid to $name to prevent naming conflicts variables: { name }, token }) ) ); } catch (error) { return yield put(uploadComplete(null, { error })); } // todo: handle graphql errors const uploadDescriptors = signedWritableUrlResponses.map( ({ data: { getSignedWritableUrl: { url, key, bucket } }, errors }) => ({ url, key, bucket }) ); let resultChan; try { resultChan = yield call(uploadFilesChannel, uploadDescriptors, files); } catch (error) { return yield put(uploadComplete(null, { error })); } let result = []; while (result.length !== files.length) { const { progress = 0, error, success, file, descriptor: { key, bucket } } = yield take(resultChan); if (success || error) { yield put(uploadProgress(key, 100)); result.push({ name: key, size: file.size, type: file.type, error: error || false, url: error ? null : `https://${bucket}.s3.amazonaws.com/${key}` }); continue; } yield put(uploadProgress(key, progress)); } const isError = result.every(e => e.error); const isWarning = !isError && result.some(e => e.error); yield put( uploadComplete(result, { warn: isWarning ? 'Some files failed to upload.' : false, error: isError ? 'All files failed to upload.' : false }) ); // fixme -- only do this on success. on failure, wait for user to ack. yield call(delay, 3000); yield put(endPick()); } export function* watchUploadRequest() { yield takeEvery(UPLOAD_REQUEST, function*(action) { const files = action.payload; yield call(uploadFileSaga, files); }); } export default function* root() { yield all([fork(watchUploadRequest)]); }
JavaScript
0.000001
@@ -1459,46 +1459,66 @@ %0A%0A -// todo: handle graphql errors%0A const +let uploadDescriptors; // %7B url, key, bucket %7D%0A try %7B%0A upl @@ -1570,16 +1570,18 @@ ap(%0A + + (%7B data: @@ -1607,96 +1607,334 @@ eUrl -: %7B url, key, bucket %7D %7D, errors %7D) =%3E (%7B%0A url,%0A key,%0A bucket%0A + %7D, errors %7D) =%3E %7B%0A if (errors && errors.length) %7B%0A throw new Error(%0A %60Call to getSignedWritableUrl returned error: $%7Berrors%5B0%5D.message%7D%60%0A );%0A %7D%0A%0A return getSignedWritableUrl;%0A %7D%0A );%0A %7D catch (e) %7B%0A return yield put(uploadComplete(null, %7B error: e.message %7D) +); %0A -); +%7D %0A%0A
4a40ba4485ece9ab6589fff884cf5fc882df229b
Disable Call Button if user clicks too frequently or app somehow is throttling
src/components/DialerPanel/index.js
src/components/DialerPanel/index.js
import React, { PropTypes, Component } from 'react'; import classnames from 'classnames'; import DialPad from '../DialPad'; import TextInput from '../TextInput'; import styles from './styles.scss'; function DialerPanel({ callButtonDisabled, className, keepToNumber, onCall, toNumber, }) { return ( <div className={classnames(styles.root, className)}> <div className={styles.dial_input}> <TextInput className={styles.dialInput} value={toNumber} onChange={(event) => { keepToNumber(event.currentTarget.value); } } /> </div> <div className={styles.dialButtons}> <DialPad className={styles.dialPad} onButtonOutput={(key) => { keepToNumber(toNumber + key); } } /> <div className={classnames(styles.callBtnRow)}> <div className={styles.callBtn}> <svg className={styles.btnSvg} viewBox="0 0 500 500"> <g className={classnames( styles.btnSvgGroup, callButtonDisabled && styles.disabled, )} onClick={onCall} > <circle className={styles.circle} cx="250" cy="250" r="200" /> <text className={styles.btnValue} x="250" y="330" dangerouslySetInnerHTML={{ __html: '&#xae;', }} /> </g> </svg> </div> </div> </div> </div> ); } DialerPanel.propTypes = { className: PropTypes.string, onCall: PropTypes.func.isRequired, callButtonDisabled: PropTypes.bool, toNumber: PropTypes.string, keepToNumber: PropTypes.func, }; export default DialerPanel;
JavaScript
0
@@ -294,16 +294,87 @@ r,%0A%7D) %7B%0A + const onCallFunc = () =%3E %7B%0A !callButtonDisabled && onCall();%0A %7D;%0A return @@ -1255,16 +1255,20 @@ =%7BonCall +Func %7D%0A
bac4832b4c7534e2ea7086c5adb8bd2a031f28c9
send trans as url params
src/components/EditWindow/module.js
src/components/EditWindow/module.js
import axios from 'axios'; import audio from 'store/audio.js'; import { get_edit_window_timespan, get_selected_words, } from 'routes/TrackDetail/module.js'; const ACTION_HANDLERS = { send_subs: (state, action) => { console.log('send subtitles',action); return state; }, }; export function playback_on() { return { type: 'playback_on', }; }; export function playback_off(audio) { return { type: 'playback_off', }; }; export function send_subs(form_values, dispatch, props) { return (dispatch,getState) => { dispatch({ type: 'send_subs', }); const state = getState(); const timespan = get_edit_window_timespan(state); const selw = get_selected_words(state); const endpoint = API_BASE + '/subsubmit/'; axios.post(endpoint, { filestem: props.stem, start: timespan.start, end: timespan.end, trans: form_values.edited_subtitles, author: state.form.username.values.username, session: localStorage.getItem('session'), }).then(console.log); }; }; const initial_state = { }; export default function reducer (state = initial_state, action) { const handler = ACTION_HANDLERS[action.type]; return handler ? handler(state, action) : state; };
JavaScript
0
@@ -842,25 +842,99 @@ ios. -post(endpoint, %7B%0A +request(%7B%0A url: endpoint,%0A method: 'POST',%0A params: %7B%0A @@ -975,16 +975,20 @@ + start: t @@ -1014,16 +1014,20 @@ + + end: t @@ -1039,16 +1039,20 @@ an.end,%0A + @@ -1104,16 +1104,20 @@ + + author: @@ -1165,16 +1165,20 @@ + session: @@ -1211,16 +1211,31 @@ sion'),%0A + %7D,%0A
507a8f42d8020cd2d9dd2ad24a66a368c18bead4
add debug fps"
src/map-generator/states/GameState.js
src/map-generator/states/GameState.js
const PATH = "res/map-generator"; import Hero from 'object/character'; import Maze from 'lib/maze'; import Room from 'lib/room'; import RoomWithCarpet from 'object/roomWithCarpet'; import RoomWithColoredCorners from "object/roomWithColoredCorners"; import { WorldWitdth, WorldHeight } from "constants/constants"; import { Character, Carpet, Corner } from "constants/keyUtils"; class GameState extends Phaser.State { constructor() { super(); this.useJsonData = false; this.JSONData = null; } init(JSONData) { if (JSONData !== undefined) { this.useJsonData = true; this.JSONData = JSONData; } } create() { this.game.stage.backgroundColor = "#4488AA"; this.game.world.setBounds(0, 0, WorldWitdth, WorldHeight); this.character = new Hero(this.game, 50, 200, Character, 0); this.maze = new Maze(this.game, this.game.world, WorldWitdth, WorldHeight, [Room, RoomWithCarpet, RoomWithColoredCorners]); this.maze.generate(game, this.JSONData); const roomPosition = this.maze.getInitialRoom().borders().center; this.character.position.setTo(roomPosition.x,roomPosition.y); this.game.add.existing(this.character); this.game.camera.follow(this.character); } update() { this.game.physics.arcade.collide(this.character, this.maze.walls()); } preload() { this.game.load.image(Character, PATH + '/character.png'); this.game.load.image(Carpet, PATH + '/carpet.png'); this.game.load.image(Corner, PATH + '/corner.png'); } } export default GameState;
JavaScript
0
@@ -636,32 +636,74 @@ %7D%0A%0A create() %7B%0A + this.game.time.advancedTiming = true;%0A this.game.st @@ -1548,16 +1548,98 @@ g');%0A %7D +%0A%0A render() %7B%0A this.game.debug.text(this.game.time.fps, 2, 14, %22#00ff00%22);%0A %7D %0A%7D%0A%0Aexpo
db3a7bce8e7303295cfdf2ff3c6f54e515e889f6
make text alignment customizable for a text node
src/components/TextNode/TextNode.js
src/components/TextNode/TextNode.js
import React from 'react' const ESCAPE_KEY = 27; const ENTER_KEY = 13; function safeGetData (field, data, node) { const source = data || [] const datum = source[(node.text.rank || 1) - 1] || {} return datum[field] || '' } class TextNode extends React.Component { static propTypes = { node: React.PropTypes.object.isRequired, data: React.PropTypes.array, setProperty: React.PropTypes.func } state = { editText: this.textValue() } textValue () { const { node, data } = this.props const type = node.text.type || 'static' return type === 'static' ? node.text.value : safeGetData(node.text.field, data, node) } onDoubleClick (e) { e.preventDefault(); this.refs.label.style.display = 'none'; this.refs.input.style.display = 'block'; this.refs.input.focus(); } commit () { const { node, setProperty } = this.props this.refs.label.style.display = 'block'; this.refs.input.style.display = 'none'; setProperty(node.id, 'text', {value: this.refs.input.value}) } handleKeyDown (e) { if (e.which === ESCAPE_KEY || e.which === ENTER_KEY) { this.commit(); } } onBlur (e) { e.preventDefault(); this.commit(); } handleChange (e) { this.setState({editText: e.target.value}); } render () { const { node } = this.props const style = { fontFamily: node.font.value, fontWeight: node.weight.value, color: node.color.value, fontSize: node.size.value } return <div style={style}> <div onDoubleClick={::this.onDoubleClick} ref='label'> {this.state.editText} </div> <input type='text' ref='input' style={{ display: 'none' }} onBlur={::this.onBlur} onChange={::this.handleChange} onKeyDown={::this.handleKeyDown} value={this.state.editText} /> </div> } } module.exports = TextNode
JavaScript
0
@@ -1339,32 +1339,33 @@ %7D = this.props%0A +%0A const style @@ -1498,24 +1498,63 @@ e.size.value +,%0A textAlign: node.textAlign.value %0A %7D%0A%0A
eeb4bfa1f8431c394934224210643e31446cb88a
Fix error page loading
src/mmw/js/src/core/error/handlers.js
src/mmw/js/src/core/error/handlers.js
"use strict"; var router = require('../../router').router, modalModels = require('../modals/models'), modalViews = require('../modals/views'), App = require('../../app'); var ErrorHandlers = { itsi: function() { router.navigate(''); var alertView = new modalViews.AlertView({ model: new modalModels.AlertModel({ alertMessage: "We're sorry, but there was an error logging you in with your" + " ITSI credentials. Please log in using another method or" + " continue as a guest.", alertType: modalModels.AlertTypes.error }) }); alertView.render(); App.showLoginModal(); }, hydroshareNotFound: function() { router.navigate(''); var alertView = new modalViews.AlertView({ model: new modalModels.AlertModel({ alertMessage: "We're sorry, but we couldn't find a project corresponding " + "to that HydroShare Resource. If accessing a public resource, " + "please make sure it has an <code>mmw_project_snapshot.json</code> file. " + "If accessing a private resource, please make sure you link your " + "WikiWatershed account to HydroShare in your Account Settings.", alertType: modalModels.AlertTypes.error }) }); alertView.render(); }, generic: function(type) { router.navigate(''); var alertView = new modalViews.AlertView({ model: new modalModels.AlertModel({ alertMessage: "We're sorry, but an error occurred in the application.", alertType: modalModels.AlertTypes.error }) }); alertView.render(); console.log("[MMW] An unknown error occurred: " + type); } }; module.exports = { ErrorHandlers: ErrorHandlers };
JavaScript
0
@@ -241,32 +241,51 @@ uter.navigate('' +, %7B trigger: true %7D );%0A var a @@ -812,32 +812,51 @@ uter.navigate('' +, %7B trigger: true %7D );%0A var a @@ -1587,16 +1587,35 @@ igate('' +, %7B trigger: true %7D );%0A
a7d4613b1fd9bb64e767bc1582fc185ff01aafbf
Modify end in delay story to capture completion
src/models/emissions/index.stories.js
src/models/emissions/index.stories.js
import React from 'react' import { storiesOf } from '@kadira/storybook' import { distinctUntilChanged } from 'rxjs/operator/distinctUntilChanged' import { map } from 'rxjs/operator/map' import { first } from 'rxjs/operator/first' import { delay } from 'rxjs/operator/delay' import { combineLatest } from 'rxjs/observable/combineLatest' import { scan } from 'rxjs/operator/scan' import ObservableRenderer from '../../components/ObservableRenderer' import { transformEmissions } from './index' import { EmissionsView } from '../../components/observable' storiesOf('Emissions', module) .add('.distinctUntilChanged()', () => { const width = 80 const input = [ { x: 5, d: 1 }, { x: 20, d: 2 }, { x: 35, d: 2 }, { x: 60, d: 1 }, { x: 70, d: 3 } ] const output = transformEmissions( obs => obs::distinctUntilChanged(), width, input ) return ( <div> <EmissionsView emissions={input} end={width} completion={width} /> <ObservableRenderer source={output} transform={({ emissions, completion }) => ( <EmissionsView emissions={emissions} end={width} completion={completion} /> )} /> </div> ) }) .add('.map(x => x * 10)', () => { const width = 80 const input = [ { x: 5, d: 1 }, { x: 20, d: 2 }, { x: 35, d: 2 }, { x: 60, d: 1 }, { x: 70, d: 3 } ] const output = transformEmissions( obs => obs::map(x => x * 10), width, input ) return ( <div> <EmissionsView emissions={input} end={width} completion={width} /> <ObservableRenderer source={output} transform={({ emissions, completion }) => ( <EmissionsView emissions={emissions} end={width} completion={completion} /> )} /> </div> ) }) .add('.first()', () => { const width = 80 const input = [ { x: 5, d: 1 }, { x: 20, d: 2 }, { x: 35, d: 2 }, { x: 60, d: 1 }, { x: 70, d: 3 } ] const output = transformEmissions( obs => obs::first(), width, input ) return ( <div> <EmissionsView emissions={input} end={width} completion={width} /> <ObservableRenderer source={output} transform={({ emissions, completion }) => ( <EmissionsView emissions={emissions} end={width} completion={completion} /> )} /> </div> ) }) .add('.delay(5)', () => { const width = 80 const input = [ { x: 5, d: 1 }, { x: 20, d: 2 }, { x: 35, d: 2 }, { x: 60, d: 1 }, { x: 70, d: 3 } ] const output = transformEmissions( (obs, scheduler) => obs::delay(5, scheduler), width, input ) return ( <div> <EmissionsView emissions={input} end={width} completion={width} /> <ObservableRenderer source={output} transform={({ emissions, completion }) => ( <EmissionsView emissions={emissions} end={width} completion={completion} /> )} /> </div> ) }) .add('.combineLatest((x, y) => `${x}${y}`)', () => { const width = 80 const inputA = [ { x: 5, d: 1 }, { x: 20, d: 2 }, { x: 35, d: 3 }, { x: 60, d: 4 }, { x: 70, d: 5 } ] const inputB = [ { x: 5, d: 'A' }, { x: 28, d: 'B' }, { x: 35, d: 'C' }, { x: 45, d: 'D' }, { x: 70, d: 'E' } ] const output = transformEmissions( (a, b, scheduler) => combineLatest(a, b, (x, y) => `${x}${y}`, scheduler), width, inputA, inputB ) return ( <div> <EmissionsView emissions={inputA} end={width} completion={width} /> <EmissionsView emissions={inputB} end={width} completion={width} /> <ObservableRenderer source={output} transform={({ emissions, completion }) => ( <EmissionsView emissions={emissions} end={width} completion={completion} /> )} /> </div> ) }) .add('.scan((acc, d) => acc + d)', () => { const width = 80 const input = [ { x: 5, d: 1 }, { x: 20, d: 2 }, { x: 35, d: 3 }, { x: 60, d: 4 }, { x: 70, d: 5 } ] const reducer = (acc, d) => acc + d const output = transformEmissions( obs => obs::scan((acc, d) => acc + d), width, input ) return ( <div> <EmissionsView emissions={input} end={width} completion={width} /> <ObservableRenderer source={output} transform={({ emissions, completion }) => ( <EmissionsView emissions={emissions} end={width} completion={completion} /> )} /> </div> ) })
JavaScript
0
@@ -3195,32 +3195,36 @@ end=%7Bwidth + + 5 %7D%0A comp @@ -3437,32 +3437,36 @@ end=%7Bwidth + + 5 %7D%0A
976b5acd959c2ea4af016e9038fce27449d33eba
Add program filter to student classroom request
src/modules/students/actions/index.js
src/modules/students/actions/index.js
import { browserHistory } from 'react-router'; import fetch from 'isomorphic-fetch'; import apiClient from 'panoptes-client/lib/api-client'; import { saveAs } from 'browser-filesaver'; const mapConfig = require('../../../constants/mapExplorer.config.json'); import config from '../../../constants/config'; import * as types from '../../../constants/actionTypes'; // Action creators export function joinClassroom(id, token) { return dispatch => { dispatch({ type: types.JOIN_CLASSROOM }); return fetch(config.eduAPI.root + config.eduAPI.students + id + '/join', { method: 'POST', mode: 'cors', headers: new Headers({ 'Authorization': apiClient.headers.Authorization, 'Content-Type': 'application/json', }), body: JSON.stringify({'join_token': token}) }) .then(response => { if (response.status < 200 || response.status > 202) { return null; } return response.json(); }) .then(json => { if (json && json.data) { dispatch({ type: types.JOIN_CLASSROOM_SUCCESS, data: json.data, members: json.included }); } else { dispatch({ type: types.JOIN_CLASSROOM_ERROR }); } }) .then(() => browserHistory.push('/students/')) .catch(response => console.log('RESPONSE-error: ', response)); }; } export function fetchStudentClassrooms() { return dispatch => { dispatch({ type: types.REQUEST_STUDENT_CLASSROOMS, }); return fetch(config.eduAPI.root + config.eduAPI.students, { method: 'GET', mode: 'cors', headers: new Headers({ 'Authorization': apiClient.headers.Authorization, 'Content-Type': 'application/json' }) }) .then(response => response.json()) .then(json => dispatch({ type: types.RECEIVE_STUDENT_CLASSROOMS, data: json.data, error: false, members: json.included, })) .catch(response => dispatch({ type: types.RECEIVE_STUDENT_CLASSROOMS, data: [], error: true, }) ); } } export function fetchStudentAssignments() { return dispatch => { dispatch({ type: types.REQUEST_ASSIGNMENTS, }); return fetch(config.eduAPI.root + config.eduAPI.assignments, { method: 'GET', mode: 'cors', headers: new Headers({ 'Authorization': apiClient.headers.Authorization, 'Content-Type': 'application/json' }) }) .then(response => response.json()) .then(json => dispatch({ type: types.RECEIVE_ASSIGNMENTS, data: json.data, student_data: json.included, })) .catch(response => dispatch({ type: types.RECEIVE_ASSIGNMENTS_ERROR, data: [], student_data: [], })); } }
JavaScript
0
@@ -1565,24 +1565,67 @@ API.students + + %60?program_id=$%7Bconfig.eduAPI.programId%7D%60 , %7B%0A me
d1239113399430e181e709fe9fc2700931465c70
update header
imports/ui/components/header/header.js
imports/ui/components/header/header.js
import { Meteor } from 'meteor/meteor'; import './header.html'; Template.header.helpers({ }); Template.header.events({ 'mouseenter #products'(event, instance) { $('.products').slideDown( "slow"); }, 'mouseenter #downloads'(event, instance) { $('.downloads').slideDown( "slow"); }, 'mouseenter #applications'(event, instance) { $('.project').slideDown( "slow"); }, 'mouseenter #project'(event, instance) { $('.project').slideDown( "slow"); }, 'mouseenter #freeware'(event, instance) { $('.freeware').slideDown( "slow"); }, //leave mouse 'mouseleave #products'(event, instance) { $('.cbp-hrsub').hide(); }, 'mouseleave #downloads'(event, instance) { $('.cbp-hrsub').hide(); }, 'mouseleave #project'(event, instance) { $('.cbp-hrsub').hide(); }, 'mouseleave #applications'(event, instance) { $('.cbp-hrsub').hide(); }, 'mouseleave #freeware'(event, instance) { $('.cbp-hrsub').hide(); } });
JavaScript
0.000001
@@ -189,39 +189,35 @@ cts').slideDown( - %22slow%22 +300 );%0A %7D,%0A 'm @@ -283,39 +283,35 @@ ads').slideDown( - %22slow%22 +300 );%0A %7D,%0A 'm @@ -378,39 +378,35 @@ ect').slideDown( - %22slow%22 +300 );%0A %7D,%0A 'm @@ -468,39 +468,35 @@ ect').slideDown( - %22slow%22 +300 );%0A %7D,%0A 'm @@ -572,15 +572,11 @@ own( - %22slow%22 +300 );%0A
431dfc62c608289eef170118288189bd693e6b99
add value check
plugins/gui/frontend/gosa/source/class/gosa/ui/form/WindowListItem.js
plugins/gui/frontend/gosa/source/class/gosa/ui/form/WindowListItem.js
/* * This file is part of the GOsa project - http://gosa-project.org * * Copyright: * (C) 2010-2017 GONICUS GmbH, Germany, http://www.gonicus.de * * License: * LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html * * See the LICENSE file in the project's top-level directory for details. */ qx.Class.define("gosa.ui.form.WindowListItem", { extend: qx.ui.form.ListItem, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function(label, icon, model) { this.base(arguments, label, icon, model); this.addListener("tap", function() { this.getWindow().setActive(true); }, this); }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { appearance : { refine : true, init : "gosa-listitem-window" }, window: { check: "qx.ui.window.Window", nullable: true }, object: { check: "Object", nullable: true, apply: "_applyObject" }, selected: { check: "Boolean", init: false, apply: "_applySelected" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { // property apply _applySelected: function(value) { if (value) { this.addState("selected"); } else { this.removeState("selected"); } }, // property apply _applyObject: function(object) { if (object) { if (object instanceof gosa.ui.form.WorkflowItem) { object.bind("label", this, "label"); object.bind("icon", this, "icon", { converter : function(value) { return value.startsWith("@") ? value : "/workflow/" + object.getId() + "/32/" + value; } }); } else if (!object.uuid) { // new object this.setLabel(object.baseType+"*"); this.setIcon(gosa.util.Icons.getIconByType(object.baseType, 22)); } else { // we need to break out of the property apply chain to allow promises to be used // otherwise we get a warning about a created but not returned promise new qx.util.DeferredCall(function() { // try to get the search result for this dn, to get the mapped title/icon values gosa.io.Rpc.getInstance().cA("getObjectSearchItem", object.dn) .then(function(result) { this.setLabel(result.title); this.setIcon(result.icon ? result.icon : gosa.util.Icons.getIconByType(result.tag, 22)); }, this) .catch(function(error) { this.error(error); // fallback var dnPart = qx.util.StringSplit.split(qx.util.StringSplit.split(object.dn, "\,")[0], "=")[1]; this.setLabel(dnPart); }, this); }, this).schedule(); } } } } });
JavaScript
0.000001
@@ -2004,16 +2004,26 @@ return + !value %7C%7C value.s
44641dee7b85667bd8603a1d42d86087a7a4e3cf
Update news after schedule
app/updateChannel.js
app/updateChannel.js
'use strict' const TelegramBot = require('node-telegram-bot-api'); const config = require('../config'); const utils = require('./utils'); const Kinospartak = require('./Kinospartak/Kinospartak'); const bot = new TelegramBot(config.TOKEN); const kinospartak = new Kinospartak(); /** * updateSchedule - update schedule and push updates to Telegram channel * * @return {Promise} */ function updateSchedule() { return kinospartak.getChanges() .then(changes => changes.length ? utils.formatSchedule(changes) : Promise.reject('No changes')) .then(messages => utils.sendInOrder(bot, config.CHANNEL, messages)) .then(() => kinospartak.commitChanges()) }; /** * updateNews - update news and push updates to Telegram channel * * @return {Promise} */ function updateNews() { return kinospartak.getLatestNews() .then(news => news.length ? utils.formatNews(news) : Promise.reject('No news')) .then(messages => utils.sendInOrder(bot, config.CHANNEL, messages)) .then(() => kinospartak.setNewsOffset(new Date().toString())) }; Promise.all([ updateSchedule(), updateNews() ]).catch(error => console.error(error))
JavaScript
0
@@ -1080,24 +1080,8 @@ %7D;%0A%0A -Promise.all(%5B%0A upda @@ -1096,61 +1096,33 @@ le() -, %0A -updateNews()%0A%5D).catch(error =%3E console.error(error +.then(() =%3E updateNews( ))%0A
9b66d3c1f73faa8153cb1e20c8693b1601e4fd16
change walking time calculations
app/utils/helpers.js
app/utils/helpers.js
var helpers = { shuffle(array, start) { var m = array.length, t, i; start = start || 0; while (m > start) { i = Math.floor(Math.random()*(--m - start+1)+start); t = array[m]; array[m] = array[i]; array[i] = t; } return array; }, getRandomDate(start, end) { return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); }, formatNameString(string) { return string.replace(/\s+/g,'-').toLowerCase(); }, formatIdString(string) { return string.replace(/-/g,' ').toLowerCase().replace(/\b\w/g, function (m) { return m.toUpperCase(); }); }, getRadians(deg) { return deg * Math.PI / 180; }, getDegrees(rad) { return rad * 180 / Math.PI; }, metersToMiles(m) { return m * 0.00062137; }, kilometersToMiles(km) { return km * 0.621371; }, milesToKilometers(m) { return m * 1.60934; }, milesToMins(m) { // 1 mile ~ 15 mins var mins = Math.round(m * 15); if( mins === 0 ) { return '<1'; } return mins; } }; export default helpers;
JavaScript
0.000002
@@ -949,17 +949,17 @@ mile ~ 1 -5 +0 mins%0A @@ -991,9 +991,9 @@ * 1 -5 +0 );%0A%0A
e1ce4dc1373171f72b78ac213a5393b1d523bc4f
Add jsdoc comment to formatter
sources/formatter.js
sources/formatter.js
/* =================================================== * JavaScript 2ch-client Library * https://github.com/sh19910711/js2ch * =================================================== * Copyright (c) 2013 Hiroyuki Sano * * Licensed under MIT License. * http://opensource.org/licenses/MIT * =================================================== */ (function() { define([ 'underscore' ], function(_) { var Formatter = function() {}; Formatter.prototype = {}; var proto = _(Formatter.prototype); proto.extend({ // 与えられたオブジェクトを何らかの形に整える(デバッグ出力などで利用) format: function format(obj) { // TODO: 種類に合わせて分岐、普通のオブジェクトのときはそのまま返す return obj; } }); return new Formatter(); }); }) .call(this);
JavaScript
0
@@ -341,16 +341,93 @@ ==== */%0A +/**%0A * @fileOverview %E4%B8%8E%E3%81%88%E3%82%89%E3%82%8C%E3%81%9F%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E3%82%92%E4%BD%95%E3%82%89%E3%81%8B%E3%81%AE%E5%BD%A2%E3%81%AB%E6%95%B4%E3%81%88%E3%82%8B%E3%83%A9%E3%82%A4%E3%83%96%E3%83%A9%E3%83%AA%0A * @author Hiroyuki Sano%0A */%0A (functio @@ -475,24 +475,70 @@ nction(_) %7B%0A + /**%0A * @constructor Formatter%0A */%0A var Form @@ -658,17 +658,46 @@ %0A / -/ +**%0A * @description %5B%E6%9C%AA%E5%AE%9F%E8%A3%85%5D %E4%B8%8E%E3%81%88%E3%82%89%E3%82%8C%E3%81%9F%E3%82%AA%E3%83%96 @@ -724,16 +724,168 @@ %E5%8A%9B%E3%81%AA%E3%81%A9%E3%81%A7%E5%88%A9%E7%94%A8%EF%BC%89%0A + * @memberof Formatter%0A *%0A * @param %7BObject%7D obj%0A * %E5%A4%89%E6%8F%9B%E3%81%97%E3%81%9F%E3%81%84%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%0A * @return %7BObject%7D%0A * %E4%BD%95%E3%82%89%E3%81%8B%E3%81%AE%E5%BD%A2%E5%BC%8F%E3%81%AB%E5%A4%89%E6%8F%9B%E3%81%95%E3%82%8C%E3%81%9F%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%0A */%0A fo
0008b453ac8798917e6dba3081a0da84564ad9da
Fix loop behavior
src/components/core/loop/loopFix.js
src/components/core/loop/loopFix.js
export default function () { const swiper = this; const { params, activeIndex, slides, loopedSlides, allowSlidePrev, allowSlideNext, snapGrid, rtlTranslate: rtl, } = swiper; let newIndex; swiper.allowSlidePrev = true; swiper.allowSlideNext = true; const snapTranslate = -snapGrid[activeIndex]; const diff = snapTranslate - swiper.getTranslate(); // Fix For Negative Oversliding if (activeIndex < loopedSlides) { newIndex = (slides.length - (loopedSlides * 3)) + activeIndex; newIndex += loopedSlides; const slideChanged = swiper.slideTo(newIndex, 0, false, true); if (slideChanged && diff !== 0) { swiper.setTranslate((rtl ? -swiper.translate : swiper.translate) - diff); } } else if ((params.slidesPerView === 'auto' && activeIndex >= loopedSlides * 2) || (activeIndex > slides.length - (params.slidesPerView * 2))) { // Fix For Positive Oversliding newIndex = -slides.length + activeIndex + loopedSlides; newIndex += loopedSlides; const slideChanged = swiper.slideTo(newIndex, 0, false, true); if (slideChanged && diff !== 0) { swiper.setTranslate((rtl ? -swiper.translate : swiper.translate) - diff); } } swiper.allowSlidePrev = allowSlidePrev; swiper.allowSlideNext = allowSlideNext; }
JavaScript
0.000002
@@ -819,16 +819,17 @@ eIndex %3E += slides. @@ -841,34 +841,20 @@ h - -(params.slidesPerView * 2) +loopedSlides )) %7B
e071d3283a6bada83ab79b3cb074133f1eb45c86
add focus to text input
src/components/fields/Text/index.js
src/components/fields/Text/index.js
import React from 'react' import PropTypes from 'prop-types' export default class Text extends React.Component { static propTypes = { onChange: PropTypes.func, value: PropTypes.string, fieldType: PropTypes.string, passProps: PropTypes.object, placeholder: PropTypes.node, errorMessage: PropTypes.node, disabled: PropTypes.bool, label: PropTypes.node, description: PropTypes.node, onEnter: PropTypes.func } static defaultProps = { fieldType: 'text', value: '', onEnter: () => {} } handleKeyDown = event => { if (event.key === 'Enter') { this.props.onEnter() } } render() { return ( <div> <div className="label">{this.props.label}</div> <div className="os-input-container"> <input ref="input" className="os-input-text" type={this.props.fieldType} value={this.props.value || ''} placeholder={this.props.placeholder} onChange={event => this.props.onChange(event.target.value)} disabled={this.props.disabled} onKeyDown={this.handleKeyDown} {...this.props.passProps} /> </div> <div className="description">{this.props.description}</div> <div className="os-input-error">{this.props.errorMessage}</div> </div> ) } }
JavaScript
0.000005
@@ -636,16 +636,67 @@ %7D%0A %7D%0A%0A + focus = () =%3E %7B%0A this.refs.input.focus()%0A %7D%0A%0A render
f5d273798476278ab2d06c83bb01646cc5fb56b1
Update namespace
lib/node_modules/@stdlib/simulate/iter/lib/index.js
lib/node_modules/@stdlib/simulate/iter/lib/index.js
/** * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace ns */ var ns = {}; /** * @name iterawgn * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/simulate/iter/awgn} */ setReadOnly( ns, 'iterawgn', require( '@stdlib/simulate/iter/awgn' ) ); /** * @name iterawln * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/simulate/iter/awln} */ setReadOnly( ns, 'iterawln', require( '@stdlib/simulate/iter/awln' ) ); /** * @name iterawun * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/simulate/iter/awun} */ setReadOnly( ns, 'iterawun', require( '@stdlib/simulate/iter/awun' ) ); /** * @name iterCosineWave * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/simulate/iter/cosine-wave} */ setReadOnly( ns, 'iterCosineWave', require( '@stdlib/simulate/iter/cosine-wave' ) ); /** * @name iterDiracComb * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/simulate/iter/dirac-comb} */ setReadOnly( ns, 'iterDiracComb', require( '@stdlib/simulate/iter/dirac-comb' ) ); /** * @name iterPulseWave * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/simulate/iter/pulse-wave} */ setReadOnly( ns, 'iterPulseWave', require( '@stdlib/simulate/iter/pulse-wave' ) ); /** * @name iterSawtoothWave * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/simulate/iter/sawtooth-wave} */ setReadOnly( ns, 'iterSawtoothWave', require( '@stdlib/simulate/iter/sawtooth-wave' ) ); /** * @name iterSineWave * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/simulate/iter/sine-wave} */ setReadOnly( ns, 'iterSineWave', require( '@stdlib/simulate/iter/sine-wave' ) ); /** * @name iterSquareWave * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/simulate/iter/square-wave} */ setReadOnly( ns, 'iterSquareWave', require( '@stdlib/simulate/iter/square-wave' ) ); /** * @name iterTriangleWave * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/simulate/iter/triangle-wave} */ setReadOnly( ns, 'iterTriangleWave', require( '@stdlib/simulate/iter/triangle-wave' ) ); // EXPORTS // module.exports = ns;
JavaScript
0.000001
@@ -1911,32 +1911,258 @@ rac-comb' ) );%0A%0A +/**%0A* @name iterPeriodicSinc%0A* @memberof ns%0A* @readonly%0A* @type %7BFunction%7D%0A* @see %7B@link module:@stdlib/simulate/iter/periodic-sinc%7D%0A*/%0AsetReadOnly( ns, 'iterPeriodicSinc', require( '@stdlib/simulate/iter/periodic-sinc' ) );%0A%0A /**%0A* @name iter
8223c983096f2a4f714001024541430ad57f6b38
Set contrib-type during authors exporting.
src/converter/r2t/ConvertAuthors.js
src/converter/r2t/ConvertAuthors.js
import { OrganisationConverter, PersonConverter } from './EntityConverters' import { expandContribGroup, removeEmptyElementsIfNoChildren } from './r2tHelpers' export default class ConvertAuthors { import(dom, api) { const pubMetaDb = api.pubMetaDb expandContribGroup(dom, 'author') expandContribGroup(dom, 'editor') const affs = dom.findAll('article-meta > aff') // Convert <aff> elements to organisation entities affs.forEach(aff => { let entityId = OrganisationConverter.import(aff, pubMetaDb) aff.setAttribute('rid', entityId) aff.empty() }) // Convert contrib elements to person entities _importPersons(dom, pubMetaDb, 'author') _importPersons(dom, pubMetaDb, 'editor') _importPersons(dom, pubMetaDb, 'inventor') _importPersons(dom, pubMetaDb, 'sponsor') } export(dom, api) { const $$ = dom.createElement.bind(dom) const pubMetaDb = api.pubMetaDb // NOTE: We must export authors and editors first, as otherwise we'd be // loosing the relationship of internal aff ids and global org ids. _exportPersons($$, dom, pubMetaDb, 'author') _exportPersons($$, dom, pubMetaDb, 'editor') _exportPersons($$, dom, pubMetaDb, 'inventor') _exportPersons($$, dom, pubMetaDb, 'sponsor') const affs = dom.findAll('article-meta > aff') affs.forEach(aff => { let entity = pubMetaDb.get(aff.attr('rid')) let newAffEl = OrganisationConverter.export($$, entity, pubMetaDb) // We want to keep the original document-specific id, and just assign // the element's content. aff.innerHTML = newAffEl.innerHTML aff.removeAttr('rid') }) // Remove all empty contrib-groups as they are not valid JATS removeEmptyElementsIfNoChildren(dom, 'contrib-group') } } function _importPersons(dom, pubMetaDb, type) { let contribGroup = dom.find(`contrib-group[content-type=${type}]`) if(contribGroup === null) return let contribs = contribGroup.findAll('contrib') contribs.forEach(contrib => { // TODO: detect group authors and use special GroupAuthorConverter let entityId = PersonConverter.import(contrib, pubMetaDb) contrib.setAttribute('rid', entityId) contrib.empty() }) } function _exportPersons($$, dom, pubMetaDb, type) { let contribGroup = dom.find(`contrib-group[content-type=${type}]`) if(contribGroup === null) return let contribs = contribGroup.findAll('contrib') contribs.forEach(contrib => { let node = pubMetaDb.get(contrib.attr('rid')) // TODO: detect group authors and use special GroupAuthorConverter let newContribEl = PersonConverter.export($$, node, pubMetaDb) contrib.innerHTML = newContribEl.innerHTML contrib.removeAttr('rid') }) }
JavaScript
0
@@ -2698,24 +2698,75 @@ l.innerHTML%0A + contrib.setAttribute('contrib-type', 'person')%0A contrib.
f76c38ecaa368810daa01f84dcc5a39705f7e639
Remove rest of navigation usages
src/Oro/Bundle/ReminderBundle/Resources/public/js/reminder-handler.js
src/Oro/Bundle/ReminderBundle/Resources/public/js/reminder-handler.js
/*global define*/ define( ['jquery', 'orosync/js/sync', 'oroui/js/messenger', 'routing', 'underscore', 'oronavigation/js/navigation', 'oroui/js/mediator'], function ($, sync, messenger, routing, _, Navigation, mediator) { /** * @export ororeminder/js/reminder-handler * @class ororeminder.ReminderHandler */ return { removeDates: {}, reminders: {}, /** * Initialize event listening * * @param {integer} id Current user id * @param {Boolean} wampEnable Is WAMP enabled */ init: function (id, wampEnable) { var self = this; mediator.on('page-rendered page:afterChange', function () { self.showReminders(); }); if (wampEnable) { this.initWamp(id); } }, /** * Initialize WAMP subscribing * * @param {integer} id Current user id */ initWamp: function (id) { var self = this; sync.subscribe('oro/reminder/remind_user_' + id, function (data) { var reminders = JSON.parse(data); self.addReminders(reminders); self.showReminders(); }); }, /** * Set reminders * * @param {Array} reminders */ setReminders: function (reminders) { var self = this; this.reminders = {}; _.each(reminders, function (reminder) { self.addReminder(reminder); }); }, /** * Add reminders * * @param {Array} reminders */ addReminders: function (reminders) { var self = this; _.each(reminders, function (reminder) { self.addReminder(reminder); }); }, /** * Add reminder * * @param {Object} newReminder */ addReminder: function (newReminder) { var uniqueId = newReminder.uniqueId; var newId = newReminder.id; var oldReminder = this.reminders[uniqueId]; if (!oldReminder) { var removeDate = this.removeDates[uniqueId]; var currentDate = new Date(); // If was already removed less then 60 secs ago, ignore it if (removeDate && currentDate.getTime() - removeDate.getTime() < 60000) { return; } this.reminders[uniqueId] = newReminder; } else if (oldReminder.id != newId) { oldReminder.duplicateIds = oldReminder.duplicateIds || []; if (_.indexOf(oldReminder.duplicateIds, newId)) { oldReminder.duplicateIds.push(newId); } } }, /** * Remove reminder by uinque id * * @param {integer} uniqueId */ removeReminder: function (uniqueId) { var reminder = this.reminders[uniqueId]; if (!reminder) { return; } var url = routing.generate('oro_api_post_reminder_shown'); var removeIds = reminder.duplicateIds || []; removeIds.push(reminder.id); $.post(url, { 'ids': removeIds }); this.removeDates[uniqueId] = new Date(); delete this.reminders[uniqueId]; }, /** * Show reminders */ showReminders: function () { var self = this; // Remove all reminders $('.alert-reminder').remove(); _.each(this.reminders, function (reminder, uniqueId) { var message = this.getReminderMessage(reminder); message += '(<a class="reminder-dismiss-link" data-id="' + reminder.id + '" data-unique-id="' + reminder.uniqueId + '" href="javascript:void(0);">dismiss</a>)'; var actions = messenger.notificationFlashMessage('reminder', message, {delay: false, flash: false}); var data = { actions: actions, uniqueId: uniqueId }; $('.reminder-dismiss-link[data-id="' + reminder.id + '"]') .bind('click', data, function (event) { self.removeReminder(event.data.uniqueId); event.data.actions.close(); }); }, this); var navigation = Navigation.getInstance(); $('.alert-reminder .close').unbind('click').bind('click', function () { $(this).parents('.alert-reminder').find('.reminders_dismiss_link').click(); }); $('.alert-reminder .hash-navigation-link').unbind('click').bind('click', function (event) { event.preventDefault(); var url = $(this).attr('href'); navigation.setLocation(url); }); }, /** * @param {object} reminder * @returns {string} */ getReminderMessage: function (reminder) { var message = ''; try { message = '<i class="icon-bell"></i>'; var template = $('.reminder_templates[data-identifier="' + reminder.templateId + '"]').html(); if ($.trim(template) == '') { template = $('.reminder_templates[data-identifier="default"]').html(); } message += _.template(template, reminder); } catch (ex) { // Suppress possible exceptions during template processing if (console && (typeof console.log === 'function')) { console.log('Exception occurred when compiling reminder template', ex); } } return message; } }; });
JavaScript
0
@@ -103,43 +103,8 @@ re', - 'oronavigation/js/navigation',%0A 'or @@ -171,20 +171,8 @@ , _, - Navigation, med @@ -4945,68 +4945,8 @@ );%0A%0A - var navigation = Navigation.getInstance();%0A%0A @@ -5374,34 +5374,49 @@ -navigation.setLocation(url +mediator.execute('redirectTo', %7Burl: url%7D );%0A
91b1726012a17cfffb0947a604e79aeb8c5be73b
Fix logLevel reference
src-server/logger.js
src-server/logger.js
import _ from "lodash"; import Emitter from "eventemitter3"; import util from "util"; const logLevel = { "silly" : { level: 0, logger: console.log.bind(console), label: "\u001b[37m[%s] \u001b[m", color: "\u001b[37m", }, "verbose" : { level: 1, logger: console.log.bind(console), label: "[%s] ", color: "", }, "info" : { level: 3, logger: console.info.bind(console), label: "\u001b[36;1m[%s] \u001b[m", color: "\u001b[36m", }, "debug" : { level: 2, logger: console.info.bind(console), label: "\u001b[32;1m[%s] \u001b[m", color: "\u001b[32m", }, "warn" : { level: 4, logger: console.error.bind(console), label: "\u001b[33;1m[%s] \u001b[m", color: "\u001b[33m", }, "error" : { level: 5, logger: console.error.bind(console), label: "\u001b[31;1m[%s] \u001b[m", color: "\u001b[31m", }, }; export default class Logger extends Emitter { static get logLevel() { return logLevel; } /** * @class Logger * @constructor * @param {Object} options * @param {Object} options.logLevel logging level (log specified level or more) */ constructor(options) { super(); this.options = _.defaults({}, options, { logLevel : logLevel.info }); Object.keys(logLevel).forEach((logType) => { const logger = logLevel[logType].logger; const labeler = logLevel[logType].label; const color = logLevel[logType].color; const level = logLevel[logType].level; this[logType] = (label, message, ...more) => { if (level < this.options.logLevel) { return; } const logLabel = util.format(labeler, label); const plainMessage = util.format(message, ...more); const logMessage = color + plainMessage + "\u001b[m"; logger(logLabel + logMessage); this.emit("log", { type: logType, level, label: label, message : plainMessage }); }; }); } setLogLevel(level) { if (typeof level === "string") { this.options.logLevel = logLevel[level]; } else if (typeof level === "number") { this.options.logLevel = level; } } }
JavaScript
0.000001
@@ -1451,16 +1451,22 @@ vel.info +.level %0A
64f19b65ec411b4d7f4e13c15513b85a17b8dbaa
Remove attributes param
test/acceptance/user-render-timeout-limit.js
test/acceptance/user-render-timeout-limit.js
require('../support/test_helper'); const assert = require('../support/assert'); const TestClient = require('../support/test-client'); const timeoutErrorTilePath = `${process.cwd()}/assets/render-timeout-fallback.png`; const pointSleepSql = ` SELECT pg_sleep(0.5), 'SRID=3857;POINT(0 0)'::geometry the_geom_webmercator, 1 cartodb_id, 2 val `; // during instatiation we validate tile 30/0/0, creating a point in that tile `pg_sleep` will throw a timeout const validationPointSleepSql = ` SELECT pg_sleep(0.5), ST_Transform('SRID=4326;POINT(-180 85.05112877)'::geometry, 3857) the_geom_webmercator, 1 cartodb_id, 2 val `; const createMapConfig = ({ version = '1.6.0', type = 'cartodb', sql = pointSleepSql, cartocss = TestClient.CARTOCSS.POINTS, cartocss_version = '2.3.0', interactivity = 'cartodb_id', countBy = 'cartodb_id', attributes } = {}) => ({ version, layers: [{ type, options: { source: { id: 'a0' }, cartocss, cartocss_version, interactivity, attributes } }], analyses: [ { id: 'a0', type: 'source', params: { query: sql } } ], dataviews: { count: { source: { id: 'a0' }, type: 'formula', options: { column: countBy, operation: 'count' } } } }); describe('user render timeout limit', function () { describe('map instantiation => validation', function () { beforeEach(function (done) { const mapconfig = createMapConfig({ sql: validationPointSleepSql }); this.testClient = new TestClient(mapconfig, 1234); this.testClient.setUserRenderTimeoutLimit('localhost', 50, done); }); afterEach(function (done) { this.testClient.setUserRenderTimeoutLimit('localhost', 0, (err) => { if (err) { return done(err); } this.testClient.drain(done); }); }); it('layergroup creation fails due to statement timeout', function (done) { const expectedResponse = { status: 400, headers: { 'Content-Type': 'application/json; charset=utf-8' } }; this.testClient.getLayergroup(expectedResponse, (err, timeoutError) => { assert.ifError(err); assert.deepEqual(timeoutError, { errors: ["Render timed out"], errors_with_context: [{ type: "layer", message: "Render timed out", layer: { id: "layer0", index: 0, type: "mapnik" } }] }); done(); }); }); }); describe('raster', function () { describe('with onTileErrorStrategy ENABLED', function () { let onTileErrorStrategy; beforeEach(function (done) { onTileErrorStrategy = global.environment.enabledFeatures.onTileErrorStrategy; global.environment.enabledFeatures.onTileErrorStrategy = true; const mapconfig = createMapConfig(); this.testClient = new TestClient(mapconfig, 1234); this.testClient.setUserRenderTimeoutLimit('localhost', 50, done); }); afterEach(function (done) { global.environment.enabledFeatures.onTileErrorStrategy = onTileErrorStrategy; this.testClient.setUserRenderTimeoutLimit('localhost', 0, (err) => { if (err) { return done(err); } this.testClient.drain(done); }); }); it('layergroup creation works but tile request fails due to render timeout', function (done) { this.testClient.getTile(0, 0, 0, {}, (err, res, tile) => { assert.ifError(err); assert.imageIsSimilarToFile(tile, timeoutErrorTilePath, 0.05, (err) => { assert.ifError(err); done(); }); }); }); }); describe('with onTileErrorStrategy DISABLED', function() { var onTileErrorStrategy; beforeEach(function (done) { onTileErrorStrategy = global.environment.enabledFeatures.onTileErrorStrategy; global.environment.enabledFeatures.onTileErrorStrategy = false; const mapconfig = createMapConfig(); this.testClient = new TestClient(mapconfig, 1234); this.testClient.setUserRenderTimeoutLimit('localhost', 50, done); }); afterEach(function (done) { global.environment.enabledFeatures.onTileErrorStrategy = onTileErrorStrategy; this.testClient.setUserRenderTimeoutLimit('localhost', 0, (err) => { if (err) { return done(err); } this.testClient.drain(done); }); }); it('layergroup creation works even if render tile is slow', function (done) { var params = { status: 400, contentType: 'application/json; charset=utf-8' }; this.testClient.getTile(0, 0, 0, params, (err, res, tile) => { assert.ifError(err); assert.equal(tile.errors[0], 'Render timed out'); done(); }); }); }); }); describe('vector', function () { beforeEach(function (done) { const mapconfig = createMapConfig(); this.testClient = new TestClient(mapconfig, 1234); this.testClient.setUserRenderTimeoutLimit('localhost', 50, done); }); afterEach(function (done) { this.testClient.setUserRenderTimeoutLimit('localhost', 0, (err) => { if (err) { return done(err); } this.testClient.drain(done); }); }); it('layergroup creation works but vector tile request fails due to render timeout', function (done) { const params = { format: 'mvt', status: 400 }; this.testClient.getTile(0, 0, 0, params, (err, res, tile) => { assert.ifError(err); assert.deepEqual(tile, { errors: ['Render timed out'], errors_with_context: [{ type: 'unknown', message: 'Render timed out' }] }); done(); }); }); }); describe('interativity', function () { beforeEach(function (done) { const mapconfig = createMapConfig(); this.testClient = new TestClient(mapconfig, 1234); this.testClient.setUserRenderTimeoutLimit('localhost', 50, done); }); afterEach(function (done) { this.testClient.setUserRenderTimeoutLimit('localhost', 0, (err) => { if (err) { return done(err); } this.testClient.drain(done); }); }); it('layergroup creation works but "grid.json" tile request fails due to render timeout', function (done) { const params = { layers: 'mapnik', format: 'grid.json', status: 400 }; this.testClient.getTile(0, 0, 0, params, (err, res, tile) => { assert.ifError(err); assert.deepEqual(tile, { errors: ['Render timed out'], errors_with_context: [{ type: 'unknown', message: 'Render timed out' }] }); done(); }); }); }); });
JavaScript
0.000002
@@ -925,24 +925,8 @@ _id' -,%0A attributes %0A%7D = @@ -1140,32 +1140,8 @@ vity -,%0A attributes %0A
8c36fe0f6cfe89e71a7ab81fda82d54ee4bf8ae5
Fix operator priorities issue
test/bin/node-scripts/GitHubMsgPublisher.es6
test/bin/node-scripts/GitHubMsgPublisher.es6
/** * Created by vcernomschi on 6/17/16. */ 'use strict'; import GitHubApi from 'github'; export default class GitHubMsgPublisher { /** * @returns {string} * @constructor */ static get isPullRequest() { let pullRequest = process.env['TRAVIS_PULL_REQUEST']; return (pullRequest !== 'false' || !isNaN(pullRequest)); } /** * @returns {string} * @constructor */ static get gitPRNumber() { return process.env['TRAVIS_PULL_REQUEST']; } /** * @returns {string} * @constructor */ static get gitPrUrl() { return `https://api.github.com/repos/${GitHubMsgPublisher.gitUser}/${GitHubMsgPublisher.gitRepoName}/pulls/${GitHubMsgPublisher.gitPRNumber}`; } /** * @returns {string} * @constructor */ static get gitUser() { return process.env['TRAVIS_REPO_SLUG'].replace(/(.*)\/.*/i, '$1'); } /** * @returns {string} * @constructor */ static get gitRepoName() { return process.env['TRAVIS_REPO_SLUG'].replace(/.*\/(.*)/i, '$1'); } constructor() { this.github = new GitHubApi({ debug: false, protocol: 'https', host: 'api.github.com', timeout: 5000, headers: { 'user-agent': 'Code-Coverage-GitHub-App' }, followRedirects: false, // default: true; there's currently an issue with non-get redirects, so allow ability to disable follow-redirects includePreview: true // default: false; includes accept headers to allow use of stuff under preview period }); this.github.authenticate({ type: 'oauth', token: process.env['GITHUB_OAUTH_TOKEN'], }); } /** * Add comments for PR or fails if coverage * @param {Number} s3SumPercent - s3 summary coverage percent * @param {Number} localSumPercent - local summary coverage percent * @param {Function} callback */ addComment(s3SumPercent, localSumPercent, callback) { let commentMsg; let isFailed = (localSumPercent < s3SumPercent); let failMsg = 'Failed due to decreasing coverage'; //no need to add comments for !PR if (!GitHubMsgPublisher.isPullRequest) { callback(null, null); return; } if (isFailed) { commentMsg = `:x: coverage decreased from ${s3SumPercent}% to ${localSumPercent}%`; } else if (localSumPercent === s3SumPercent) { //use it when need to add comments for the same coverage //commentMsg = `:warning: coverage remained the same at ${localSumPercent}%`; console.log(`:warning: coverage remained the same at ${localSumPercent}%`); callback(null, null); return; } else { commentMsg = `:white_check_mark: coverage increased from ${s3SumPercent}% to ${localSumPercent}%`; } this.github.issues.getComments({ user: GitHubMsgPublisher.gitUser, repo: GitHubMsgPublisher.gitRepoName, number: GitHubMsgPublisher.gitPRNumber, }, (err, issues) => { let isCommentAdded = false; if (err) { console.log(err); callback(err, null); return; } for (let issue of issues) { if (issue.hasOwnProperty('body') && issue.body === commentMsg) { isCommentAdded = true; console.log('Comment has already been added: ', commentMsg); if (isFailed) { console.log(failMsg); process.exit(1) } } } if (!isCommentAdded) { this.github.issues.createComment({ user: GitHubMsgPublisher.gitUser, repo: GitHubMsgPublisher.gitRepoName, number: GitHubMsgPublisher.gitPRNumber, body: commentMsg, }, (err, res) => { if (err) { console.log(err); callback(err, null); return; } callback(null, res); if (isFailed) { console.log(failMsg); process.exit(1) } }); } } ); } }
JavaScript
0.000003
@@ -1918,16 +1918,66 @@ mentMsg; +%0A%0A //failed if coverage decreased more that 1 %25 %0A let @@ -1988,16 +1988,17 @@ ailed = +( (localSu @@ -2005,16 +2005,21 @@ mPercent + + 1) %3C s3Sum @@ -2381,278 +2381,302 @@ ) %7B%0A -%0A -//use it when need to add comments for the same coverage%0A //commentMsg = %60:warning: coverage remained the same at $%7BlocalSumPercent%7D%25%60;%0A console.log(%60:warning: coverage remained the same at $%7BlocalSumPercent%7D%25%60);%0A callback(null, null);%0A return +commentMsg = %60:white_check_mark: coverage remained the same at $%7BlocalSumPercent%7D%25%60;%0A %7D else if (-1 %3C (localSumPercent - s3SumPercent) && (localSumPercent - s3SumPercent) %3C 0) %7B%0A commentMsg = %60:warning: coverage decreased less than 1%25 from $%7Bs3SumPercent%7D%25 to $%7BlocalSumPercent%7D%25%60 ;%0A
8916cbdcf6eeaa11ad02522bd6dbc7d72cf471e8
Test the happy path
test/bindings/http/unmarshaller_0_2_tests.js
test/bindings/http/unmarshaller_0_2_tests.js
var expect = require("chai").expect; var Unmarshaller = require("../../../lib/bindings/http/unmarshaller_0_2.js"); var Cloudevent = require("../../../index.js"); const type = "com.github.pull.create"; const source = "urn:event:from:myapi/resourse/123"; const webhook = "https://cloudevents.io/webhook"; const contentType = "application/cloudevents+json; charset=utf-8"; const now = new Date(); const schemaurl = "http://cloudevents.io/schema.json"; const ceContentType = "application/json"; const data = { foo: "bar" }; describe("HTTP Transport Binding Unmarshaller", () => { it("Throw error when payload is null", () => { // setup var payload = null; var un = new Unmarshaller(); // act and assert expect(un.unmarshall.bind(un, payload)) .to.throw("payload is null or undefined"); }); it("Throw error when headers is null", () => { // setup var payload = {}; var headers = null; var un = new Unmarshaller(); // act and assert expect(un.unmarshall.bind(un, payload, headers)) .to.throw("headers is null or undefined"); }); it("Throw error when there is no content-type header", () => { // setup var payload = {}; var headers = {}; var un = new Unmarshaller(); // act and assert expect(un.unmarshall.bind(un, payload, headers)) .to.throw("content-type header not found"); }); it("Throw error when content-type is not allowed", () => { // setup var payload = {}; var headers = { "content-type":"text/xml" }; var un = new Unmarshaller(); // act and assert expect(un.unmarshall.bind(un, payload, headers)) .to.throw("content type not allowed"); }); describe("Structured", () => { it("Throw error when has not allowed mime", () => { // setup var payload = {}; var headers = { "content-type":"application/cloudevents+zip" }; var un = new Unmarshaller(); // act and assert expect(un.unmarshall.bind(un, payload, headers)) .to.throw("structured+type not allowed"); }); it("Throw error when the event does not follow the spec 0.2", () => { // setup var payload = new Cloudevent() .type(type) .source(source) .contenttype(ceContentType) .time(now) .schemaurl(schemaurl) .data(data) .toString(); var headers = { "content-type":"application/cloudevents+json" }; var un = new Unmarshaller(); // act and assert expect(un.unmarshall.bind(un, payload, headers)) .to.throw("invalid payload"); }); }); });
JavaScript
0
@@ -2682,16 +2682,612 @@ %0A %7D); +%0A%0A it(%22Should accept event that follow the spec 0.2%22, () =%3E %7B%0A // setup%0A var payload =%0A new Cloudevent(Cloudevent.specs%5B%220.2%22%5D)%0A .type(type)%0A .source(source)%0A .contenttype(ceContentType)%0A .time(now)%0A .schemaurl(schemaurl)%0A .data(data)%0A .toString();%0A%0A var headers = %7B%0A %22content-type%22:%22application/cloudevents+json%22%0A %7D;%0A%0A var un = new Unmarshaller();%0A%0A // act%0A var actual = un.unmarshall(payload, headers);%0A%0A // assert%0A expect(actual)%0A .to.be.an(%22object%22);%0A %7D); %0A %7D);%0A%7D
eb0987b8560910f2500bdb4cc91d8ab511e70ec6
Improve logging for phantom test launch failures
test/browser/test-browser-instrumentation.js
test/browser/test-browser-instrumentation.js
/*jslint nomen: true */ var which = require('which'), phantom, path = require('path'), fs = require('fs'), child_process = require('child_process'), filesFor = require('../../lib/util/file-matcher').filesFor, Instrumenter = require('../../lib/instrumenter'), instrumenter = new Instrumenter({ backdoor: { omitTrackerSuffix: true } }), ROOT = path.resolve(__dirname, '..', '..', 'lib'), common = require('../common'), filesToInstrument, server, exited, cp; function runPhantom(cmd, script, port, files) { var args = [ script ]; args.push(port); args.push.apply(args, files); console.log('Start phantom'); cp = child_process.spawn(cmd, args); cp.stdout.on('data', function (data) { process.stdout.write(data); }); cp.stderr.on('data', function (data) { process.stderr.write(data); }); cp.on('exit', function () { exited = 1; }); } module.exports = { setUp: function (cb) { try { phantom = which.sync('phantomjs'); } catch (ex) {} filesFor({ root: ROOT, includes: [ '**/*.js' ], xexcludes: [ '**/instrumenter.js' ], relative: true }, function (err, files) { filesToInstrument = files; cb(); }); }, "should produce identical instrumentation results when instrumentation run on browser v/s nodejs": function (test) { if (!phantom) { console.error('******************************************************************'); console.error('No phantomjs found on path, skipping browser instrumentation test'); console.error('******************************************************************'); test.done(); return; } var finalFn = function () { if (server) { server.close(); } if (!cp.exited) { cp.kill(); } }, server, port = 9000; try { console.log('Start server'); server = require('./support/server').create(port, process.env.SELF_COVER ? instrumenter : null, ROOT); server.on('instrumented', function (file, instrumented) { var code = fs.readFileSync(path.resolve(ROOT, file), 'utf8'), serverSideInstrumented = instrumenter.instrumentSync(code, file); test.equal(serverSideInstrumented, instrumented, 'No match for [' + file + ']'); }); server.on('done', function (coverage) { if (common.isSelfCover()) { try { if (coverage) { fs.writeFileSync(path.resolve(common.getCoverageDir(), 'coverage-browser.json'), JSON.stringify(coverage), 'utf8'); } else { console.log('No coverage found'); } } catch (err) { console.error(err.message || err); console.error(err.stack); test.ok(false, err.message || err); } } finalFn(); test.done(); }); runPhantom(phantom, path.resolve(__dirname, 'support', 'phantom-test.client.js'), port, filesToInstrument); } catch (ex) { console.error(ex.message || ex); console.error(ex.stack); test.ok(false, ex.message || ex); test.done(); } } };
JavaScript
0
@@ -542,28 +542,37 @@ port, files +, errorCB ) %7B%0A - var args @@ -717,212 +717,199 @@ args -);%0A cp.stdout.on('data', function (data) %7B process.stdout.write(data); %7D);%0A cp.stderr.on('data', function (data) %7B process.stderr.write(data); %7D);%0A cp.on('exit', function () %7B%0A exited = 1; +, %7Bstdio: 'inherit'%7D);%0A cp.on('exit', function (code, signal) %7B%0A exited = 1;%0A if (signal) %7B%0A errorCB(new Error('Phantom exited with signal: ' + signal));%0A %7D %0A @@ -3361,16 +3361,122 @@ strument +, function (err) %7B%0A test.ok(false, err.message);%0A test.done();%0A %7D );%0A
796ca5a5998af35ac522da8ed6a53e194fccc67b
Fix value reset
src/DebounceInput.js
src/DebounceInput.js
import React from 'react'; import debounce from 'lodash.debounce'; import {shouldComponentUpdate} from 'react/lib/ReactComponentWithPureRenderMixin'; const DebounceInput = React.createClass({ propTypes: { onChange: React.PropTypes.func.isRequired, value: React.PropTypes.string, minLength: React.PropTypes.number, debounceTimeout: React.PropTypes.number }, getDefaultProps() { return { minLength: 0, value: '', debounceTimeout: 100 }; }, getInitialState() { return { value: this.props.value }; }, shouldComponentUpdate, componentWillReceiveProps({value}) { if (this.state.value !== value) { this.setState({value}); } }, componentWillUpdate({minLength, debounceTimeout}, {value}) { this.maybeUpdateNotifier(debounceTimeout); this.maybeNotify(minLength, value); }, componentWillMount() { this.createNotifier(this.props.debounceTimeout); }, createNotifier(debounceTimeout) { this.notify = debounce(this.props.onChange, debounceTimeout); }, maybeUpdateNotifier(debounceTimeout) { if (debounceTimeout !== this.props.debounceTimeout) { this.createNotifier(debounceTimeout); } }, maybeNotify(minLength, value) { const {value: oldValue} = this.state; if (value === oldValue) { return; } if (value.length >= minLength) { this.notify(value); return; } // If user hits backspace and goes below minLength consider it cleaning the value if (value.length < oldValue.length) { this.notify(''); } }, render() { const {onChange, value: v, minLength, debounceTimeout, ...props} = this.props; return ( <input type="text" {...props} value={this.state.value} onChange={({target: {value}}) => this.setState({value})} /> ); } }); export default DebounceInput;
JavaScript
0.000003
@@ -433,25 +433,8 @@ 0,%0A - value: '',%0A @@ -623,16 +623,48 @@ if ( +typeof value !== 'undefined' && this.sta
2e2d5cd0f905797a0991d9ac0e467da86f459365
allow switch views without clicking start
src/devtools/panel/js/birbal.app.js
src/devtools/panel/js/birbal.app.js
(function (angular, birbalJS) { 'use strict'; angular.module('birbal-app', ['background-service-app', 'panel-view-app']) .controller('panelViewController', ['$scope', 'backgroundService', function ($scope, backgroundService) { // default first message on inspect tab load, letting app know I'm ready // send after listener setup backgroundService.informBackground(null, 'init', birbalJS.END_POINTS.BACKGROUND); $scope.digestMeasures = { performanceTime: [] }; var actionList = []; ///////////////////////////////////////////////////////// // background action listener ///////////////////////////////////////////////////////// $scope.$on('panelActions', function (event, actions) { actions.forEach(function (detail) { actionList[detail.action].apply(null, detail.args); }); }); actionList.changePanelView = function (viewName, viewData) { // default is dashboard // viewname is html file in partials $scope.$applyAsync(function () { $scope.view = viewName; //initializing csInfo for template data for first time or after cleanup $scope.csInfo = $scope.csInfo || {}; angular.extend($scope.csInfo, viewData); }); }; actionList.clearResources = function () { // clear app data // digestMeasuresBox = digestTmplData = undefined; $scope.$applyAsync(function () { $scope.view = ''; delete $scope.csInfo; // $scope.digestMeasures = { // performanceTime: [] // }; }); }; actionList.digestMeasures = function (timeMeasure) { // initialize time measures for first time $scope.$applyAsync(function () { $scope.digestMeasures.performanceTime.push(timeMeasure); }); }; ///////////////////////////////////////////////////////// // Sidebar actions ///////////////////////////////////////////////////////// var sidebar = {}; sidebar.disableme = function () { actionList.clearResources(); backgroundService.informBackground(null, 'disableme', birbalJS.END_POINTS.BACKGROUND); }; sidebar.changePanelView = function (viewName) { actionList.changePanelView(viewName); }; //sidebar for html use $scope.sidebar = sidebar; ///////////////////////////////////////////////////////// // initpage actions ///////////////////////////////////////////////////////// $scope.initpage = {}; $scope.initpage.enableMe = function () { // register/enable/refresh backgroundService.informBackground({ ngModule: $scope.csInfo.ngModule, task: 'runAnalysis' }); sidebar.changePanelView('dashboard'); }; ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// }]); }(angular, birbalJS));
JavaScript
0
@@ -2318,24 +2318,278 @@ viewName) %7B%0A + if ($scope.view === 'initPage' && $scope.csInfo.ngModule) %7B%0A // register/enable/refresh%0A backgroundService.informBackground(%7B%0A ngModule: $scope.csInfo.ngModule,%0A task: 'runAnalysis'%0A %7D);%0A %7D%0A acti
6f2c4a041b885f79d1aeb28408c5ab6a6a92a7ea
Tidy `t/insert/ambiguous-last-page.t.js`.
t/insert/ambiguous-last-page.t.js
t/insert/ambiguous-last-page.t.js
#!/usr/bin/env node require('./proof')(3, function (step, Strata, tmp, deepEqual, serialize, gather, equal) { var strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3 }), fs = require('fs') step(function () { serialize(__dirname + '/fixtures/ambiguous.before.json', tmp, step()) }, function () { strata.open(step()) }, function () { gather(step, strata) }, function (records) { deepEqual(records, [ 'a', 'd', 'f', 'g', 'h', 'i', 'l', 'm', 'n' ], 'records') }, function () { strata.mutator('l', step()) }, function (cursor) { step(function () { cursor.indexOf('z', step()) }, function (index) { cursor.insert('z', 'z', ~index, step()) }, function (unambiguous) { cursor.unlock() equal(unambiguous, 0, 'unambiguous') }, function () { gather(step, strata) }) }, function (records) { deepEqual(records, [ 'a', 'd', 'f', 'g', 'h', 'i', 'l', 'm', 'n', 'z' ], 'records after insert') }, function() { strata.close(step()) }) })
JavaScript
0
@@ -68,19 +68,8 @@ tmp, - deepEqual, ser @@ -83,16 +83,27 @@ gather, + deepEqual, equal) @@ -183,28 +183,8 @@ 3 %7D) -, fs = require('fs') %0A
e73ce2d29d97c26cf220e6a4f0c93bb6de81cd08
add cap
src/main/webapp/js/webglsprint/Main.js
src/main/webapp/js/webglsprint/Main.js
Ext.define('webglsprint.Main', { singleton: true }, function() { /** * Main application launch function. To be called after page has finished loading. */ webglsprint.Main.launch = function() { //Create a framerate tracker, throw it in the top right var stats = new Stats(); stats.setMode(0); // 0: fps, 1: ms stats.domElement.style.position = 'absolute'; stats.domElement.style.right = '0px'; stats.domElement.style.top = '0px'; document.body.appendChild( stats.domElement ); var projector = new THREE.Projector(); var raycaster = new THREE.Raycaster(); //Make our request for a lot of boreholes... var maxBoreholes = 1000; var boreholeId = undefined; //'boreholes.5271'; webglsprint.boreholes.Loader.getBoreholes(maxBoreholes, boreholeId, function(success, message, boreholes) { if (!success) { alert('ERROR: ' + message); return; } Ext.get('loading-text').remove(); alert('Rendering ' + boreholes.length + ' boreholes now.\nTo look around, hold down the mouse and drag. To move the camera, use WASD'); if (!boreholes.length) { return; } //Just pull a reference the <canvas> element, set it to "full size" in //the browser window var canvasEl = Ext.get('webgl-sprint-canvas').dom; canvasEl.width = window.innerWidth; canvasEl.height = window.innerHeight; //Create the basic ThreeJS elements //See also: http://threejs.org/docs/#Manual/Introduction/Creating_a_scene var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(75, canvasEl.width / canvasEl.height, 0.1, 10000); var renderer = new THREE.WebGLRenderer({ canvas : Ext.get('webgl-sprint-canvas').dom }); //We need to figure out the mean x,y,z values in order to point our camera //at something interesting var mean = { xTotal : 0, yTotal : 0, zTotal : 0, n : 0 }; var material = new THREE.MeshLambertMaterial({ needsUpdate: true, map: THREE.ImageUtils.loadTexture('img/example-texture-long.png') }); //Iterate over our JSON representation of N boreholes for (i = 0; i < boreholes.length; ++i) { var points = []; for (j = 0; j < boreholes[i].points.length; ++j) { var point = boreholes[i].points[j]; mean.xTotal += point.x; mean.yTotal += point.y; mean.zTotal += point.z; mean.n++; points.push(new THREE.Vector3(point.x, point.y, point.z)); } //The tube geometry will divide the points up into a set of n segments //with a specified number of points on the radius. var segments = Math.ceil(Math.log(points.length) / Math.LN2); //lets decimate according to an arbitrary scale var radius = 5; var thickness = 0.1; //This doesn't increase/decrease polygons. Just their scale var path = new THREE.SplineCurve3(points); var geometry = new THREE.TubeGeometry(path, segments, 10, radius, false); //var material = new THREE.MeshBasicMaterial( { color: Math.floor(Math.random()*16777215), wireframe: true} ); var tube = new THREE.Mesh(geometry, material); tube.borehole = boreholes[i]; scene.add(tube); } var light = new THREE.AmbientLight( 0xa0a0a0 ); // soft white light scene.add( light ); var directionalLight = new THREE.DirectionalLight( 0xa0a0a0, 1 ); directionalLight.position.set( 0, 1, 0 ); scene.add( directionalLight ); mean.x = mean.xTotal / mean.n; mean.y = mean.yTotal / mean.n; mean.z = mean.zTotal / mean.n; //Just plonk our camera right in the middle of the geometries //hopefully it looks roughly in the right direction camera.position.x = mean.x; camera.position.y = mean.y; camera.position.z = mean.z; // This is a plugin that makes the camera interactive // The user can look with mouse and pan with WASD var controls = new THREE.FlyControls( camera ); controls.movementSpeed = 10; controls.domElement = Ext.get('viewport').dom; controls.rollSpeed = 0.01; controls.autoForward = false; controls.dragToLook = true; // We need a function that repeatedly loops // Drawing updates to our scene based on the current // camera position var update = function() { requestAnimationFrame( update ); stats.begin(); controls.update(1); renderer.render(scene, camera); stats.end(); }; update(); //This is in case the user resizes their browser window window.addEventListener('resize', onWindowResize, false ); function onWindowResize( event ) { camera.aspect = window.innerWidth / window.innerHeight; renderer.setSize( window.innerWidth, window.innerHeight ); renderer.render( scene, camera ); }; // mouse-right click handler Ext.get('webgl-sprint-canvas').dom.addEventListener('mousedown', onMouseDown, false); function onMouseDown(event) { if (event.button == 2) { var x = ( event.clientX / window.innerWidth ) * 2 - 1; var y = - ( event.clientY / window.innerHeight ) * 2 + 1; var vector = new THREE.Vector3(x, y, 1); projector.unprojectVector(vector, camera); raycaster.set(camera.position, vector.sub(camera.position).normalize()); var intersects = raycaster.intersectObjects(scene.children); if ( intersects.length > 0 ) { var bh = intersects[0].object.borehole; Ext.create('Ext.window.Window', { title: bh.name, height: 200, width: 400, layout: 'fit', items: [{ xtype: 'panel', html: '<ul><li>totalDepth: '+bh.totalDepth+'</li><li>points: '+bh.points.length+'</li></ul>' }] }).show(); } } }; }); } });
JavaScript
0.000002
@@ -3892,16 +3892,328 @@ d(tube); +%0D%0A%0D%0A //VT: add capping to the ends of the borehole(I can't get the cap to fit nicely%0D%0A var caps = new THREE.Mesh( new THREE.CircleGeometry( 10, 5, 45, Math.PI * 2 ), material );%0D%0A caps.position.set( points%5B0%5D.x, points%5B0%5D.y, points%5B0%5D.z );%0D%0A%09%09%09%09scene.add( caps );%0D%0A%0D%0A %0D%0A
a4f155231cec203717082085c41c146e456e1f1d
Add indexes and unique constraint.
migrations/20180314172812-create-laundry-records.js
migrations/20180314172812-create-laundry-records.js
'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.sequelize.query(` CREATE OR REPLACE FUNCTION create_versioning_trigger(recent regclass, history regclass) RETURNS void AS $$ BEGIN EXECUTE format('CREATE TRIGGER versioning_cd BEFORE INSERT OR DELETE ON %s FOR EACH ROW EXECUTE PROCEDURE versioning(%I, %s, true)', recent, 'period', history); EXECUTE format('CREATE TRIGGER versioning_up BEFORE UPDATE ON %s FOR EACH ROW WHEN ((OLD.*) IS DISTINCT FROM (NEW.*)) EXECUTE PROCEDURE versioning(%I, %s, true)', recent, 'period', history); END $$ LANGUAGE plpgsql; CREATE TABLE laundry_players ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), nickname VARCHAR UNIQUE NOT NULL, privacy VARCHAR UNIQUE NOT NULL, user_id uuid REFERENCES users (id) NOT NULL, created_at TIMESTAMP WITH TIME ZONE NOT NULL, updated_at TIMESTAMP WITH TIME ZONE NOT NULL ); CREATE TABLE laundry_records ( id uuid PRIMARY KEY, card_name VARCHAR NOT NULL, rating REAL NOT NULL, max_rating REAL NOT NULL, icon VARCHAR NOT NULL, title VARCHAR NOT NULL, period tstzrange NOT NULL, player_id uuid REFERENCES laundry_players (id) NOT NULL ); CREATE TABLE laundry_records_recent ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), player_id uuid REFERENCES laundry_players (id) NOT NULL ) INHERITS (laundry_records); CREATE TABLE laundry_records_history ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), player_id uuid REFERENCES laundry_players (id) NOT NULL ) INHERITS (laundry_records); CREATE INDEX ON laundry_records_recent USING GIST (period); CREATE INDEX ON laundry_records_history USING GIST (period); SELECT create_versioning_trigger('laundry_records_recent', 'laundry_records_history'); `); }, down: (queryInterface, Sequelize) => { return queryInterface.sequelize.query(` DROP TABLE laundry_records_recent; DROP TABLE laundry_records_history; DROP TABLE laundry_records; DROP TABLE laundry_players; DROP FUNCTION IF EXISTS create_versioning_trigger(recent regclass, history regclass); `); } };
JavaScript
0
@@ -1143,16 +1143,42 @@ T NULL,%0A + class VARCHAR NOT NULL,%0A player @@ -1219,32 +1219,32 @@ s (id) NOT NULL%0A - );%0A%0ACREATE TABLE @@ -1358,32 +1358,39 @@ dry_players (id) + UNIQUE NOT NULL%0A) INHE @@ -1410,24 +1410,171 @@ _records);%0A%0A +CREATE INDEX ON laundry_records_recent(card_name);%0ACREATE INDEX ON laundry_records_recent(rating);%0ACREATE INDEX ON laundry_records_recent(class);%0A%0A CREATE TABLE
21ec062c9a6c9661b7a3808fbbbaf1681701760a
Change Link component for a tag in LinkedIn logo
src/elements/linkedin-icon/index.js
src/elements/linkedin-icon/index.js
//@flow import React from "react"; import { Link } from "react-router-dom"; import { pure, compose, withState, withHandlers } from "recompose"; import { ThemeProvider } from "styled-components"; import mainTheme from "../../global/style/mainTheme"; import { Logo } from "./Logo"; const enhance = compose( withState("isActive", "setActive", false), withHandlers({ addActive: props => () => props.setActive(true), rmActive: props => () => props.setActive(false) }), pure ); export const LinkedInLogo = enhance( ({ addActive, rmActive, isActive }: { addActive: () => any, rmActive: () => any, isActive: boolean }) => ( <ThemeProvider theme={mainTheme}> <Link to="https://www.linkedin.com/in/oliver-askew-5791a333/" onMouseEnter={addActive} onMouseLeave={rmActive} > <Logo isActive={isActive} /> </Link> </ThemeProvider> ) );
JavaScript
0
@@ -33,49 +33,8 @@ t%22;%0A -import %7B Link %7D from %22react-router-dom%22;%0A impo @@ -527,16 +527,30 @@ isActive +,%0A ...props %0A %7D: %7B%0A @@ -677,20 +677,17 @@ %0A %3C -Link +a %0A @@ -691,10 +691,12 @@ -to +href =%22ht @@ -863,20 +863,17 @@ %3C/ -Link +a %3E%0A %3C/
077242d046e3e755ff82ba4b29cce2477fd50bea
Change ports and env variable names
config/seneca-options.js
config/seneca-options.js
'use strict'; var senecaOptions = { transport: { web: { port: process.env.PORT || 8080 } }, apiBaseUrl: process.env.API_BASE_URL || 'http://localhost:3000', apiSecret: process.env.API_SECRET || '' }; module.exports = senecaOptions;
JavaScript
0
@@ -96,16 +96,31 @@ env. +BADGES_SERVICE_ PORT %7C%7C 8080 @@ -119,12 +119,13 @@ %7C%7C -8080 +10305 %0A @@ -204,11 +204,11 @@ ost: -300 +808 0',%0A
5f464f98f1ff86caac02eca207704c1961b07be1
include vue_shared scripts within common_vue chunk
config/webpack.config.js
config/webpack.config.js
'use strict'; var fs = require('fs'); var path = require('path'); var webpack = require('webpack'); var StatsPlugin = require('stats-webpack-plugin'); var CompressionPlugin = require('compression-webpack-plugin'); var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; var ROOT_PATH = path.resolve(__dirname, '..'); var IS_PRODUCTION = process.env.NODE_ENV === 'production'; var IS_DEV_SERVER = process.argv[1].indexOf('webpack-dev-server') !== -1; var DEV_SERVER_PORT = parseInt(process.env.DEV_SERVER_PORT, 10) || 3808; var DEV_SERVER_LIVERELOAD = process.env.DEV_SERVER_LIVERELOAD !== 'false'; var WEBPACK_REPORT = process.env.WEBPACK_REPORT; var config = { context: path.join(ROOT_PATH, 'app/assets/javascripts'), entry: { common: './commons/index.js', common_vue: ['vue', 'vue-resource'], application: './application.js', blob_edit: './blob_edit/blob_edit_bundle.js', boards: './boards/boards_bundle.js', simulate_drag: './test_utils/simulate_drag.js', cycle_analytics: './cycle_analytics/cycle_analytics_bundle.js', commit_pipelines: './commit/pipelines/pipelines_bundle.js', diff_notes: './diff_notes/diff_notes_bundle.js', environments: './environments/environments_bundle.js', environments_folder: './environments/folder/environments_folder_bundle.js', filtered_search: './filtered_search/filtered_search_bundle.js', graphs: './graphs/graphs_bundle.js', groups_list: './groups_list.js', issuable: './issuable/issuable_bundle.js', merge_conflicts: './merge_conflicts/merge_conflicts_bundle.js', merge_request_widget: './merge_request_widget/ci_bundle.js', network: './network/network_bundle.js', profile: './profile/profile_bundle.js', protected_branches: './protected_branches/protected_branches_bundle.js', snippet: './snippet/snippet_bundle.js', terminal: './terminal/terminal_bundle.js', users: './users/users_bundle.js', lib_chart: './lib/chart.js', lib_d3: './lib/d3.js', vue_pipelines: './vue_pipelines_index/index.js', }, output: { path: path.join(ROOT_PATH, 'public/assets/webpack'), publicPath: '/assets/webpack/', filename: IS_PRODUCTION ? '[name]-[chunkhash].js' : '[name].js' }, devtool: 'inline-source-map', module: { rules: [ { test: /\.(js|es6)$/, exclude: /(node_modules|vendor\/assets)/, loader: 'babel-loader', options: { presets: [ ["es2015", {"modules": false}], 'stage-2' ] } }, { test: /\.svg$/, use: 'raw-loader' } ] }, plugins: [ // manifest filename must match config.webpack.manifest_filename // webpack-rails only needs assetsByChunkName to function properly new StatsPlugin('manifest.json', { chunkModules: false, source: false, chunks: false, modules: false, assets: true }), // prevent pikaday from including moment.js new webpack.IgnorePlugin(/moment/, /pikaday/), // fix legacy jQuery plugins which depend on globals new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', }), // use deterministic module ids in all environments IS_PRODUCTION ? new webpack.HashedModuleIdsPlugin() : new webpack.NamedModulesPlugin(), // create cacheable common library bundle for all vue chunks new webpack.optimize.CommonsChunkPlugin({ name: 'common_vue', chunks: [ 'boards', 'commit_pipelines', 'cycle_analytics', 'diff_notes', 'environments', 'environments_folder', 'issuable', 'merge_conflicts', 'vue_pipelines', ], minChunks: Infinity, }), // create cacheable common library bundles new webpack.optimize.CommonsChunkPlugin({ names: ['application', 'common', 'manifest'], }), ], resolve: { extensions: ['.js', '.es6', '.js.es6'], alias: { '~': path.join(ROOT_PATH, 'app/assets/javascripts'), 'emoji-aliases$': path.join(ROOT_PATH, 'fixtures/emojis/aliases.json'), 'icons': path.join(ROOT_PATH, 'app/views/shared/icons'), 'vendor': path.join(ROOT_PATH, 'vendor/assets/javascripts'), 'vue$': 'vue/dist/vue.common.js', } } } if (IS_PRODUCTION) { config.devtool = 'source-map'; config.plugins.push( new webpack.NoEmitOnErrorsPlugin(), new webpack.LoaderOptionsPlugin({ minimize: true, debug: false }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new CompressionPlugin({ asset: '[path].gz[query]', }) ); } if (IS_DEV_SERVER) { config.devServer = { port: DEV_SERVER_PORT, headers: { 'Access-Control-Allow-Origin': '*' }, stats: 'errors-only', inline: DEV_SERVER_LIVERELOAD }; config.output.publicPath = '//localhost:' + DEV_SERVER_PORT + config.output.publicPath; } if (WEBPACK_REPORT) { config.plugins.push( new BundleAnalyzerPlugin({ analyzerMode: 'static', generateStatsFile: true, openAnalyzer: false, reportFilename: path.join(ROOT_PATH, 'webpack-report/index.html'), statsFilename: path.join(ROOT_PATH, 'webpack-report/stats.json'), }) ); } module.exports = config;
JavaScript
0
@@ -4001,16 +4001,113 @@ ks: -Infinity +function(module, count) %7B%0A return module.resource && (/vue_shared/).test(module.resource);%0A %7D ,%0A
7540cab6bb0444403d8c7a19976a4a9772883250
Fix handleClick is not a function bug
src/modules/unit/components/MapView.js
src/modules/unit/components/MapView.js
// @flow import React, {Component, PropTypes} from 'react'; import {Link} from 'react-router'; import isEmpty from 'lodash/isEmpty'; import SMIcon from '../../home/components/SMIcon'; import OSMIcon from '../../home/components/OSMIcon'; import {View} from './View'; import Logo from '../../home/components/Logo'; import Disclaimer from '../../home/components/Disclaimer'; import {Map, TileLayer, ZoomControl} from 'react-leaflet'; import Control from '../../map/components/Control'; //import Control from 'react-leaflet-control'; import {mobileBreakpoint} from '../../common/constants'; import {languages} from '../../language/constants'; import {MAP_URL, DEFAULT_ZOOM, MIN_ZOOM, BOUNDARIES} from '../../map/constants'; import {latLngToArray} from '../../map/helpers'; import {getUnitPosition} from '../helpers'; import UnitsOnMap from './UnitsOnMap'; import UserLocationMarker from '../../map/components/UserLocationMarker'; import {Modal} from 'react-bootstrap'; import {translate} from 'react-i18next'; class MapView extends Component { static propTypes = { position: PropTypes.array.isRequired, units: PropTypes.array }; state: { isMobile: boolean }; constructor(props: Object) { super(props); this.state = { isMobile: window.innerWidth < mobileBreakpoint, menuOpen: false, modalOpen: false, zoomLevel: DEFAULT_ZOOM }; this.locateUser = this.locateUser.bind(this); this.updateIsMobile = this.updateIsMobile.bind(this); this.handleClick = this.handleClick.bind(this); this.toggleMenu = this.toggleMenu.bind(this); this.toggleModal = this.toggleModal.bind(this); this.openModal = this.openModal.bind(this); this.closeModal = this.closeModal.bind(this); this.handleZoom = this.handleZoom.bind(this); this.setView = this.setView.bind(this); } componentDidMount() { window.addEventListener('resize', this.updateIsMobile); } componentWillUnmount() { window.removeEventListener('resize', this.updateIsMobile); //this.refs.map.leafletElement.setActiveArea('activeArea'); } componentWillReceiveProps(nextProps) { if (nextProps.params.unitId && !isEmpty(nextProps.units)) { const unit = nextProps.units.filter((unit) => unit.id == nextProps.params.unitId)[0]; !isEmpty(unit) && this.centerMapToUnit(unit); } /*if (nextProps.position[0] !== this.props.position[0] || nextProps.position[1] !== this.props.position[1]) { console.log('here'); this.refs.map.leafletElement.setView([60,25]); }*/ } centerMapToUnit(unit: Object) { if (this.state.isMobile) { let location = getUnitPosition(unit); location[0] = location[0] + 0.02; //For some reason could not use reverse here so had to do this weird way. this.refs.map.leafletElement.setView(location, DEFAULT_ZOOM); } else { let location = getUnitPosition(unit); location[1] = location[1] - 0.04; this.refs.map.leafletElement.setView(location, DEFAULT_ZOOM); } } handleZoom() { this.setState({zoomLevel: this.refs.map.leafletElement.getZoom()}); } updateIsMobile() { this.setState({isMobile: window.innerWidth < mobileBreakpoint}); } locateUser() { this.refs.map.leafletElement.locate({setView: true}); } handleClick(event: Object) { this.props.setLocation(latLngToArray(event.latlng)); } toggleMenu() { if(this.state.menuOpen) { this.setState({menuOpen: false}); } else { this.setState({menuOpen: true}); } } toggleModal() { if(this.state.modalOpen) { this.setState({modalOpen: false}); } else { this.setState({modalOpen: true}); } } setView(coordinates) { this.refs.map.leafletElement.setView(coordinates); } openModal() { this.setState({modalOpen: true}); } closeModal() { this.setState({modalOpen: false}); } render() { const {position, selectedUnitId, units, selected, activeLanguage, openUnit, changeLanguage, t} = this.props; const {isMobile, zoomLevel, menuOpen} = this.state; return ( <View id="map-view" className="map-view" isSelected={selected}> <Map ref="map" zoomControl={false} attributionControl={false} center={position} maxBounds={BOUNDARIES} zoom={DEFAULT_ZOOM} minZoom={MIN_ZOOM} onClick={this.handleClick} onLocationfound={this.handleClick} onZoomend={this.handleZoom}> <TileLayer url={MAP_URL} attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' /> <UserLocationMarker /> <UnitsOnMap units={units} zoomLevel={zoomLevel} selectedUnitId={selectedUnitId} openUnit={openUnit}/> {!isMobile && <ZoomControl position="bottomright" />} <Control handleClick={this.locateUser} className="leaflet-control-locate" position="bottomright"> <OSMIcon icon="locate" /> </Control> <LanguageChanger activeLanguage={activeLanguage} changeLanguage={changeLanguage} /> {menuOpen ? <InfoMenu t={t} openModal={this.openModal} /> : null} <Control handleClick={this.toggleMenu} className="leaflet-control-info" position={isMobile ? 'bottomleft' : 'topright'}> <SMIcon icon="info" /> </Control> </Map> <Logo/> {this.state.modalOpen ? <AboutModal closeModal={this.closeModal} t={t}/> : null} </View> ); } } export default translate(null, {withRef: true})(MapView); const LanguageChanger = ({changeLanguage, activeLanguage}) => <div className="language-changer"> {Object.keys(languages).filter((language) => languages[language] !== activeLanguage).map((languageKey, index) => ( <div key={languageKey} style={{ display: 'flex' }}> <a onClick={() => changeLanguage(languages[languageKey])}> {languageKey} </a> {index < Object.keys(languages).length - 2 ? <div style={{ marginLeft: 2, marginRight: 2 }}>|</div> : null} </div>) )} </div>; const InfoMenu = ({openModal, t}) => <div className="info-menu"> <InfoMenuItem icon='info' t={t}> {t('MAP.INFO_MENU.GIVE_FEEDBACK')} </InfoMenuItem> <InfoMenuItem icon='info' handleClick={openModal}> {t('MAP.INFO_MENU.ABOUT_SERVICE')} </InfoMenuItem> <InfoMenuItem> <a target="_blank" href='http://osm.org/copyright' style={{padding: 1}}>&copy; {t('MAP.ATTRIBUTION')} </a> </InfoMenuItem> </div>; const InfoMenuItem = ({children, handleClick, icon}) => <div className="info-menu-item" onClick={() => handleClick()}> {icon ? <SMIcon icon={icon} style={{paddingRight: 2}}/> : null} {children} </div>; const AboutModal = ({closeModal, t}) => <div className="about-modal-backdrop"> <div className="about-modal-box"> <div className="about-modal-controls"> <SMIcon icon="close" onClick={() => closeModal()} /> </div> <div className="about-modal-content"> {t('MAP.ABOUT')} </div> </div> </div>;
JavaScript
0.000004
@@ -6436,24 +6436,49 @@ InfoMenuItem + handleClick=%7B() =%3E null%7D %3E%0A %3Ca t
d91275be74e56b6199bbc794a806692c0b40233b
Make changes requested in code review
src/foam/u2/view/ScrollTableView.js
src/foam/u2/view/ScrollTableView.js
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.u2.view', name: 'ScrollTableView', extends: 'foam.u2.Element', requires: [ 'foam.dao.FnSink', 'foam.graphics.ScrollCView', 'foam.mlang.sink.Count', 'foam.u2.view.TableView' ], constants: [ { type: 'Integer', name: 'TABLE_HEAD_HEIGHT', value: 40 } ], properties: [ { class: 'foam.dao.DAOProperty', name: 'data' }, { class: 'Int', name: 'limit', value: 18, // TODO make this a funciton of the height. }, { class: 'Int', name: 'skip', }, { class: 'foam.dao.DAOProperty', name: 'scrolledDAO', expression: function(data, limit, skip) { return data && data.limit(limit).skip(skip); }, }, 'columns', { class: 'FObjectArray', of: 'foam.core.Action', name: 'contextMenuActions' }, { class: 'Int', name: 'daoCount' }, 'selection', { class: 'Boolean', name: 'editColumnsEnabled', documentation: ` Set to true if users should be allowed to choose which columns to use. `, value: true }, { class: 'Int', name: 'rowHeight', documentation: 'The height of one row of the table in px.', value: 48 }, { class: 'Boolean', name: 'fitInScreen', documentation: ` If true, the table height will be dynamically set such that the table will not overflow off of the bottom of the page. `, value: false }, { name: 'table_', documentation: ` A reference to the table element we use in the fitInScreen calculations. ` }, { type: 'Int', name: 'accumulator', value: 0, documentation: `Used internally to mimic native scrolling speed.`, adapt: function(_, v) { return v % this.rowHeight; } } ], methods: [ function init() { this.onDetach(this.data$proxy.listen(this.FnSink.create({fn:this.onDAOUpdate}))); this.onDAOUpdate(); }, function initE() { // TODO probably shouldn't be using a table. this.start('table'). on('wheel', this.onWheel). start('tr'). start('td'). style({ 'vertical-align': 'top' }). start(this.TableView, { data$: this.scrolledDAO$, columns: this.columns, contextMenuActions: this.contextMenuActions, selection$: this.selection$, editColumnsEnabled: this.editColumnsEnabled }, this.table_$). end(). end(). start('td'). style({ 'vertical-align': 'top' }). show(this.daoCount$.map((count) => count >= this.limit)). add(this.slot(function(limit) { return this.ScrollCView.create({ value$: this.skip$, extent$: this.limit$, height: this.rowHeight * limit + this.TABLE_HEAD_HEIGHT, width: 12, size$: this.daoCount$, }); })). end(). end(). end(); if ( this.fitInScreen ) { this.onload.sub(this.updateTableHeight); window.addEventListener('resize', this.updateTableHeight); this.onDetach(() => { window.removeEventListener('resize', this.updateTableHeight); }); } } ], listeners: [ { name: 'onWheel', code: function(e) { var negative = e.deltaY < 0; var rows = Math.floor(Math.abs(this.accumulator + e.deltaY) / this.rowHeight); this.accumulator += e.deltaY; this.skip = Math.max(0, this.skip + (negative ? -rows : rows)); if ( e.deltaY !== 0 ) e.preventDefault(); } }, { // TODO: Avoid onDAOUpdate approaches. name: 'onDAOUpdate', isFramed: true, code: function() { var self = this; this.data$proxy.select(this.Count.create()).then(function(s) { self.daoCount = s.value; }) } }, { name: 'updateTableHeight', code: function() { // Find the distance from the top of the table to the top of the screen. var distanceFromTop = this.table_.el().getBoundingClientRect().y; // Calculate the remaining space we have to make use of. var remainingSpace = window.innerHeight - distanceFromTop; // Set the limit such that we make maximum use of the space without // overflowing. this.limit = Math.max(1, Math.floor((remainingSpace - this.TABLE_HEAD_HEIGHT) / this.rowHeight)); } } ] });
JavaScript
0
@@ -1839,28 +1839,29 @@ %7B%0A -type +class : 'Int',%0A @@ -1888,24 +1888,8 @@ r',%0A - value: 0,%0A @@ -1905,17 +1905,17 @@ tation: -%60 +' Used int @@ -1954,17 +1954,17 @@ g speed. -%60 +' ,%0A
22d4df70d9265a1a0bf28a9b1b528299786730db
add creds to make login functional test pass
src/functional-tests/tests/login.js
src/functional-tests/tests/login.js
import LoginPage from '../pages/login'; import DashboardPage from '../pages/dashboard'; // eslint-disable-next-line no-unused-expressions fixture `Login Process`.page `http://localhost:3001`; test('Logging in sends you to the dashboard', async t => { // Starting on the homepage sends you to the login page initially. const initialLocation = await t.eval(() => window.location); await t.expect(initialLocation.pathname).eql('/login'); const loginPage = new LoginPage(); await t .typeText(loginPage.emailInput, 'monksp@monksp.org') .typeText(loginPage.passwordInput, 'foo') .click(loginPage.submitButton); // Once we've logged in, we should land on the dashboard. const dashboardPage = new DashboardPage(); const afterLoginLocation = await t.eval(() => window.location); await t.expect(afterLoginLocation.pathname).eql(dashboardPage.pathName); // Once logged in, the homepage sends you to the dashboard, as well. await t.navigateTo('/'); const finalLocation = await t.eval(() => window.location); await t.expect(finalLocation.pathname).eql(dashboardPage.pathName); });
JavaScript
0
@@ -525,25 +525,36 @@ t, ' -monksp@monksp.org +romans@myews.onmicrosoft.com ')%0A @@ -596,11 +596,26 @@ t, ' -foo +enterprise: engage ')%0A
b17d3c486a3530e5e59579f3ac61bfb68b1851ce
Fix datepicker test
tests/acceptance/edit-form-validation-test/validation-datepicker-test.js
tests/acceptance/edit-form-validation-test/validation-datepicker-test.js
import Ember from 'ember'; import { executeTest} from './execute-validation-test'; executeTest('check operation datepicker', (store, assert, app) => { assert.expect(3); let path = 'components-acceptance-tests/edit-form-validation/validation'; // Open validation page. visit(path); andThen(() => { assert.equal(currentPath(), path); let $validationField = Ember.$(Ember.$('.field.error')[4]); $validationField = $validationField.children('.inline'); let $validationFlexberryErrorLable = $validationField.children('.label'); let $validationDateField = Ember.$('.calendar.link.icon'); // Check default validationmessage text. assert.equal($validationFlexberryErrorLable.text().trim(), 'Date is required', 'Datepicker have default value'); Ember.run(() => { // Open datepicker calendar. $validationDateField.click(); let $validationDateButton = Ember.$('.available'); $validationDateButton = Ember.$($validationDateButton[18]); // Select date. $validationDateButton.click(); }); // Check validationmessage text. $validationFlexberryErrorLable = $validationField.children('.label'); // Waiting for completion _setProperOffsetToCalendar(). let done = assert.async(); setTimeout(function() { assert.equal($validationFlexberryErrorLable.text().trim(), '', 'Datepicker have value'); done(); }, 2000); }); });
JavaScript
0.000001
@@ -920,16 +920,29 @@ vailable +:not(.active) ');%0A
dde3dd7b731c9d6f3e372fbc5b978d62e01a66a5
Use provided 'style' alias within Component file
templates/javascript/Component.js
templates/javascript/Component.js
'use strict'; var React = require('react/addons'); <% if (stylesLanguage === 'css') { %>require('../../styles/<%= classedFileName %>.css');<% } %><% if (stylesLanguage === 'sass') { %>require('../../styles/<%= classedFileName %>.sass');<% } %><% if (stylesLanguage === 'scss') { %>require('../../styles/<%= classedFileName %>.scss');<% } %><% if (stylesLanguage === 'less') { %>require('../../styles/<%= classedFileName %>.less');<% } %><% if (stylesLanguage === 'stylus') { %>require('../../styles/<%= classedFileName %>.styl');<% } %> var <%= classedName %> = React.createClass({ render: function () { return ( <div> <p>Content for <%= classedName %></p> </div> ); } }); <% if (es6) { %>export default <%= classedName %>; <% } else { %>module.exports = <%= classedName %>; <% } %>
JavaScript
0.000009
@@ -84,38 +84,32 @@ ') %7B %25%3Erequire(' -../../ styles/%3C%25= class @@ -176,38 +176,32 @@ %7B %25%3Erequire(' -../../ styles/%3C%25= class @@ -269,38 +269,32 @@ %7B %25%3Erequire(' -../../ styles/%3C%25= class @@ -362,38 +362,32 @@ %7B %25%3Erequire(' -../../ styles/%3C%25= class @@ -467,14 +467,8 @@ re(' -../../ styl
dd3600de79743aa23d3bf86b1ac2821a3ce854b9
Update Mapzen API Key
src/geo/geocoder/mapzen-geocoder.js
src/geo/geocoder/mapzen-geocoder.js
var $ = require('jquery'); /** * geocoders for different services * * should implement a function called geocode the gets * the address and call callback with a list of placemarks with lat, lon * (at least) */ var MAPZEN = { keys: { app_id: 'search-DH1Lkhw' }, geocode: function (address, callback) { address = address.toLowerCase() .replace(/é/g, 'e') .replace(/á/g, 'a') .replace(/í/g, 'i') .replace(/ó/g, 'o') .replace(/ú/g, 'u'); var protocol = ''; if (window.location.protocol.indexOf('http') === -1) { protocol = 'http:'; } $.getJSON(protocol + '//search.mapzen.com/v1/search?text=' + encodeURIComponent(address) + '&api_key=' + this.keys.app_id, function (data) { var coordinates = []; if (data && data.features && data.features.length > 0) { var res = data.features; for (var i in res) { var r = res[i]; var position; position = { lat: r.geometry.coordinates[1], lon: r.geometry.coordinates[0] }; if (r.properties.layer) { position.type = r.properties.layer; } if (r.properties.label) { position.title = r.properties.label; } coordinates.push(position); } } if (callback) { callback.call(this, coordinates); } }); } }; module.exports = MAPZEN;
JavaScript
0
@@ -252,22 +252,22 @@ d: ' -search-DH1Lkhw +mapzen-YfBeDWS '%0A
89e78c78806d21b1c92fdce17ce9f4872e6bb899
Access a property using a string literal within a pair of square brackets when the property name is not a reserved word will trigger an error. Don't fool around with travis-sensei.
src/pages/strategy/tabs/wikia/wikia.js
src/pages/strategy/tabs/wikia/wikia.js
(function(){ "use strict"; KC3StrategyTabs.wikia = new KC3StrategyTab("wikia"); KC3StrategyTabs.wikia.definition = { tabSelf: KC3StrategyTabs.wikia, fleets: [], /* INIT Prepares all data needed ---------------------------------*/ init: function(){ PlayerManager.loadFleets(); console.log(PlayerManager.fleets); console.log("http://www.kancolle-calc.net/deckbuilder.html?predeck=".concat(encodeURI( JSON.stringify({ "version":3, "f1":this.generate_fleet_JSON(PlayerManager.fleets[0]), "f2":this.generate_fleet_JSON(PlayerManager.fleets[1]), "f3":this.generate_fleet_JSON(PlayerManager.fleets[2]), "f4":this.generate_fleet_JSON(PlayerManager.fleets[3]), }) ))); }, /* EXECUTE Places data onto the interface ---------------------------------*/ execute: function(){ $('.tab_wikia .wikia_list').html(''); this.show_fleet_code(0, PlayerManager.fleets[0]); this.show_fleet_code(1, PlayerManager.fleets[1]); this.show_fleet_code(2, PlayerManager.fleets[2]); this.show_fleet_code(3, PlayerManager.fleets[3]); }, /* Split the name and remodel with a slash --------------------------------------------*/ process_ship_name: function(ship) { var api_name = ship.name(); var base_name = api_name .replace(' Kai Ni', '') .replace(' Kai', '') .replace(' zwei', '') .replace(' drei', '') .replace(' Carrier Kai Ni', '') .replace(' Carrier Kai', '') .replace(' Carrier', ''); // Special case because Chiyoda and Chitose have an "A" remodel which could be part of a name if(api_name.substr(0, 7) == 'Chiyoda' || api_name.substr(0, 7) == 'Chitose') { base_name = base_name.replace('-A', ''); } var remodel = api_name.split(base_name + ' ')[1] || ''; return [base_name, remodel]; }, /* Show wikia code for a single fleet --------------------------------------------*/ show_fleet_code: function(index, fleet) { if(!fleet.active) return false; // Create the box and apply basic values var box = $('.tab_wikia .factory .wikia_box').clone().appendTo('.tab_wikia .wikia_list'); box.attr('id', 'wikia_box' + index); $('.wikia_name', box).text(fleet.name); // Start up the code string var code = "{{EventComp\n"; // Iterate over the ships in this fleet for(var i = 0; i < fleet.ships.length; i++) { if(fleet.ships[i] > -1) code += this.show_ship_code(box, fleet.ships[i]); } code += "| hq = " + PlayerManager.hq.level + "\n"; code += "}}"; $('.wikia_code', box).text(code); }, /* Show wikia code for a single ship --------------------------------------------*/ show_ship_code: function(box, ship_id) { var ship = KC3ShipManager.get(ship_id); var ship_name = this.process_ship_name(ship).join('/'); var code = ''; code += "| " + ship_name + "\n"; code += "| " + ship.level + "\n"; code += this.show_equip_code(ship.items[0]); code += this.show_equip_code(ship.items[1]); code += this.show_equip_code(ship.items[2]); code += this.show_equip_code(ship.items[3]); code += "|-\n"; return code; }, show_equip_code: function(equip_id) { if(equip_id > -1) { var equip = KC3GearManager.get(equip_id); return "| " + equip.name() + "\n"; } else { return ''; } }, /* Code for generating deckbuilder style JSON data. --------------------------------------------*/ generate_fleet_JSON: function(fleet) { var result = {}; for(var i = 0; i < fleet.ships.length; i++) { if(fleet.ships[i] > -1){ result["s".concat(i+1)] = this.generate_ship_JSON(fleet.ships[i]); } } return result; }, generate_ship_JSON: function(ship_ID) { var result = {}; var ship = KC3ShipManager.get(ship_ID); result["id"] = ship.masterId; result["lv"] = ship.level; result["luck"] = ship.lk[0]; result["items"] = this.generate_equipment_JSON(ship); return result; }, generate_equipment_JSON: function(shipObj) { var result = {}; for(var i = 0; i < 4; i++) { if(shipObj.items[i]> -1){ result["i".concat(i+1)] ={ "id":KC3GearManager.get(shipObj.items[i]).masterId, "rf":KC3GearManager.get(shipObj.items[i]).stars }; } else { break; } } return result; }, }; })();
JavaScript
0
@@ -4137,14 +4137,11 @@ sult -%5B%22id%22%5D +.id = s @@ -4170,14 +4170,11 @@ sult -%5B%22lv%22%5D +.lv = s @@ -4200,16 +4200,13 @@ sult -%5B%22 +. luck -%22%5D = s @@ -4232,17 +4232,14 @@ sult -%5B%22 +. items -%22%5D = t
ff0fd30e7f8c3c837d218f35161a57a86fd71fc6
Simplify error cases of callback.js
lib/android/plugin/android/callback.js
lib/android/plugin/android/callback.js
var port = null, token = null, xmlhttp; module.exports = { start: function callback() { // cordova/exec depends on this module, so we can't require cordova/exec on the module level. var exec = require('cordova/exec'), xmlhttp = new XMLHttpRequest(); // Callback function when XMLHttpRequest is ready xmlhttp.onreadystatechange=function(){ if (!xmlhttp) { return; } if(xmlhttp.readyState === 4){ // If callback has JavaScript statement to execute if (xmlhttp.status === 200) { // Need to url decode the response var msg = decodeURIComponent(xmlhttp.responseText); setTimeout(function() { try { var t = eval(msg); } catch (e) { // If we're getting an error here, seeing the message will help in debugging console.log("JSCallback: Message from Server: " + msg); console.log("JSCallback Error: "+e); } }, 1); setTimeout(callback, 1); } // If callback ping (used to keep XHR request from timing out) else if (xmlhttp.status === 404) { setTimeout(callback, 10); } // If security error else if (xmlhttp.status === 403) { console.log("JSCallback Error: Invalid token. Stopping callbacks."); } // If server is stopping else if (xmlhttp.status === 503) { console.log("JSCallback Server Closed: Stopping callbacks."); } // If request wasn't GET else if (xmlhttp.status === 400) { console.log("JSCallback Error: Bad request. Stopping callbacks."); } // If error, revert to polling else { console.log("JSCallback Error: Request failed."); exec.setNativeToJsBridgeMode(exec.nativeToJsModes.POLLING); } } }; if (port === null) { port = prompt("getPort", "gap_callbackServer:"); } if (token === null) { token = prompt("getToken", "gap_callbackServer:"); } xmlhttp.open("GET", "http://127.0.0.1:"+port+"/"+token , true); xmlhttp.send(); }, stop: function() { if (xmlhttp) { var tmp = xmlhttp; xmlhttp = null; tmp.abort(); } }, isAvailable: function() { return ("true" != prompt("usePolling", "gap_callbackServer:")); } };
JavaScript
0.000021
@@ -1507,624 +1507,153 @@ // -If security error%0A else if (xmlhttp.status === 403) %7B%0A console.log(%22JSCallback Error: Invalid token. Stopping callbacks.%22);%0A %7D%0A%0A // If server is stopping%0A else if (xmlhttp.status === 503) %7B%0A console.log(%22JSCallback Server Closed: Stopping callbacks.%22);%0A %7D%0A%0A // If request wasn't GET%0A else if (xmlhttp.status === 400) %7B%0A console.log(%22JSCallback Error: Bad request. Stopping callbacks.%22);%0A %7D%0A%0A // If error, revert to polling +0 == Page is unloading.%0A // 400 == Bad request.%0A // 403 == invalid token.%0A // 503 == server stopped. %0A @@ -1741,10 +1741,39 @@ iled -.%22 + with status %22 + xmlhttp.status );%0A
52c6a060d6e3e251c3577a06cecffbe2ef8008e7
allow extension of the edition widget
addons/base_setup/static/src/js/res_config_edition.js
addons/base_setup/static/src/js/res_config_edition.js
odoo.define('base_setup.ResConfigEdition', function (require) { "use strict"; var Widget = require('web.Widget'); var widget_registry = require('web.widget_registry'); var session = require ('web.session'); var ResConfigEdition = Widget.extend({ template: 'res_config_edition', /** * @override */ init: function () { this._super.apply(this, arguments); this.server_version = session.server_version; }, }); widget_registry.add('res_config_edition', ResConfigEdition); });
JavaScript
0.000001
@@ -478,16 +478,166 @@ ersion;%0A + this.expiration_date = session.expiration_date%0A ? moment(session.expiration_date)%0A : moment().add(30, 'd');%0A @@ -710,13 +710,43 @@ dition); +%0A%0A return ResConfigEdition; %0A%7D);%0A
2b688ad4e539b8069451f768dfc284266bc630ab
Handle undefined reference
lib/telegram2discord/handleEntities.js
lib/telegram2discord/handleEntities.js
"use strict"; /************************** * Import important stuff * **************************/ // Nothing /***************************** * Define the entity handler * *****************************/ /** * Converts entities (usernames, code, ...) in Telegram messages to Discord format * * @param {String} text The text to handle * @param {MessageEntity[]} entities Array of entities for the text * @param {Discord.Client} dcBot The Discord bot * @param {Bridge} bridge The bridge this message is crossing * * @return {String} The fully converted string */ function handleEntities(text, entities, dcBot, bridge) { // Don't mess up the original const substitutedText = text !== undefined ? text.split("") : [""]; // Markdown links to put on the message const markdownLinks = []; // Make sure messages without entities don't crash the thing if (!Array.isArray(entities)) { entities = []; } // Iterate over the entities backwards, to not fuck up the offset for (let i = entities.length-1; i >= 0; i--) { // Select the entity object const e = entities[i]; // Extract the entity part const part = text.substring(e.offset, e.offset+e.length); // The string to substitute let substitute = part; // Do something based on entity type switch (e.type) { case "mention": case "text_mention": { // A mention. Substitute the Discord user ID or Discord role ID if one exists const mentionable = part.substring(1); const dcUser = dcBot.channels.get(bridge.discord.channelId).members.find("displayName", mentionable); const dcRole = dcBot.guilds.get(bridge.discord.serverId).roles.find("name", mentionable); substitute = dcUser !== null ? `<@${dcUser.id}>` : `<@&${dcRole.id}>`; break; } case "code": { // Inline code. Add backticks substitute = "`" + part + "`"; break; } case "pre": { // Code block. Add triple backticks substitute = "```\n" + part + "\n```"; break; } case "text_link": { // Markdown style link. 'part' is the text, 'e.url' is the URL // substitute = "[" + part + "](" + e.url + ")"; // Discord appears to not be able to handle this type of links. Make the substitution an object which can be found and properly substituted later markdownLinks.unshift(e.url); substitute = { type: "mdlink", text: part }; break; } case "bold": { // Bold text substitute = "**" + part + "**"; break; } case "italic": { // Italic text substitute = "*" + part + "*"; break; } case "hashtag": { // Possible name of a Discord channel on the same Discord server const channelName = part.substring(1); // Find out if this is a channel on the bridged Discord server const channel = dcBot.guilds.get(bridge.discord.serverId).channels.find("name", channelName); // Make Discord recognize it as a channel mention if (channel !== null) { substitute = `<#${channel.id}>`; } break; } case "url": case "bot_command": case "email": default: { // Just leave it as it is break; } } // Do the substitution if there is a change if (substitute !== part) { substitutedText.splice(e.offset, e.length, substitute); } } // Put the markdown links on the end, if there are any if (markdownLinks.length > 0) { substitutedText.push("\n\n"); for (let i = 0; i < markdownLinks.length; i++) { // Find out where the corresponding text is const index = substitutedText.findIndex((e) => e instanceof Object && e.type === "mdlink"); const obj = substitutedText[index]; // Replace the object with the proper text and reference substitutedText[index] = `${obj.text}[${i+1}]`; // Push the link to the end substitutedText.push(`[${i+1}]: ${markdownLinks[i]}\n`); } } // Return the converted string return substitutedText.join(""); } /*********************** * Export the function * ***********************/ module.exports = handleEntities;
JavaScript
0.000002
@@ -1711,16 +1711,34 @@ .id%7D%3E%60 : + dcRole !== null ? %60%3C@&$%7Bd @@ -1744,24 +1744,38 @@ dcRole.id%7D%3E%60 + : mentionable ;%0A%09%09%09%09break;
36fa253c2831924612ee371e021f43fd01841f75
Fix broken mobile scrolling for settings pages
lib/ui/src/components/layout/mobile.js
lib/ui/src/components/layout/mobile.js
import React, { Component, Children } from 'react'; import PropTypes from 'prop-types'; import { styled } from '@storybook/theming'; import { TabButton } from '@storybook/components'; import { Root } from './container'; const Pane = styled.div( { transition: 'transform .2s ease', position: 'absolute', top: 0, height: '100%', }, ({ theme }) => ({ background: theme.background.content, '&:nth-of-type(1)': { borderRight: `1px solid ${theme.appBorderColor}`, }, '&:nth-of-type(3)': { borderLeft: `1px solid ${theme.appBorderColor}`, }, }), ({ index }) => { switch (index) { case 0: { return { width: '80vw', transform: 'translateX(-80vw)', left: 0, }; } case 1: { return { width: '100%', transform: 'translateX(0) scale(1)', left: 0, }; } case 2: { return { width: '80vw', transform: 'translateX(80vw)', right: 0, }; } default: { return {}; } } }, ({ active, index }) => { switch (true) { case index === 0 && active === 0: { return { transform: 'translateX(-0px)', }; } case index === 1 && active === 0: { return { transform: 'translateX(40vw) translateY(-42.5vh) translateY(40px) scale(0.2)', }; } case index === 1 && active === 2: { return { transform: 'translateX(-40vw) translateY(-42.5vh) translateY(40px) scale(0.2)', }; } case index === 2 && active === 2: { return { transform: 'translateX(0px)', }; } default: { return {}; } } } ); const Panels = React.memo(({ children, active }) => ( <Panels.Container> {Children.toArray(children).map((item, index) => ( // eslint-disable-next-line react/no-array-index-key <Pane key={index} index={index} active={active}> {item} </Pane> ))} </Panels.Container> )); Panels.displayName = 'Panels'; Panels.propTypes = { children: PropTypes.node.isRequired, active: PropTypes.number.isRequired, }; Panels.Container = styled.div({ position: 'fixed', top: 0, left: 0, width: '100vw', height: 'calc(100% - 40px)', }); const Bar = styled.nav( { position: 'fixed', bottom: 0, left: 0, width: '100vw', height: 40, display: 'flex', boxShadow: '0 1px 5px 0 rgba(0, 0, 0, 0.1)', '& > *': { flex: 1, }, }, ({ theme }) => ({ background: theme.barBg, }) ); // eslint-disable-next-line react/no-multi-comp class Mobile extends Component { constructor(props) { super(); const { options } = props; this.state = { active: !!options.initialActive, }; } render() { const { Nav, Preview, Panel, pages, viewMode, options } = this.props; const { active } = this.state; return ( <Root> <Panels active={active}> <Nav /> <div> <div hidden={!viewMode}> <Preview isToolshown={options.isToolshown} id="main" viewMode={viewMode} debug={options} /> </div> {pages.map(({ key, route: Route, render: content }) => ( <Route key={key}>{content()}</Route> ))} </div> <Panel hidden={!viewMode} /> </Panels> <Bar active={active}> <TabButton onClick={() => this.setState({ active: 0 })} active={active === 0}> Sidebar </TabButton> <TabButton onClick={() => this.setState({ active: 1 })} active={active === 1 || active === false} > {viewMode ? 'Canvas' : null} {pages.map(({ key, route: Route }) => ( <Route key={key}>{key}</Route> ))} </TabButton> {viewMode ? ( <TabButton onClick={() => this.setState({ active: 2 })} active={active === 2}> Addons </TabButton> ) : null} </Bar> </Root> ); } } Mobile.displayName = 'MobileLayout'; Mobile.propTypes = { Nav: PropTypes.any.isRequired, // eslint-disable-line react/forbid-prop-types Preview: PropTypes.any.isRequired, // eslint-disable-line react/forbid-prop-types Panel: PropTypes.any.isRequired, // eslint-disable-line react/forbid-prop-types pages: PropTypes.arrayOf( PropTypes.shape({ key: PropTypes.string.isRequired, route: PropTypes.func.isRequired, render: PropTypes.func.isRequired, }) ).isRequired, viewMode: PropTypes.oneOf(['story', 'info']), options: PropTypes.shape({ initialActive: PropTypes.number, }).isRequired, }; Mobile.defaultProps = { viewMode: undefined, }; export { Mobile };
JavaScript
0.000001
@@ -340,16 +340,38 @@ '100%25',%0A + overflow: 'auto',%0A %7D,%0A (
f4a2138227e75b68922891c6236522c2b5bce760
update title
routes/mainRoutes.js
routes/mainRoutes.js
Router.route('/', function () { this.render('HomeTpt'); SEO.set({ title: 'Home -' + Meteor.App.NAME }); }); Router.route('/activ', function () { this.render('ActivListTpt'); SEO.set({ title: 'Home -' + Meteor.App.NAME }); }); Router.route('/activ/new', function () { this.render('ActivNewTpt'); SEO.set({ title: 'Home -' + Meteor.App.NAME }); }); Router.route('/activ/detail', function () { this.render('ActivDetailTpt'); SEO.set({ title: 'Home -' + Meteor.App.NAME }); }); Router.route('/login', function () { this.render('LoginTpt'); SEO.set({ title: 'Home -' + Meteor.App.NAME }); }); Router.route('/update-profile', function () { this.render('UpdateProfileTpt'); SEO.set({ title: 'Home -' + Meteor.App.NAME }); });
JavaScript
0.000001
@@ -69,32 +69,33 @@ %7B title: 'Home - + ' + Meteor.App.N @@ -94,32 +94,32 @@ or.App.NAME %7D);%0A - %7D);%0A%0ARouter.rout @@ -193,32 +193,33 @@ %7B title: 'Home - + ' + Meteor.App.N @@ -320,32 +320,33 @@ %7B title: 'Home - + ' + Meteor.App.N @@ -453,32 +453,33 @@ %7B title: 'Home - + ' + Meteor.App.N @@ -573,32 +573,33 @@ %7B title: 'Home - + ' + Meteor.App.N @@ -684,32 +684,32 @@ teProfileTpt');%0A - SEO.set(%7B titl @@ -718,16 +718,17 @@ 'Home - + ' + Mete
9d5d4083cad67b461fc4bb7f489749d9f082eee2
Add fallback
routes/upload-scp.js
routes/upload-scp.js
import express from "express"; const router = new express.Router(); import fs from "fs"; import multipart from "connect-multiparty"; import ProjectManager from "../objects/ProjectManager.js"; const multipartMiddleware = multipart(); router.post("/", multipartMiddleware, (req, res) => { const newPath = `${__dirname}/../project-scp-files/project.scp`; // Check to facilitate file upload from website as well as Java Application let projectObject = req.files.project; if (!req.files.project) { projectObject = req.files.file; } if (projectObject && projectObject.name.endsWith(".scp")) { fs.rename(projectObject.path, newPath, (err) => { if (err) { res.json({ succes: false, message: "Some error occurred, please try again later!" }); } else { ProjectManager.waitForXML((projectManager) => { projectManager.reloadProject(() => { res.json({ succes: true, message: "Project successfully uploaden!" }); }); }); } }); } else { res.json({ succes: false, message: "Please upload a .scp file." }); } }); router.get("/", (req, res) => { res.render("upload"); }); module.exports = router;
JavaScript
0.000004
@@ -716,109 +716,728 @@ -res.json(%7B%0A succes: false, message: %22Some error occurred, please try again later!%22 +fs.createReadStream(projectObject.path).pipe(fs.createWriteStream(newPath));%0A fs.unlink(projectObject.path, (error) =%3E %7B%0A if (error) %7B%0A res.status(500).json(%7Bsucces: false,%0A message: %22Some error occurred, please try again later!%22 %7D);%0A %7D else %7B%0A ProjectManager.waitForXML((projectManager) =%3E %7B%0A projectManager.reloadProject(() =%3E %7B%0A res.json(%7B succes: true,%0A message: %22Project successfully uploaded!%22 %7D);%0A %7D);%0A %7D);%0A %7D%0A %7D); @@ -1666,17 +1666,17 @@ uploade -n +d !%22 %7D);%0A @@ -1749,32 +1749,32 @@ );%0A %7D else %7B%0A - res.json @@ -1761,32 +1761,44 @@ e %7B%0A res. +status(400). json(%7B succes: f
0c32e3d95f605eb812cf1b1ef96d6e20e4e8f7a5
update threshold xfce example
example_test_suites/example_xfce/case1/sakuli_demo.js
example_test_suites/example_xfce/case1/sakuli_demo.js
/* * Sakuli - Testing and Monitoring-Tool for Websites and common UIs. * * Copyright 2013 - 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ _dynamicInclude($includeFolder); var testCase = new TestCase(40, 60); var env = new Environment(); var screen = new Region(); var appCalc = new Application("/usr/bin/gnome-calculator"); var appGedit = new Application("/usr/bin/gedit"); function checkCentOS() { var dist = env.runCommand('cat /etc/os-release').getOutput(); if (dist.match(/NAME=.*CentOS.*/)) { Logger.logInfo('Detected distribution: CentOS >> override some image patterns'); testCase.addImagePaths("centos"); } } try { checkCentOS(); _highlight(_link("SSL Manager")); _highlight(_link("Logs")); _highlight(_link("Online Documentation")); _highlight(_link("Test Pages")); _highlight(_link("Sample Application")); testCase.endOfStep("Test Sahi landing page", 5); appCalc.open(); screen.waitForImage("calculator.png", 5).mouseMove().highlight(); env.type("525"); env.sleep(2); var calcRegion = appCalc.getRegion(); calcRegion.find("plus.png").highlight().click().type("100"); calcRegion.find("result.png").highlight().click(); screen.waitForImage("625", 5).highlight(); testCase.endOfStep("Calculation", 15); appGedit.open(); screen.waitForImage("gedit.png", 10).highlight(); env.paste("Initial test passed. Sakuli, Sahi and Sikuli seem to work fine. Exiting..."); testCase.endOfStep("Editor", 10); env.sleep(4); } catch (e) { testCase.handleException(e); } finally { appCalc.close(true); //silent appGedit.kill(true); //silent, without exit prompt testCase.saveResult(); }
JavaScript
0
@@ -1853,17 +1853,17 @@ ation%22, -1 +2 5);%0A
9a73139887fc16d092c52c934d754f400d961113
remove old code
src/js/core/LineSegmentsGeometry.js
src/js/core/LineSegmentsGeometry.js
import { Box3, Float32BufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InterleavedBufferAttribute, Sphere, Vector3, } from '../three'; var LineSegmentsGeometry = function () { InstancedBufferGeometry.call( this ); this.type = 'LineSegmentsGeometry'; var positions = [ - 1, 2, 0, 1, 2, 0, - 1, 1, 0, 1, 1, 0, - 1, 0, 0, 1, 0, 0, - 1, - 1, 0, 1, - 1, 0 ]; var uvs = [ - 1, 2, 1, 2, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 2, 1, - 2 ]; var index = [ 0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5 ]; this.setIndex( index ); this.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); }; LineSegmentsGeometry.prototype = Object.assign( Object.create( InstancedBufferGeometry.prototype ), { constructor: LineSegmentsGeometry, isLineSegmentsGeometry: true, applyMatrix4: function ( matrix ) { var start = this.attributes.instanceStart; var end = this.attributes.instanceEnd; if ( start !== undefined ) { start.applyMatrix4( matrix ); end.applyMatrix4( matrix ); start.needsUpdate = true; } if ( this.boundingBox !== null ) { this.computeBoundingBox(); } if ( this.boundingSphere !== null ) { this.computeBoundingSphere(); } return this; }, setPositions: function ( array ) { var lineSegments; if ( array instanceof Float32Array ) { lineSegments = array; } else if ( Array.isArray( array ) ) { lineSegments = new Float32Array( array ); } var instanceBuffer = new InstancedInterleavedBuffer( lineSegments, 6, 1 ); // xyz, xyz this.setAttribute( 'instanceStart', new InterleavedBufferAttribute( instanceBuffer, 3, 0 ) ); // xyz this.setAttribute( 'instanceEnd', new InterleavedBufferAttribute( instanceBuffer, 3, 3 ) ); // xyz // this.computeBoundingBox(); this.computeBoundingSphere(); return this; }, setColors: function ( array ) { var colors; if ( array instanceof Float32Array ) { colors = array; } else if ( Array.isArray( array ) ) { colors = new Float32Array( array ); } var instanceColorBuffer = new InstancedInterleavedBuffer( colors, 6, 1 ); // rgb, rgb this.setAttribute( 'instanceColorStart', new InterleavedBufferAttribute( instanceColorBuffer, 3, 0 ) ); // rgb this.setAttribute( 'instanceColorEnd', new InterleavedBufferAttribute( instanceColorBuffer, 3, 3 ) ); // rgb return this; }, computeBoundingBox: function () { var box = new Box3(); return function computeBoundingBox() { if ( this.boundingBox === null ) { this.boundingBox = new Box3(); } var start = this.attributes.instanceStart; var end = this.attributes.instanceEnd; if ( start !== undefined && end !== undefined ) { this.boundingBox.setFromBufferAttribute( start ); box.setFromBufferAttribute( end ); this.boundingBox.union( box ); } }; }(), computeBoundingSphere: function () { var vector = new Vector3(); return function computeBoundingSphere() { if ( this.boundingSphere === null ) { this.boundingSphere = new Sphere(); } if ( this.boundingBox === null ) { this.computeBoundingBox(); } var start = this.attributes.instanceStart; var end = this.attributes.instanceEnd; if ( start !== undefined && end !== undefined ) { var center = this.boundingSphere.center; this.boundingBox.getCenter( center ); var maxRadiusSq = 0; for ( var i = 0, il = start.count; i < il; i ++ ) { vector.fromBufferAttribute( start, i ); maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); vector.fromBufferAttribute( end, i ); maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); } this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); if ( isNaN( this.boundingSphere.radius ) ) { console.error( 'THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.', this ); } } }; }(), applyMatrix: function ( matrix ) { console.warn( 'THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().' ); return this.applyMatrix4( matrix ); } } ); export { LineSegmentsGeometry };
JavaScript
0.999865
@@ -4084,188 +4084,8 @@ ),%0A%0A -%09applyMatrix: function ( matrix ) %7B%0A%0A%09%09console.warn( 'THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().' );%0A%0A%09%09return this.applyMatrix4( matrix );%0A%0A%09%7D%0A%0A %7D );
496291cfe9cc4a64a00c826cb4b10a58ce4005f0
优化vc.on函数
java110-front/src/main/resources/static/js/vc-core.js
java110-front/src/main/resources/static/js/vc-core.js
/** 初始化vue 对象 @param vc vue component对象 @param vmOptions Vue参数 **/ (function(vc,vmOptions){ console.log("vmOptions:",vmOptions); vc.component = new Vue(vmOptions); })(window.vc,window.vc.vmOptions); /** vc监听事件 **/ (function(vc){ /** 事件监听 **/ vc.on = function(_componentName,_value,_callback){ if(vc.cosoleFlag){ console.log("监听ON事件",_componentName,_value); } vc.component.$on(_componentName+'_'+_value,_callback); }; /** 事件触发 **/ vc.emit = function(_componentName,_value,_param){ if(vc.cosoleFlag){ console.log("监听emit事件",_componentName,_value,_param); } vc.component.$emit(_componentName+'_'+_value,_param); }; })(window.vc); /** * vue对象 执行初始化方法 */ (function(vc){ vc.initEvent.forEach(function(eventMethod){ eventMethod(); }); vc.initMethod.forEach(function(callback){ callback(); }); })(window.vc);
JavaScript
0.000001
@@ -330,32 +330,122 @@ lue,_callback)%7B%0A +%0A vc.component.$on(_componentName+'_'+_value,%0A function ()%7B%0A if(vc.co @@ -436,32 +436,33 @@ if(vc.co +n soleFlag)%7B%0A @@ -460,32 +460,44 @@ g)%7B%0A + + console.log(%22%E7%9B%91%E5%90%ACO @@ -537,70 +537,85 @@ -%7D%0A vc.component.$on(_componentName+'_'+_value,_callback + %7D%0A _callback();%0A %7D%0A );%0A @@ -708,16 +708,16 @@ param)%7B%0A - @@ -724,16 +724,17 @@ if(vc.co +n soleFlag
bcccdb68d8e7feddf7d2b0311357449b602b9c0c
Optimize login.
kanban/component/login/controllers/loginController.js
kanban/component/login/controllers/loginController.js
/** * Created by xubt on 4/20/16. */ kanbanApp.controller('loginController', ['$scope', '$location', '$q', 'publicKeyServices', 'loginService', 'localStorageService', '$uibModalInstance', '$uibModal', 'timerMessageService', function ($scope, $location, $q, publicKeyServices, loginService, localStorageService, $uibModalInstance, $uibModal, timerMessageService) { $scope.title = "登录"; $scope.isDisableLoginButton = false; $scope.loginButtonText = "登录"; $scope.login = function () { $scope.isDisableLoginButton = true; $scope.loginButtonText = "登录中.."; var publicKeyPromise = publicKeyServices.loadPublicKey(localStorageService.get("publicKeyLink")); publicKeyPromise.then(function (_data) { var encrypt = new JSEncrypt(); encrypt.setPublicKey(_data.publicKey); var identity = $scope.identity; var encryptedPassword = encrypt.encrypt($scope.password); var login = _data._links.login.href; var loadingInstance = timerMessageService.loading(); loginService.login(login, identity, encryptedPassword).then(function (_identity) { $uibModalInstance.dismiss('cancel'); localStorageService.clearAll(); localStorageService.set("identity.token", _identity.token); localStorageService.set("identity.userName", _identity.userName); localStorageService.set("user.links", _identity._links); localStorageService.set("currentUser", _identity); var currentPath = $location.path(); if (currentPath.indexOf("welcome")) { $location.path(_identity.userName + '/boards'); } timerMessageService.message("登录成功,正在为你准备数据.."); }).finally(function () { $scope.isDisableLoginButton = false; $scope.loginButtonText = "登录"; timerMessageService.close(loadingInstance); }); }); }; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }; $scope.openForgetPasswordModal = function () { $uibModalInstance.dismiss('cancel'); $uibModal.open({ animation: true, templateUrl: 'component/password/partials/forget-password.html', controller: "passwordController", size: 'sm', backdrop: "static" }); }; $scope.register = function () { $uibModal.open({ animation: true, templateUrl: 'component/register/partials/register.html', controller: "registerController", size: 'sm', backdrop: "static" }); }; }]);
JavaScript
0
@@ -219,16 +219,27 @@ ervice', + 'toaster', %0A fun @@ -371,16 +371,25 @@ eService +, toaster ) %7B%0A @@ -1874,76 +1874,8 @@ %7D%0A - timerMessageService.message(%22%E7%99%BB%E5%BD%95%E6%88%90%E5%8A%9F%EF%BC%8C%E6%AD%A3%E5%9C%A8%E4%B8%BA%E4%BD%A0%E5%87%86%E5%A4%87%E6%95%B0%E6%8D%AE..%22);%0A
4d339aa2b86fff236ad3b12e10ea89b30b3fb51f
fix console log
server/public/scripts/controllers/login.controller.js
server/public/scripts/controllers/login.controller.js
app.controller('LoginController', ['$scope', '$mdDialog', '$firebaseAuth', function($scope, $mdDialog, $firebaseAuth){ console.log('diag controller is running'); var auth = $firebaseAuth(); var self = this; var logIn = function() { auth.$signInWithPopup("google").then(function(firebaseUser) { console.log("Firebase Authenticated as: ", firebaseUser.user); }).catch(function(error) { console.log("Authentication failed: ", error); }); }; self.hide = function() { $mdDialog.hide(); }; self.cancel = function() { $mdDialog.cancel(); }; self.answer = function(answer) { logIn(); // $mdDialog.hide(answer); // console.log('from dialog controller', answer); }; }]);
JavaScript
0.000002
@@ -131,12 +131,13 @@ og(' -diag +login con
4e5a459bddc68fde2e6726c21c28a861b15bd4ca
Fix (test added)
client/app/scripts/superdesk-users/tests/users_spec.js
client/app/scripts/superdesk-users/tests/users_spec.js
'use strict'; describe('users api', function() { beforeEach(module('superdesk.users')); beforeEach(module('superdesk.mocks')); it('can create user', inject(function(usersService, api, $q, $rootScope) { var user = {}, data = {'UserName': 'foo', 'Password': 'bar'}; spyOn(api, 'save').and.returnValue($q.when({})); usersService.save(user, data).then(function() {}); $rootScope.$digest(); expect(api.save).toHaveBeenCalled(); })); it('can update user', inject(function(usersService, api, $q, $rootScope) { var user = {UserName: 'foo', FirstName: 'a'}, data = {FirstName: 'foo', LastName: 'bar'}; spyOn(api, 'save').and.returnValue($q.when({})); usersService.save(user, data); $rootScope.$digest(); expect(api.save).toHaveBeenCalled(); expect(user.FirstName).toBe('foo'); expect(user.LastName).toBe('bar'); })); xit('can change user password', inject(function(usersService, resource, $rootScope) { var user = {UserPassword: {href: 'pwd_url'}}; spyOn(resource, 'replace'); usersService.changePassword(user, 'old', 'new'); expect(resource.replace).toHaveBeenCalledWith('pwd_url', { old_pwd: 'old', new_pwd: 'new' }); })); }); describe('userlist service', function() { beforeEach(module('superdesk.users')); beforeEach(module('superdesk.mocks')); beforeEach(module(function($provide) { $provide.service('api', function($q) { return function(resource) { return { query: function() { return $q.when({_items: [{_id: 1}, {_id: 2}, {_id: 3}]}); }, getById: function() { return $q.when({_id: 1}); } }; }; }); })); it('can fetch users', inject(function(userList, $rootScope) { var res = null; userList.get() .then(function(result) { res = result; }); $rootScope.$digest(); expect(res).toEqual({_items: [{_id: 1}, {_id: 2}, {_id: 3}]}); })); it('can return users from cache', inject(function(userList, $rootScope, api) { userList.get().then(function(result) {}); $rootScope.$digest(); api = jasmine.createSpy('api'); userList.get().then(function(result) {}); $rootScope.$digest(); expect(api).not.toHaveBeenCalled(); })); it('can fetch single user', inject(function(userList, $rootScope) { var res = null; userList.getUser(1) .then(function(result) { res = result; }); $rootScope.$digest(); expect(res).toEqual({_id: 1}); })); it('can return single user from default cacher', inject(function(userList, $rootScope, api) { userList.get().then(function(result) {}); $rootScope.$digest(); api = jasmine.createSpy('api'); userList.getUser(1).then(function(result) {}); $rootScope.$digest(); expect(api).not.toHaveBeenCalled(); })); });
JavaScript
0
@@ -3200,24 +3200,1038 @@ nCalled();%0A %7D));%0A%7D);%0A +%0Adescribe('mentio directive', function() %7B%0A%0A beforeEach(module('superdesk.users'));%0A beforeEach(module('superdesk.mocks'));%0A beforeEach(module('templates'));%0A%0A beforeEach(module(function($provide) %7B%0A $provide.service('api', function($q) %7B%0A return function(resource) %7B%0A return %7B%0A query: function() %7B%0A return $q.when(%7B_items: %5B%7B_id: 1, username: 'moo'%7D, %7B_id: 2, username: 'foo'%7D, %7B_id: 3, username: 'fast'%7D%5D%7D);%0A %7D%0A %7D;%0A %7D;%0A %7D);%0A %7D));%0A%0A it('can return sorted users', inject(function($rootScope, $compile) %7B%0A var scope = $rootScope.$new(true);%0A var elem = $compile('%3Cdiv sd-user-mentio%3E%3C/div%3E')(scope);%0A scope.$digest();%0A%0A var iscope = elem.scope();%0A iscope.searchUsers();%0A $rootScope.$digest();%0A expect(iscope.users).toEqual(%5B%7B_id: 3, username: 'fast'%7D, %7B_id: 2, username: 'foo'%7D, %7B_id: 1, username: 'moo'%7D%5D);%0A %7D));%0A%7D);%0A
986b543afd5a89fa40accb486b7d6dfac9ddf056
allow empty line in config type preperties
console/src/main/resources/static/console-fe/src/utils/validateContent.js
console/src/main/resources/static/console-fe/src/utils/validateContent.js
import * as yamljs from 'yamljs'; export default { /** * 检测json是否合法 */ validateJson(str) { try { return !!JSON.parse(str); } catch (e) { return false; } }, /** * 检测xml和html是否合法 */ validateXml(str) { try { if (typeof DOMParser !== 'undefined') { let parserObj = new window.DOMParser() .parseFromString(str, 'application/xml') .getElementsByTagName('parsererror') || {}; return parserObj.length === 0; } else if (typeof window.ActiveXObject !== 'undefined') { let xml = new window.ActiveXObject('Microsoft.XMLDOM'); xml.async = 'false'; xml.loadXML(str); return xml; } } catch (e) { return false; } }, /** * 检测yaml是否合法 */ validateYaml(str) { try { return yamljs.parse(str); } catch (e) { return false; } }, /** * 检测属性是否正确 */ validateProperties(str = '') { const reg = /^[^=]+=.+$/; return str .replace('\n\r', '\n') .split('\n') .every(_str => reg.test(_str.trim())); }, /** * 根据类型验证类型 */ validate({ content, type }) { let validateObj = { json: this.validateJson, xml: this.validateXml, 'text/html': this.validateXml, html: this.validateXml, properties: this.validateProperties, yaml: this.validateYaml, }; if (!validateObj[type]) { return true; } return validateObj[type](content); }, };
JavaScript
0.000002
@@ -1052,24 +1052,52 @@ split('%5Cn')%0A + .filter(_str =%3E _str)%0A .every
3893b72762de6f25c9644a71614485faf8b6a65e
Use is-nan to check for NaN return values
lib/node_modules/@stdlib/math/base/special/gamma/test/other/test.gamma.js
lib/node_modules/@stdlib/math/base/special/gamma/test/other/test.gamma.js
'use strict'; // MODULES // var tape = require( 'tape' ); var incrspace = require( '@stdlib/math/generics/utils/incrspace' ); var abs = require( '@stdlib/math/base/special/abs' ); var PINF = require( '@stdlib/math/constants/float64-pinf' ); var NINF = require( '@stdlib/math/constants/float64-ninf' ); var gamma = require( 'gamma' ); // FIXTURES // var data1 = require( './../fixtures/data1.json' ); var expected1 = require( './../fixtures/expected1.json' ); var data2 = require( './../fixtures/data2.json' ); var expected2 = require( './../fixtures/expected2.json' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( typeof gamma === 'function', 'main export is a function' ); t.end(); }); tape( 'if provided a negative integer, the function returns `NaN`', function test( t ) { var values = incrspace( -1, -1000, -1 ); var v; var i; for ( i = 0; i < values.length; i++ ) { v = gamma( values[ i ] ); t.ok( v !== v, 'returns NaN when provided ' + values[ i ] ); } t.end(); }); tape( 'if provided negative infinity, the function returns `NaN`', function test( t ) { var v = gamma( NINF ); t.ok( v !== v, 'returns NaN when provided negative infinity' ); t.end(); }); tape( 'if provided `NaN`, the function returns `NaN`', function test( t ) { var v = gamma( NaN ); t.ok( v !== v, 'returns NaN when provided a NaN' ); t.end(); }); tape( 'if provided `-0`, the function returns negative infinity', function test( t ) { var v = gamma( -0 ); t.equal( v, NINF, 'returns -infinity' ); t.end(); }); tape( 'if provided `+0`, the function returns positive infinity', function test( t ) { var v = gamma( 0 ); t.equal( v, PINF, 'returns +infinity' ); t.end(); }); tape( 'if `x > 171.6144...`, the function returns positive infinity', function test( t ) { var values = incrspace( 172, 1000, 10.1234 ); var v; var i; for ( i = 0; i < values.length; i++ ) { v = gamma( values[ i ] ); t.equal( v, PINF, 'returns +infinity when provided ' + values[ i ] ); } t.end(); }); tape( 'if `x < -170.56749...`, the function returns positive infinity', function test( t ) { var values = incrspace( -170.57, -1000, -10.1234 ); var v; var i; for ( i = 0; i < values.length; i++ ) { v = gamma( values[ i ] ); t.equal( v, PINF, 'returns +infinity when provided ' + values[ i ] ); } t.end(); }); tape( 'the function evaluates the gamma function (positive integers)', function test( t ) { var delta; var tol; var v; var i; for ( i = 0; i < data1.length; i++ ) { v = gamma( data1[ i ] ); delta = abs( v - expected1[ i ] ); tol = 2.75e-12 * Math.max( 1, abs( v ), abs( expected1[ i ] ) ); t.ok( delta <= tol, 'within tolerance. x: ' + data1[ i ] + '. Value: ' + v + '. Expected: ' + expected1[ i ] + '. Tolerance: ' + tol + '.' ); } t.end(); }); tape( 'the function evaluates the gamma function (decimal values)', function test( t ) { var delta; var tol; var v; var i; for ( i = 0; i < data2.length; i++ ) { v = gamma( data2[ i ] ); delta = abs( v - expected2[ i ] ); tol = 2.75e-12 * Math.max( 1, abs( v ), abs( expected2[ i ] ) ); t.ok( delta <= tol, 'within tolerance. x: ' + data2[ i ] + '. Value: ' + v + '. Expected: ' + expected2[ i ] + '. Tolerance: ' + tol + '.' ); } t.end(); }); tape( 'if provided a positive integer, the function returns the factorial of (n-1)', function test( t ) { t.equal( gamma( 4 ), 6, 'returns 6' ); t.equal( gamma( 5 ), 24, 'returns 24' ); t.equal( gamma( 6 ), 120, 'returns 120' ); t.end(); });
JavaScript
0.000004
@@ -49,24 +49,81 @@ ( 'tape' );%0A +var isnan = require( '@stdlib/math/base/utils/is-nan' );%0A var incrspac @@ -174,24 +174,24 @@ crspace' );%0A - var abs = re @@ -701,16 +701,46 @@ %7B%0A%09t.ok( + true, __filename );%0A%09t.equal( typeof @@ -748,12 +748,9 @@ amma - === +, 'fu @@ -1025,27 +1025,39 @@ );%0A%09%09t. -ok( v !== v +equal( isnan( v ), true , 'retur @@ -1225,35 +1225,47 @@ NINF );%0A%09t. -ok( v !== v +equal( isnan( v ), true , 'returns N @@ -1424,19 +1424,31 @@ %0A%09t. -ok( v !== v +equal( isnan( v ), true , 'r
4ab9e2d8258f98f5171f8e610ce119ffb3205c52
Fix PanResponderExample
RNTester/js/examples/PanResponder/PanResponderExample.js
RNTester/js/examples/PanResponder/PanResponderExample.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow weak */ 'use strict'; const React = require('react'); const {PanResponder, StyleSheet, View} = require('react-native'); import type { PanResponderInstance, GestureState, } from '../../../../Libraries/Interaction/PanResponder'; import type {PressEvent} from '../../../../Libraries/Types/CoreEventTypes'; type CircleStyles = { backgroundColor?: string, left?: number, top?: number, }; const CIRCLE_SIZE = 80; type Props = $ReadOnly<{||}>; class PanResponderExample extends React.Component<Props> { _handleStartShouldSetPanResponder = ( event: PressEvent, gestureState: GestureState, ): boolean => { // Should we become active when the user presses down on the circle? return true; }; _handleMoveShouldSetPanResponder = ( event: PressEvent, gestureState: GestureState, ): boolean => { // Should we become active when the user moves a touch over the circle? return true; }; _handlePanResponderGrant = ( event: PressEvent, gestureState: GestureState, ) => { this._highlight(); }; _handlePanResponderMove = (event: PressEvent, gestureState: GestureState) => { this._circleStyles.style.left = this._previousLeft + gestureState.dx; this._circleStyles.style.top = this._previousTop + gestureState.dy; this._updateNativeStyles(); }; _handlePanResponderEnd = (event: PressEvent, gestureState: GestureState) => { this._unHighlight(); this._previousLeft += gestureState.dx; this._previousTop += gestureState.dy; }; _panResponder: PanResponderInstance = PanResponder.create({ onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder, onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder, onPanResponderGrant: this._handlePanResponderGrant, onPanResponderMove: this._handlePanResponderMove, onPanResponderRelease: this._handlePanResponderEnd, onPanResponderTerminate: this._handlePanResponderEnd, }); _previousLeft: number = 0; _previousTop: number = 0; _circleStyles: {|style: CircleStyles|} = {style: {}}; circle: ?React.ElementRef<typeof View> = null; UNSAFE_componentWillMount() { this._previousLeft = 20; this._previousTop = 84; this._circleStyles = { style: { left: this._previousLeft, top: this._previousTop, backgroundColor: 'green', }, }; } componentDidMount() { this._updateNativeStyles(); } _highlight() { this._circleStyles.style.backgroundColor = 'blue'; this._updateNativeStyles(); } _unHighlight() { this._circleStyles.style.backgroundColor = 'green'; this._updateNativeStyles(); } _updateNativeStyles() { this.circle && this.circle.setNativeProps(this._circleStyles); } render() { return ( <View style={styles.container}> <View ref={circle => { this.circle = circle; }} style={styles.circle} {...this._panResponder.panHandlers} /> </View> ); } } const styles = StyleSheet.create({ circle: { width: CIRCLE_SIZE, height: CIRCLE_SIZE, borderRadius: CIRCLE_SIZE / 2, position: 'absolute', left: 0, top: 0, }, container: { flex: 1, paddingTop: 64, }, }); exports.title = 'PanResponder Sample'; exports.description = 'Shows the Use of PanResponder to provide basic gesture handling'; exports.examples = [ { title: 'Basic gresture handling', render: function(): React.Element<typeof PanResponderExample> { return <PanResponderExample />; }, }, ];
JavaScript
0
@@ -3315,24 +3315,54 @@ IRCLE_SIZE,%0A + backgroundColor: 'green',%0A borderRa @@ -3476,22 +3476,19 @@ -paddingTop: 64 +height: 500 ,%0A @@ -3669,17 +3669,16 @@ 'Basic g -r esture h
480c4c674c69b2d39ef8f0f69ad1967609334b81
Add to the Docker option
plugins/services/src/js/components/forms/GeneralServiceFormSection.js
plugins/services/src/js/components/forms/GeneralServiceFormSection.js
import React, {Component} from 'react'; import {Tooltip} from 'reactjs-components'; import AdvancedSection from '../../../../../../src/js/components/form/AdvancedSection'; import AdvancedSectionContent from '../../../../../../src/js/components/form/AdvancedSectionContent'; import AdvancedSectionLabel from '../../../../../../src/js/components/form/AdvancedSectionLabel'; import ContainerServiceFormSection from './ContainerServiceFormSection'; import FieldError from '../../../../../../src/js/components/form/FieldError'; import FieldHelp from '../../../../../../src/js/components/form/FieldHelp'; import FieldInput from '../../../../../../src/js/components/form/FieldInput'; import FieldLabel from '../../../../../../src/js/components/form/FieldLabel'; import {findNestedPropertyInObject} from '../../../../../../src/js/utils/Util'; import FormGroup from '../../../../../../src/js/components/form/FormGroup'; import MetadataStore from '../../../../../../src/js/stores/MetadataStore'; import Icon from '../../../../../../src/js/components/Icon'; import General from '../../reducers/serviceForm/General'; import VolumeConstants from '../../constants/VolumeConstants'; const {MESOS, DOCKER} = VolumeConstants.type; const containerRuntimes = { [MESOS]: { label: <span>Universal Container Runtime</span>, helpText: 'Native container engine in Mesos using standard Linux features. Supports multiple containers (Pods) and GPU resources.' }, [DOCKER]: { label: <span>Docker Engine</span>, helpText: 'Docker’s container runtime. No support for multiple containers (Pods) or GPU resources.' } }; class GeneralServiceFormSection extends Component { getRuntimeSelections(data = {}) { let {container = {}, cmd, gpus} = data; let isDisabled = {}; let disabledTooltipContent; let type = container.type || MESOS; let image = findNestedPropertyInObject(container, 'docker.image'); // Single container with command and no image, disable 'DOCKER' if (cmd && !image) { isDisabled[DOCKER] = true; disabledTooltipContent = 'If you want to use Docker Engine you have to enter a container image, otherwise please select Universal Container Runtime.'; } // TODO: Handle GPUs if (gpus != null) { isDisabled[DOCKER] = true; disabledTooltipContent = 'Docker Engine does not support GPU resources, please select Universal Container Runtime if you want to use GPU resources.'; } return Object.keys(containerRuntimes).map((runtimeName, index) => { let {helpText, label} = containerRuntimes[runtimeName]; let field = ( <FieldLabel className="text-align-left" key={index}> <FieldInput checked={Boolean(type === runtimeName)} disabled={isDisabled[runtimeName]} name="container.type" type="radio" value={runtimeName} /> {label} <FieldHelp>{helpText}</FieldHelp> </FieldLabel> ); // Wrap field in tooltip if disabled and content populated if (isDisabled[runtimeName] && disabledTooltipContent) { field = ( <Tooltip content={disabledTooltipContent} interactive={true} key={index} maxWidth={300} scrollContainer=".gm-scroll-view" wrapText={true}> {field} </Tooltip> ); } return field; }); } getIDHelpBlock() { return ( <span> {'Include the path to your service, if applicable. E.g. /dev/tools/my-service. '} <a href="https://mesosphere.github.io/marathon/docs/application-groups.html" target="_blank"> More information </a>. </span> ); } render() { let {data, errors} = this.props; let typeErrors = findNestedPropertyInObject(errors, 'container.type'); let runtimeTooltipContent = ( <span> {'You can run Docker containers with both container runtimes. The Universal Container Runtime is better supported in DC/OS. '} <a href={MetadataStore.buildDocsURI('/usage/containerizers/')} target="_blank"> More information </a>. </span> ); return ( <div className="form flush-bottom"> <div className="form-row-element"> <h2 className="form-header flush-top short-bottom"> Services </h2> <p> Configure your service below. Start by giving your service a name. </p> </div> <div className="flex row"> <FormGroup className="column-8" required={true} showError={Boolean(errors.id)}> <FieldLabel> Service Name </FieldLabel> <FieldInput name="id" type="text" value={data.id} /> <FieldHelp>{this.getIDHelpBlock()}</FieldHelp> <FieldError>{errors.id}</FieldError> </FormGroup> <FormGroup className="column-4" showError={Boolean(errors.instances)}> <FieldLabel> Instances </FieldLabel> <FieldInput name="instances" min={0} type="number" value={data.instances} /> <FieldError>{errors.instances}</FieldError> </FormGroup> </div> <AdvancedSection> <AdvancedSectionLabel> Advanced Service Settings </AdvancedSectionLabel> <AdvancedSectionContent> <h3 className="short-top short-bottom"> {'Container Runtime '} <Tooltip content={runtimeTooltipContent} interactive={true} maxWidth={300} scrollContainer=".gm-scroll-view" wrapText={true}> <Icon color="grey" id="ring-question" size="mini" family="mini" /> </Tooltip> </h3> <p>The container runtime is responsible for running your service. We support the Mesos and Docker containerizers.</p> <FormGroup showError={Boolean(typeErrors)}> {this.getRuntimeSelections(data)} <FieldError>{typeErrors}</FieldError> </FormGroup> </AdvancedSectionContent> </AdvancedSection> <ContainerServiceFormSection data={data} errors={errors} /> </div> ); } } GeneralServiceFormSection.defaultProps = { data: {}, errors: {} }; GeneralServiceFormSection.propTypes = { data: React.PropTypes.object, errors: React.PropTypes.object }; GeneralServiceFormSection.configReducers = General; module.exports = GeneralServiceFormSection;
JavaScript
0.000002
@@ -1488,16 +1488,39 @@ r Engine + %3Cem%3E(recommended)%3C/em%3E %3C/span%3E,
e8b046964e658740df0210a38f7f1b21bb2a7239
Fix promise usage
Sources/IO/Core/DataAccessHelper/HttpDataAccessHelper.js
Sources/IO/Core/DataAccessHelper/HttpDataAccessHelper.js
import pako from 'pako'; import macro from 'vtk.js/Sources/macro'; import Endian from 'vtk.js/Sources/Common/Core/Endian'; import { DataTypeByteSize } from 'vtk.js/Sources/Common/Core/DataArray/Constants'; const { vtkErrorMacro, vtkDebugMacro } = macro; let requestCount = 0; function fetchBinary(url, options = {}) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = (e) => { if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.status === 0) { resolve(xhr.response); } else { reject(xhr, e); } } }; if (options && options.progressCallback) { xhr.addEventListener('progress', options.progressCallback); } // Make request xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.send(); }); } function fetchArray(instance = {}, baseURL, array, options = {}) { if (array.ref && !array.ref.pending) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); const url = [ baseURL, array.ref.basepath, options.compression ? `${array.ref.id}.gz` : array.ref.id, ].join('/'); xhr.onreadystatechange = (e) => { if (xhr.readyState === 1) { array.ref.pending = true; if (++requestCount === 1 && instance.invokeBusy) { instance.invokeBusy(true); } } if (xhr.readyState === 4) { array.ref.pending = false; if (xhr.status === 200 || xhr.status === 0) { array.buffer = xhr.response; if (options.compression) { if (array.dataType === 'string' || array.dataType === 'JSON') { array.buffer = pako.inflate(new Uint8Array(array.buffer), { to: 'string', }); } else { array.buffer = pako.inflate( new Uint8Array(array.buffer) ).buffer; } } if (array.ref.encode === 'JSON') { array.values = JSON.parse(array.buffer); } else { if (Endian.ENDIANNESS !== array.ref.encode && Endian.ENDIANNESS) { // Need to swap bytes vtkDebugMacro(`Swap bytes of ${array.name}`); Endian.swapBytes( array.buffer, DataTypeByteSize[array.dataType] ); } array.values = new window[array.dataType](array.buffer); } if (array.values.length !== array.size) { vtkErrorMacro( `Error in FetchArray: ${ array.name }, does not have the proper array size. Got ${ array.values.length }, instead of ${array.size}` ); } // Done with the ref and work delete array.ref; if (--requestCount === 0 && instance.invokeBusy) { instance.invokeBusy(false); } if (instance.modified) { instance.modified(); } resolve(array); } else { reject(xhr, e); } } }; if (options && options.progressCallback) { xhr.addEventListener('progress', options.progressCallback); } // Make request xhr.open('GET', url, true); xhr.responseType = options.compression || array.dataType !== 'string' ? 'arraybuffer' : 'text'; xhr.send(); }); } return new Promise((resolve, reject) => { resolve(array); }); } // ---------------------------------------------------------------------------- function fetchJSON(instance = {}, url, options = {}) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = (e) => { if (xhr.readyState === 1) { if (++requestCount === 1 && instance.invokeBusy) { instance.invokeBusy(true); } } if (xhr.readyState === 4) { if (--requestCount === 0 && instance.invokeBusy) { instance.invokeBusy(false); } if (xhr.status === 200 || xhr.status === 0) { if (options.compression) { resolve( JSON.parse( pako.inflate(new Uint8Array(xhr.response), { to: 'string' }) ) ); } else { resolve(JSON.parse(xhr.responseText)); } } else { reject(xhr, e); } } }; if (options && options.progressCallback) { xhr.addEventListener('progress', options.progressCallback); } // Make request xhr.open('GET', url, true); xhr.responseType = options.compression ? 'arraybuffer' : 'text'; xhr.send(); }); } // ---------------------------------------------------------------------------- function fetchText(instance = {}, url, options = {}) { if (options && options.compression && options.compression !== 'gz') { vtkErrorMacro('Supported algorithms are: [gz]'); vtkErrorMacro(`Unkown compression algorithm: ${options.compression}`); } return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = (e) => { if (xhr.readyState === 1) { if (++requestCount === 1 && instance.invokeBusy) { instance.invokeBusy(true); } } if (xhr.readyState === 4) { if (--requestCount === 0 && instance.invokeBusy) { instance.invokeBusy(false); } if (xhr.status === 200 || xhr.status === 0) { if (options.compression) { resolve( pako.inflate(new Uint8Array(xhr.response), { to: 'string' }) ); } else { resolve(xhr.responseText); } } else { reject(xhr, e); } } }; if (options.progressCallback) { xhr.addEventListener('progress', options.progressCallback); } // Make request xhr.open('GET', url, true); xhr.responseType = options.compression ? 'arraybuffer' : 'text'; xhr.send(); }); } // ---------------------------------------------------------------------------- export default { fetchArray, fetchJSON, fetchText, fetchBinary, // Only for HTTP };
JavaScript
0
@@ -250,16 +250,67 @@ macro;%0A%0A +/* eslint-disable prefer-promise-reject-errors */%0A%0A let requ @@ -634,38 +634,42 @@ reject( +%7B xhr, e + %7D );%0A %7D%0A @@ -3293,38 +3293,42 @@ reject( +%7B xhr, e + %7D );%0A %7D%0A @@ -3702,47 +3702,16 @@ urn -new Promise -((resolve, reject) =%3E %7B%0A +. reso @@ -3722,22 +3722,16 @@ array);%0A - %7D);%0A %7D%0A%0A// -- @@ -4625,38 +4625,42 @@ reject( +%7B xhr, e + %7D );%0A %7D%0A @@ -5995,22 +5995,26 @@ reject( +%7B xhr, e + %7D );%0A @@ -6459,11 +6459,61 @@ or HTTP%0A - %7D;%0A +%0A/* eslint-enable prefer-promise-reject-errors */%0A
1bc0febdf56a49d70f61eda1cc81f405a5ba7064
Patch for CKEditor and IE11
server/theme/default/libraries/bootstrap/js/bootstrap-ckeditor-fix.js
server/theme/default/libraries/bootstrap/js/bootstrap-ckeditor-fix.js
// bootstrap-ckeditor-fix.js // hack to fix ckeditor/bootstrap compatiability bug when ckeditor appears in a bootstrap modal dialog // // Include this file AFTER both jQuery and bootstrap are loaded. $.fn.modal.Constructor.prototype.enforceFocus = function() { modal_this = this $(document).on('focusin.modal', function (e) { if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select') && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_text')) { modal_this.$element.focus() } }) };
JavaScript
0
@@ -422,74 +422,49 @@ -&& !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select') +// add whatever conditions you need here: %0A @@ -508,29 +508,8 @@ 'cke -_dialog_ui_input_text '))
78cee3bc3ed1a9351d6533a95ab2f5e2c77762e5
update step 5 with Sarah's edits
src/app/components/msp/application/confirmation/i18n/data/en/index.js
src/app/components/msp/application/confirmation/i18n/data/en/index.js
module.exports = { pageTitle: '<i class="fa fa-check success" aria-hidden="true"></i> Your application has been submitted.', secondTitle: 'What happens next', nextStep1: "<a>Print your application</a> for your records", nextStep2: "Allow 21 business days for your application to be processed", nextStep3: "Once your application is processed, you will receive a letter in the mail indicating your eligibility for MSP and the date your basic health coverage will begin (if applicable). You may have a <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents/eligibility-and-enrolment/how-to-enrol/coverage-wait-period' target='_blank'>wait period</a>.", nextStep4: "Once you receive your first bill, you can get your <a href='http://www2.gov.bc.ca/gov/content/governments/government-id/bc-services-card' target='blank'>BC Services Card</a> – visit <a href='http://www.icbc.com/Pages/default.aspx'target='_blank'>ICBC</a> or <a href='http://www2.gov.bc.ca/gov/content/governments/organizational-structure/ministries-organizations/ministries/technology-innovation-and-citizens-services/servicebc' target='blank'>Service BC</a> to get one", nextStep5: "Low income individuals and families, who have lived in Canada for at least a year, may also be eligible for financial help with paying the monthly premium – <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents/premiums/regular-premium-assistance' target='_blank'>find out about premium assistance</a> <i class='fa fa-external-link' aria-hidden='true'></i>", nextStep6: "Depending on your income, you may be eligible for <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/pharmacare-for-bc-residents/who-we-cover/fair-pharmacare-plan' target='_blank'>FairPharmacare</a> <i class='fa fa-external-link' aria-hidden='true'></i>, to help with the cost of eligible prescription drugs and designated medical supplies", nextStep7: "If you have questions, contact <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents-contact-us' target='_blank'>Health Insurance BC</a>" }
JavaScript
0
@@ -1209,19 +1209,18 @@ viduals -and +or familie @@ -1220,17 +1220,16 @@ families -, who hav
4c9943ac38e8f006e0a13dd3154bc74a4ae5ca3b
Fix an image path on the mobile landing page
react/features/unsupported-browser/components/UnsupportedMobileBrowser.js
react/features/unsupported-browser/components/UnsupportedMobileBrowser.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Platform } from '../../base/react'; /** * The map of platforms to URLs at which the mobile app for the associated * platform is available for download. * * @private */ const _URLS = { android: 'https://play.google.com/store/apps/details?id=org.jitsi.meet', ios: 'https://itunes.apple.com/us/app/jitsi-meet/id1165103905' }; /** * React component representing mobile browser page. * * @class UnsupportedMobileBrowser */ class UnsupportedMobileBrowser extends Component { /** * UnsupportedMobileBrowser component's property types. * * @static */ static propTypes = { /** * The name of the conference room to be joined upon clicking the * respective button. * * @private * @type {string} */ _room: React.PropTypes.string } /** * Initializes the text and URL of the `Start a conference` / `Join the * conversation` button which takes the user to the mobile app. * * @inheritdoc */ componentWillMount() { const joinText = this.props._room ? 'Join the conversation' : 'Start a conference'; // If the user installed the app while this Component was displayed // (e.g. the user clicked the Download the App button), then we would // like to open the current URL in the mobile app. The only way to do it // appears to be a link with an app-specific scheme, not a Universal // Link. const joinURL = `org.jitsi.meet:${window.location.href}`; this.setState({ joinText, joinURL }); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { const ns = 'unsupported-mobile-browser'; const downloadButtonClassName = `${ns}__button ${ns}__button_primary`; return ( <div className = { ns }> <div className = { `${ns}__body` }> <img className = { `${ns}__logo` } src = '/images/logo-blue.svg' /> <p className = { `${ns}__text` }> You need <strong>Jitsi Meet</strong> to join a conversation on your mobile </p> <a href = { _URLS[Platform.OS] }> <button className = { downloadButtonClassName }> Download the App </button> </a> <p className = { `${ns}__text ${ns}__text_small` }> or if you already have it <br /> <strong>then</strong> </p> <a href = { this.state.joinURL }> <button className = { `${ns}__button` }> { this.state.joinText } </button> </a> </div> { this._renderStyle() } </div> ); } /** * Renders an HTML style element with CSS specific to * this UnsupportedMobileBrowser. * * @private * @returns {ReactElement} */ _renderStyle() { // Temasys provide lib-jitsi-meet/modules/RTC/adapter.screenshare.js // which detects whether the browser supports WebRTC. If the browser // does not support WebRTC, it displays an alert in the form of a yellow // bar at the top of the page. The alert notifies the user that the // browser does not support WebRTC and, if Temasys provide a plugin for // the browser, the alert contains a button to initiate installing the // browser. When Temasys do not provide a plugin for the browser, we do // not want the alert on the unsupported-browser page because the // notification about the lack of WebRTC support is the whole point of // the unsupported-browser page. return ( <style type = 'text/css'> { 'iframe[name="adapterjs-alert"] { display: none; }' } </style> ); } } /** * Maps (parts of) the Redux state to the associated UnsupportedMobileBrowser's * props. * * @param {Object} state - Redux state. * @private * @returns {{ * _room: string * }} */ function _mapStateToProps(state) { return { /** * The name of the conference room to be joined upon clicking the * respective button. * * @private * @type {string} */ _room: state['features/base/conference'].room }; } export default connect(_mapStateToProps)(UnsupportedMobileBrowser);
JavaScript
0.010778
@@ -2211,17 +2211,16 @@ src = ' -/ images/l
d001d63d96fc2cdceca9d52813666e0782adbd4c
add sortedOrgs
src/containers/organizations/components/OrganizationsListComponent.js
src/containers/organizations/components/OrganizationsListComponent.js
/* * @flow */ import React from 'react'; import DocumentTitle from 'react-document-title'; import Immutable from 'immutable'; import styled from 'styled-components'; import { connect } from 'react-redux'; import { hashHistory } from 'react-router'; import { bindActionCreators } from 'redux'; import LoadingSpinner from '../../../components/asynccontent/LoadingSpinner'; import Button from '../../../components/buttons/Button'; import OverviewCard from '../../../components/cards/OverviewCard'; import StyledFlexContainerStacked from '../../../components/flex/StyledFlexContainerStacked'; import { sortOrganizations } from '../utils/OrgsUtils'; import { fetchOrganizationsRequest } from '../actions/OrganizationsActionFactory'; const OrgOverviewCardCollection = styled(StyledFlexContainerStacked)` margin-bottom: 25px; `; function mapStateToProps(state :Immutable.Map) { const isFetchingOrgs :boolean = state.getIn(['organizations', 'isFetchingOrgs']); const isSearchingOrgs :boolean = state.getIn(['organizations', 'isSearchingOrgs']); const organizations :Immutable.Map = state.getIn(['organizations', 'organizations'], Immutable.Map()); const visibleOrganizationIds :Immutable.Set = state.getIn( ['organizations', 'visibleOrganizationIds'], Immutable.Set() ); return { isFetchingOrgs, isSearchingOrgs, organizations, visibleOrganizationIds }; } function mapDispatchToProps(dispatch :Function) { const actions = { fetchOrganizationsRequest }; return { actions: bindActionCreators(actions, dispatch) }; } class OrganizationsListComponent extends React.Component { static propTypes = { actions: React.PropTypes.shape({ fetchOrganizationsRequest: React.PropTypes.func.isRequired }).isRequired, auth: React.PropTypes.object.isRequired, isFetchingOrgs: React.PropTypes.bool.isRequired, isSearchingOrgs: React.PropTypes.bool.isRequired, organizations: React.PropTypes.instanceOf(Immutable.Map).isRequired, visibleOrganizationIds: React.PropTypes.instanceOf(Immutable.Set).isRequired }; componentDidMount() { this.props.actions.fetchOrganizationsRequest(); } renderOrganization = (organization :Immutable.Map) => { const viewOrgDetailsOnClick = () => { hashHistory.push(`/orgs/${organization.get('id')}`); }; const viewOrgDetailsButton = ( <Button scStyle="purple" onClick={viewOrgDetailsOnClick}> View Organization </Button> ); return ( <OverviewCard key={organization.get('id')} title={organization.get('title')} description={organization.get('description')} actionControl={viewOrgDetailsButton} /> ); } renderOrganizations = () => { const { visibleOrganizationIds, organizations } = this.props; const sortedOrgs = sortOrganizations(visibleOrganizationIds, organizations, this.props.auth); Object.keys(sortedOrgs).forEach((orgType) => { sortedOrgs[orgType] = sortedOrgs[orgType].map((org) => { return this.renderOrganization(org); }); }); if (sortedOrgs.yourOrgs.length === 0 && sortedOrgs.memberOfOrgs.length === 0 && sortedOrgs.publicOrgs.length === 0) { return this.renderNoOrganizations(); } // TODO: this can be refactored let yourOrgsOverviewCardCollection = null; if (sortedOrgs.yourOrgs.length > 0) { yourOrgsOverviewCardCollection = ( <OrgOverviewCardCollection> <h2>Owner</h2> { sortedOrgs.yourOrgs } </OrgOverviewCardCollection> ); } let memberOfOrgsOverviewCardCollection = null; if (sortedOrgs.memberOfOrgs.length > 0) { memberOfOrgsOverviewCardCollection = ( <OrgOverviewCardCollection> <h2>Member</h2> { sortedOrgs.memberOfOrgs } </OrgOverviewCardCollection> ); } let publicOrgsOverviewCardCollection = null; if (sortedOrgs.publicOrgs.length > 0) { publicOrgsOverviewCardCollection = ( <OrgOverviewCardCollection> <h3>Other Organizations</h3> <h4>These organizations are visible to the public.</h4> { sortedOrgs.publicOrgs } </OrgOverviewCardCollection> ); } const shouldHideDivider = ((yourOrgs.length > 0 || memberOfOrgs.length > 0) && publicOrgs.length === 0) || ((yourOrgs.length === 0 && memberOfOrgs.length === 0) && publicOrgs.length > 0); return ( <StyledFlexContainerStacked> { yourOrgsOverviewCardCollection } { memberOfOrgsOverviewCardCollection } { shouldHideDivider ? null : <hr /> } { publicOrgsOverviewCardCollection } </StyledFlexContainerStacked> ); } renderNoOrganizations = () => { // TODO: need a better view when there's no organizations to show return ( <div>No organizations found.</div> ); } render() { // TODO: async content loading const content = (this.props.isFetchingOrgs || this.props.isSearchingOrgs) ? <LoadingSpinner /> : this.renderOrganizations(); return ( <DocumentTitle title="Organizations"> { content } </DocumentTitle> ); } } export default connect(mapStateToProps, mapDispatchToProps)(OrganizationsListComponent);
JavaScript
0
@@ -4286,16 +4286,27 @@ der = (( +sortedOrgs. yourOrgs @@ -4320,16 +4320,27 @@ %3E 0 %7C%7C +sortedOrgs. memberOf @@ -4355,24 +4355,35 @@ gth %3E 0) && +sortedOrgs. publicOrgs.l @@ -4406,16 +4406,27 @@ %7C%7C (( +sortedOrgs. yourOrgs @@ -4442,16 +4442,27 @@ == 0 && +sortedOrgs. memberOf @@ -4483,16 +4483,27 @@ = 0) && +sortedOrgs. publicOr
7ed574f42787d64e51f9c100cfd2e49df6ebf3ec
use toBe instead of toEqueal when === comparison is required
src/Aap/Bundle/AapSiteBundle/Resources/public/js/test/unit/string.spec.js
src/Aap/Bundle/AapSiteBundle/Resources/public/js/test/unit/string.spec.js
/*global define, describe, jasmine, it, expect*/ /** * @author Joppe Aarts <joppe@apestaartje.info> * @copyright Apestaartje <http://apestaartje.info> */ define( ['lib/lang/string'], function (Str) { 'use strict'; describe('string tests', function () { it('trim', function () { expect(Str.trim(' foo ')).toEqual('foo'); }); it('snake to camelcase', function () { expect(Str.snakeToCamelCase('snake_styled_var_name')).toEqual('snakeStyledVarName'); }); it('spine to camelcase', function () { expect(Str.spineToCamelCase('spine-styled-var-name')).toEqual('spineStyledVarName'); }); it ('ucfirst', function () { expect(Str.ucfirst('are you sure?')).toEqual('Are you sure?'); }); }); } );
JavaScript
0
@@ -360,21 +360,18 @@ ')).to -Equal +Be ('foo'); @@ -511,21 +511,18 @@ me')).to -Equal +Be ('snakeS @@ -677,21 +677,18 @@ me')).to -Equal +Be ('spineS @@ -820,13 +820,10 @@ ).to -Equal +Be ('Ar
a7d1d913432646b2fd09d1dc94e6c55600587570
Remove controller based isSaving references
addon/pods/components/rui-validatable-input/component.js
addon/pods/components/rui-validatable-input/component.js
import Ember from 'ember' import layout from './template' const { Component, computed, defineProperty } = Ember export default Component.extend({ classNameBindings: ['isInvalid:has-error', 'isValid:has-success'], classNames: ['rui-validatable-input'], layout, model: null, placeholder: '', type: 'text', valuePath: '', async: false, init() { this._super(...arguments) const valuePath = this.get('valuePath') defineProperty(this, 'validation', computed.oneWay(`model.validations.attrs.${valuePath}`)) defineProperty(this, 'value', computed.alias(`model.${valuePath}`)) }, // This method ensures that if presence is required // But the initial value is undefined or an empty string // (the case with new records) we can still validate even though // the `didChange` attr would report it had not validatePresenceWithEmptyDefault: computed('value', function() { const validationOptions = Object.keys( this.get(`model.validations.attrs.${this.get('valuePath')}.options`)) return (validationOptions.indexOf('presence') !== -1) && (this.get('value') === '') || (this.get('value') === undefined) }), // The attribute has changed UNLESS // the validator includes presence and // the value is undefined or empty didChange: computed('value', 'model.hasDirtyAttributes', 'isSaving', function() { if (this.get('validatePresenceWithEmptyDefault')) { return true } const attrsChanged = this.get('model') ? this.get('model').changedAttributes() : {} return this.get('valuePath') in attrsChanged }), // Compute the property to give priority to // `isSaving` property if found on controller isSavingComputed: computed('model.isSaving', 'targetObject.isSaving', function() { const isSavingFromController = this.get('targetObject.isSaving') if ((typeof isSavingFromController !== 'undefined') && (isSavingFromController !== null)) { return isSavingFromController } return this.get('model.isSaving') }), // Checks for in processing statuses // Ensures validations don't show when: // input is clean, is validating, model is saving validatable: computed( 'didChange', 'validation.isValidating', 'isSavingComputed', function() { return this.get('didChange') && !this.get('validation.isValidating') && !this.get('isSavingComputed') } ), // Base values that compute validation state _isInvalid: computed.and('validation.isInvalid', 'validatable'), _isValid: computed.and('validation.isValid', 'validatable'), // Checks property `didValidate` on controller // Used to only show validation if `async` is true didValidate: computed.oneWay('targetObject.didValidate'), // Validation binding attributes with check for async settings // if async is true, don't display either until `didValidate` isInvalid: computed('_isInvalid', 'didValidate', function() { if (this.get('async')) { return this.get('_isInvalid') && this.get('didValidate') } return this.get('_isInvalid') }), isValid: computed('_isValid', 'didValidate', function() { if (this.get('async')) { return this.get('_isValid') && this.get('didValidate') } return this.get('_isValid') }) })
JavaScript
0.000001
@@ -1349,16 +1349,22 @@ utes', ' +model. isSaving @@ -1371,32 +1371,32 @@ ', function() %7B%0A - if (this.get @@ -1598,450 +1598,8 @@ ),%0A%0A - // Compute the property to give priority to%0A // %60isSaving%60 property if found on controller%0A%0A isSavingComputed: computed('model.isSaving', 'targetObject.isSaving', function() %7B%0A const isSavingFromController = this.get('targetObject.isSaving')%0A if ((typeof isSavingFromController !== 'undefined') &&%0A (isSavingFromController !== null)) %7B%0A return isSavingFromController%0A %7D%0A return this.get('model.isSaving')%0A %7D),%0A%0A // @@ -1806,24 +1806,30 @@ ',%0A ' +model. isSaving Computed @@ -1820,24 +1820,16 @@ isSaving -Computed ',%0A f @@ -1941,24 +1941,30 @@ is.get(' +model. isSaving Computed @@ -1959,16 +1959,8 @@ ving -Computed ')%0A
690475ae52741fa0e88015bef3ed1b07af868fc7
fix IE bug. IE doesnt support dataset
src/lazymaltbeer.js
src/lazymaltbeer.js
var Lazymaltbeer = function() { 'use strict'; /** * Lazy load images with img tag. * * @param imgPlaceholder the placeholder is a html node of any type (e.g. a span element). * The node has to provide a data element src and alt. */ var lazyLoadImg = function(imgPlaceholder) { var img = document.createElement("img"); img.src = imgPlaceholder.dataset.src; img.alt = imgPlaceholder.dataset.alt; imgPlaceholder.parentNode.insertBefore(img, imgPlaceholder); }; return { lazyLoadImg: lazyLoadImg }; };
JavaScript
0
@@ -416,19 +416,32 @@ der. -dataset. +getAttribute(%22data- src +%22) ;%0A @@ -475,19 +475,32 @@ der. -dataset. +getAttribute(%22data- alt +%22) ;%0A%0A
474d521e7fde9a751c9238de1287f8bc0148845b
Add data for new raid
src/legacy/raids.js
src/legacy/raids.js
export default [ {id: 'vale_guardian', raid: 'Forsaken Thicket', wing: 'Spirit Vale', name: 'Vale Guardian', type: 'Boss'}, {id: 'spirit_woods', raid: 'Forsaken Thicket', wing: 'Spirit Vale', name: 'Spirit Woods', type: 'Checkpoint'}, {id: 'gorseval', raid: 'Forsaken Thicket', wing: 'Spirit Vale', name: 'Gorseval', type: 'Boss'}, {id: 'sabetha', raid: 'Forsaken Thicket', wing: 'Spirit Vale', name: 'Sabetha', type: 'Boss'}, {id: 'slothasor', raid: 'Forsaken Thicket', wing: 'Salvation Pass', name: 'Slothasor', type: 'Boss'}, {id: 'bandit_trio', raid: 'Forsaken Thicket', wing: 'Salvation Pass', name: 'Bandit Trio', type: 'Boss'}, {id: 'matthias', raid: 'Forsaken Thicket', wing: 'Salvation Pass', name: 'Matthias', type: 'Boss'}, {id: 'escort', raid: 'Forsaken Thicket', wing: 'Stronghold of the Faithful', name: 'Escort', type: 'Boss'}, {id: 'keep_construct', raid: 'Forsaken Thicket', wing: 'Stronghold of the Faithful', name: 'Keep Construct', type: 'Boss'}, {id: 'twisted_castle', raid: 'Forsaken Thicket', wing: 'Stronghold of the Faithful', name: 'Twisted Castle', type: 'Checkpoint'}, {id: 'xera', raid: 'Forsaken Thicket', wing: 'Stronghold of the Faithful', name: 'Xera', type: 'Boss'}, {id: 'cairn', raid: 'Bastion of the Penitent', wing: 'Bastion of the Penitent', name: 'Cairn', type: 'Boss'}, {id: 'mursaat_overseer', raid: 'Bastion of the Penitent', wing: 'Bastion of the Penitent', name: 'Mursaat Overseer', type: 'Boss'}, {id: 'samarog', raid: 'Bastion of the Penitent', wing: 'Bastion of the Penitent', name: 'Samarog', type: 'Boss'}, {id: 'deimos', raid: 'Bastion of the Penitent', wing: 'Bastion of the Penitent', name: 'Deimos', type: 'Boss'}, {id: 'soulless_horror', raid: 'Hall of Chains', wing: 'Hall of Chains', name: 'Soulless Horror', type: 'Boss'}, {id: 'river_of_souls', raid: 'Hall of Chains', wing: 'Hall of Chains', name: 'River of Souls', type: 'Boss'}, {id: 'statues_of_grenth', raid: 'Hall of Chains', wing: 'Hall of Chains', name: 'Statues of Grenth', type: 'Boss'}, {id: 'voice_in_the_void', raid: 'Hall of Chains', wing: 'Hall of Chains', name: 'Voice in the Void', type: 'Boss'}, {id: 'conjured_amalgamate', raid: 'Mythwright Gambit', wing: 'Mythwright Gambit', name: 'Conjured Amalgamate', type: 'Boss'}, {id: 'twin_largos', raid: 'Mythwright Gambit', wing: 'Mythwright Gambit', name: 'Twin Largos', type: 'Boss'}, {id: 'qadim', raid: 'Mythwright Gambit', wing: 'Mythwright Gambit', name: 'Qadim', type: 'Boss'} ]
JavaScript
0
@@ -10,16 +10,38 @@ fault %5B%0A + // Forsaken Thicket%0A %7Bid: ' @@ -133,32 +133,32 @@ type: 'Boss'%7D,%0A - %7Bid: 'spirit_w @@ -1233,32 +1233,61 @@ type: 'Boss'%7D,%0A%0A + // Bastion of the Penitent%0A %7Bid: 'cairn', @@ -1739,32 +1739,52 @@ type: 'Boss'%7D,%0A%0A + // Hall of Chains%0A %7Bid: 'soulless @@ -2222,32 +2222,55 @@ type: 'Boss'%7D,%0A%0A + // Mythwright Gambit%0A %7Bid: 'conjured @@ -2485,32 +2485,32 @@ type: 'Boss'%7D,%0A - %7Bid: 'qadim', @@ -2575,27 +2575,517 @@ : 'Qadim', type: + 'Boss'%7D,%0A%0A // The Key of Ahdashim%0A %7Bid: 'gate', raid: 'The Key of Ahdashim', wing: 'The Key of Ahdashim', name: 'Gate', type: 'Checkpoint'%7D,%0A %7Bid: 'adina', raid: 'The Key of Ahdashim', wing: 'The Key of Ahdashim', name: 'Cardinal Adina', type: 'Boss'%7D,%0A %7Bid: 'sabir', raid: 'The Key of Ahdashim', wing: 'The Key of Ahdashim', name: 'Cardinal Sabir', type: 'Boss'%7D,%0A %7Bid: 'qadim_the_peerless', raid: 'The Key of Ahdashim', wing: 'The Key of Ahdashim', name: 'Qadim the Peerless', type: 'Boss'%7D%0A%5D%0A
8a316f33a7575d69f1c05ba87ca2f006d65ad471
Add TODO to validate inputs.
DSA-Campaign-Uplift-Estimation/src/main/webapp/Create/create-script.js
DSA-Campaign-Uplift-Estimation/src/main/webapp/Create/create-script.js
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. let userEmail = "example@google.com"; let userId = 0; /* * Submission form only requires 2 decimals, this function enforces that rule */ function setTwoNumberDecimal() { this.value = parseFloat(this.value).toFixed(2); } /* * verifyLoginStatus() is ran on page load * and obtains the user email associated with the user. */ function verifyLoginStatus() { fetch('/userapi').then(response => response.json()).then(loginStatus => { userEmail = loginStatus.Email; userId = loginStatus.id; console.log(loginStatus); return loginStatus.isLoggedIn; }); return false; } /* * This function allows preset data to be saved while the form is being * filled out. Alerts the user of the status of their saved preset. */ function submitPresetData() { let xmlhttp= window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange = function() { if (xmlhttp.status === 0) { alert("Preset saved!"); } else if ((xmlhttp.status < 200) && (xmlhttp.status >= 400)) { alert("Error: Preset cannot be saved. Please try again later."); } } var presetName = prompt("What would you like to call the preset?", "Preset Name"); if (presetName == null || presetName == "") { return; } // dynamically build a URI string with form elements var keyval_pairs = []; // TODO: Add email id and preset id keyval_pairs.push(encodeURIComponent("userEmail") + "=" + encodeURIComponent(userEmail)); keyval_pairs.push(encodeURIComponent("userId") + "=" + encodeURIComponent(userId)); keyval_pairs.push(encodeURIComponent("presetId") + "=" + encodeURIComponent(presetName)); var form = document.getElementById('campaign-form'); // get the comment form for (var i = 0; i < form.elements.length; i++) { var curr_element = form.elements[i]; keyval_pairs.push(encodeURIComponent(curr_element.name) + "=" + encodeURIComponent(curr_element.value)); } // divide each parameter with '&' var queryString = keyval_pairs.join("&"); xmlhttp.open("POST", '/preset', true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); alert(queryString); xmlhttp.send(queryString); } /* * updatePresetData takes in a presetId and userId and sends a GET request * to '/preset'. Once received, the preset data in the comment form is updated * with all updated links. * * @param presetId id identifying the preset. * @param userId id identifying the user requesting the data. */ function updatePresetData(presetId, userId) { }
JavaScript
0
@@ -3159,8 +3159,102 @@ ) %7B%0A %0A%7D +%0A%0A// TODO: validate DSA campaign inputs (e.g. campaign status must be %22pending%22 or %22complete%22)
5cbd75f443a87c9a966ffe0320d8258c6691d4ba
Set angular as default in blueprint
blueprints/ember-cli-changelog/files/config/changelog.js
blueprints/ember-cli-changelog/files/config/changelog.js
// jshint node:true // For details on each option run `ember help release` module.exports = { // ember style guide: https://github.com/emberjs/ember.js/blob/master/CONTRIBUTING.md#commit-tagging // angular style guide: https://github.com/angular/angular.js/blob/v1.4.8/CONTRIBUTING.md#commit // jquery style guide: https://contribute.jquery.org/commits-and-pull-requests/#commit-guidelines style: 'ember', // 'angular' 'jquery' head: 'master', base: '-last', // a branch or tag name, `-last` defaults to the version in package.json hooks: { /* parser: function(commit) { return commit; } filter: function(commit) { return true; }, groupSort: function(commits) { return { commits: commits }; }, format: function(commit) { return commit.title; }, */ } };
JavaScript
0.000001
@@ -405,20 +405,22 @@ e: ' -embe +angula r', // ' angu @@ -415,22 +415,20 @@ r', // ' -angula +embe r' 'jque
d6995180327eae28cd2b7f72888c9c3f1a2005d7
Add validation rules for stellar addresses
src/lib/Validate.js
src/lib/Validate.js
import _ from 'lodash'; import directory from '../directory'; // Some validation regexes and rules in this file are taken from Stellar Laboratory // Do not take code out from this file into other files // Stellar Laboratory is licensed under Apache 2.0 // https://github.com/stellar/laboratory // First argument is always input const RESULT_EMPTY = { ready: false, } const RESULT_VALID = { ready: true, } function result(errorMessage) { return { ready: false, message: errorMessage, } } const Validate = { publicKey(input) { if (input === '') { return null; } return StellarSdk.Keypair.isValidPublicKey(input); }, assetCode(input) { return _.isString(input) && input.match(/^[a-zA-Z0-9]+$/g) && input.length > 0 && input.length < 12; }, amount(input) { if (input === '') { return null; } let inputIsPositive = !!input.charAt(0) !== '-'; let inputValidNumber = !!input.match(/^[0-9]*(\.[0-9]+){0,1}$/g); let inputPrecisionLessThan7 = !input.match(/\.([0-9]){8,}$/g); return inputIsPositive && inputValidNumber && inputPrecisionLessThan7; }, // Below are the Validators using the new compound return types memo(input, type) { if (input === '') { return RESULT_EMPTY; } // type is of type: 'MEMO_ID' |'MEMO_TEXT' | 'MEMO_HASH' | 'MEMO_RETURN' switch (type) { case 'MEMO_ID': if (!input.match(/^[0-9]*$/g)) { return result('MEMO_ID only accepts a positive integer.'); } if (input !== StellarSdk.UnsignedHyper.fromString(input).toString()) { return result(`MEMO_ID is an unsigned 64-bit integer and the max valid value is ${StellarSdk.UnsignedHyper.MAX_UNSIGNED_VALUE.toString()}`) } break; case 'MEMO_TEXT': let memoTextBytes = Buffer.byteLength(input, 'utf8'); if (memoTextBytes > 28) { return result(`MEMO_TEXT accepts a string of up to 28 bytes. ${memoTextBytes} bytes entered.`); } break; case 'MEMO_HASH': case 'MEMO_RETURN': if (!input.match(/^[0-9a-f]{64}$/gi)) { return result(`${type} accepts a 32-byte hash in hexadecimal format (64 characters).`); } break; } return RESULT_VALID; } }; export default Validate;
JavaScript
0
@@ -415,22 +415,19 @@ unction -result +err (errorMe @@ -1432,22 +1432,19 @@ return -result +err ('MEMO_I @@ -1577,30 +1577,27 @@ return -result +err (%60MEMO_ID is @@ -1884,22 +1884,19 @@ return -result +err (%60MEMO_T @@ -2102,14 +2102,11 @@ urn -result +err (%60$%7B @@ -2232,16 +2232,541 @@ LID;%0A %7D +,%0A address(input, type) %7B%0A if (input === '') %7B%0A return RESULT_EMPTY;%0A %7D%0A%0A // Regex covers 99%25 of the use cases.%0A // - Allows any character in user part except * and , as specified in Stellar docs%0A // - Includes all valid addresses and a few invalid ones too such as fake TLD or misuse of hyphens or excessive length%0A if (!input.match(/%5E%5B%5E%5C*%5C,%5D+%5C*(%5B%5C-a-zA-Z0-9%5D+%5C.)*(%5Ba-zA-Z0-9%5D%7B2,%7D)%7B1%7D$/)) %7B%0A return err('Stellar federation address is improperly formatted.');%0A %7D%0A%0A return RESULT_VALID;%0A %7D, %0A%7D;%0A%0Aexp
512f22816f83f4dacfb1a147115cdf191679fd49
Rename gtmAnalyticsPropertyID to singleAnalyticsPropertyID.
assets/js/modules/tagmanager/components/setup/SetupFormInstructions.js
assets/js/modules/tagmanager/components/setup/SetupFormInstructions.js
/** * Tag Manager Setup Form Instructions component. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { __, sprintf } from '@wordpress/i18n'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { STORE_NAME as CORE_MODULES } from '../../../../googlesitekit/modules/datastore/constants'; import { STORE_NAME } from '../../datastore/constants'; import { STORE_NAME as MODULES_ANALYTICS } from '../../../analytics/datastore/constants'; import ErrorText from '../../../../components/error-text'; import { FormInstructions } from '../common'; const { useSelect } = Data; export default function SetupFormInstructions() { const gtmAnalyticsPropertyID = useSelect( ( select ) => select( STORE_NAME ).getSingleAnalyticsPropertyID() ); const hasMultipleAnalyticsPropertyIDs = useSelect( ( select ) => select( STORE_NAME ).hasMultipleAnalyticsPropertyIDs() ); const analyticsPropertyID = useSelect( ( select ) => select( MODULES_ANALYTICS ).getPropertyID() ); const analyticsModuleActive = useSelect( ( select ) => select( CORE_MODULES ).isModuleActive( 'analytics' ) ); if ( [ gtmAnalyticsPropertyID, hasMultipleAnalyticsPropertyIDs, analyticsPropertyID, analyticsModuleActive ].includes( undefined ) ) { return <FormInstructions />; } // Multiple property IDs implies secondary AMP where selected containers don't reference the same Analytics property ID. if ( hasMultipleAnalyticsPropertyIDs ) { const message = __( 'Looks like you’re already using Google Analytics within your Google Tag Manager configurations. However, the configured Analytics tags reference different property IDs. You need to configure the same Analytics property in both containers.', 'google-site-kit' ); return <ErrorText message={ message } />; } if ( analyticsModuleActive ) { // If the Analytics module is active, and selected containers reference a different property ID // than is currently set in the Analytics module, display an error explaining why the user is blocked. if ( gtmAnalyticsPropertyID && gtmAnalyticsPropertyID !== analyticsPropertyID ) { /* translators: %1$s: GTM Analytics property ID, %2$s: Analytics property ID */ const message = __( 'Looks like you’re already using Google Analytics within your Google Tag Manager configuration. However, its Analytics property %1$s is different from the Analytics property %2$s, which is currently selected in the plugin. You need to configure the same Analytics property in both places.', 'google-site-kit' ); return <ErrorText message={ sprintf( message, gtmAnalyticsPropertyID, analyticsPropertyID ) } />; } // If the Analytics module is active, and the Analytics property ID in GTM // matches the property ID configured for the Analytics module, // inform the user that GTM will take over outputting the tag/snippet. if ( analyticsModuleActive && gtmAnalyticsPropertyID && gtmAnalyticsPropertyID === analyticsPropertyID ) { /* translators: %s: Analytics property ID */ const message = __( 'Looks like you’re using Google Analytics. Your Analytics property %s is already set up in your Google Tag Manager configuration, so Site Kit will switch to using Google Tag Manager for Analytics.', 'google-site-kit' ); return ( <p> { sprintf( message, gtmAnalyticsPropertyID ) } </p> ); } } // If the Analytics module is not active, and selected containers reference a singular property ID, // recommend continuing with Analytics setup. if ( ! analyticsModuleActive && gtmAnalyticsPropertyID ) { return ( <p> { __( 'Looks like you’re already using Google Analytics within your Google Tag Manager configuration. Activate the Google Analytics module in Site Kit to see relevant insights in your dashboard.', 'google-site-kit' ) } </p> ); } return <FormInstructions />; }
JavaScript
0
@@ -1254,19 +1254,22 @@ %0A%09const -gtm +single Analytic @@ -1708,19 +1708,22 @@ %09if ( %5B -gtm +single Analytic @@ -2614,19 +2614,22 @@ %0A%09%09if ( -gtm +single Analytic @@ -2635,35 +2635,38 @@ csPropertyID && -gtm +single AnalyticsPropert @@ -3157,35 +3157,38 @@ rintf( message, -gtm +single AnalyticsPropert @@ -3464,35 +3464,38 @@ ModuleActive && -gtm +single AnalyticsPropert @@ -3497,27 +3497,30 @@ opertyID && -gtm +single AnalyticsPro @@ -3891,19 +3891,22 @@ essage, -gtm +single Analytic @@ -4129,11 +4129,14 @@ && -gtm +single Anal
276c3eeefc4cc83856f733c959d927b159c678c4
Restrict fullscreen mode to tablets and above
wcfsetup/install/files/js/3rdParty/redactor2/plugins/WoltLabFullscreen.js
wcfsetup/install/files/js/3rdParty/redactor2/plugins/WoltLabFullscreen.js
$.Redactor.prototype.WoltLabCode = function() { "use strict"; var _button; return { init: function() { _button = this.button.add('woltlabFullscreen', ''); this.button.addCallback(_button, this.WoltLabCode._toggle.bind(this)); }, _toggle: function () { _button[0].children[0].classList.toggle('fa-compress'); _button[0].children[0].classList.toggle('fa-expand'); if (this.core.box()[0].classList.toggle('redactorBoxFullscreen')) { WCF.System.DisableScrolling.disable(); this.core.editor()[0].style.setProperty('height', 'calc(100% - ' + ~~this.core.toolbar()[0].clientHeight + 'px)', ''); } else { WCF.System.DisableScrolling.enable(); this.core.editor()[0].style.removeProperty('height'); } } }; };
JavaScript
0.998987
@@ -21,20 +21,26 @@ .WoltLab -Code +Fullscreen = funct @@ -64,16 +64,38 @@ ict%22;%0A%09%0A +%09var _active = false;%0A %09var _bu @@ -132,25 +132,28 @@ tion() %7B%0A%09%09%09 -_ +var button = thi @@ -218,17 +218,16 @@ allback( -_ button, @@ -242,20 +242,494 @@ tLab -Code._toggle +Fullscreen._toggle.bind(this));%0A%09%09%09%0A%09%09%09_button = button%5B0%5D;%0A%09%09%09elHide(_button.parentNode);%0A%09%09%09%0A%09%09%09require(%5B'Ui/Screen'%5D, (function (UiScreen) %7B%0A%09%09%09%09UiScreen.on('screen-sm-up', %7B%0A%09%09%09%09%09match: function () %7B%0A%09%09%09%09%09%09elShow(_button.parentNode);%0A%09%09%09%09%09%7D,%0A%09%09%09%09%09unmatch: (function () %7B%0A%09%09%09%09%09%09elHide(_button.parentNode);%0A%09%09%09%09%09%09%0A%09%09%09%09%09%09if (_active) %7B%0A%09%09%09%09%09%09%09this.WoltLabFullscreen._toggle();%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%7D).bind(this),%0A%09%09%09%09%09setup: function () %7B%0A%09%09%09%09%09%09elShow(_button.parentNode);%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D);%0A%09%09%09%7D) .bin @@ -773,35 +773,32 @@ () %7B%0A%09%09%09_button -%5B0%5D .children%5B0%5D.cla @@ -837,19 +837,16 @@ %09_button -%5B0%5D .childre @@ -1118,24 +1118,44 @@ 'px)', '');%0A +%09%09%09%09_active = true;%0A %09%09%09%7D%0A%09%09%09else @@ -1257,16 +1257,37 @@ ight');%0A +%09%09%09%09_active = false;%0A %09%09%09%7D%0A%09%09%7D
5bfc26d81ab897fbfce340301787ac6734e5a968
add options to filter for case management tasks
webapps/client/scripts/filter/modals/cam-tasklist-filter-form-criteria.js
webapps/client/scripts/filter/modals/cam-tasklist-filter-form-criteria.js
define(function() { 'use strict'; var dateExpLangHelp = 'E.g.: ${ now() }, ${ timeDate() } or ${ timeDate().plusWeeks(2) })'; var userExpLangHelp = 'E.g.: ${ currentUser() }'; var groupExpLangHelp = 'E.g.: ${ currentUserGroups() }'; // check that the date format follows `yyyy-MM-dd'T'HH:mm:ss` or is an expression language string var expressionsExp = /^[\s]*(\#|\$)\{/; var dateExp = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(|\.[0-9]{0,4})(|Z)$/; function dateValidate(value) { if (expressionsExp.test(value)) { return false; } return !dateExp.test(value) ? 'INVALID_DATE' : false; } var criteria = [ { group: 'Process Instance', options: [ { name: 'processInstanceId', label: 'Id' }, { name: 'processInstanceBusinessKey', label: 'Business Key' }, { name: 'processInstanceBusinessKeyLike', label: 'Business Key Like' // }, // { // name: 'processVariables', // label: 'Variables' } ] }, { group: 'Process definition', options: [ { name: 'processDefinitionId', label: 'Id' }, { name: 'processDefinitionKey', label: 'Key' }, { name: 'processDefinitionName', label: 'Name' }, { name: 'processDefinitionNameLike', label: 'Name Like' } ] }, { group: 'Other', options: [ { name: 'active', label: 'Active' }, { name: 'activityInstanceIdIn', label: 'Activity Instance Id In' }, { name: 'executionId', label: 'Execution Id' } ] }, { group: 'User / Group', options: [ { name: 'assignee', label: 'Assignee', expressionSupport: true, help: userExpLangHelp }, { name: 'assigneeLike', label: 'Assignee Like', expressionSupport: true, help: userExpLangHelp }, { name: 'owner', label: 'Owner', expressionSupport: true, help: userExpLangHelp }, { name: 'candidateGroup', label: 'Candidate Group', expressionSupport: true, help: groupExpLangHelp }, { name: 'candidateGroups', label: 'Candidate Groups', expressionSupport: true, help: groupExpLangHelp }, { name: 'candidateUser', label: 'Candidate User', expressionSupport: true, help: userExpLangHelp }, { name: 'involvedUser', label: 'Involved User', expressionSupport: true, help: userExpLangHelp }, { name: 'unassigned', label: 'Unassigned' }, { name: 'delegationState', label: 'Delegation State' } ] }, { group: 'Task', options: [ { name: 'taskDefinitionKey', label: 'Definition Key' }, { name: 'taskDefinitionKeyLike', label: 'Definition Key Like' }, { name: 'name', label: 'Name' }, { name: 'nameLike', label: 'Name Like' }, { name: 'description', label: 'Description' }, { name: 'descriptionLike', label: 'Description Like' }, { name: 'priority', label: 'Priority' }, { name: 'maxPriority', label: 'Priority Max' }, { name: 'minPriority', label: 'Priority Min' // }, // { // name: 'taskVariables', // label: 'Variables' } ] }, { group: 'Dates', options: [ { name: 'createdBefore', label: 'Created Before', expressionSupport: true, help: dateExpLangHelp, validate: dateValidate }, { name: 'createdAfter', label: 'Created After', expressionSupport: true, help: dateExpLangHelp, validate: dateValidate }, { name: 'dueBefore', label: 'Due Before', expressionSupport: true, help: dateExpLangHelp, validate: dateValidate }, { name: 'dueAfter', label: 'Due After', expressionSupport: true, help: dateExpLangHelp, validate: dateValidate }, { name: 'followUpAfter', label: 'Follow Up After', expressionSupport: true, help: dateExpLangHelp, validate: dateValidate }, { name: 'followUpBefore', label: 'Follow Up Before', expressionSupport: true, help: dateExpLangHelp, validate: dateValidate }, { name: 'followUpBeforeOrNotExistent', label: 'Follow Up Before or Not Existent', expressionSupport: true, help: dateExpLangHelp, validate: dateValidate } ] } ]; return criteria; });
JavaScript
0
@@ -1525,32 +1525,436 @@ %5D%0A %7D,%0A %7B%0A + group: 'Case definition',%0A options: %5B%0A %7B%0A name: 'caseDefinitionId',%0A label: 'Id'%0A %7D,%0A %7B%0A name: 'caseDefinitionKey',%0A label: 'Key'%0A %7D,%0A %7B%0A name: 'caseDefinitionName',%0A label: 'Name'%0A %7D,%0A %7B%0A name: 'caseDefinitionNameLike',%0A label: 'Name Like'%0A %7D%0A %5D%0A %7D,%0A %7B%0A group: 'Ot
88b6c4aa3b18cb47ed46e75d92c4dee1100cd3d5
code review: typos
automatic-api.js
automatic-api.js
// a node.js module to interface with the Automatic cloud API // cf., https://www.automatic.com/developer/ var events = require('events') , oauth = require('oauth') , util = require('util') , uuid = require('node-uuid') ; var DEFAULT_LOGGER = { error : function(msg, props) { console.log(msg); if (!!props) console.log(props); } , warning : function(msg, props) { console.log(msg); if (!!props) console.log(props); } , notice : function(msg, props) { console.log(msg); if (!!props) console.log(props); } , info : function(msg, props) { console.log(msg); if (!!props) console.log(props); } , debug : function(msg, props) { console.log(msg); if (!!props) console.log(props); } }; var AutomaticAPI = function(options) { var k; var self = this; if (!(self instanceof AutomaticAPI)) return new AutomaticAPI(options); self.options = options; if ((!self.options.clientID) || (!self.options.clientSecret)) throw new Error('clientID and clientSecret required'); self.logger = self.options.logger || {}; for (k in DEFAULT_LOGGER) { if ((DEFAULT_LOGGER.hasOwnProperty(k)) && (typeof self.logger[k] === 'undefined')) self.logger[k] = DEFAULT_LOGGER[k]; } self.oauth2 = new oauth.OAuth2(self.options.clientID, self.options.clientSecret, 'https://automatic.com', '/oauth/authorize', '/oauth/access_token'); self.oauth2.setAuthType('token'); // not 'Bearer' }; util.inherits(AutomaticAPI, events.EventEmitter); AutomaticAPI.prototype.authenticateURL = function(scopes, redirectURL) { var self = this; if (!scopes) scopes = AutomaticAPI.allScopes; self.cookie = uuid.v4(); return self.oauth2.getAuthorizeUrl({ scope : scopes.join(',') , response_type : 'code' , redirectURL : redirectURL , state : self.cookie }); }; AutomaticAPI.prototype.authorize = function(code, state, callback) { var self = this; if (typeof callback !== 'function') throw new Error('callback is mandatory for login'); if (self.cookie !== state) callback(new Error('cross-site request forgery suspected')); self.aouth2.getOAuthAccessToken(code, { grant_type: 'authorization_code'}, function (err, accessToken, refreshToken, results) { if (!!err) return callback(err); self.accessToken = accessToken; self.refreshToken = refreshToken; if (!!results.expires_in) self.expires_in = results.expires_in; if (!!results.scope) self.scopes = results.scope.split(' '); console.log(JSON.stringify(results)); callback(null, results.user, self.scopes); }); return self; }; AutomaticAPI.prototype.roundtrip = function(method, path, json, callback) { var self = this; if ((!callback) && (typeof json === 'function')) { callback = json; json = null; } return self.invoke(method, path, json, function(err, code, results) { callback(err, results); }); }; AutomaticAPI.prototype.invoke = function(method, path, json, callback) { var self = this; if ((!callback) && (typeof json === 'function')) { callback = json; json = null; } if (!callback) { callback = function(err, results) { if (!!err) self.logger.error('invoke', { exception: err }); else self.logger.info(path, { results: results }); }; } self.oauth2._request(method, 'https://api.automatic.com/v1' + path, null, json, self.accessToken, !!json ? { 'Content-Type': 'application/json' } : null, function(err, body, response) { var expected = { GET : [ 200 ] , PUT : [ 200 ] , POST : [ 200, 201, 202 ] , DELETE : [ 200 ] }[method]; var results = {}; if (!!err) return callback(err, response.statusCode); try { results = JSON.parse(body); } catch(ex) { self.logger.error(path, { event: 'json', diagnostic: ex.message, body: body }); return callback(ex, response.statusCode); } if (expected.indexOf(response.statusCode) === -1) { self.logger.error(path, { event: 'https', code: response.statusCode, body: body }); return callback(new Error('HTTP response ' + response.statusCode), response.statusCode, results); } callback(null, response.statusCode, results); }); return self; }; AutomaticAPI.allScopes = [ 'scope:location' , 'scope:vehicle' , 'scope:trip:summary' , 'scope:ignition:on' , 'scope:ignition:off' , 'scope:notification:speeding' , 'scope:notification:hard_brake' , 'scope:notification:hard_accel' , 'scope:region:changed' , 'scope:parking:changed' , 'scope:mil:on' , 'scope:mil:off' ]; exports.AutomaticAPI = AutomaticAPI;
JavaScript
0.999995
@@ -1468,16 +1468,20 @@ https:// +www. automati @@ -2440,10 +2440,10 @@ elf. -a o +a uth2 @@ -3701,73 +3701,8 @@ ath, - null, json, self.accessToken,%0A !!j @@ -3753,16 +3753,63 @@ : null, +%0A json, self.accessToken, functio
d72326fe7646a6c44d08637141f7df5f7d293fb7
Fix issues with the seed script
src/helpers/seeder.js
src/helpers/seeder.js
#!/usr/bin/env node const storage = require('../storage') const fixtures = require('./fixtures') const recipes = fixtures.createRecipes(10) function save (recipe) { return storage.put(recipe.id, recipe) } storage.connect() .then(() => { return Promise.all(recipes.map(recipe => save(recipe))) }) .then(() => { console.log('Database was successfuly seeded.\n') }) .catch(error => { throw error })
JavaScript
0.000001
@@ -151,16 +151,20 @@ n save ( +db, recipe) @@ -186,16 +186,20 @@ age.put( +db, recipe.i @@ -228,16 +228,36 @@ connect( +process.env.NODE_ENV )%0A .the @@ -251,32 +251,34 @@ E_ENV)%0A .then(( +db ) =%3E %7B%0A retur @@ -318,16 +318,20 @@ =%3E save( +db, recipe))
0983ef48b57aa2c6dc8965258c34673832959b28
Fix root component's prop types
react/index.native.js
react/index.native.js
import 'es6-symbol/implement'; import React, { Component } from 'react'; import { AppRegistry, Linking } from 'react-native'; import { App } from './features/app'; /** * React Native doesn't support specifying props to the main/root component (in * the JS/JSX source code). So create a wrapper React Component (class) around * features/app's App instead. * * @extends Component */ class Root extends Component { /** * {@code Root} component's property types. * * @static */ static propTypes = { /** * The URL, if any, with which the app was launched. */ url: React.PropTypes.string, /** * Whether the Welcome page is enabled. If {@code true}, the Welcome * page is rendered when the {@link App} is not at a location (URL) * identifying a Jitsi Meet conference/room. */ welcomePageEnabled: React.PropTypes.bool }; /** * Initializes a new {@code Root} instance. * * @param {Object} props - The read-only properties with which the new * instance is to be initialized. */ constructor(props) { super(props); /** * The initial state of this Component. * * @type {{ * url: string * }} */ this.state = { /** * The URL, if any, with which the app was launched. * * @type {string} */ url: this.props.url }; // Handle the URL, if any, with which the app was launched. But props // have precedence. if (typeof this.props.url === 'undefined') { Linking.getInitialURL() .then(url => { if (typeof this.state.url === 'undefined') { this.setState({ url }); } }) .catch(err => { console.error('Failed to get initial URL', err); if (typeof this.state.url === 'undefined') { // Start with an empty URL if getting the initial URL // fails; otherwise, nothing will be rendered. this.setState({ url: null }); } }); } } /** * Implements React's {@link Component#componentWillReceiveProps()}. * * New props can be set from the native side by setting the appProperties * property (on iOS) or calling setAppProperties (on Android). * * @inheritdoc */ componentWillReceiveProps({ url }) { if (this.props.url !== url) { this.setState({ url: url || null }); } } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { const { url } = this.state; // XXX We don't render the App component until we get the initial URL. // Either it's null or some other non-null defined value. if (typeof url === 'undefined') { return null; } const { // The following props are forked in state: url: _, // eslint-disable-line no-unused-vars // The remaining props are passed through to App. ...props } = this.props; return ( <App { ...props } url = { url } /> ); } } // Register the main/root Component. AppRegistry.registerComponent('App', () => Root);
JavaScript
0
@@ -157,16 +157,64 @@ es/app'; +%0Aimport %7B equals %7D from './features/base/redux'; %0A%0A/**%0A * @@ -686,22 +686,109 @@ opTypes. -string +oneOfType(%5B%0A React.PropTypes.object,%0A React.PropTypes.string%0A %5D) ,%0A%0A @@ -1412,16 +1412,23 @@ url: +object%7C string%0A @@ -1593,16 +1593,23 @@ @type %7B +object%7C string%7D%0A @@ -2796,16 +2796,24 @@ if +(!equals (this.pr @@ -2823,17 +2823,15 @@ .url - !== +, url) +) %7B%0A
0eeea296743791802d66c4907b998d2534789e1a
add change avatar methods to actor client;
actor-apps/app-web/src/app/utils/ActorClient.js
actor-apps/app-web/src/app/utils/ActorClient.js
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ export default { requestSms(phone, success, failure) { window.messenger.requestSms(phone, success, failure); }, sendCode(code, success, failure) { window.messenger.sendCode(code, success, failure); }, signUp(name, success, failure) { window.messenger.signUp(name, success, failure); }, isLoggedIn() { return window.messenger.isLoggedIn(); }, bindDialogs(callback) { window.messenger.bindDialogs(callback); }, unbindDialogs(callback) { window.messenger.unbindDialogs(callback); }, bindChat(peer, callback) { window.messenger.bindChat(peer, callback); }, unbindChat(peer, callback) { window.messenger.unbindChat(peer, callback); }, bindGroup(gid, callback) { window.messenger.bindGroup(gid, callback); }, unbindGroup(gid, callback) { window.messenger.unbindGroup(gid, callback); }, bindUser(uid, callback) { window.messenger.bindUser(uid, callback); }, unbindUser(uid, callback) { window.messenger.unbindUser(uid, callback); }, bindTyping(peer, callback) { window.messenger.bindTyping(peer, callback); }, unbindTyping(peer, callback) { window.messenger.unbindTyping(peer, callback); }, bindContacts(peer, callback) { window.messenger.bindContacts(peer, callback); }, unbindContacts(peer, callback) { window.messenger.unbindContacts(peer, callback); }, bindConnectState(callback) { window.messenger.bindConnectState(callback); }, unbindConnectState(callback) { window.messenger.unbindConnectState(callback); }, getUser(uid) { return window.messenger.getUser(uid); }, getUid() { return window.messenger.getUid(); }, getGroup(gid) { return window.messenger.getGroup(gid); }, getInviteUrl(gid) { return window.messenger.getInviteLink(gid); }, sendTextMessage(peer, text) { window.messenger.sendMessage(peer, text); }, sendFileMessage(peer, file) { window.messenger.sendFile(peer, file); }, sendPhotoMessage(peer, photo) { window.messenger.sendPhoto(peer, photo); }, sendClipboardPhotoMessage(peer, photo) { window.messenger.sendClipboardPhoto(peer, photo); }, onMessageShown(peer, message) { window.messenger.onMessageShown(peer, message); }, onChatEnd (peer) { window.messenger.onChatEnd(peer); }, onDialogsEnd () { window.messenger.onDialogsEnd(); }, onConversationOpen(peer) { window.messenger.onConversationOpen(peer); }, onConversationClosed(peer) { window.messenger.onConversationClosed(peer); }, onTyping(peer) { window.messenger.onTyping(peer); }, onAppHidden() { window.messenger.onAppHidden(); }, onAppVisible() { window.messenger.onAppVisible(); }, editMyName(string) { window.messenger.editMyName(string); }, addContact(uid) { window.messenger.addContact(uid); }, removeContact(uid) { window.messenger.removeContact(uid); }, // Groups joinGroup (url) { console.log('Joining group by url: ' + url); const p = window.messenger.joinGroupViaLink(url); return p; }, leaveGroup(gid) { return window.messenger.leaveGroup(gid); }, createGroup(title, avatar, userIds) { console.log('Creating group', title, userIds); return window.messenger.createGroup(title, avatar, userIds); }, kickMember(gid, uid) { return window.messenger.kickMember(gid, uid); }, inviteMember(gid, uid) { return window.messenger.inviteMember(gid, uid); }, getIntegrationToken(gid) { return window.messenger.getIntegrationToken(gid); }, loadDraft(peer) { return window.messenger.loadDraft(peer); }, saveDraft(peer, draft) { if (draft !== null) { window.messenger.saveDraft(peer, draft); } }, getUserPeer(uid) { return window.messenger.getUserPeer(uid); }, getGroupPeer(gid) { return window.messenger.getGroupPeer(gid); }, isNotificationsEnabled(peer) { return window.messenger.isNotificationsEnabled(peer); }, changeNotificationsEnabled(peer, isEnabled) { window.messenger.changeNotificationsEnabled(peer, isEnabled); }, findUsers(phone) { return window.messenger.findUsers(phone.toString()); }, deleteMessages(peer, rids) { return window.messenger.deleteMessages(peer, rids); }, // Mentions findMentions(gid, query = '') { return window.messenger.findMentions(gid, query); }, // Nickname editMyNick(string) { window.messenger.editMyNick(string) }, bindGlobalCounter(callback) { return window.messenger.bindGlobalCounter(callback); }, bindTempGlobalCounter(callback) { return window.messenger.bindTempGlobalCounter(callback); }, deleteChat(peer) { return window.messenger.deleteChat(peer); }, clearChat(peer) { return window.messenger.clearChat(peer); }, editMyAbout(about) { return window.messenger.editMyAbout(about); }, editGroupTitle(gid, title) { return window.messenger.editGroupTitle(gid, title); }, renderMarkdown(markdownText) { return window.messenger.renderMarkdown(markdownText); }, // Settings changeNotificationsEnabled(peer, isEnabled) { window.messenger.changeNotificationsEnabled(peer, isEnabled); }, isNotificationsEnabled(peer) { return window.messenger.isNotificationsEnabled(peer); }, isSendByEnterEnabled() { return window.messenger.isSendByEnterEnabled(); }, changeSendByEnter(isEnabled) { window.messenger.changeSendByEnter(isEnabled); }, isGroupsNotificationsEnabled() { return window.messenger.isGroupsNotificationsEnabled(); }, changeGroupNotificationsEnabled(isEnabled) { window.messenger.changeGroupNotificationsEnabled(isEnabled); }, isOnlyMentionNotifications() { return window.messenger.isOnlyMentionNotifications(); }, changeIsOnlyMentionNotifications(isEnabled) { window.messenger.changeIsOnlyMentionNotifications(isEnabled); }, isSoundEffectsEnabled() { return window.messenger.isSoundEffectsEnabled(); }, changeSoundEffectsEnabled(isEnabled) { window.messenger.changeSoundEffectsEnabled(isEnabled); }, isShowNotificationsTextEnabled() { return window.messenger.isShowNotificationsTextEnabled(); }, changeIsShowNotificationTextEnabled(isEnabled) { window.messenger.changeIsShowNotificationTextEnabled(isEnabled); }, loadSessions() { return window.messenger.loadSessions(); }, terminateSession(id) { return window.messenger.terminateSession(id); }, terminateAllSessions() { return window.messenger.terminateAllSessions(); } }
JavaScript
0
@@ -6682,14 +6682,179 @@ ions();%0A + %7D,%0A%0A changeMyAvatar(avatar) %7B%0A window.messenger.changeMyAvatar(avatar)%0A %7D,%0A%0A changeGroupAvatar(gid, avatar) %7B%0A window.messenger.changeGroupAvatar(avatar)%0A %7D%0A%7D%0A