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
05c263066d0496435fd8ff7feff911de76406b7c
Fix bug: for when parameters is not provided
src/js/components/forms/InputsParams/index.js
src/js/components/forms/InputsParams/index.js
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import cn from 'classnames'; class FileInput extends Component { render() { const {form, name, description, required} = this.props; if (form.type == 'select') { return ( <div className="file-input"> <label><b>{name}</b> <span>{description}</span> {required ? <i>*required</i> : null}</label> <select className="form-control" name={name}> {form.options.map(o => <option key={o} value={o}>{o}</option>)} </select> </div> ); } return ( <div className="form-group file-input"> <label><b>{name}</b> <span>{description}</span> {required ? <i>*required</i> : null}</label> <input type="file" className="form-control" name={name} onChange={ev => this.props.onChange(ev, name)}/> </div> ); } static propTypes = { description: PropTypes.string.isRequired, form: PropTypes.object.isRequired, name: PropTypes.string.isRequired, required: PropTypes.bool, onChange: PropTypes.func.isRequired, }; } class Parameter extends Component { render() { const {form, name, description, default: def} = this.props; const v = typeof this.props.value != 'undefined' ? this.props.value : def; return ( <div className="form-group"> <label><b>{name}</b> <span>{description}</span></label> <input type={form.type} className="form-control" defaultValue={v} name={name} onChange={ev => this.props.onChange(ev, name)} /> </div> ); } static propTypes = { description: PropTypes.string.isRequired, form: PropTypes.object.isRequired, name: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, default: PropTypes.any.isRequired, value: PropTypes.any, } } export default class InputsParams extends Component { constructor(props) { super(props); this.state = { inputs: this.props.workflow.inputs, }; } render() { const {workflow:{self, inputs, parameters}} = this.props; return ( <div className="padded-more"> <p> <b>{self.name}</b> requires following inputs and parameters. </p> <div> <h3>Input files</h3> {Object.keys(inputs).map(key => <FileInput onChange={this.onInputChange.bind(this)} key={key} name={key} {...inputs[key]} />)} </div> <div> <h3>Parameters</h3> {this._renderParametersForm(parameters)} </div> <div> <button className="btn btn-default btn-large">← Back</button> <button className={cn('btn','btn-primary','btn-large','pull-right',{disabled:this.props.sending})} onClick={this.onSubmit.bind(this)}>Submit</button> </div> </div> ); } _renderParametersForm(params) { if (Object.keys(params).length == 0) { return ( <p>This workflow does not offer any configurable parameters.</p> ); } return ( <div> <p>Following parameters are configurable, but not necessary to be changed.</p> {Object.keys(params).map(name => <Parameter onChange={this.onParameterChange.bind(this)} key={name} name={name} {...params[name]} />)} </div> ); } onInputChange(ev, name) { if (!ev.target.files.length) return; const inputs = {...this.state.inputs}; inputs[name].file = ev.target.files[0]; this.setState({inputs}); } onParameterChange(ev, name) { this.props.setParameter(name, ev.target.value); } onSubmit() { this.props.onSubmit({inputs: this.state.inputs}); } static propTypes = { sending: PropTypes.bool, workflow: PropTypes.object.isRequired, onSubmit: PropTypes.func.isRequired, setParameter: PropTypes.func.isRequired, } }
JavaScript
0.000001
@@ -2906,16 +2906,21 @@ m(params + = %7B%7D ) %7B%0A
665ff94ff73bf658fbba2d31deee3c93c4a4eae2
Revert "FIX: Don't show `undefined` in the footer text."
app/assets/javascripts/discourse/controllers/discovery/topics.js.es6
app/assets/javascripts/discourse/controllers/discovery/topics.js.es6
import DiscoveryController from 'discourse/controllers/discovery'; import { queryParams } from 'discourse/controllers/discovery-sortable'; var controllerOpts = { needs: ['discovery'], bulkSelectEnabled: false, selected: [], period: null, redirectedReason: Em.computed.alias('currentUser.redirected_to_top_reason'), order: 'default', ascending: false, actions: { changeSort: function(sortBy) { if (sortBy === this.get('order')) { this.toggleProperty('ascending'); } else { this.setProperties({ order: sortBy, ascending: false }); } this.get('model').refreshSort(sortBy, this.get('ascending')); }, // Show newly inserted topics showInserted: function() { var tracker = Discourse.TopicTrackingState.current(); // Move inserted into topics this.get('content').loadBefore(tracker.get('newIncoming')); tracker.resetTracking(); return false; }, refresh: function() { var filter = this.get('model.filter'), self = this; this.setProperties({ order: 'default', ascending: false }); // Don't refresh if we're still loading if (this.get('controllers.discovery.loading')) { return; } // If we `send('loading')` here, due to returning true it bubbles up to the // router and ember throws an error due to missing `handlerInfos`. // Lesson learned: Don't call `loading` yourself. this.set('controllers.discovery.loading', true); Discourse.TopicList.find(filter).then(function(list) { self.setProperties({ model: list, selected: [] }); var tracking = Discourse.TopicTrackingState.current(); if (tracking) { tracking.sync(list, filter); } self.send('loadingComplete'); }); }, toggleBulkSelect: function() { this.toggleProperty('bulkSelectEnabled'); this.get('selected').clear(); }, resetNew: function() { var self = this; Discourse.TopicTrackingState.current().resetNew(); Discourse.Topic.resetNew().then(function() { self.send('refresh'); }); }, dismissRead: function(operationType) { var self = this, selected = this.get('selected'), operation; if(operationType === "posts"){ operation = { type: 'dismiss_posts' }; } else { operation = { type: 'change_notification_level', notification_level_id: Discourse.Topic.NotificationLevel.REGULAR }; } var promise; if (selected.length > 0) { promise = Discourse.Topic.bulkOperation(selected, operation); } else { promise = Discourse.Topic.bulkOperationByFilter('unread', operation, this.get('category.id')); } promise.then(function(result) { if (result && result.topic_ids) { var tracker = Discourse.TopicTrackingState.current(); result.topic_ids.forEach(function(t) { tracker.removeTopic(t); }); tracker.incrementMessageCount(); } self.send('refresh'); }); } }, topicTrackingState: function() { return Discourse.TopicTrackingState.current(); }.property(), isFilterPage: function(filter, filterType) { return filter.match(new RegExp(filterType + '$', 'gi')) ? true : false; }, showDismissRead: function() { return this.isFilterPage(this.get('filter'), 'unread') && this.get('topics.length') > 0; }.property('filter', 'topics.length'), showResetNew: function() { return this.get('filter') === 'new' && this.get('topics.length') > 0; }.property('filter', 'topics.length'), showDismissAtTop: function() { return (this.isFilterPage(this.get('filter'), 'new') || this.isFilterPage(this.get('filter'), 'unread')) && this.get('topics.length') >= 30; }.property('filter', 'topics.length'), canBulkSelect: Em.computed.alias('currentUser.staff'), hasTopics: Em.computed.gt('topics.length', 0), allLoaded: Em.computed.empty('more_topics_url'), latest: Discourse.computed.endWith('filter', 'latest'), new: Discourse.computed.endWith('filter', 'new'), top: Em.computed.notEmpty('period'), yearly: Em.computed.equal('period', 'yearly'), monthly: Em.computed.equal('period', 'monthly'), weekly: Em.computed.equal('period', 'weekly'), daily: Em.computed.equal('period', 'daily'), footerMessage: function() { if (!this.get('allLoaded')) { return; } var category = this.get('category'); if( category ) { return I18n.t('topics.bottom.category', {category: category.get('name')}); } else { var split = this.get('filter').split('/'); if (this.get('topics.length') === 0) { return I18n.t("topics.none." + split[0], { category: split[1] }); } else { return I18n.t("topics.bottom." + split[0], { category: split[1] }); } } }.property('allLoaded', 'topics.length'), footerEducation: function() { if (!this.get('allLoaded') || this.get('topics.length') > 0 || !Discourse.User.current()) { return ""; } var split = this.get('filter').split('/'); if (split[0] !== 'new' && split[0] !== 'unread' && split[0] !== 'starred') { return ""; } return I18n.t("topics.none.educate." + split[0], { userPrefsUrl: Discourse.getURL("/users/") + (Discourse.User.currentProp("username_lower")) + "/preferences" }); }.property('allLoaded', 'topics.length'), loadMoreTopics: function() { return this.get('model').loadMore(); } }; Ember.keys(queryParams).forEach(function(p) { // If we don't have a default value, initialize it to null if (typeof controllerOpts[p] === 'undefined') { controllerOpts[p] = null; } }); export default DiscoveryController.extend(controllerOpts);
JavaScript
0
@@ -5118,35 +5118,32 @@ rent()) %7B return - %22%22 ; %7D%0A%0A var spl @@ -5270,11 +5270,8 @@ turn - %22%22 ; %7D%0A
27b7fe065b155fd4cb8ca53198c6a9c5a50e7dc4
change way query is inferred
adaptors/base.adp.js
adaptors/base.adp.js
/** * @fileOverview Provide a common interface for drivers. */ var __ = require('lodash'); var EntityCrud = require('../lib/entity-crud'); /** * Provide a common interface for drivers. * * @param {Object=} optUdo Optionally define the current handling user * @constructor * @extends {crude.Entity} */ var AdaptorBase = module.exports = EntityCrud.extend(function(/* optUdo */) { /** @type {string} The default 'id' field name */ this._idName = '_id'; /** @type {?Object|Function} The ORM model */ this.Model = null; // make sure model is defined before invoking operations. this.create.before(this._checkModelExists.bind(this)); this.read.before(this._checkModelExists.bind(this)); this.readOne.before(this._checkModelExists.bind(this)); this.readLimit.before(this._checkModelExists.bind(this)); this.update.before(this._checkModelExists.bind(this)); this.delete.before(this._checkModelExists.bind(this)); this.count.before(this._checkModelExists.bind(this)); }); /** * Helper to return the query properly formated based on type of id. * * @param {string|Object} id the item id or query for item. * @protected */ AdaptorBase.prototype._getQuery = function(id) { var q = {}; return (__.isObject(id)) ? id : (q[this._idName] = id, q); }; /** * Dependency Injection. * * @param {*} The ORM. */ AdaptorBase.prototype.setModel = function(/* model */) { throw new Error('Not Implemented'); }; /** * Checks if model has been set, throws if not */ AdaptorBase.prototype._checkModelExists = function() { if (!this.Model) {throw new Error('No Mongoose.Model defined, use setModel()');} };
JavaScript
0.999999
@@ -1208,23 +1208,24 @@ ar q +uery = %7B%7D;%0A +%0A -return +if (__ @@ -1243,40 +1243,91 @@ d)) -? id : (q%5Bthis._idName%5D = id, q) +%7B%0A return id;%0A %7D%0A%0A if (id) %7B%0A query%5Bthis._idName%5D = id;%0A %7D%0A%0A return query ;%0A%7D;
8d08bf6358c169727c449036dd77beb2c89de471
Fix queue
addon/utils/queue.js
addon/utils/queue.js
import Ember from 'ember'; export default Ember.Object.extend({ /* The queue of promises */ _queue: [Ember.RSVP.resolve()], /** If set to `true` then error occurring should not stop performing operations in queue. @property continueOnError @type Boolean @default true */ continueOnError: true, attach(callback) { const queueKey = this._queue.length; this._queue[queueKey] = new Ember.RSVP.Promise((resolve, reject) => { this._queue[queueKey - 1].then(() => { callback(resolve, reject); }).catch((reason) => { Ember.Logger.error(reason); if (this.continueOnError) { resolve(); } else { reject(); } }); }); return this._queue[queueKey]; } });
JavaScript
0.000001
@@ -103,30 +103,12 @@ ue: -%5BEmber.RSVP.resolve()%5D +null ,%0A%0A @@ -300,16 +300,350 @@ true,%0A%0A + /* Init instance of queue */%0A init() %7B%0A this.set('_queue', %5BEmber.RSVP.resolve()%5D);%0A %7D,%0A%0A /**%0A Adds callback to then end of queue of Promises.%0A%0A @method attach%0A @param %7BFunction%7D callback Callback to add to the end of queue. Takes %60resolve%60 and %60reject%60 functions of new Promise as params.%0A @return %7BPromise%7D%0A */%0A attach @@ -824,16 +824,23 @@ +return callback @@ -940,16 +940,21 @@ f (this. +get(' continue @@ -960,16 +960,18 @@ eOnError +') ) %7B%0A @@ -1004,16 +1004,16 @@ else %7B%0A - @@ -1021,16 +1021,22 @@ reject( +reason );%0A
aa3c861b89966426427c1adbfc3dd3868cd07789
correct EntryFieldDescription spec
test/spec/factory/EntryFieldDescriptionSpec.js
test/spec/factory/EntryFieldDescriptionSpec.js
var EntryFieldDescription = require('lib/factory/EntryFieldDescription'); var domAttr = require('min-dom').attr, domQuery = require('min-dom').query; describe('factory/EntryFieldDescription', function() { describe('show', function() { it('should use provided callback name', function() { // when var html = EntryFieldDescription(translate, 'desc', { show: 'show' }); // then expect(domAttr(html, 'data-show')).to.equal('show'); }); it('should not set "data-show" attribute if callback name is not present', function() { // when var html1 = EntryFieldDescription(translate, 'desc'); var html2 = EntryFieldDescription(translate, 'desc', { show: undefined }); // then expect(domAttr(html1, 'data-show')).not.to.exist; expect(domAttr(html2, 'data-show')).not.to.exist; }); }); describe('escaping', function() { it('should escape HTML', function() { // when var html = EntryFieldDescription(translate, '<html />'); // then expect(domQuery('.description__text', html).innerHTML).to.equal('&lt;html /&gt;'); }); it('should preserve plain <a href>', function() { // when var html = EntryFieldDescription(translate, 'Hallo <a href="http://foo">FOO</a> <a href="https://bar">BAR</a>!'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hallo <a href="http://foo" target="_blank">FOO</a> <a href="https://bar" target="_blank">BAR</a>!' ); }); it('should preserve query string in plain <a href>', function() { // when var html = EntryFieldDescription(translate, 'Hallo <a href="http://foo?foo=bar&foo.bar[]=1">FOO</a>'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hallo <a href="http://foo?foo=bar&amp;foo.bar[]=1" target="_blank">FOO</a>' ); }); it('should preserve <a> and <br/>', function() { // when var html = EntryFieldDescription(translate, '<div>' + '<a href="http://foo">' + '<p>' + '<br />' + '</p>' + '</a>' + '<br />' + '<a href="http://bar">BAR</a>' + '</div>' ); // then expect(domQuery('.description__text', html).innerHTML).to.equal( '&lt;div&gt;' + '<a href="http://foo" target="_blank">' + '&lt;p&gt;' + '<br>' + '&lt;/p&gt;' + '</a>' + '<br>' + '<a href="http://bar" target="_blank">BAR</a>' + '&lt;/div&gt;' ); }); it('should handle markdown special chars in <a href>', function() { // when var html = EntryFieldDescription(translate, 'Hallo <a href="http://foo?()[]">[]FOO</a>'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hallo <a href="http://foo?()[]" target="_blank">[]FOO</a>' ); }); it('should ignore custom <a href>', function() { // when var html = EntryFieldDescription(translate, 'Hallo <a class="foo" href="http://foo">FOO</a>!'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hallo &lt;a class="foo" href="http://foo"&gt;FOO&lt;/a&gt;!' ); }); it('should ignore broken <a href>', function() { // when var html = EntryFieldDescription(translate, 'Hallo <a href="http://foo>FOO</a>!'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hallo &lt;a href="http://foo&gt;FOO&lt;/a&gt;!' ); }); it('should ignore non HTTP(S) protocol <a href>', function() { // when var html = EntryFieldDescription(translate, 'Hallo <a href="javascript:foo()">FOO</a>!'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hallo &lt;a href="javascript:foo()"&gt;FOO&lt;/a&gt;!' ); }); it('should transform markdown link', function() { // when var html = EntryFieldDescription(translate, 'Hallo [FOO](http://foo) [BAR](https://bar?a=1&b=10)!'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hallo <a href="http://foo" target="_blank">FOO</a> <a href="https://bar?a=1&amp;b=10" target="_blank">BAR</a>!' ); }); it('should ignore broken markdown link', function() { // when var html = EntryFieldDescription(translate, 'Hallo [FOO](http://foo'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hallo [FOO](http://foo' ); }); it('should transform HTML in markdown link', function() { // when var html = EntryFieldDescription(translate, 'Hallo ["FOO" <div/>](http://foo)'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hallo <a href="http://foo" target="_blank">"FOO" &lt;div/&gt;</a>' ); }); it('should preserve line breaks', function() { // when var html = EntryFieldDescription(translate, 'Hello <br/> world'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hello <br> world' ); }); it('should ignore whitespaces in br tag', function() { // when var html = EntryFieldDescription(translate, 'Hello <br /> world'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hello <br> world' ); }); it('should preserve line breaks within <a> text', function() { // when var html = EntryFieldDescription(translate, '<a href="https://test.com"> HELLO <br/> WORLD </a>'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( '<a href="https://test.com" target="_blank"> HELLO <br> WORLD </a>' ); }); it('should not ignore <a> if br used within URL field', function() { // when var html = EntryFieldDescription(translate, '<a href="https://test<br />website.com"> HELLO <br/> WORLD </a>'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( '<a href="https://test&lt;br /&gt;website.com" target="_blank"> HELLO <br> WORLD </a>' ); }); it('should handle special HTML chars in markdown link', function() { // when var html = EntryFieldDescription(translate, 'Hallo [YOU](http://foo=<" []>)'); // then expect(domQuery('.description__text', html).innerHTML).to.equal( 'Hallo <a href="http://foo=%3C%22%20%5B%5D%3E" target="_blank">YOU</a>' ); }); }); }); // helpers ////////// function translate(string) { return string; }
JavaScript
0
@@ -6295,20 +6295,14 @@ test -&lt;br /&gt; +%3Cbr /%3E webs
30800668dc9f96baa3baf909b30d52a965f4712a
Update script.js
Web/js/script.js
Web/js/script.js
$(document).ready(function() { // nav // nav clase $(".nav a").on("click", function(){ $(".nav").find(".active").removeClass("active"); $(this).parent().addClass("active"); }); // nav tag $('nav').affix({ offset: { top: function() { return $('#imagen-inicial').height(); } } }); // end nav function makeParallax() { $('.parallax-window-1').parallax({imageSrc: 'images/Aitor1.jpg'}); }; makeParallax(); $(window).resize(function () { makeParallax(); }); // velocidad parallax /* var parallax = document.querySelectorAll(".parallax"), speed = 0.5; window.onscroll = function(){ [].slice.call(parallax).forEach(function(el,i){ var windowYOffset = window.pageYOffset, elBackgrounPos = "0 " + (windowYOffset * speed) + "px"; alert(elBackgrounPos); el.style.backgroundPosition = elBackgrounPos; }); };*/ // end velocidad parallax $('a[href*="#"]:not([href="#"])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html, body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); // Animación var $window = $(window), win_height_padded = $window.height() * 1.1, isTouch = Modernizr.touch; if (isTouch) { $('.revealOnScroll').addClass('animated'); } $window.on('scroll', revealOnScroll); function revealOnScroll() { makeParallax(); var scrolled = $window.scrollTop(), win_height_padded = $window.height() * 1.1; // Showed... $(".revealOnScroll:not(.animated)").each(function () { var $this = $(this), offsetTop = $this.offset().top; if (scrolled + win_height_padded > offsetTop) { if ($this.data('timeout')) { window.setTimeout(function(){ $this.addClass('animated ' + $this.data('animation')); }, parseInt($this.data('timeout'),10)); } else { $this.addClass('animated ' + $this.data('animation')); } } }); // Hidden... $(".revealOnScroll.animated").each(function (index) { var $this = $(this), offsetTop = $this.offset().top; if (scrolled + win_height_padded < offsetTop) { $(this).removeClass('animated fadeInUp flipInX lightSpeedIn') } }); } revealOnScroll(); });
JavaScript
0.000002
@@ -1694,37 +1694,16 @@ roll() %7B -%0A makeParallax();%0A %0A
69690a9096b143f984284086fdfb700acbc07a79
update knex model to use tableName const (#287)
packages/generator-feathers/generators/service/templates/model/knex.js
packages/generator-feathers/generators/service/templates/model/knex.js
/* eslint-disable no-console */ // <%= name %>-model.js - A KnexJS // // See http://knexjs.org/ // for more of what you can do here. module.exports = function (app) { const db = app.get('knexClient'); db.schema.hasTable('<%= kebabName %>').then(exists => { if(!exists) { db.schema.createTable('<%= kebabName %>', table => { table.increments('id'); table.string('text'); }).then( () => console.log('Updated <%= kebabName %> table'), e => console.error('Error updating <%= kebabName %> table', e) ); } }); return db; };
JavaScript
0
@@ -198,16 +198,55 @@ ient');%0A + const tableName = '%3C%25= kebabName %25%3E'; %0A db.sc @@ -259,34 +259,25 @@ asTable( -'%3C%25= kebabName %25%3E' +tableName ).then(e @@ -333,34 +333,25 @@ teTable( -'%3C%25= kebabName %25%3E' +tableName , table @@ -425,22 +425,16 @@ %7D) -.then( %0A @@ -434,16 +434,22 @@ +.then( () =%3E co @@ -462,42 +462,38 @@ log( -'Upd +%60Cre ated -%3C%25= kebab +$%7Btable Name - %25%3E +%7D table -'), +%60)) %0A @@ -497,16 +497,23 @@ +.catch( e =%3E con @@ -527,58 +527,47 @@ ror( -' +%60 Error -upd +cre ating -%3C%25= kebab +$%7Btable Name - %25%3E +%7D table -' +%60 , e) -%0A );%0A
9bc721a27ad216bb2368967f8db7341079cd1a23
fix data.maybe
definitions/npm/data.maybe_v1.x.x/flow_v0.32.x-/data.maybe_v1.x.x.js
definitions/npm/data.maybe_v1.x.x/flow_v0.32.x-/data.maybe_v1.x.x.js
// @flow import type Either from "data.either"; interface Functor<A> { map<B>(f: (a: A) => B): Functor<B>; } interface Apply<A> extends Functor<A> { ap<B>(fab: Apply<(a: A) => B>): Apply<B>; } interface Applicative<A> extends Apply<A> { static of<B>(b: B): Applicative<B>; } interface Chain<A> extends Apply<A> { chain<B>(f: (a: A) => Chain<B>): Chain<B>; } interface Monad<A> extends Applicative<A>, Chain<A> {} interface Validation<F, S> extends Applicative<S> {} declare module "data.maybe" { declare class IMaybe<T> { isNothing: boolean; isJust: boolean; isEqual(om: IMaybe<T>): boolean; toString(): string; toJSON(): Object; get(): T; getOrElse(defaultValue: T): T; map<B>(f: (v: T) => B): IMaybe<B>; ap<B>(fb: IMaybe<B> | Applicative<B>): IMaybe<B>; chain<B>(f: (v: T) => IMaybe<B>): IMaybe<B>; orElse<T>(f: () => IMaybe<T>): IMaybe<T>; cata<B>(patterns: {| Nothing: () => B, Just: (v: T) => B |}): B; static Nothing<T>(): IMaybe<T>; static Just<T>(value: T): IMaybe<T>; static of<T>(value: T): IMaybe<T>; static fromNullable(value: ?T): IMaybe<T>; static fromEither<L, R>(em: Either<L, R>): IMaybe<R>; static fromValidation<F, S>(vm: Validation<F, S>): IMaybe<S>; } declare module.exports: typeof IMaybe; }
JavaScript
0.0003
@@ -7,57 +7,155 @@ ow%0A%0A -import type Either from %22data.either%22;%0A%0Ainterface +// TODO Once we support dependencies, put into declare module%0Aimport type Either from %22data.either%22;%0A%0Adeclare module %22data.maybe%22 %7B%0A declare class Fun @@ -164,16 +164,18 @@ or%3CA%3E %7B%0A + map%3CB%3E @@ -200,36 +200,44 @@ Functor%3CB%3E;%0A + %7D%0A%0A -interface + declare class Apply%3CA%3E ex @@ -255,16 +255,18 @@ or%3CA%3E %7B%0A + ap%3CB%3E( @@ -301,28 +301,36 @@ ply%3CB%3E;%0A + %7D%0A%0A -interface + declare class Applica @@ -356,16 +356,18 @@ ly%3CA%3E %7B%0A + static @@ -396,28 +396,36 @@ ive%3CB%3E;%0A + %7D%0A%0A -interface + declare class Chain%3CA @@ -445,16 +445,18 @@ ly%3CA%3E %7B%0A + chain%3C @@ -492,19 +492,30 @@ ain%3CB%3E;%0A -%7D%0A%0A + %7D%0A declare interfac @@ -562,25 +562,31 @@ %3CA%3E %7B%7D%0A%0A -interface + declare class Validat @@ -626,38 +626,8 @@ %7B%7D%0A%0A -declare module %22data.maybe%22 %7B%0A de
8ccc0437c31c1e8a80411e998243e79e8fcf6b59
update GhostButton
src/GhostButton/GhostButton.js
src/GhostButton/GhostButton.js
/** * @file GhostButton component * @author liangxiaojun(liangxiaojun@derbysoft.com) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import BaseButton from '../_BaseButton'; import TipProvider from '../TipProvider'; import Theme from '../Theme'; import Position from '../_statics/Position'; import Util from '../_vendors/Util'; class GhostButton extends Component { static Theme = Theme; static TipPosition = Position; constructor(props, ...restArgs) { super(props, ...restArgs); } /** * public */ startRipple = e => { this.refs.baseButton && this.refs.baseButton.startRipple(e); }; /** * public */ endRipple = () => { this.refs.baseButton && this.refs.baseButton.endRipple(); }; render() { const {children, className, ...restProps} = this.props, buttonClassName = classNames('ghost-button', { [className]: className }); return ( <BaseButton {...restProps} ref="baseButton" className={buttonClassName}> {children} </BaseButton> ); } } GhostButton.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * The button theme.Can be primary,highlight,success,warning,error. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * If true,the button will have rounded corners. */ isRounded: PropTypes.bool, /** * If true,the button will be round. */ isCircular: PropTypes.bool, /** * The title of the button. */ title: PropTypes.string, /** * The text of the button.Type can be string or number. */ value: PropTypes.any, /** * The type of button.Can be reset,submit or button. */ type: PropTypes.string, /** * Disables the button if set to true. */ disabled: PropTypes.bool, /** * If true,the button will be have loading effect. */ isLoading: PropTypes.bool, /** * If true,the element's ripple effect will be disabled. */ disableTouchRipple: PropTypes.bool, /** * Use this property to display an icon.It will display on the left. */ iconCls: PropTypes.string, /** * Use this property to display an icon.It will display on the right. */ rightIconCls: PropTypes.string, /** * If true,the ripple effect will be display centered. */ rippleDisplayCenter: PropTypes.bool, tip: PropTypes.string, tipPosition: PropTypes.oneOf(Util.enumerateValue(TipProvider.Position)), /** * You can create a complicated renderer callback instead of value prop. */ renderer: PropTypes.func, /** * Callback function fired when the button is touch-tapped. */ onClick: PropTypes.func }; GhostButton.defaultProps = { theme: Theme.DEFAULT, isRounded: false, isCircular: false, value: '', disabled: false, type: 'button', isLoading: false, disableTouchRipple: false, rippleDisplayCenter: false, tipPosition: TipProvider.Position.BOTTOM }; export default GhostButton;
JavaScript
0
@@ -834,24 +834,160 @@ ();%0A %7D;%0A%0A + /**%0A * public%0A */%0A triggerRipple = e =%3E %7B%0A this.refs.baseButton && this.refs.baseButton.triggerRipple(e);%0A %7D;%0A%0A render()
a9a76cddfe7a2efef07c861c047f532768f7cc3e
Add braces to control block
src/main/webapp/components/utils/getFields.js
src/main/webapp/components/utils/getFields.js
import {getField} from "./getField"; /** * Creates a new object whose fields are either equal to obj[field] * or defaultValue. * Useful for extracting a subset of fields from an object. * * @param obj the object to query the fields for. * @param fields an array of the target fields, in string form. * @param defaultValue the value to be used if obj[field] === undefined. */ export const getFields = (obj, fields, defaultValue) => { const res = {}; for (const field of fields) res[field] = getField(obj, field, defaultValue); return res; }
JavaScript
0
@@ -489,16 +489,18 @@ fields) + %7B res%5Bfie @@ -540,16 +540,18 @@ tValue); + %7D %0A retur
7fa08226e38a15bca37f1811d54cb9ad87c59959
Replace extracting with extract
src/main/webapp/components/utils/getFields.js
src/main/webapp/components/utils/getFields.js
import {getField} from "./getField"; /** * Creates a new object whose fields are either equal to obj[field] * or defaultValue. * Useful for extracting a subset of fields from an object. * * @param obj the object to query the fields for. * @param fields an array of the target fields, in string form. * @param defaultValue the value to be used if obj[field] === undefined. * @deprecated extracting values with destructuring instead. * @see {@link https://github.com/googleinterns/step240-2020/pull/176|GitHub} */ export const getFields = (obj, fields, defaultValue) => { const res = {}; for (const field of fields) { res[field] = getField(obj, field, defaultValue); } return res; }
JavaScript
0.999997
@@ -395,19 +395,16 @@ extract -ing values
5767242231d8a23b51faca2d3847ee20e559c483
Discard the playerToken if it is about to expire
src/online/scoreboard-system/OnlineService.js
src/online/scoreboard-system/OnlineService.js
import Auth0 from 'auth0-js' import createScoreboardClient from './createScoreboardClient' export class OnlineService { constructor ({ server, storagePrefix = 'scoreboard.auth', authOptions }) { const auth = new Auth0.WebAuth({ ...authOptions, redirectUri: window.location.href, responseType: 'token id_token' }) this._scoreboardClient = createScoreboardClient({ server, auth }) this._storagePrefix = storagePrefix this._updateUserFromStorage() this._renewPlayerToken() } _updateUserFromStorage () { const loadUser = (text) => { if (!text) return null try { return JSON.parse(text) } catch (e) { return null } } this._currentUser = loadUser(localStorage[`${this._storagePrefix}.id`]) } _renewPlayerToken () { const playerToken = this._currentUser && this._currentUser.playerToken if (!playerToken) return const username = this._currentUser.username return this._scoreboardClient.renewPlayerToken({ playerToken }) .then(newToken => { localStorage[`${this._storagePrefix}.id`] = JSON.stringify({ username: username, playerToken: newToken }) }) } getCurrentUser () { if (this._currentUser && this._currentUser.playerToken) { return { username: this._currentUser.username } } else { return null } } isLoggedIn () { return !!this._currentUser } signUp ({ username, password, email }) { return this._scoreboardClient.signUp({ username, password, email }) .then(signUpResult => { localStorage[`${this._storagePrefix}.id`] = JSON.stringify({ username: username, playerToken: signUpResult.playerToken }) this._updateUserFromStorage() }) } logIn ({ username, password }) { return this._scoreboardClient.loginByUsernamePassword({ username, password }) .then(loginResult => { localStorage[`${this._storagePrefix}.id`] = JSON.stringify({ username: username, playerToken: loginResult.playerToken }) this._updateUserFromStorage() return this.getCurrentUser() }) } async logOut () { delete localStorage[`${this._storagePrefix}.id`] this._updateUserFromStorage() } async submitScore (info) { if (!this._currentUser) { throw new Error('Not logged in') } const result = await this._scoreboardClient.submitScore({ playerToken: this._currentUser.playerToken, md5: info.md5, playMode: info.playMode, input: { score: info.score, combo: info.combo, count: info.count, total: info.total, log: info.log } }) const data = { md5: info.md5, playMode: info.playMode, ...toEntry(result.data.registerScore.resultingRow) } return data } // Retrieves a record. // // Returns a record object. async retrieveRecord (level, user) { const result = await this._scoreboardClient.retrieveRecord({ playerToken: this._currentUser.playerToken, md5: level.md5, playMode: level.playMode, }) const myRecord = result.data.chart.level.myRecord return myRecord && { md5: level.md5, playMode: level.playMode, ...toEntry(myRecord) } } // Retrieves the scoreboard async retrieveScoreboard ({ md5, playMode }) { const result = await this._scoreboardClient.retrieveScoreboard({ md5, playMode }) return { data: result.data.chart.level.leaderboard.map(toEntry) } } // Retrieve multiple records! // // Items is an array of song items. They have a md5 property. async retrieveMultipleRecords (items) { const result = await this._scoreboardClient.retrieveRankingEntries({ playerToken: this._currentUser.playerToken, md5s: items.map(item => item.md5) }) const entries = result.data.me.records.map(item => ({ ...toEntry(item), md5: item.md5, playMode: item.playMode })) return entries } } export default OnlineService function toEntry (row) { return { rank: row.rank, score: row.entry.score, combo: row.entry.combo, count: row.entry.count, total: row.entry.total, playerName: row.entry.player.name, recordedAt: new Date(row.entry.recordedAt), playCount: row.entry.playCount, playNumber: row.entry.playNumber } }
JavaScript
0
@@ -403,24 +403,30 @@ Client(%7B +%0A server, auth %7D) @@ -417,21 +417,53 @@ server, - auth +%0A auth,%0A log: () =%3E %7B %7D%0A %7D)%0A @@ -682,31 +682,358 @@ -return JSON.parse(text) +const data = JSON.parse(text)%0A const playerToken = data.playerToken%0A const playerTokenExpires = JSON.parse(atob(playerToken.split('.')%5B1%5D)).exp * 1000%0A if (Date.now() %3E playerTokenExpires - 86400e3) %7B%0A console.warn('Authentication token is about to expire, skipping!')%0A return null%0A %7D%0A return data %0A
893b43ec955d822f1be1bc37a99d43577e1c8797
replace bookService with persistenceService (work in progress)
src/app/components/services/books/books.service.js
src/app/components/services/books/books.service.js
let self; class BooksService { /*@ngInject*/ constructor(warlockOfFiretopMountainService, templeOfTerrorService, creatureFromHavocService, messagesService, $translate, constants, persistenceService) { self = this; self.messagesService = messagesService; self.$translate = $translate; self.constants = constants; self.persistenceService = persistenceService; self.books = []; self.addBook(warlockOfFiretopMountainService.getBook()); self.addBook(templeOfTerrorService.getBook()); self.addBook(creatureFromHavocService.getBook()); } getBooks() { return self.books; } getParagraph(bookId, paragraphNr) { let book = self.getBook(bookId); if (!!book) { if (!!book.paragraphs) { let i; for (i = 0; i < book.paragraphs.length; i++) { // use type coersion if (paragraphNr == book.paragraphs[i].paragraphNr) { return book.paragraphs[i]; } } } return self.createNewParagraph(paragraphNr); } } createNewParagraph(paragraphNr) { return { version : self.constants.version, paragraphNr : paragraphNr, description : '', choices : [] }; } getBook(bookId) { let i; for (i = 0; i < self.books.length; i++) { if (bookId === self.books[i].urlName) { return self.books[i]; } } self.messagesService.errorMessage(self.$translate.instant('Cannot find book') + " '" + bookId + "'", false); return null; } addBook(book) { self.books.push(book); self.saveBookToPersistence(book); } saveBookToPersistence(book) { let previousSavedBook = self.persistenceService.getBook(book.id); if (!previousSavedBook || new Number(previousSavedBook.version) < new Number(book.version)) { self.persistenceService.setBook(book); // TODO replace paragraph } } } export default BooksService;
JavaScript
0.000001
@@ -1525,15 +1525,10 @@ %5Bi%5D. -urlName +id ) %7B%0A
fa050657874210792ed0c3d24e72638a1815da00
Fix #541
src/page/search/advanced-search/action-bar.js
src/page/search/advanced-search/action-bar.js
// Dependencies const builder = require('focus-core').component.builder; const {reduce} = require('lodash/collection'); const {omit} = require('lodash/object'); // Components const ListActionBar = require('../../../list/action-bar/index').component; //Mixins const i18nMixin = require('../../../common/i18n/mixin'); const Bar = { mixins: [i18nMixin], /** * Get the default props * @return {object} the default props */ getDefaultProps() { return ({ orderableColumnList: {}, groupableColumnList: {}, orderSelected: undefined, selectionStatus: undefined, selectionAction: undefined, groupingKey: undefined, selectedFacets: {}, action: undefined, lineOperationList: undefined }); }, /** * Filter the facet list so that the scope facet is not displayed * @return {object} The filtered facet list */ _filterFacetList() { const {selectedFacets} = this.props; return reduce(selectedFacets, (result, facet, facetKey) => { result[facetKey] = { label: this.i18n(`live.filter.facets.${facetKey}`), value: facet.data.label }; return result; }, {}); }, /** * On facet click, remove it from the selected facets, and update the store * @param {string} key The facet key to remove */ _onFacetClick(key) { const {selectedFacets, action: {updateProperties}} = this.props; updateProperties({selectedFacets: omit(selectedFacets, key)}); }, /** * Update the store to ask for a new results order * @param {string} key the filed key to sort by * @param {boolean} order the sort direciton, ascending or descending */ _orderAction(key, order) { this.props.action.updateProperties({ sortBy: key, sortAsc: order }); }, /** * Group by the given key * @param {string} key The facet key to base the grouping on */ _groupAction(key) { this.props.action.updateProperties({ groupingKey: key }); }, /** * Render the component * @return {HTML} the rendered component */ render() { return ( <ListActionBar data-focus='advanced-search-action-bar' facetClickAction={this._onFacetClick} facetList={this._filterFacetList()} groupAction={this._groupAction} groupLabelPrefix='live.filter.facets.' groupSelectedKey={this.props.groupingKey} groupableColumnList={this.props.groupableColumnList} operationList={this.props.lineOperationList} orderAction={this._orderAction} orderSelected={this.props.sortBy} orderableColumnList={this.props.orderableColumnList} selectionAction={this.props.selectionAction} selectionStatus={this.props.selectionStatus} /> ); } }; module.exports = builder(Bar);
JavaScript
0
@@ -2796,21 +2796,17 @@ s.props. -lineO +o peration
889fa23be4a465e2091292252a870925df81fad2
fix typo
Leaflet/walkalytics.js
Leaflet/walkalytics.js
// create map var map = new L.map('map', { center: new L.latLng(46.947999, 7.448148), zoom: 15 }); // add basemap new L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', { subdomains: ['1', '2', '3', '4'], attribution: 'Map data © <a href="http://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors | Tiles Courtesy of <a href="http://www.mapquest.com/" target="_blank">MapQuest</a> <img src="http://developer.mapquest.com/content/osm/mq_logo.png">' }).addTo(map); // walkalytics configs var walkalytics = { }; walkalytics.maxminutes = 16; walkalytics.clicked = 0; walkalytics.set_apikey = function(apikey) { walkalytics.apikey = apikey; } // create marker walkalytics.marker = new L.marker(map.getCenter()); // add an event listener to map map.on('click', function(evt) { walkalytics.click(evt.latlng); }) walkalytics.click = function(coords) { if (!coords) { return true }; if (walkalytics.clicked == 0) { // remove existing marker map.removeLayer(walkalytics.marker); // block clicks until we're done walkalytics.clicked = 1; // change cursor $(".map").css({"cursor":"wait"}) // set and show marker at new location walkalytics.marker.setLatLng(coords); walkalytics.marker.addTo(map); // pan to clicked locatiom map.panTo(coords, { duration: 1.0 // seconds }); // if existing, remove isochrone layer if (walkalytics.isochrone_layer) { map.removeLayer(walkalytics.isochrone_layer);} // request new isochrone layer walkalytics.calc_isochrone(coords); } } walkalytics.calc_isochrone = function(coords) { // project coordinates: lat/lng (WGS84) to meters (EPSG:3857) for api call projcoords = L.CRS.EPSG3857.project(coords); var x = parseInt(projcoords["x"]); var y = parseInt(projcoords["y"]); var url = "https://api.walkalytics.com/v1/isochrone?"; inputparams ={ "x": x, "y": y, "subscription-key": walkalytics.apikey, "maxduration": walkalytics.maxminutes*60, "outputsize": 512 } url = url + jQuery.param(inputparams); $.ajax({ type: "POST", url: url, crossDomain: true, dataType: "json", failure: function(errMsg) { alert(errMsg); $(".map").css({"cursor":"default"}) walkalytics.clicked = 0; }, success: function( data ) { if (data["status"] == "error") { alert(data["msg"]); $(".map").css({"cursor":"default"}) walkalytics.clicked = 0; return(false); } llcoords = walkalytics.metersToLatLng( data["xllcorner"], data["yllcorner"] ); urcoords = walkalytics.metersToLatLng( data["xllcorner"] + data["ncols"] * data["cellsize"], data["yllcorner"] + data["nrows"] * data["cellsize"] ); var imageBounds = L.latLngBounds(llcoords, urcoords); walkalytics.isochrone_layer = new L.imageOverlay( data["img"], imageBounds, { opacity: 0.7, attribution: '<a href="http://walkalytics.com">Walktime &copy; EBP</a>' }); map.addLayer(walkalytics.isochrone_layer); $(".map").css({"cursor":"default"}) walkalytics.clicked = 0; } }).fail(function(response) { $(".map").css({"cursor":"default"}) walkalytics.clicked = 0; if (response.status == 429) { alert("Rate limit exceeded."); } else if (response.status == 403) { alert("It seems you are not authorized to use this service."); } else { alert("Walkalytics service is currently not available."); } }); } // unproject coordinates: meters (EPSG:3857) tolat/lng (WGS84) walkalytics.metersToLatLng = function(x, y) { earthradius = 6378137; return map.options.crs.projection.unproject(new L.point(x, y).divideBy(earthradius)) }
JavaScript
0.999991
@@ -4120,16 +4120,17 @@ 3857) to + lat/lng
d484372c7f42f78a7cbb4abfe5ca5f03d2255870
introduce concept of platform name, based on class name, because webpack.
src/BasePlatform.js
src/BasePlatform.js
// @flow /* Copyright 2016 Aviral Dasgupta Copyright 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Base class for classes that provide platform-specific functionality * eg. Setting an application badge or displaying notifications * * Instances of this class are provided by the application. */ export default class BasePlatform { constructor() { this.notificationCount = 0; this.errorDidOccur = false; } setNotificationCount(count: number) { this.notificationCount = count; } setErrorStatus(errorDidOccur: boolean) { this.errorDidOccur = errorDidOccur; } /** * Returns true if the platform supports displaying * notifications, otherwise false. */ supportsNotifications(): boolean { return false; } /** * Returns true if the application currently has permission * to display notifications. Otherwise false. */ maySendNotifications(): boolean { return false; } /** * Requests permission to send notifications. Returns * a promise that is resolved when the user has responded * to the request. The promise has a single string argument * that is 'granted' if the user allowed the request or * 'denied' otherwise. */ requestNotificationPermission(): Promise<string> { } displayNotification(title: string, msg: string, avatarUrl: string, room: Object) { } /** * Returns a promise that resolves to a string representing * the current version of the application. */ getAppVersion() { throw new Error("getAppVersion not implemented!"); } /* * If it's not expected that capturing the screen will work * with getUserMedia, return a string explaining why not. * Otherwise, return null. */ screenCaptureErrorString() { return "Not implemented"; } /** * Restarts the application, without neccessarily reloading * any application code */ reload() { throw new Error("reload not implemented!"); } }
JavaScript
0
@@ -933,24 +933,128 @@ lse;%0A %7D%0A%0A + // Used primarily for Analytics%0A getHumanReadableName() %7B%0A return 'Base Platform';%0A %7D%0A%0A setNotif
5b1ce8be706f6730cc19371b794f7eb88b257986
Remove jQuery Dependency
src/EventHandler.js
src/EventHandler.js
/** * EventHandler - Handles triggering and listening to the events of an entity. * @param {Object} entity - The entity to which the handler is attaching to. * @param {Array.<string>} events - An array of event names that this handler will use. * @constructor */ var EventHandler = function (entity, events) { this.entity = entity; this.events = { all: [] }; if (events) { for (var i = 0, l = events.length; i < l; i++) { this.events[events[i]] = []; } } this.alias(); }; /** * Aliases triggering and listening methods onto the entity */ EventHandler.prototype.alias = function () { this.entity.on = $.proxy(this.on, this); this.entity.once = $.proxy(this.once, this); this.entity.off = $.proxy(this.off, this); this.entity.trigger = $.proxy(this.trigger, this); }; /** * Adds a listener to the entity for the specified event. * @param {!string} eventName - Name of event to attach listener to. * @param {!Function} action - The listener function to be trigger on event. * @param {Object} context - The scope that will be applied to the action. * @return {Object} The entity the handler is attached to. */ EventHandler.prototype.on = function (eventName, action, context) { if (!(eventName in this.events)) { this.events[eventName] = []; } this.events[eventName].push({ action: action, context: context || this.entity }); return this.entity; }; /** * Adds a listener to the entity for the specified event that will only fire once. * @param {!string} eventName - Name of event to attach listener to. * @param {!Function} action - The listener function to be trigger on event. * @param {Object} context - The scope that will be applied to the action. * @return {Object} The entity the handler is attached to. */ EventHandler.prototype.once = function (eventName, action, context) { var self = this, once = function () { self.off(eventName, once); action.apply(this, arguments); }; once._action = action; return this.on(eventName, once, context); }; /** * Removes alls listener from the entity. Removes all listeners on the enitity matching provided criteria. * @param {string} eventName - Name of event to remove listener from. * @param {Function} action - The listener function for the event. * @param {Object} context - The scope for the action. * @return {Object} The entity the handler is attached to. */ EventHandler.prototype.off = function (eventName, action, context) { if (!action && !context) { if (!eventName) { this.clear(); } else { this.events[eventName] = []; } return this.entity; } var i, length, ev, events = this.events[eventName], retain = []; for (i = 0, length = events.length; i < length; i++) { ev = events[i]; if ((action && action !== ev.action && action !== ev.action._action) || (context && context !== ev.context)) { retain.push(ev); } } this.events[eventName] = retain; return this.entity; }; /** * Trigger all listeners for the provided eventName. * @param {string} eventName - Name of event to trigger listeners for. * @param {Array} args - A list to be passed to the trigger listeners. * @return {Object} The entity the handler is attached to. */ EventHandler.prototype.trigger = function (eventName, args) { if (eventName in this.events) { this.triggerEvents(this.events[eventName], args || []); } if ('all' in this.events) { this.triggerEvents(this.events.all, args || []); } return this.entity; }; /** * Helper method for triggering events. Handles calling a list of listeners. * @param {Array.<Function>} events - The list of listeners to be called. * @param {Array} args - The list of arguments to be passed to each listener. * @private */ EventHandler.prototype.triggerEvents = function (events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) { ev = events[i]; ev.action.call(ev.context); } break; case 1: while (++i < l) { ev = events[i]; ev.action.call(ev.context, a1); } break; case 2: while (++i < l) { ev = events[i]; ev.action.call(ev.context, a1, a2); } break; case 3: while (++i < l) { ev = events[i]; ev.action.call(ev.context, a1, a2, a3); } break; default: while (++i < l) { ev = events[i]; ev.action.apply(ev.context, args); } break; } }; /** * Helper method for clearing all events. * @private */ EventHandler.prototype.clear = function () { for (var key in this.events) { if (this.events.hasOwnProperty(key)) { this.events[key] = []; } } }; /** * Global Variable Exports */ window.EventHandler = EventHandler;
JavaScript
0.000001
@@ -601,201 +601,425 @@ %7B%0A%09 -this.entity.on = $.proxy(this.on, this);%0A%09this.entity.once = $.proxy(this.once, this);%0A%09this.entity.off = $.proxy(this.off, this);%0A%09this.entity.trigger = $.proxy(this.trigger, this) +var self = this;%0A%0A%09this.entity.on = function (eventName, action, context) %7B%0A%09%09self.on(eventName, action, context);%0A%09%7D;%0A%0A%09this.entity.once = function (eventName, action, context) %7B%0A%09%09self.once(eventName, action, context);%0A%09%7D;%0A%0A%09this.entity.off = function (eventName, action, context) %7B%0A%09%09self.off(eventName, action, context);%0A%09%7D;%0A%0A%09this.entity.trigger = function (eventName, args) %7B%0A%09%09self.trigger(eventName, args);%0A%09%7D ;%0A%7D;
8510cd4df2ba7c29a70212aa182eb056cd38564e
Remove the check for "inside a frame"
src/IFrameWindow.js
src/IFrameWindow.js
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. import { Log } from './Log.js'; const DefaultTimeout = 10000; export class IFrameWindow { constructor(params) { this._promise = new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject; }); this._boundMessageEvent = this._message.bind(this); window.addEventListener("message", this._boundMessageEvent, false); this._frame = window.document.createElement("iframe"); // shotgun approach this._frame.style.visibility = "hidden"; this._frame.style.position = "absolute"; this._frame.style.display = "none"; this._frame.style.width = 0; this._frame.style.height = 0; window.document.body.appendChild(this._frame); } navigate(params) { if (!params || !params.url) { this._error("No url provided"); } else { let timeout = params.silentRequestTimeout || DefaultTimeout; Log.debug("IFrameWindow.navigate: Using timeout of:", timeout); this._timer = window.setTimeout(this._timeout.bind(this), timeout); this._frame.src = params.url; } return this.promise; } get promise() { return this._promise; } _success(data) { this._cleanup(); Log.debug("IFrameWindow: Successful response from frame window"); this._resolve(data); } _error(message) { this._cleanup(); Log.error(message); this._reject(new Error(message)); } close() { this._cleanup(); } _cleanup() { if (this._frame) { Log.debug("IFrameWindow: cleanup"); window.removeEventListener("message", this._boundMessageEvent, false); window.clearTimeout(this._timer); window.document.body.removeChild(this._frame); this._timer = null; this._frame = null; this._boundMessageEvent = null; } } _timeout() { Log.debug("IFrameWindow.timeout"); this._error("Frame window timed out"); } _message(e) { Log.debug("IFrameWindow.message"); if (this._timer && e.origin === this._origin && e.source === this._frame.contentWindow ) { let url = e.data; if (url) { this._success({ url: url }); } else { this._error("Invalid response from frame"); } } } get _origin() { return location.protocol + "//" + location.host; } static notifyParent(url) { Log.debug("IFrameWindow.notifyParent"); if (window.frameElement) { url = url || window.location.href; if (url) { Log.debug("IFrameWindow.notifyParent: posting url message to parent"); window.parent.postMessage(url, location.protocol + "//" + location.host); } } } }
JavaScript
0
@@ -2877,47 +2877,8 @@ %22);%0A - if (window.frameElement) %7B%0A @@ -2916,36 +2916,32 @@ n.href;%0A - if (url) %7B%0A @@ -2927,36 +2927,32 @@ if (url) %7B%0A - Log. @@ -3026,28 +3026,24 @@ - - window.paren @@ -3104,30 +3104,16 @@ .host);%0A - %7D%0A
601defb1885cd630a9ab76eb16a87dfc5de8bfc6
comment update
Challenge13.js
Challenge13.js
// Write a JavaScript function that takes a sentence as an argument and determines which word in that sentence has the greatest number of repeated letters (the repeated letters do not have to be consecutive). // // If the sentence has multiple words with the same max of repeated letters, return them all in an Array. // // Test Case // // Would select the words: // wordSelector("I attribute my success to this: I never gave or took any excuse. –Florence Nightingale") // // ["attribute", "success"] function wordSelector(sentence) { // 1) split sentence to array // var array = sentence.split(" "); // match method is more useful var array = sentence.match(/[a-z]+/ig); // var arraySort = []; for(var i=0; i < array.length; i++) { var arrayWord = array[i]; for(var j=0; j < arrayWord.length; j++) { var repeatCount = 0; for(var k=0; arrayWord.length; k++) { if(arrayWord[i] == arrayWord[j]) { console.log("repeatCount:" + repeatCount); repeatCount++; } } } } // var mapped = array.map(function(el, i) { // console.log("mapped: el " + el + "mapped: i " + i); // // return { // // index: i, value: el.toLowerCase() // // }; // }) // 2) to check } console.log(wordSelector("I attribute my success to this: I never gave or took any excuse. –Florence Nightingale"));
JavaScript
0
@@ -571,40 +571,37 @@ // -var array = sentence.split(%22 %22); +How to: split or match Method %0A / @@ -629,16 +629,56 @@ e useful + to manipulate one line of code %22.%22, %22%E2%80%93%22 %0A var a @@ -717,33 +717,8 @@ );%0A%0A - // var arraySort = %5B%5D;%0A fo
7cdc6b6f4d9dfdb560a2e4febea2262f527b6394
Update index.js
src/Notify/index.js
src/Notify/index.js
import { Component, PropTypes } from 'react' import Portal from 'react-portal' import NotifyMesssage from './NotifyMesssage' import cx from 'classnames' export default class Notify extends Component { static propTypes = { notifications: PropTypes.arrayOf(PropTypes.object).isRequired, position: PropTypes.string, } static defaultProps = { type: 'primary', className: 'uk-notify', position: 'top-center', notifications: [], } state = { isOpened: false, } handleClick = () => { this.setState({ isOpened: true, }) } render() { const { position, notifications, } = this.props const className = cx('uk-notify', { 'uk-notify-top-center': position === 'top-center', 'uk-notify-top-left': position === 'top-left', 'uk-notify-top-right': position === 'top-right', 'uk-notify-bottom-center': position === 'bottom-center', 'uk-notify-bottom-left': position === 'bottom-left', 'uk-notify-bottom-right': position === 'bottom-right', }) return ( <Portal isOpened={notifications.length > 0} onClose={this.handleClick} > <div className={className}> {notifications.map(({ type, message, id, isSticky, timeout, icon }) => ( <NotifyMesssage icon={icon} isSticky={isSticky} key={id} timeout={timeout} type={type} > {message} </NotifyMesssage> ))} </div> </Portal> ) } }
JavaScript
0.000002
@@ -72,16 +72,45 @@ portal'%0A +import cx from 'classnames'%0A%0A import N @@ -150,36 +150,8 @@ age' -%0Aimport cx from 'classnames' %0A%0Aex
d829f75c1237ed59861cd3f189b0ef7db3081bc5
remove 'js' prefix from component initialisation
Resources/public/js/components/bulk-price/main.js
Resources/public/js/components/bulk-price/main.js
/* * This file is part of the Sulu CMS. * * (c) MASSIVE ART WebServices GmbH * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ /** * @class bulk-price@suluproduct * @constructor * * @param {Object} [options] Configuration object * @param {Array} [options.data] Array of data [object] * @param {Array} [options.instanceName] string instance name */ define(['text!suluproduct/components/bulk-price/bulk-price.html'], function(BulkPriceTemplate) { 'use strict'; var defaults = { instanceName: null, data: [], translations: {}, currency: null }, constants = { minimumQuantity: 0, maxBulkElements: 4, bulkPriceIdPrefix: 'bulk-price-' }, eventNamespace = 'sulu.products.bulk-price.', /** returns normalized event names */ createEventName = function(postFix) { return eventNamespace + (this.options.instanceName ? this.options.instanceName + '.' : '') + postFix; }, /** * @event sulu.products.bulk-price.initialized * @description Emitted when component is initialized */ INITIALIZED = function() { return createEventName.call(this, 'initialized'); }, /** * Returns the sales price and splits salesprice from prices array (price with minimum quantity 0) * additionally formats prices according locale * @param prices * @returns price */ getSalesPriceAndRemoveFromPrices = function(prices) { var salesPrice = null, idx = null; this.sandbox.util.foreach(prices, function(price, index) { if (parseFloat(price.minimumQuantity) === constants.minimumQuantity && idx === null) { salesPrice = price; idx = index; } price.minimumQuantity = (!!price.minimumQuantity || price.minimumQuantity === 0) ? this.sandbox.numberFormat(parseFloat(price.minimumQuantity), 'n') : ''; price.price = (!!price.price || price.price === 0) ? this.sandbox.numberFormat(price.price, 'n') : ''; }.bind(this)); // remove sales price if (idx !== null) { prices.splice(idx, 1); } return salesPrice; }, addEmptyObjects = function(prices) { var i = prices.length; if (i < constants.maxBulkElements) { for (; i < constants.maxBulkElements; i++) { prices.push({}); } } return prices; }, bindDomEvents = function() { this.sandbox.dom.on(this.$el, 'change', function() { refreshData.call(this); }.bind(this), 'input'); this.sandbox.dom.on(this.$el, 'blur', function() { this.sandbox.emit("sulu.content.changed"); }.bind(this), 'input'); }, refreshData = function() { // get sales price var priceItems = [], $salesPrice = this.sandbox.dom.find('.salesprice', this.$el), salesPriceValue = this.sandbox.dom.val($salesPrice), salesPriceId = this.sandbox.dom.data($salesPrice, 'id'), salesPrice, $prices = this.sandbox.dom.find('.table tbody tr', this.$el), priceValue, priceQuantity, priceId; // update sales price if (!!salesPriceValue) { salesPrice = { price: !!salesPriceValue ? this.sandbox.parseFloat(salesPriceValue) : null, minimumQuantitiy: constants.minimumQuantity, id: !!salesPriceId ? salesPriceId : null, currency: this.options.currency }; priceItems.push(salesPrice); } // bulk prices this.sandbox.util.foreach($prices, function($price) { priceId = this.sandbox.dom.data($price, 'id'); priceQuantity = this.sandbox.dom.val(this.sandbox.dom.find('input.minimumQuantity', $price)); priceValue = this.sandbox.dom.val(this.sandbox.dom.find('input.price', $price)); if (!!priceQuantity && !!priceValue) { priceItems.push({ minimumQuantity: this.sandbox.parseFloat(priceQuantity), price: this.sandbox.parseFloat(priceValue), currency: this.options.currency, id: !!priceId ? priceId : null }); } }.bind(this)); // special prices var specialPrice = {}; specialPrice.currency = {}; specialPrice.dateStart = $('#js-input-dateStart' + this.options.currency.code).val(); specialPrice.dateEnd = $('#js-input-dateEnd' + this.options.currency.code).val(); specialPrice.price = $('#js-input' + this.options.currency.code).val(); specialPrice.currency = this.options.currency; this.sandbox.dom.data(this.$el, 'itemsSpecialPrice', specialPrice); this.sandbox.dom.data(this.$el, 'items', priceItems); this.sandbox.emit('sulu.products.bulk-price.changed'); }, initDateComponents = function(tmplSelectors) { this.sandbox.start([ { name: 'input@husky', options: { el: '#' + tmplSelectors.dateStart, instanceName: 'js-' + tmplSelectors.dateStart, inputId: 'js-' + tmplSelectors.dateStart, skin: 'date' } } ]); this.sandbox.start([ { name: 'input@husky', options: { el: '#' + tmplSelectors.dateEnd, instanceName: 'js-' + tmplSelectors.dateEnd, inputId: 'js-' + tmplSelectors.dateEnd, skin: 'date' } } ]); }; return { initialize: function() { var prices = [], salesPrice, specialPrice = {}, tmplSelectors = {}; this.options = this.sandbox.util.extend({}, defaults, this.options); if (this.options.data.prices) { prices = this.sandbox.util.extend([], this.options.data.prices); salesPrice = getSalesPriceAndRemoveFromPrices.call(this, prices); } if (this.options.data.specialPrice) { specialPrice = this.options.data.specialPrice; specialPrice.price = this.sandbox.numberFormat(specialPrice.price, 'n'); } tmplSelectors.price = "js-input" + this.options.data.currencyCode; tmplSelectors.dateStart = "input-dateStart" + this.options.data.currencyCode; tmplSelectors.dateEnd = "input-dateEnd" + this.options.data.currencyCode; specialPrice.tmplSelectors = tmplSelectors; prices = addEmptyObjects.call(this, prices); bindDomEvents.call(this); this.render(prices, salesPrice, specialPrice); refreshData.call(this); initDateComponents.call(this, tmplSelectors); this.sandbox.emit(INITIALIZED.call(this)); }, render: function(prices, salesPrice, specialPrice) { var data = { idPrefix: constants.bulkPriceIdPrefix, currency: this.options.currency, salesPrice: salesPrice, translate: this.sandbox.translate, prices: prices, specialPrice: specialPrice }, $el = this.sandbox.util.template(BulkPriceTemplate, data); this.sandbox.dom.append(this.options.el, $el); } }; });
JavaScript
0.000015
@@ -5807,32 +5807,24 @@ nstanceName: - 'js-' + tmplSelecto @@ -5865,32 +5865,24 @@ inputId: - 'js-' + tmplSelecto @@ -6205,24 +6205,16 @@ nceName: - 'js-' + tmplSel @@ -6265,16 +6265,8 @@ tId: - 'js-' + tmp @@ -7200,24 +7200,27 @@ ateStart = %22 +js- input-dateSt @@ -7295,16 +7295,19 @@ eEnd = %22 +js- input-da
9f2eae207da4f63c674cf6684d9ae818d9678b46
Create the config page
src/client/javascript/pages/configuration.react.js
src/client/javascript/pages/configuration.react.js
const ConfigurationPage = React.createClass({ render: function () { return <div><h1>Configuration</h1></div>; } }); module.exports = ConfigurationPage;
JavaScript
0.000001
@@ -45,74 +45,1962 @@ %7B%0A -render: function () %7B%0A return %3Cdiv%3E%3Ch1%3EConfiguration%3C/h1%3E%3C/div%3E +setWidth: function (event) %7B%0A let width = event.target.value;%0A%0A this.setState(state =%3E %7B%0A return %7B%0A width: width,%0A height: state.height,%0A showConsole: state.showConsole,%0A %7D;%0A %7D);%0A %7D,%0A setHeight: function (event) %7B%0A let height = event.target.value;%0A%0A this.setState(state =%3E %7B%0A return %7B%0A width: state.width,%0A height: height,%0A showConsole: state.showConsole,%0A %7D;%0A %7D);%0A %7D,%0A getInitialState: () =%3E %7B%0A return %7B%0A width: 1500,%0A height: 900,%0A showConsole: false,%0A %7D;%0A %7D,%0A render: function () %7B%0A return (%0A %3Cdiv%3E%0A %3Ch1%3EConfiguration%3C/h1%3E%0A %3Cform%3E%0A %3Cdiv className=%22form-group row%22%3E%0A %3Clabel htmlFor=%22width%22 className=%22col-sm-4 form-control-label%22%3EWidth%3C/label%3E%0A %3Cdiv className=%22col-sm-8%22%3E%0A %3Cinput type=%22number%22 className=%22form-control%22 id=%22width%22 value=%7Bthis.state.width%7D onChange=%7Bthis.setWidth%7D /%3E%0A %3C/div%3E%0A %3C/div%3E%0A %3Cdiv className=%22form-group row%22%3E%0A %3Clabel htmlFor=%22height%22 className=%22col-sm-4 form-control-label%22%3EHeight%3C/label%3E%0A %3Cdiv className=%22col-sm-8%22%3E%0A %3Cinput type=%22number%22 className=%22form-control%22 id=%22height%22 value=%7Bthis.state.height%7D onChange=%7Bthis.setHeight%7D /%3E%0A %3C/div%3E%0A %3C/div%3E%0A %3Cdiv className=%22form-group row%22%3E%0A %3Clabel className=%22col-sm-4%22%3EConsole%3C/label%3E%0A %3Cdiv className=%22col-sm-8%22%3E%0A %3Cdiv className=%22checkbox%22%3E%0A %3Clabel%3E%0A %3Cinput type=%22checkbox%22 checked=%7Bthis.state.value%7D /%3E Show console%0A %3C/label%3E%0A %3C/div%3E%0A %3C/div%3E%0A %3C/div%3E%0A %3Cdiv className=%22form-group row%22%3E%0A %3Cdiv className=%22col-sm-offset-4 col-sm-8%22%3E%0A %3Cbutton type=%22submit%22 className=%22btn btn-primary%22 disabled%3ESave%3C/button%3E%0A %3C/div%3E%0A %3C/div%3E%0A %3C/form%3E%0A %3C/div%3E%0A ) ;%0A
55fb5fc27bf5ce299bb7c831cbe1a7e421ff7d8e
Suppress the unknown types warnings in es6_runtime.js
src/com/google/javascript/jscomp/js/es6_runtime.js
src/com/google/javascript/jscomp/js/es6_runtime.js
/* * Copyright 2014 The Closure Compiler 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. */ /** * Runtime functions required for transpilation from ES6 to ES3. * * @author mattloring@google.com (Matthew Loring) */ /** The global object. */ $jscomp.global = this; /** * Initializes Symbol.iterator, if it's not already defined. */ $jscomp.initSymbolIterator = function() { Symbol = $jscomp.global.Symbol || {}; if (!Symbol.iterator) { Symbol.iterator = '$jscomp$iterator'; } // Only need to do this once. All future calls are no-ops. $jscomp.initSymbolIterator = function() {}; }; /** * Creates an iterator for the given iterable. * * @param {string|!Array<T>|!Iterable<T>|!Iterator<T>} iterable * @return {!Iterator<T>} * @template T */ $jscomp.makeIterator = function(iterable) { $jscomp.initSymbolIterator(); if (iterable[Symbol.iterator]) { return iterable[Symbol.iterator](); } if (!(iterable instanceof Array) && typeof iterable != 'string') { throw new Error(); } var index = 0; return /** @type {!Iterator} */ ({ next: function() { if (index == iterable.length) { return { done: true }; } else { return { done: false, value: iterable[index++] }; } } }); }; /** * Transfers properties on the from object onto the to object. * * @param {!Object} to * @param {!Object} from */ $jscomp.copyProperties = function(to, from) { for (var p in from) { to[p] = from[p]; } }; /** * Inherit the prototype methods from one constructor into another. * * NOTE: This is a copy of goog.inherits moved here to remove dependency on * the closure library for Es6ToEs3 transpilation. * * Usage: * <pre> * function ParentClass(a, b) { } * ParentClass.prototype.foo = function(a) { }; * * function ChildClass(a, b, c) { * ChildClass.base(this, 'constructor', a, b); * } * $jscomp$inherits(ChildClass, ParentClass); * * var child = new ChildClass('a', 'b', 'see'); * child.foo(); // This works. * </pre> * * @param {!Function} childCtor Child class. * @param {!Function} parentCtor Parent class. */ $jscomp.inherits = function(childCtor, parentCtor) { /** @constructor */ function tempCtor() {} tempCtor.prototype = parentCtor.prototype; childCtor.prototype = new tempCtor(); /** @override */ childCtor.prototype.constructor = childCtor; };
JavaScript
0.999595
@@ -852,16 +852,50 @@ efined.%0A + * @suppress %7BreportUnknownTypes%7D%0A */%0A$jsc @@ -1316,16 +1316,50 @@ plate T%0A + * @suppress %7BreportUnknownTypes%7D%0A */%0A$jsc
aacd4cfbf00876375ff3a3560582c9f1f94ae7f2
Fix bug of using less instead of uglify
build/shared-gulpfile.js
build/shared-gulpfile.js
/** * Common build actions that can be shared between applications fairly easily. * Brings in TypeScript compilation, Jade compilation and LESS compilation. */ "use strict"; const ts = require("gulp-typescript"); const eventStream = require("event-stream"); const tslint = require("gulp-tslint"); const babel = require("gulp-babel"); const path = require("path"); const jade = require("gulp-jade"); const notify = require("gulp-notify"); const less = require("gulp-less"); const less = require("gulp-uglify"); const combiner = require("stream-combiner2"); const ngAnnotate = require('gulp-ng-annotate'); const concat = require("gulp-concat"); // Used to stop the 'watch' behavior from breaking on emited errors, errors should stop the process // in all other cases but 'watch' as 'watch' is ongoing, iterating, always on process :) let globalEmit = false; let typeScriptOptions = { typescript: require("typescript"), target: "es6", sourceMap: true, removeComments: false, declaration: true, noImplicitAny: true, module: "es2015", failOnTypeErrors: true, suppressImplicitAnyIndexErrors: true }; const createOptions = (userOptions, defaults) => { // Make copy and keep the original unaltered let options = Object.keys(defaults).map(k => defaults[k]); if (!userOptions) { return options; } // Update the newly created options with the user values Object.keys(userOptions).forEach(k => options[k] = userOptions[k]); return options; }; /** * Creates the shared gulp build tasks with shared gulp. * * @param {Object} gulp Gulp object. * @returns {Object} Gulp Object with build functions. */ const sharedGulp = (gulp) => { return { /** * Turns off emitting. Needs to be set off during watch operations. During watch operation we do not allow * the build to fail on emited errors. So blocking emits. */ globalEmitOff: () => globalEmit = false, /** * Turns on emitting. Needs to be set on during normal build actions so that the build fails on errors. */ globalEmitOn: () => globalEmit = true, /** * Creates TypeScript compilation for given sources files and outputs them into a preferred release location. * Used for frontend and backend TypeScript. * @param {String[]} sources Array of source files * @param {String} outputDirectory Location to output the JS files to. * @param {Object} options Typescript options file. Accepts common typescript flags. * @returns {Object} Gulp stream. */ createPlainTypeScriptTask: (sources, outputDirectory, options) => { const tsOptions = createOptions(options, typeScriptOptions); // Execute streams let stream = gulp .src(sources) // Pipe source to lint .pipe(tslint()) .pipe(tslint.report("verbose", { emitError: globalEmit })) // Push through to compiler .pipe(ts(tsOptions)) // Through babel (es6->es5) .pipe(babel()); if (tsOptions.angular === true) { stream = stream.pipe(ngAnnotate()); } if (tsOptions.concat === true) { stream = stream.pipe(concat("app.js")); } if (tsOptions.uglify === true) { stream = stream.pipe(uglify()); } return stream.pipe(gulp.dest(outputDirectory)); }, /** * Creates TypeScript compilation for given sources files and outputs them into a preferred release location. * Used for frontend TypeScript. Specific compilation task for Angular projects, heavily leans on * ngAnnotate and ngTemplates. * @param {String[]} sources Array of source files * @param {String} outputDirectory Location to output the JS files to. * @param {Object} options Typescript options file. Accepts common typescript flags. * @returns {Object} Gulp stream. */ createAngularTypeScriptTask: (sources, outputDirectory, options) => { options.angular = true; return this.createPlainTypeScriptTask(sources, outputDirectory, options); }, /** * Creates Jade compilation for given sources files and outputs them into a preferred release location. * @param {String[]} sources Array of source files * @param {String} outputDirectory Location to output the HTML files to. * @param {Object} options Jade options file. Accepts common jade flags. * @returns {Object} Gulp stream. */ createJadeTask: (sources, outputDirectory, options) => { const jadeOptions = createOptions(options, { pretty: true }); const j = jade(); // Depending on the global emit state we either allow the jade compiler to stop the execution on error or not, // when we are running in "watch" state we do not want it to stop as it stops the watch process if(globalEmit === false) { j.on('error', notify.onError(error => { return 'An error occurred while compiling Jade.\nLook in the console for details.\n' + error; })); } return gulp.src(sources) .pipe(j) .pipe(gulp.dest(outputDirectory)); }, /** * Creates LESS compilation for given sources files and outputs them into a preferred release location. * @param {String[]} sources Array of source files * @param {String} outputDirectory Location to output the CSS files to. * @param {Object} options Jade options file. Accepts common jade flags. * @returns {Object} Gulp stream. */ createLessTask: (sources, outputDirectory, options) => { const combined = combiner.obj([ gulp.src(sources), less(options), gulp.dest(outputDirectory) ]); if (globalEmit === false) { combined.on("error", notify.onError(error => { return 'An error occurred while compiling Less.\nLook in the console for details.\n' + error; })) } return combined; } } } module.exports = sharedGulp;
JavaScript
0
@@ -469,36 +469,38 @@ p-less%22);%0Aconst -less +uglify = require(%22gulp
f07e3dc399bcf8f053497bb6c1ed744fae4fa5d2
set up basic tests for GeneSummaryMaster
src/features/GeneSummary/GeneSummaryMaster.test.js
src/features/GeneSummary/GeneSummaryMaster.test.js
import React from "react" import { shallow } from "enzyme" import "../../setupTests" import { GeneSummaryMaster } from "./GeneSummaryMaster" describe("GeneSummary/GeneSummaryMaster", () => { // tests go here })
JavaScript
0
@@ -133,16 +133,56 @@ yMaster%22 +%0Aimport Tab from %22@material-ui/core/Tab%22 %0A%0Adescri @@ -231,24 +231,1085 @@ %7B%0A -// tests go here +const json = %7B%0A data: %7B%0A attributes: %7B%0A group: %5B%22protein%22, %22goa%22, %22orthologs%22, %22phenotypes%22, %22references%22%5D,%0A subgroup: %5B%0A %22general%22,%0A %22genomic%22,%0A %22protein%22,%0A %22goa%22,%0A %22dbxrefs%22,%0A %22summary%22,%0A %22publication%22,%0A %5D,%0A %7D,%0A %7D,%0A %7D%0A%0A const props = %7B%0A classes: %7B%0A root: %7B%7D,%0A tabs: %7B%7D,%0A tab: %7B%7D,%0A %7D,%0A match: %7B%0A params: %7B%0A id: %22id number%22,%0A %7D,%0A %7D,%0A %7D%0A const wrapper = shallow(%3CGeneSummaryMaster %7B...props%7D /%3E)%0A it(%22renders without crashing%22, () =%3E %7B%0A shallow(%3CGeneSummaryMaster %7B...props%7D /%3E)%0A %7D)%0A%0A describe(%22generateTabs method%22, () =%3E %7B%0A const generateTabs = wrapper.instance().generateTabs(json)%0A%0A it(%22should produce an array of five items%22, () =%3E %7B%0A expect(generateTabs.length).toBe(5)%0A %7D)%0A %7D)%0A%0A describe(%22generatePanels method%22, () =%3E %7B%0A const generatePanels = wrapper.instance().generatePanels(json)%0A%0A it(%22should produce an array of seven items%22, () =%3E %7B%0A expect(generatePanels.length).toBe(7)%0A %7D)%0A %7D) %0A%7D)%0A
b0e4e45e7bb953eb860f456ca3a41d55629756cb
Fix notification popup menu item CSS
src/foam/nanos/notification/NotificationRowView.js
src/foam/nanos/notification/NotificationRowView.js
/** *@license *Copyright 2018 The FOAM Authors. All Rights Reserved. *http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.nanos.notification', name: 'NotificationRowView', extends: 'foam.u2.View', requires: [ 'foam.nanos.auth.User', 'foam.nanos.notification.NotificationView', 'foam.u2.PopupView' ], imports: [ 'invoiceDAO', 'notificationDAO', 'stack', 'user', 'userDAO' ], exports: [ 'as data' ], css: ` ^ i { margin-top: 5px; } ^ .popUpDropDown { padding: 0 !important; z-index: 1000; width: 165px; background: white; opacity: 1; box-shadow: 2px 2px 2px 2px rgba(0, 0, 0, 0.19); } ^ .net-nanopay-ui-ActionView-optionsDropDown { width: 26px !important; height: 26px !important; border: none !important; background-color: rgba(164, 179, 184, 0.0); float: right; margin-right:20px !important; margin-top:20px !important; } ^ .net-nanopay-ui-ActionView-optionsDropDown > img { height:23px; } ^ .dot{ height: 500px; width: 500px; border-radius: 50%; color:black; } ^ .net-nanopay-ui-ActionView-optionsDropDown:hover { background-color: rgba(164, 179, 184, 0.3); } ^ .popUpDropDown > div { width: 165px; height: 20px; font-size: 14px; font-weight: 300; letter-spacing: 0.2px; color: #093649; line-height: 30px; } ^ .popUpDropDown > div:hover { background-color: #59a5d5; color: white; cursor: pointer; } ^ .net-nanopay-ui-ActionView { background-color: rgba(201, 76, 76, 0.0); width: 135px; height: 40px; border-radius: 2px; border: solid 1px #59a5d5; margin-left:20px; margin-top:10px; } ^ .net-nanopay-ui-ActionView > span { height: 40px; font-family: Roboto; font-size: 14px; font-weight: 300; line-height: 2.86; letter-spacing: 0.2px; text-align: center; color: #59a5d5; } ^ .net-nanopay-ui-ActionView-popup { background-color: rgba(201, 76, 76, 0.0); width: 135px; height: 40px; border-radius: 2px; border: solid 1px #59a5d5; margin-bottom:20px; margin-left:20px; margin-top:10px; } ^ .net-nanopay-ui-ActionView-popup > span { height: 40px; font-family: Roboto; font-size: 14px; font-weight: 300; line-height: 2.86; letter-spacing: 0.2px; text-align: center; color: #59a5d5; } ^ div { padding-bottom:20px; } ^ .msg { font-size: 12px; word-wrap: break-word; padding-bottom: 0; padding-top: 20; line-height: 1.4; padding-left: 20px; width: 414px; -webkit-line-clamp: 4; -webkit-box-orient: vertical; display: -webkit-box; text-overflow: ellipsis; margin-right: 10; overflow: hidden; color: #093649; } ^ .msg.fully-visible { display: block; } `, properties: [ 'of', 'optionsBtn_', 'optionPopup_' ], methods: [ function initE() { this .on('mouseover', this.read) .addClass(this.myClass()); this.tag(this.OPTIONS_DROP_DOWN, { icon: 'images/ic-options.png', showLabel: true }, this.optionsBtn_$); this.add(this.NotificationView.create({ of: this.data.cls_, data: this.data })); } ], actions: [ { name: 'optionsDropDown', label: '', code: function(X) { var self = this; self.optionPopup_ = this.PopupView.create({ width: 165, x: -137, y: 40 }); self.optionPopup_.addClass('popUpDropDown') .start('div').add('Remove') .on('click', this.removeNotification) .end() .callIf(this.data.notificationType !== 'General', function() { this.start('div') .add('Not show like this') .on('click', self.hideNotificationType) .end(); }) .start('div') .add('Mark as Unread') .on('click', this.markUnread) .end(); self.optionsBtn_.add(self.optionPopup_); } }, ], listeners: [ function removeNotification() { this.notificationDAO.remove(this.data); }, function hideNotificationType() { this.user = this.user.clone(); this.user.disabledTopics.push(this.data.notificationType); this.userDAO.put(this.user); this.stack.push({ class: 'foam.nanos.notification.NotificationListView' }); }, function read() { if ( ! this.data.read ) { this.data.read = true; this.notificationDAO.put(this.data); } }, function markUnread() { if ( this.data.read ) { this.data.read = false; this.notificationDAO.put(this.data); } this.stack.push({ class: 'foam.nanos.notification.NotificationListView' }); } ] });
JavaScript
0.000007
@@ -1476,30 +1476,8 @@ px;%0A - height: 20px;%0A @@ -1590,25 +1590,23 @@ -line-height: 3 +padding: 1 0px + 0 ;%0A
41499aeb8e0f5b478b1d762c978169d3852b8d7b
Update calculateValueDistance utility
src/js/utils/NumberUtils/calculateValueDistance.js
src/js/utils/NumberUtils/calculateValueDistance.js
/** @module utils/NumberUtils/calculateValueDistance */ /** * This calculates the distance from a screen x location to a position in some element * by comparing the width of the element and the element's page position to the screen * x position. * * If the distance is not _normalized_ the distance will be updated to be a percentage * of the element's total width. * * @param {Number} x - the screen x location. * @param {Number} width - the element's width * @param {Number} left - the element's page x position. * @param {Boolean} normalize - boolean if the distance should be a percentage. * * @return {Number} the distance from the element's left position to the page x * location. */ function calculateDistance(x, width, left, normalize) { const distance = Math.min( width, Math.max(0, x - left) ); return normalize ? distance : distance / width * 100; } /** * This calculates the new value and distance for a slider. It will compare the page x * location of a touch or mouse event to the slider's track page x position. If the * final value and distance should be _normalized_, they will be updated to be rounded * with the scale and steps in mind. * * The distance will always be contained within a percentage of 0 - 100 while the * value will be contained within the min and max values. * * @param {Number} x - the page x location of the touch or mouse event. * @param {Number} width - the slider's width * @param {Number} left - the slider's left position in the page. * @param {Number} scale - the total number values included in the slider. * @param {Number} step - the amount to increment by. * @param {Number} min - the min value for the slider. * @param {Number} max - the max value for the slider. * @param {Boolean} normalize - boolean if the vaue and distance should be _normalized_. * * @return {Object} an object with the value and distance. */ export default function calculateValueDistance(x, width, left, scale, step, min, max, normalize) { let value; let distance = calculateDistance(x, width, left, normalize); if (normalize) { value = Math.round(distance / (width / scale)); if (step < 1) { const decimals = String(step).split('.')[1]; const corrector = typeof decimals !== 'undefined' && decimals.length > 0 ? Math.pow(10, decimals.length) : 1; const modded = (value * corrector) % (step * corrector); if (modded !== 0 && modded >= step / 2) { value += (step - modded); } else if (modded !== 0) { value -= modded; } } distance = value / scale * 100; value += min; } else { value = min + Math.round(distance / 100 * scale); } if (step > 1) { value *= step; } else if (step > 0 && step < 1) { value *= step; } return { distance: Math.max(0, Math.min(100, distance)), value: Math.max(min, Math.min(max, value)), }; }
JavaScript
0
@@ -2626,18 +2626,34 @@ value -+ = + (value * step) + min;%0A @@ -2678,16 +2678,23 @@ = min + + step * Math.ro @@ -2731,106 +2731,8 @@ %7D%0A%0A - if (step %3E 1) %7B%0A value *= step;%0A %7D else if (step %3E 0 && step %3C 1) %7B%0A value *= step;%0A %7D%0A%0A re
c330186d8b08b65c7cc435f5c8f61e32b1ccfc06
Fix zooming
OverviewViewManager.js
OverviewViewManager.js
// ------------------------------------------------------------------------ /* * Copyright (c) 2014 Thomas Valera. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ /* * OverviewViewManager * * Defines the manager for the overview view. * This manager handles the display of the view. * * * Events fired: * OverviewAttached * ZoomApplied * OverviewVisible * OverviewHidden */ // ------------------------------------------------------------------------ /*global define, brackets, Mustache, $ */ /*jslint nomen: true, vars: true */ define(function (require, exports, module) { 'use strict'; var SimpleSlider = require("plugins/simple-slider.min"), _unrenderedOverview = require("text!htmlContent/overview.html"), _unrenderedToolbarIcon = require("text!htmlContent/toolbar.html"), masterLineHeight = null, masterFontSize = null, _renderedOverview = null, _renderedToolbarIcon = null, slider = null, zoom = 0.5; // ------------------------------------------------------------------------ /* * HELPER FUNCTIONS */ // ------------------------------------------------------------------------ /* * Triggers the given event */ function _triggerEvent(event, data) { $(exports).triggerHandler(event, data); } /* * Returns the overview */ function getOverview() { return $("#code-overview-wrapper"); } /* * Returns the toolbar icon */ function _getToolbarIcon() { return $("#code-overview-icon"); } // ------------------------------------------------------------------------ /* * RENDER FUNCTIONS */ // ------------------------------------------------------------------------ /* * Returns a rendered toolbar view */ function _renderToolbarIcon() { var view = $(Mustache.render(_unrenderedToolbarIcon)); return view; } /* * Returns a rendered overview view */ function _renderOverview() { var view = $(Mustache.render(_unrenderedOverview)); return view; } /* * Sets the zoom */ function _applyZoom() { // Get overview var overview = getOverview(); // Get overview content var content = overview.find("#code-overview-content"); // Get Overview's CodeMirror wrapper var CMWrapper = content.find(".CodeMirror").first(); if (CMWrapper.length > 0) { // If first time zooming, use this chance to get the original values if (masterFontSize === null || masterLineHeight === null) { masterFontSize = CMWrapper.css("font-size").replace("px", ""); masterLineHeight = CMWrapper.css("line-height").replace("px", ""); } // Apply zoom and add px to make usable string var newFontSize = masterFontSize * zoom + "px", newLineHeight = masterLineHeight * zoom + "px"; // Set properties to overview's CodeMirror CMWrapper.get(0).style.setProperty("font-size", newFontSize, "!important"); CMWrapper.get(0).style.setProperty("line-height", newLineHeight, "!important"); _triggerEvent("ZoomApplied", {}); } } // ------------------------------------------------------------------------ /* * LISTENERS FUNCTIONS */ // ------------------------------------------------------------------------ /* * Sets the listeners for the slider */ function _setSliderListeners() { // Get overview var overview = getOverview(); // Get slider slider = overview.find("#code-overview-slider"); // Initialize slider slider.simpleSlider(); // Bind on change slider.bind("slider:changed", function (event, data) { zoom = data.ratio; _applyZoom(); }); } /* * Sets the listeners for the toolbar icon */ function _setToolbarIconListeners() { // On click on icon $("#code-overview-icon").click(function () { // Get overview and icon var overview = getOverview(), icon = _getToolbarIcon(); if (overview !== null) { // If visible, hide if (overview.is(":visible")) { overview.hide(); _triggerEvent("OverviewHidden", {}); } else if (icon.hasClass("enabled")) { // Else if hidden and enabled // Show overview and reload editors // NOTE: The order is important as the editor will // only attach itself to a visible overview. overview.show(); _triggerEvent("OverviewVisible", {}); // Set default zoom slider.simpleSlider("setRatio", zoom); } } }); } // ------------------------------------------------------------------------ /* * DISPLAY FUNCTIONS */ // ------------------------------------------------------------------------ /* * Attaches the overview */ function _attachOverview() { // Append overview to editor holder $("#editor-holder").append(_renderedOverview); // Set width to overview getOverview().css("width", 200); // Get width of main view var mainWidth = $(".main-view").first().width(); // Set width to overview's content // This will allow an overflow of the text instead of breaking // it and making spurious lines in the overview $("#code-overview-content").css("width", mainWidth); // Set listeners _setSliderListeners(); // Listeners for the overview are really only the click listener. // This is done in the OverviewManager by listening to the editor's events // Trigger event _triggerEvent("OverviewAttached", {}); } /* * Attaches the toolbar icon */ function _attachToolbarIcon() { // Add toolbar after live icon $("#main-toolbar").find("#toolbar-go-live").after(_renderedToolbarIcon); // Set listeners _setToolbarIconListeners(); } // ------------------------------------------------------------------------ /* * API FUNCTIONS */ // ------------------------------------------------------------------------ /* * Enables the overview */ function enable() { // Get icon var icon = _getToolbarIcon(); // If disabled, enable if (icon.hasClass("disabled")) { icon.removeClass("disabled"); icon.addClass("enabled"); } _applyZoom(); } /* * Disables the overview. * Hides it if necessary */ function disable() { // Get icon var icon = _getToolbarIcon(); // If enabled, disable if (icon.hasClass("enabled")) { icon.removeClass("enabled"); icon.addClass("disabled"); // Get overview var overview = getOverview(); if (overview !== null) { // If visible, hide if (overview.is(":visible")) { overview.hide(); } } } } /* * Initializes the view manager. */ function init() { // Render views _renderedOverview = _renderOverview(); _renderedToolbarIcon = _renderToolbarIcon(); // Display views _attachToolbarIcon(); _attachOverview(); } // API exports.init = init; exports.enable = enable; exports.disable = disable; exports.getOverview = getOverview; });
JavaScript
0.000327
@@ -3818,16 +3818,136 @@ first(); +%0A%0A // Get overview's CodeMirror-scroll wrapper%0A var CMScroll = content.find(%22.CodeMirror-scroll%22).first(); %0A @@ -4576,16 +4576,23 @@ deMirror +-scroll %0A @@ -4602,40 +4602,18 @@ CM -Wrapper.get(0).style.setProperty +Scroll.css (%22fo @@ -4668,40 +4668,18 @@ CM -Wrapper.get(0).style.setProperty +Scroll.css (%22li
a58e7c8df0373b3b0ee0891a6733728dee04d305
Refactor getRolePermissions to take property parameter
src/views/Main/Schemas/Components/AllPermissions.js
src/views/Main/Schemas/Components/AllPermissions.js
import React, { PropTypes } from 'react'; import { PermissionsApi, PrincipalsApi } from 'loom-data'; import { Permission } from '../../../../core/permissions/Permission'; import ActionConsts from '../../../../utils/Consts/ActionConsts'; import { ROLE, AUTHENTICATED_USER } from '../../../../utils/Consts/UserRoleConsts'; import UserPermissionsTable from './UserPermissionsTable'; import RolePermissionsTable from './RolePermissionsTable'; import Page from '../../../../components/page/Page'; import { connect } from 'react-redux'; import styles from '../styles.module.css'; const views = { GLOBAL: 0, ROLES: 1, EMAILS: 2 }; const accessOptions = { Hidden: 'Hidden', Discover: 'Discover', Link: 'Link', Read: 'Read', Write: 'Write', Owner: 'Owner' }; const permissionOptions = { Discover: 'Discover', Link: 'Link', Read: 'Read', Write: 'Write', Owner: 'Owner' }; const U_HEADERS = ['Users', 'Roles', 'Permissions']; const USERS = [{ id: 0, email: 'corwin@thedataloom.com', role: '(all)', permissions: 'Read, Write, Discover, Link', expand: [{ role: 'admin', permissions: 'Read, Write, Discover, Link' }, { role: 'xyz', permissions: 'Read, Write' }] }, { id: 1, email: 'matthew@thedataloom.com', role: '(all)', permissions: ['read', 'write'], expand: [{ role: 'role', permissions: ['read', 'write', 'discover', 'link'] }] }, { id: 2, email: 'katherine@thedataloom.com', role: '(all)', permissions: ['read'], expand: [{ role: 'role', permissions: ['read', 'write', 'discover', 'link'] }] }]; const R_HEADERS = ['Roles', 'Permissions']; class AllPermissions extends React.Component { constructor(props) { super(props); this.state = { entityUserPermissions: [], entityRolePermissions: [] }; this.getUserPermissions = this.getUserPermissions.bind(this); } componentDidMount() { // console.log('CDM properties? ', this.props.properties); } componentWillReceiveProps(nextProps) { const { properties } = this.props; console.log('PROPS!:', nextProps); this.getUserPermissions(); this.getRolePermissions(); // console.log('props properties:'); Object.keys(properties).forEach((property) => { this.getUserPermissions(properties[property]); this.getRolePermissions(properties[property]); }) } getUserPermissions = (property) => { const { userAcls, roleAcls } = property ? property : this.props; const { allUsersById } = this.props; const userPermissions = []; console.log('userAcls, roleAcls, allUsersById:', userAcls, roleAcls, allUsersById); // For each user, add their permissions Object.keys(allUsersById).forEach((userId) => { if (userId && allUsersById[userId]) { const user = { id: userId, email: allUsersById[userId].email, roles: [], permissions: [], expand: [] // set of {role, permissions} }; // Add individual permissions Object.keys(userAcls).forEach((permissionKey) => { if (userAcls[permissionKey].indexOf(userId) !== -1) { user.permissions.push(permissionKey); } }); if (allUsersById[userId].roles.length > 0) { Object.keys(roleAcls).forEach((permissionKey) => { allUsersById[userId].roles.forEach((role) => { if (roleAcls[permissionKey].indexOf(role) !== -1 && user.permissions.indexOf(permissionKey) === -1) { user.permissions.push(permissionKey); } }); }); } userPermissions.push(user); } }); this.setEntityUserPermissions(userPermissions, property); } setEntityUserPermissions = (permissions, property) => { const formattedPermissions = permissions.slice(); // Format permissions for table formattedPermissions.forEach((permission) => { if (permission) { if (permission.permissions.length === 0) { permission.permissions = '-'; } else { permission.permissions = permission.permissions.join(', '); } } }); // property ? this.setState( {${property.title}: formattedPermissions} ) : this.setState( { entityUserPermissions: formattedPermissions } ); property ? this.setState({ testProperty: formattedPermissions }) : this.setState({ entityUserPermissions: formattedPermissions }); } getRolePermissions = (set) => { const { roleAcls } = this.props; const rolePermissions = {}; // Get all roles and their respective permissions Object.keys(roleAcls).forEach((permission) => { roleAcls[permission].forEach((role) => { if (!rolePermissions.hasOwnProperty(role)) { rolePermissions[role] = []; } if (rolePermissions[role].indexOf(permission) === -1) { rolePermissions[role].push(permission); } }); }); this.setRolePermissions(rolePermissions); } setRolePermissions = (permissions) => { const formattedPermissions = {}; // Format data for table Object.keys(permissions).forEach((permission) => { formattedPermissions[permission] = permissions[permission].join(', '); }); this.setState({ entityRolePermissions: formattedPermissions }); } render() { return ( <Page> <Page.Header> <Page.Title>All Permissions</Page.Title> </Page.Header> <Page.Body> <h3>Entity Permissions</h3> <UserPermissionsTable users={this.state.entityUserPermissions} headers={U_HEADERS} /> <RolePermissionsTable roles={this.state.entityRolePermissions} headers={R_HEADERS} /> <h3>Property A Permissions</h3> <UserPermissionsTable users={this.state.entityUserPermissions} headers={U_HEADERS} /> <RolePermissionsTable roles={this.state.entityRolePermissions} headers={R_HEADERS} /> </Page.Body> </Page> ); } } function mapStateToProps(state) { const entitySetDetail = state.get('entitySetDetail'); return { allUsersById: entitySetDetail.get('allUsersById').toJS(), properties: entitySetDetail.get('properties').toJS(), userAcls: entitySetDetail.get('userAcls').toJS(), roleAcls: entitySetDetail.get('roleAcls').toJS() }; } function mapDispatchToProps(dispatch, ownProps) { return { }; } export default connect(mapStateToProps, mapDispatchToProps)(AllPermissions);
JavaScript
0
@@ -4473,19 +4473,24 @@ ions = ( -set +property ) =%3E %7B%0A @@ -4509,34 +4509,123 @@ oleAcls %7D = -this.props +property ? property : this.props;%0A property ? console.log('WE GOTTA PROPERTY:', property) : null ;%0A const @@ -5088,16 +5088,26 @@ missions +, property );%0A %7D%0A%0A @@ -5141,16 +5141,26 @@ missions +, property ) =%3E %7B%0A @@ -5361,32 +5361,213 @@ ');%0A %7D);%0A%0A + // TODO: SET unique name for each property%0A property ? this.setState(%7B testPropertyRolePermissions: formattedPermissions %7D, () =%3E %7Bconsole.log('PROP ROLES SET:', this.state)%7D) : this.setState(%7B
e9ef1415c755b8fe141f557c108b4a880c32ba9e
Update Example to support the new library version
Example/App.js
Example/App.js
/** * @flow */ import { Image, StyleSheet, Text, TouchableWithoutFeedback, View, } from 'react-native'; import React, { Component } from 'react'; import ImageCarousel from 'react-native-image-carousel'; const urls = [ 'https://d919ce141ef35c47fc40-b9166a60eccf0f83d2d9c63fa65b9129.ssl.cf5.rackcdn.com/images/66807.max-620x600.jpg', 'https://d919ce141ef35c47fc40-b9166a60eccf0f83d2d9c63fa65b9129.ssl.cf5.rackcdn.com/images/67003.max-620x600.jpg', 'https://d919ce141ef35c47fc40-b9166a60eccf0f83d2d9c63fa65b9129.ssl.cf5.rackcdn.com/images/51681.max-620x600.jpg', 'https://d919ce141ef35c47fc40-b9166a60eccf0f83d2d9c63fa65b9129.ssl.cf5.rackcdn.com/images/66812.max-620x600.jpg', 'https://myanimelist.cdn-dena.com/s/common/uploaded_files/1438960604-925d1997518b66f8508c749f36810793.jpeg', ]; export default class App extends Component<any, any, any> { _imageCarousel: ImageCarousel; componentWillMount() { (this: any)._renderHeader = this._renderHeader.bind(this); } _renderHeader(): ReactElement<any> { return ( <TouchableWithoutFeedback onPress={this._imageCarousel.close}> <View> <Text style={styles.closeText}>Exit</Text> </View> </TouchableWithoutFeedback> ); } _renderFooter(): ReactElement<any> { return ( <Text style={styles.footerText}>Footer!</Text> ); } _renderContent(idx: number): ReactElement<any> { return ( <Image style={styles.container} source={{ uri: urls[idx] }} resizeMode={'contain'} /> ); } render(): ReactElement<any> { return ( <View style={styles.container}> <ImageCarousel ref={(imageCarousel: ImageCarousel) => { this._imageCarousel = imageCarousel; }} renderContent={this._renderContent} renderHeader={this._renderHeader} renderFooter={this._renderFooter} > {urls.map((url: string): ReactElement<any> => ( <Image key={url} style={styles.image} source={{ uri: url, height: 100 }} resizeMode={'contain'} /> ))} </ImageCarousel> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, closeText: { color: 'white', textAlign: 'right', padding: 10, }, footerText: { color: 'white', textAlign: 'center', }, image: { marginRight: 2, width: 100, height: 100, }, });
JavaScript
0
@@ -1363,206 +1363,8 @@ %7D%0A%0A - _renderContent(idx: number): ReactElement%3Cany%3E %7B%0A return (%0A %3CImage%0A style=%7Bstyles.container%7D%0A source=%7B%7B uri: urls%5Bidx%5D %7D%7D%0A resizeMode=%7B'contain'%7D%0A /%3E%0A );%0A %7D%0A%0A re @@ -1383,32 +1383,32 @@ tElement%3Cany%3E %7B%0A + return (%0A @@ -1592,42 +1592,43 @@ -renderContent=%7Bthis._renderContent +activeProps=%7B%7B style: %7B flex: 1 %7D %7D %7D%0A @@ -1841,24 +1841,25 @@ style=%7B +%5B styles.image @@ -1858,16 +1858,35 @@ es.image +, %7B opacity: 0.2 %7D%5D %7D%0A
667333c011d75464277a638560b2fb4a1a329cbb
Change comment style so not to end up in docs
src/bin/plugin-manager/plugin-manager.js
src/bin/plugin-manager/plugin-manager.js
const fs = require('fs') const path = require('path'); const winston = require('winston') const Promise = require('bluebird') const db = require('../../models') var messageManager = require('../message-manager/message-manager') const voluble_errors = require('../voluble-errors') const errs = require('common-errors') /** * The PluginManager keeps track of all loaded plugins, as well as initializing, loading and shutting down all detected plugins. * It also handles all plugin- and service-related operations. */ var PluginManager = { plugin_dir: "", loaded_plugins: [], /** * Find a loaded plugin object by it's ID number and return it. * @param {Number} id The ID number of the plugin to find * @returns {promise} A promise resolving to the loaded plugin object * @throws {errs.NotFoundError} Thrown when plugin with specified ID does not exist. */ getPluginById: function (id) { let p = null PluginManager.loaded_plugins.forEach(function (plugin) { if (plugin[0] == id) { p = plugin[1] } }) if (!p){ return Promise.reject(new errs.NotFoundError("Plugin with ID " + id + " does not exist.")) //return Promise.reject(Error("Plugin with ID " + id + " does not exist.")) } else { return Promise.resolve(p) } }, /** * Iterates over the `PluginManager.plugin_dir` directory and looks for available plugins. If any are found, attempt to load them. * If successfully loaded, attempt to initialize them. If successfully initialized, add them to the list of loaded plugins. */ loadAllPlugins: function () { // Cycle through plugin directory and try to init all available plugins /** * Logic - the plugin's directory is something we should be able to identify it by. * SO: We should loop through all of the directories under the plugin directory and see if a plugin exists in the database with that directory. * If so, update it's status to not initialized. Otherwise, create it as not initialized. * The point of this is so that when plugins are added, they aren't removed and re-added on startup, which could likely lead to a change in ID number in the database when a new plugin is added or an existing one removed. */ // Get a list of all of the directories under the plugin directory let plugin_subdirs = fs.readdirSync(PluginManager.plugin_dir).filter(function (element) { let plugin_subdir_fullpath = path.join(PluginManager.plugin_dir, element) if (fs.statSync(plugin_subdir_fullpath).isDirectory()) { return true } else { return false } }) winston.debug("Found plugins at:\n\t" + plugin_subdirs) // Loop through each directory and try to init a plugin if there is one plugin_subdirs.forEach(function (plugin_subdir_rel) { let plugin_file_abs = path.join(PluginManager.plugin_dir, plugin_subdir_rel, "plugin.js") if (fs.existsSync(plugin_file_abs)) { try { let plug_obj = require(plugin_file_abs)() winston.info("Loaded plugin:\n\t" + plug_obj.name) // We've found the plugin file, so now let's update the database to match. db.sequelize.model("Plugin").findOne({ where: { 'directory_name': plugin_subdir_rel } }).then(function (row) { if (!row) { // This plugin doesn't exist in the database, so let's add an entry for it return db.sequelize.model('Plugin').create({ 'name': plug_obj.name, 'directory_name': plugin_subdir_rel, 'initialized': false }) } else { // This plugin does exist, but let's make sure that Voluble doesn't think it's ready yet row.initialized = false return row.save() } }) // So now that the plugin exists in the database, let's try and make it work .then(function (service) { if (plug_obj.init()) { PluginManager.loaded_plugins.push([service.id, plug_obj]) console.log("Inited plugin " + service.id + ": " + plug_obj.name) service.initialized = true // Add a listener for the message-state-update event, so messageManager can handle it plug_obj._eventEmitter.on('message-state-update', function(msg, message_state){ messageManager.updateMessageStateAndContinue(msg, message_state, service) }) return service.save() } else { throw new voluble_errors.PluginInitFailedError("Failed to init " + plug_obj.name) } }) .catch(voluble_errors.PluginInitFailedError, function (err) { winston.error(err.message) }) } catch (err) { winston.error("Failed to load plugin: " + plugin_file_abs + "\nMessage: " + err.message) } } else { winston.info("No plugin in\n\t" + path.join(PluginManager.plugin_dir, plugin_subdir_rel)) } }) }, /** * Set the plugin directory and load all of the plugins in it. * @param {string} plugin_dir The path to the directory containing the plugins that Voluble should use. */ initAllPlugins: function (plugin_dir) { winston.debug("Attempting to load plugins") this.plugin_dir = path.resolve(plugin_dir || path.join(__dirname, "../plugins")) winston.info("Loading plugins from\n\t"+ this.plugin_dir) this.loadAllPlugins() }, /** * For each loaded plugin, call it's `shutdown()` function. */ shutdownAllPlugins: function () { db.sequelize.model('Plugin').findAll({ where: { initialized: true } }) .then(function (rows) { Promise.map(rows, function (row) { let plugin = PluginManager.getPluginById(row.id) plugin.shutdown() let index = PluginManager.loaded_plugins.indexOf(plugin) if (index > -1) { PluginManager.loaded_plugins.splice(index, 1) } plugin._eventEmitter.removeAllListeners('message-state-update') row.initialized = false return row.save() }) }) .catch(function (err) { winston.error(err.message) }) }, /** * Gets the list of services from the DB with their status. * @returns {array <Sequelize.Plugin>} An array of Sequelize rows representing loaded services. */ getAllServices: function () { return db.sequelize.model('Plugin').findAll() }, /** * Gets a single service from the DB by its' ID. * @param {Number} id The ID of the service to find. * @returns {Sequelize.Plugin} The row representing the plugin with a given ID. */ getServiceById: function (id) { return db.sequelize.model('Plugin').findOne({ where: { id: id } }) // TODO: Validate plugin exists, fail otherwise } } module.exports = PluginManager
JavaScript
0
@@ -1789,21 +1789,9 @@ / -**%0A * +/ Log @@ -1876,18 +1876,18 @@ - * +// SO: We @@ -2024,26 +2024,26 @@ ry.%0A - -* +// If so, upda @@ -2126,18 +2126,18 @@ - * +// The poi @@ -2226,16 +2226,27 @@ startup, +%0A // which c @@ -2361,20 +2361,8 @@ ved. -%0A */ %0A%0A
7b115acc0836808099387428877d76314b32cdf6
Support arbitrary ICU number formats using a quick port of git://github.com/owiber/numberformat.js.git
lib/CldrRbnfRuleSet.js
lib/CldrRbnfRuleSet.js
var _ = require('underscore'); function CldrRbnfRuleSet(config) { _.extend(this, config); this.ruleByValue = {}; } CldrRbnfRuleSet.getSafeRendererName = function (rendererName) { return ( ("render-" + rendererName) .replace(/[^\w-]/g, '-') .replace(/[-_]+([0-9a-z])/gi, function ($0, ch) { return ch.toUpperCase(); }) .replace('GREEKNUMERALMAJUSCULES', 'GreekNumeralMajuscules') ); }; CldrRbnfRuleSet.prototype = { toFunctionAst: function () { var that = this, isSeenByRuleSetType = {}; function ruleToExpressionAst(rule) { var expressionAsts = []; rule.rbnf.replace(/(?:([\<\>\=])(?:(%%?[\w\-]+)|([#,0.]+))?\1)|(?:\[([^\]]+)\])|([\x7f-\uffff:'\.\s\w\d\-]+)/gi, function ($0, specialChar, otherFormat, decimalFormat, optional, literal) { // The meanings of the substitution token characters are as follows: if (specialChar) { var expr; if (specialChar === '<') { // << if (/^\d+$/.test(rule.value)) { // In normal rule: Divide the number by the rule's divisor and format the quotient expr = ['call', ['dot', ['name', 'Math'], 'floor'], [['binary', '/', ['name', 'n'], ['num', parseInt(rule.value, 10)]]]]; } else if (rule.value === '-x') { throw new Error('<< not allowed in negative number rule'); } else { // In fraction or master rule: Isolate the number's integral part and format it. expr = ['call', ['dot', ['name', 'Math'], 'floor'], [['name', 'n']]]; } } else if (specialChar === '>') { // >> if (/\./.test(rule.value)) { // Fraction or master rule => parseInt(String(n).replace(/\d*\./, ''), 10) expr = ['call', ['name', 'parseInt'], [['call', ['dot', ['call', ['name', 'String'], [['name', 'n']]], 'replace'], [['regexp', '\\d*\\.', ''], ['string', '']]], ['num', 10]]]; } else if (rule.value === '-x') { expr = ['unary-prefix', '-', ['name', 'n']]; } else { expr = ['binary', '%', ['name', 'n'], ['num', parseInt(rule.value, 10)]]; } } else if (specialChar === '=') { // == expr = ['name', 'n']; } // FIXME: >>> not supported // The substitution descriptor (i.e., the text between the token characters) may take one of three forms: if (otherFormat) { // A rule set name: // Perform the mathematical operation on the number, and format the result using the named rule set. var otherFormatName = CldrRbnfRuleSet.getSafeRendererName(otherFormat); isSeenByRuleSetType[otherFormatName] = true; // Turn into this.<otherFormatName>(<expr>) expressionAsts.push(['call', ['dot', ['name', 'this'], otherFormatName], [expr]]); } else if (decimalFormat) { // A DecimalFormat pattern: // Perform the mathematical operation on the number, and format the result using a DecimalFormat // with the specified pattern. The pattern must begin with 0 or #. // FIXME: This is very broken. Requires support for rendering arbitrary number formats: expressionAsts.push(['call', ['dot', ['name', 'this'], 'renderNumber'], [expr]]); } else { // Nothing: if (specialChar === '>') { // If you omit the substitution descriptor in a >> substitution in a fraction rule, format the result one digit at a time using the rule set containing the current rule. expressionAsts.push(['call', ['dot', ['name', 'this'], that.type], [expr]]); } else if (specialChar === '<') { // If you omit the substitution descriptor in a << substitution in a rule in a fraction rule set, format the result using the default rule set for this renderer. // FIXME: Should be the default rule set for this renderer! expressionAsts.push(['call', ['dot', ['name', 'this'], that.type], [expr]]); } else { throw new Error('== not supported!'); } } } else if (optional) { // [ ... ] var optionalRuleExpressionAst = ruleToExpressionAst({radix: rule.radix, rbnf: optional, value: rule.value}); expressionAsts.push(['conditional', ['binary', '===', ['name', 'n'], ['num', parseInt(rule.value, 10)]], ['string', ''], optionalRuleExpressionAst]); } else if (literal) { expressionAsts.push(['string', literal]); } else { throw new Error("Unknown token in " + rule.rbnf); } }); if (expressionAsts.length === 0) { throw new Error('CldrRbnfRuleSet: Could not parse ' + rule.rbnf); } var expressionAst = expressionAsts.shift(); while (expressionAsts.length > 0) { expressionAst = ['binary', '+', expressionAst, expressionAsts.shift()]; } return expressionAst; } function conditionToStatementAst(conditionAst, rule) { return ['if', conditionAst, ['return', ruleToExpressionAst(rule)], null]; } var statementAsts = []; if (this.ruleByValue['x.0'] || this.ruleByValue['x.x']) { // var isFractional = n !== Math.floor(n); statementAsts.push(['var', [['isFractional', ['binary', '!==', ['name', 'n'], ['call', ['dot', ['name', 'Math'], 'floor'], [['name', 'n']]]]]]]); } if (this.ruleByValue['x.0']) { statementAsts.push(conditionToStatementAst(['name', 'isFractional'], this.ruleByValue['x.0'])); } if (this.ruleByValue['-x']) { statementAsts.push(conditionToStatementAst(['binary', '<', ['name', 'n'], ['num', 0]], this.ruleByValue['-x'])); } if (this.ruleByValue['x.x']) { statementAsts.push(conditionToStatementAst(['binary', '&&', ['name', 'isFractional'], ['binary', '>', ['name', 'n'], ['num', 1]]], this.ruleByValue['x.x'])); } if (this.ruleByValue['0.x']) { statementAsts.push(conditionToStatementAst(['binary', '&&', ['binary', '>', ['name', 'n'], ['num', 0]], ['binary', '<', ['name', 'n'], ['num', 1]]], this.ruleByValue['0.x'])); } Object.keys(this.ruleByValue).filter(function (value) { return /^\d+$/.test(value); }).map(function (value) { return parseInt(value, 10); }).sort(function (a, b) { return b - a; }).forEach(function (numericalValue) { statementAsts.push(conditionToStatementAst(['binary', '>=', ['name', 'n'], ['num', numericalValue]], this.ruleByValue[numericalValue])); }, this); return {functionAst: ['function', null, ['n'], statementAsts], dependencies: Object.keys(isSeenByRuleSetType)}; } }; module.exports = CldrRbnfRuleSet;
JavaScript
0.000001
@@ -3670,120 +3670,8 @@ #.%0A - // FIXME: This is very broken. Requires support for rendering arbitrary number formats:%0A @@ -3759,32 +3759,59 @@ rNumber'%5D, %5Bexpr +, %5B'string', decimalFormat%5D %5D%5D);%0A
fb0271d68690b20e6bf68f6d723da50fd9c875ea
add stat_game_type prop
lib/CorneliusAction.js
lib/CorneliusAction.js
const EventEmitter = require('events').EventEmitter; const MlbRequest = require('./MlbRequest'); /** * Represents some Cornelius action. */ class CorneliusAction extends EventEmitter { /** * Create an action. * @param {string} action * @param {object} options */ constructor(action, options) { super(); this.action = action; this.options = { query: (() => { if (options.hasOwnProperty('query') && typeof options.query === 'string') { return options.query; } else { return ''; } })(), active: (() => { if (options.hasOwnProperty('active') && typeof options.active === 'boolean') { return options.active; } else { return true; } })(), id: (() => { if (options.id && Array.isArray(options.id)) { return options.id.toString(); } else if (options.id && typeof options.id === 'string') { return options.id; } else { return ''; } })(), stat_type: (() => { if (options.hasOwnProperty('type') && typeof options.type === 'string') { return options.type.toUpperCase(); } else { return 'TEAM'; } })(), stat_role: (() => { if (options.hasOwnProperty('role') && typeof options.role === 'string') { return options.role.toUpperCase(); } else { return 'HITTING'; } })(), stat_season: (() => { if (options.hasOwnProperty('season') && typeof options.season === 'string') { return options.season; } else { return new Date().getFullYear(); } })(), pruneData: (() => { if (options.hasOwnProperty('pruneData') && typeof options.prune === 'boolean') { return options.prune; } else { return false; } })(), }; } /** * Execute the operation. */ execute() { const mlbRequest = new MlbRequest(this.action); mlbRequest .on('complete', (data) => this.emit(`${this.action}:complete`, data)) .on('error', (error) => this.emit('error', error)); mlbRequest.buildUrl(this.options).makeRequest(); } } module.exports = CorneliusAction;
JavaScript
0
@@ -1789,32 +1789,337 @@ %7D)(),%0A + stat_game_type: (() =%3E %7B%0A if (options.hasOwnProperty('stat_game_type') && typeof options.stat_game_type === 'string') %7B%0A return options.stat_game_type.toUpperCase();%0A %7D else %7B%0A return 'R';%0A %7D%0A %7D)(),%0A stat
0beac921699c0bd737667a89a97a2df743723028
Version sort fix
src/public/js/utils/get-files-by-version.js
src/public/js/utils/get-files-by-version.js
export default function (project, version) { // 1. main file // 2. min files // 3. other files // 4. map files return project.assets.filter(assets => assets.version === version)[0].files.sort((a, b) => { if (a === project.mainfile || /\.map$/i.test(b)) { return -1; } if (b === project.mainfile || /\.map$/i.test(a)) { return 1; } if (/[._-]min./i.test(a)) { if (/[._-]min./i.test(b)) { return a > b || -1; } return -1; } if (/[._-]min./i.test(b)) { return 1; } return a > b || -1; }); }
JavaScript
0.000001
@@ -352,32 +352,33 @@ %0A%09%09if (/%5B._-%5Dmin +%5C ./i.test(a)) %7B%0A%09 @@ -384,32 +384,33 @@ %09%09%09if (/%5B._-%5Dmin +%5C ./i.test(b)) %7B%0A%09 @@ -472,16 +472,17 @@ %5B._-%5Dmin +%5C ./i.test
749e9f44c0f820ac5f65130dc7ca79edb97d6ae7
Refactor PodNetworkSpecView
src/js/components/PodNetworkSpecView.js
src/js/components/PodNetworkSpecView.js
import React from 'react'; import DescriptionList from './DescriptionList'; const METHODS_TO_BIND = [ ]; class PodNetworkSpecView extends React.Component { constructor() { super(...arguments); this.state = { }; METHODS_TO_BIND.forEach((method) => { this[method] = this[method].bind(this); }); } getGeneralDetails() { let {network} = this.props; let hash = {}; if (network.name) { hash['Name'] = network.name; } if (network.mode) { hash['Mode'] = network.mode; } return <DescriptionList hash={hash} />; } getLabelSection() { let {network} = this.props; if (!network.labels || !Object.keys(network.labels).length) { return null; } return ( <div> <h5 className="inverse flush-top">Labels</h5> <DescriptionList className="nested-description-list" hash={network.labels} /> </div> ); } render() { let {network} = this.props; return ( <div className="pod-config-network"> <h5 className="inverse flush-top"> {network.name} </h5> <div> {this.getGeneralDetails()} {this.getLabelSection()} </div> </div> ); } }; PodNetworkSpecView.contextTypes = { router: React.PropTypes.func }; PodNetworkSpecView.propTypes = { network: React.PropTypes.object }; module.exports = PodNetworkSpecView;
JavaScript
0
@@ -75,38 +75,8 @@ ';%0A%0A -const METHODS_TO_BIND = %5B%0A%5D;%0A%0A clas @@ -126,180 +126,8 @@ t %7B%0A - constructor() %7B%0A super(...arguments);%0A%0A this.state = %7B%0A %7D;%0A%0A METHODS_TO_BIND.forEach((method) =%3E %7B%0A this%5Bmethod%5D = this%5Bmethod%5D.bind(this);%0A %7D);%0A %7D%0A%0A ge @@ -154,32 +154,46 @@ let %7Bnetwork +: %7Bname, mode%7D %7D = this.props;%0A @@ -212,140 +212,226 @@ = %7B -%7D; %0A -if (network.name) %7B%0A hash%5B'Name'%5D = network.name;%0A %7D%0A if (network.mode) %7B%0A hash%5B'Mode'%5D = network.mode + Name: name,%0A Mode: mode%0A %7D;%0A%0A hash = Object.keys(hash).filter(function (key) %7B%0A return hash%5Bkey%5D;%0A %7D).reduce(function (memo, key) %7B%0A memo%5Bkey%5D = hash%5Bkey%5D;%0A%0A return memo ;%0A %7D +, %7B%7D); %0A%0A @@ -507,32 +507,40 @@ let %7Bnetwork +: labels %7D = this.props;%0A @@ -548,24 +548,16 @@ if (! -network. labels %7C @@ -571,24 +571,16 @@ ct.keys( -network. labels). @@ -781,24 +781,16 @@ hash=%7B -network. labels%7D @@ -848,16 +848,24 @@ %7Bnetwork +: %7Bname%7D %7D = this @@ -987,16 +987,8 @@ %7B -network. name @@ -1138,79 +1138,8 @@ %7D;%0A%0A -PodNetworkSpecView.contextTypes = %7B%0A router: React.PropTypes.func%0A%7D;%0A%0A PodN @@ -1200,16 +1200,27 @@ s.object +.isRequired %0A%7D;%0A%0Amod
4fe6145f8cb52e4f2a3767b5dac1fe9c42d9e2e5
fix windows cross driver path not found issue
lib/NodeStuffPlugin.js
lib/NodeStuffPlugin.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var path = require("path"); var ModuleParserHelpers = require("./ModuleParserHelpers"); var ConstDependency = require("./dependencies/ConstDependency"); var BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); var UnsupportedFeatureWarning = require("./UnsupportedFeatureWarning"); var NullFactory = require("./NullFactory"); function NodeStuffPlugin(options) { this.options = options; } module.exports = NodeStuffPlugin; NodeStuffPlugin.prototype.apply = function(compiler) { compiler.plugin("compilation", function(compilation) { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); }); function ignore() { return true; } function setConstant(expressionName, value) { compiler.parser.plugin("expression " + expressionName, function() { this.state.current.addVariable(expressionName, JSON.stringify(value)); return true; }); } function setModuleConstant(expressionName, fn) { compiler.parser.plugin("expression " + expressionName, function() { this.state.current.addVariable(expressionName, JSON.stringify(fn(this.state.module))); return true; }); } var context = compiler.context; if(this.options.__filename === "mock") { setConstant("__filename", "/index.js"); } else if(this.options.__filename) { setModuleConstant("__filename", function(module) { return path.relative(context, module.resource); }); } compiler.parser.plugin("evaluate Identifier __filename", function(expr) { if(!this.state.module) return; var res = new BasicEvaluatedExpression(); res.setString(this.state.module.splitQuery(this.state.module.resource)[0]); res.setRange(expr.range); return res; }); if(this.options.__dirname === "mock") { setConstant("__dirname", "/"); } else if(this.options.__dirname) { setModuleConstant("__dirname", function(module) { return path.relative(context, module.context); }); } compiler.parser.plugin("evaluate Identifier __dirname", function(expr) { if(!this.state.module) return; var res = new BasicEvaluatedExpression(); res.setString(this.state.module.context); res.setRange(expr.range); return res; }); compiler.parser.plugin("expression require.main", function(expr) { var dep = new ConstDependency("__webpack_require__.c[0]", expr.range); dep.loc = expr.loc; this.state.current.addDependency(dep); return true; }); compiler.parser.plugin("expression require.extensions", function(expr) { var dep = new ConstDependency("(void 0)", expr.range); dep.loc = expr.loc; this.state.current.addDependency(dep); if(!this.state.module) return; this.state.module.warnings.push(new UnsupportedFeatureWarning(this.state.module, "require.extensions is not supported by webpack. Use a loader instead.")); return true; }); compiler.parser.plugin("expression module.exports", ignore); compiler.parser.plugin("expression module.loaded", ignore); compiler.parser.plugin("expression module.id", ignore); compiler.parser.plugin("evaluate Identifier module.hot", function(expr) { return new BasicEvaluatedExpression().setBoolean(false).setRange(expr.range); }); compiler.parser.plugin("expression module", function() { var moduleJsPath = path.join(__dirname, "..", "buildin", "module.js"); if(this.state.module.context) { moduleJsPath = "./" + path.relative(this.state.module.context, moduleJsPath).replace(/\\/g, "/"); } return ModuleParserHelpers.addParsedVariable(this, "module", "require(" + JSON.stringify(moduleJsPath) + ")(module)"); }); };
JavaScript
0
@@ -3467,15 +3467,8 @@ th = - %22./%22 + pat @@ -3518,16 +3518,117 @@ eJsPath) +;%0A if(!/%5E%5BA-Z%5D:/i.test(moduleJsPath)) %7B%0A moduleJsPath = %22./%22 + moduleJsPath .replace @@ -3641,16 +3641,30 @@ , %22/%22);%0A + %7D%0A %09%09%7D%0A%09%09re
cd5c973358783045dd871620a68122af8faa79fc
add Usage for ApiWrapper
lib/api/api-wrapper.js
lib/api/api-wrapper.js
'use strict' const debug = require('debug')('webd2-api:apiWrapper') const Serializer = require('../utils/serializer') const Deserializer = require('../utils/deserializer') const Relations = require('../relations/relations') class ApiWrapper { constructor (attrs, registryMoc) { let {model, serializer, deserializer} = attrs if (attrs && attrs.name) { model = attrs serializer = deserializer = undefined } if (!model || !model.name || !model.schema) { throw new TypeError("ApiWrapper needs a model with 'name' and 'schema' fields") } debug(`wrapping of '${model.name}' model`) this.model = model this.relations = new Relations(model.name, model.schema, registryMoc) if (serializer) { this.serializer = serializer // for testing } else { this.serializer = new Serializer({ modelName: model.name, attributes: model.attributesSerialize, attributesOfRelations: this.relations.getAttributesOfRelations() }) } if (deserializer) { this.deserializer = deserializer // for testing } else { const modelNamesOfRelations = this.relations.belongsToDescriptors .map((rel) => rel.relationModelName) this.deserializer = new Deserializer(modelNamesOfRelations) } } apiCreate (newData) { debug(`${this.model.name}:apiCreate`) if (!newData) { throw new TypeError(`${this.model.name}.apiCreate(newData) newData cannot be undefined`) } return this.deserializer.deserialize(newData) .then((deserializedData) => this.model.create(deserializedData)) .then((record) => this._joinRelationsAndSerialize(record)) } apiUpdate (id, updates) { debug(`${this.model.name}:apiUpdate(${id})`) if (!id || !updates) { throw new TypeError(`${this.model.name}.apiUpdate(id, updates) id and updates cannot be undefined`) } return this.deserializer.deserialize(updates) .then((deserializedData) => this.model.update(id, deserializedData)) .then((record) => this._joinRelationsAndSerialize(record)) } apiFind (id) { debug(`${this.model.name}:apiFind(${id})`) if (!id) { throw new TypeError(`${this.model.name}.apiFind(id) id cannot be undefined`) } return this.model.selectOne({id}) .then((record) => this._joinRelationsAndSerialize(record)) } /** * options format * { * withRelated: true or false, fetch or no relation's data too * * fieldsOnly * where * orderBy * <etc> constraints go to parent model * * relationsOptions: { * parentWhere - contains parent's 'where' contraint * * user: { where: {hide: false}, orderBy: 'name' }, * divisions: {where: {hide: false}} * } these options go each one to correspondent relation's model * } */ apiFetchMany (options) { debug(`${this.model.name}:apiFetchMany`) options = options || {} const relationsOptions = options.relationsOptions || {} relationsOptions.parentWhere = options.where delete options.relationsOptions // to prevent passing it to parent model return this.model.selectMany(options) .then((parentRows) => { if (options.withRelated) { return this.relations.fetchAndEmbed(parentRows, relationsOptions) } else { return this.relations.justEmbedIds(parentRows, relationsOptions) } }) .then((dataSet) => { if (options.withRelated) { return this.serializer.withRelated(dataSet) } else { return this.serializer.withoutRelated(dataSet) } }) } /** * handles one row * thus used in apiMethods that return only one row */ _joinRelationsAndSerialize (row) { debug(`${this.model.name}:_joinRelationsAndSerialize`) const dataSet = this.relations.transformBelongsToIDs([row])[0] return this.serializer.withoutRelated(dataSet) } } module.exports = ApiWrapper
JavaScript
0
@@ -219,16 +219,291 @@ ions')%0A%0A +/**%0A * REST Api wrapper%0A *%0A * Usage:%0A *%0A * const userModel = require('../models/user')%0A * const userApi = new ApiWrapper(userModel)%0A *%0A * userApi.apiFetchMany(%7BwithRelated: true, where: %7Bhide:false%7D, orderBy: 'name'%7D)%0A * .then((usersJson) =%3E %7B ... req.send(usersJson) %7D)%0A */%0A class Ap @@ -546,16 +546,17 @@ istryMoc +k ) %7B%0A @@ -989,16 +989,17 @@ istryMoc +k )%0A%0A i
85a9e6f4597a0210141d574eaa59e976504dd1a8
Support the `order` property from atom/atom#18773
lib/atom/decoration.js
lib/atom/decoration.js
import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import {Disposable} from 'event-kit'; import cx from 'classnames'; import {createItem, extractProps} from '../helpers'; import {RefHolderPropType} from '../prop-types'; import {TextEditorContext} from './atom-text-editor'; import {DecorableContext} from './marker'; import RefHolder from '../models/ref-holder'; const decorationPropTypes = { type: PropTypes.oneOf(['line', 'line-number', 'highlight', 'overlay', 'gutter', 'block']).isRequired, className: PropTypes.string, style: PropTypes.string, onlyHead: PropTypes.bool, onlyEmpty: PropTypes.bool, onlyNonEmpty: PropTypes.bool, omitEmptyLastRow: PropTypes.bool, position: PropTypes.oneOf(['head', 'tail', 'before', 'after']), avoidOverflow: PropTypes.bool, gutterName: PropTypes.string, }; class BareDecoration extends React.Component { static propTypes = { editorHolder: RefHolderPropType.isRequired, decorableHolder: RefHolderPropType.isRequired, decorateMethod: PropTypes.oneOf(['decorateMarker', 'decorateMarkerLayer']), itemHolder: RefHolderPropType, children: PropTypes.node, ...decorationPropTypes, } static defaultProps = { decorateMethod: 'decorateMarker', } constructor(props, context) { super(props, context); this.decorationHolder = new RefHolder(); this.editorSub = new Disposable(); this.decorableSub = new Disposable(); this.domNode = null; this.item = null; if (['gutter', 'overlay', 'block'].includes(this.props.type)) { this.domNode = document.createElement('div'); this.domNode.className = cx('react-atom-decoration', this.props.className); } } usesItem() { return this.domNode !== null; } componentDidMount() { this.editorSub = this.props.editorHolder.observe(this.observeParents); this.decorableSub = this.props.decorableHolder.observe(this.observeParents); } componentDidUpdate(prevProps) { if (this.props.editorHolder !== prevProps.editorHolder) { this.editorSub.dispose(); this.editorSub = this.props.editorHolder.observe(this.observeParents); } if (this.props.decorableHolder !== prevProps.decorableHolder) { this.decorableSub.dispose(); this.decorableSub = this.props.decorableHolder.observe(this.observeParents); } if ( Object.keys(decorationPropTypes).some(key => this.props[key] !== prevProps[key]) ) { this.decorationHolder.map(decoration => decoration.destroy()); this.createDecoration(); } } render() { if (this.usesItem()) { return ReactDOM.createPortal( this.props.children, this.domNode, ); } else { return null; } } observeParents = () => { this.decorationHolder.map(decoration => decoration.destroy()); const editorValid = this.props.editorHolder.map(editor => !editor.isDestroyed()).getOr(false); const markableValid = this.props.decorableHolder.map(decorable => !decorable.isDestroyed()).getOr(false); // Ensure the Marker or MarkerLayer corresponds to the context's TextEditor const markableMatches = this.props.decorableHolder.map(decorable => this.props.editorHolder.map(editor => { const layer = decorable.layer || decorable; const displayLayer = editor.getMarkerLayer(layer.id); if (!displayLayer) { return false; } if (displayLayer !== layer && displayLayer.bufferMarkerLayer !== layer) { return false; } return true; }).getOr(false)).getOr(false); if (!editorValid || !markableValid || !markableMatches) { return; } this.createDecoration(); } createDecoration() { if (this.usesItem() && !this.item) { this.item = createItem(this.domNode, this.props.itemHolder); } const opts = this.getDecorationOpts(this.props); const editor = this.props.editorHolder.get(); const decorable = this.props.decorableHolder.get(); this.decorationHolder.setter( editor[this.props.decorateMethod](decorable, opts), ); } componentWillUnmount() { this.decorationHolder.map(decoration => decoration.destroy()); this.editorSub.dispose(); this.decorableSub.dispose(); } getDecorationOpts(props) { return { ...extractProps(props, decorationPropTypes, {className: 'class'}), item: this.item, }; } } export default class Decoration extends React.Component { static propTypes = { editor: PropTypes.object, decorable: PropTypes.object, } constructor(props) { super(props); this.state = { editorHolder: RefHolder.on(this.props.editor), decorableHolder: RefHolder.on(this.props.decorable), }; } static getDerivedStateFromProps(props, state) { const editorChanged = state.editorHolder .map(editor => editor !== props.editor) .getOr(props.editor !== undefined); const decorableChanged = state.decorableHolder .map(decorable => decorable !== props.decorable) .getOr(props.decorable !== undefined); if (!editorChanged && !decorableChanged) { return null; } const nextState = {}; if (editorChanged) { nextState.editorHolder = RefHolder.on(props.editor); } if (decorableChanged) { nextState.decorableHolder = RefHolder.on(props.decorable); } return nextState; } render() { if (!this.state.editorHolder.isEmpty() && !this.state.decorableHolder.isEmpty()) { return ( <BareDecoration {...this.props} editorHolder={this.state.editorHolder} decorableHolder={this.state.decorableHolder} /> ); } return ( <TextEditorContext.Consumer> {editorHolder => ( <DecorableContext.Consumer> {({holder, decorateMethod}) => ( <BareDecoration editorHolder={editorHolder} decorableHolder={holder} decorateMethod={decorateMethod} {...this.props} /> )} </DecorableContext.Consumer> )} </TextEditorContext.Consumer> ); } }
JavaScript
0
@@ -787,16 +787,43 @@ ter'%5D),%0A + order: PropTypes.number,%0A avoidO
a5eea996a5a9d190a919fd96dfaa6b35797d3d4f
fix l10n pack for basis.l10n v2
lib/build/l10n/pack.js
lib/build/l10n/pack.js
var at = require('../../ast').js; var tmplAt = require('../../ast').tmpl; module.exports = function(flow){ function packKey(key){ if (key.charAt(0) == '#') return false; return l10nIndex.keys.hasOwnProperty(key) ? '#' + l10nIndex.keys[key].toString(36) : false; } var fconsole = flow.console; if (!flow.l10n.module) { fconsole.log('Skipped.'); fconsole.log('basis.l10n not found'); return; } if (!flow.options.l10nPack) { fconsole.log('Skipped.'); fconsole.log('Use option --l10n-pack for compression'); return; } if (flow.options.version) { fconsole.log('Skipped.'); fconsole.log('Compression is not support for new version of basis.l10n'); return; } // // main part // var l10nIndex = flow.l10n.index; if (!l10nIndex) { flow.warn({ fatal: true, message: 'l10n index must be built before compression' }); return; } // // pack definitions // fconsole.start('Pack createDictionary'); flow.l10n.defList.forEach(function(entry){ fconsole.log(entry.name); var dict = {}; dict[entry.name] = entry.keys; entry.args[2] = ['array', packDictionary(dict, l10nIndex.map).map(function(token){ return [typeof token == 'number' ? 'num' : 'string', token]; })]; }); fconsole.endl(); // // pack getToken // fconsole.start('Pack getToken'); flow.l10n.getTokenList.forEach(function(entry){ var packed = packKey(entry.key); if (packed) { fconsole.log(entry.key + ' -> ' + packed); entry.token[2] = [['string', packed]]; } else { flow.warn({ file: entry.file.relpath, message: 'l10n key ' + entry.key + ' not found (ignored)' }); } }); fconsole.endl(); // // process templates & pack l10n pathes // fconsole.start('Pack keys in templates'); flow.l10n.tmplRefs.forEach(function(entry){ var packed = packKey(entry.key); if (packed) { packed = 'l10n:' + packed; entry.host[entry.idx] = packed; fconsole.log('l10n:' + entry.key + ' -> ' + packed); } else { flow.warn({ file: entry.file.relpath, message: 'l10n key ' + entry.key + ' not found (ignored)' }); } }); fconsole.endl(); // // pack packages // fconsole.start('Pack packages'); flow.l10n.packages.forEach(function(file){ fconsole.log(file.jsRef); file.jsResourceContent = packDictionary(file.jsResourceContent, l10nIndex.map); }); fconsole.endl(); }; module.exports.handlerName = '[l10n] Compress'; // // tools // function packDictionary(dict, map){ var result = []; var flattenDict = {}; // linear for (var dictName in dict){ for (var key in dict[dictName]){ flattenDict[dictName + '.' + key] = dict[dictName][key]; } } // pack for (var i = 0, gap = -1; i < map.length; i++) { if (flattenDict[map[i]]) { if (gap != -1) result.push(gap); result.push(flattenDict[map[i]]); gap = -1; } else gap++; } if (typeof result[result.length - 1] == 'number') result.pop(); return result; }
JavaScript
0.00002
@@ -623,23 +623,20 @@ f (flow. -options +l10n .version
6d0240c42bb6db9c39c6e784dbea4484dcddb7fb
remove unnecessary variable
lib/command/publish.js
lib/command/publish.js
'use strict'; module.exports = publish; var async = require('async'); var sha = require('sha'); var node_url = require('url'); var attachment = require('./attachment'); var unpublish = require('./unpublish'); var REGEX_IS_SNAPSHOT = /\-SNAPSHOT$/; // @param {Object} options // - tar: {string} tar file path // - pkg: {Object} the object of package.json // - force: {boolean} force publishing function publish (options, callback, logger, db) { var pkg = options.pkg; // info to put into couchdb options.info = { _id: pkg.name, name: pkg.name, description: pkg.description, 'dist-tags': {}, versions: {}, readme: pkg.readme || '', maintainers: [ { name: this.options.username, email: this.options.email } ] }; publish.prepublish(options, function(err, res, json) { if(err){ return callback(err, res, json); } async.waterfall([ function(done) { publish.get_package_info(pkg.name, done, logger, db); }, function(res, info, done) { publish.check_version(options, info, function(err, res, json) { if(err){ return done(err, res, json); } publish.update_package(options, info, done, logger, db); }, logger, db); } ], callback); }, logger, db); } // Try to create a new package if not exists. // If the package already exists, the update will fail publish.prepublish = function(options, callback, logger, db) { var info = options.info; var pkg = options.pkg; logger.verbose('{{cyan prepublish}}', pkg.name); db.put(pkg.name, { json: info }, function(err, res, json) { if ( err && // 409 // -> Document update conflict, which means the document of the package exists. // This is a new version of the existing package. !(res && res.statusCode === 409) && !( json && json.reason === "must supply latest _rev to update existing package" ) ) { return callback(err, res, json); } callback(null, res, json); }); }; publish.get_package_info = function(name, callback, logger, db) { db.get( db.escape(name), callback); }; // check if there is a version conflict publish.check_version = function(options, info, callback, logger, db) { var pkg = options.pkg; var full_name = '"' + pkg.name + '@' + pkg.version + '"'; if(pkg.version in info.versions){ if(options.force){ logger.verbose('"--force" option found, force overriding ' + full_name + '.'); }else{ return callback( new Error(full_name + ' already found, maybe you should use "SNAPSHOT" version or use "--force" option.') ); } logger.verbose('Unpublish package.'); // unpublish the current version to force publishing unpublish({ name: pkg.name, version: pkg.version }, callback, logger, db); }else{ callback(); } }; // @param {Object} options of `publish` // @param {Object} info package information publish.update_package = function(options, info, callback, logger, db) { var pkg = options.pkg; var file_name = pkg.name + '-' + pkg.version + '.tgz'; logger.verbose('upload attachments:', file_name); // upload attachments(tarball) attachment({ pkg : pkg.name, name : file_name, rev : info._rev, tar : options.tar }, function(err) { if(err){ return callback(err); } sha.get(options.tar, function(err, shasum) { if(err){ return callback(err); } var pkg = options.pkg; var tag = pkg.tag || 'latest'; var escaped_name = db.escape(pkg.name); var path = escaped_name + '/' + pkg.version + '/-tag/' + tag; pkg._id = pkg.name + '@' + pkg.version; // pkg.dist = pkg.dist || {} pkg.dist = {}; pkg.dist.tarball = db.resolve(escaped_name + '/-/' + escaped_name + '-' + pkg.version + '.tgz'); pkg.dist.shasum = shasum; // update version db.put(path, { json: pkg }, callback); }); }, logger, db); };
JavaScript
0.000739
@@ -210,49 +210,8 @@ );%0A%0A -var REGEX_IS_SNAPSHOT = /%5C-SNAPSHOT$/;%0A%0A%0A // @
d226de0ceae96633225fb5c30aae509ab1fa52df
Stop overriding 0 values.
lib/config/defaults.js
lib/config/defaults.js
(function () { 'use strict'; /** * This defines defaults that will be inserted into config. */ var defaults = { http: { // Won't bind http on anything by default bind: ['127.0.0.1'], // If binding, will use default port unless instructed otherwise port: 80 }, https: { // Won't bind https on anything by default bind: [], // If binding, will use default port unless instructed otherwise port: 443, // No CA provided ca: [] }, // By default use a single redis server on localhost default port driver: ['redis:'], user: '', group: '', server: { workers: 10, maxSockets: 100, tcpTimeout: 30, deadBackendTTL: 30, retryOnError: 3, accessLog: "/var/log/hipache/access.log", httpKeepAlive: false, deadBackendOn500: true } }; var defaultsMap = function (options) { Object.keys(defaults).forEach(function (category) { if (defaults[category] instanceof Array || !(defaults[category] instanceof Object)) { return options[category] = options[category] || defaults[category]; } if (!(category in options)) { options[category] = {}; } Object.keys(defaults[category]).forEach(function (key) { options[category][key] = options[category][key] || defaults[category][key]; }); }); }; module.exports = defaultsMap; })();
JavaScript
0.000001
@@ -752,24 +752,50 @@ server: %7B%0A + debug: false,%0A @@ -807,16 +807,16 @@ rs: 10,%0A - @@ -1287,15 +1287,12 @@ -return +if ( opti @@ -1302,24 +1302,58 @@ %5Bcategory%5D = += undefined) %7B%0A options%5Bcat @@ -1359,18 +1359,17 @@ tegory%5D -%7C%7C += default @@ -1377,24 +1377,85 @@ %5Bcategory%5D;%0A + %7D%0A return options%5Bcategory%5D;%0A @@ -1629,32 +1629,36 @@ +if ( options%5Bcategory @@ -1665,16 +1665,50 @@ %5D%5Bkey%5D = += undefined) %7B%0A options @@ -1723,18 +1723,17 @@ y%5D%5Bkey%5D -%7C%7C += default @@ -1746,24 +1746,42 @@ gory%5D%5Bkey%5D;%0A + %7D%0A
5075dc1a4be313a091fa9f63a0dc282368403059
update features
app/features_spec.js
app/features_spec.js
export default { submission: false, voting: false, tagging: true, proposalsPageGroupedByTags: false, networking: true, recommendations: true, editAcceptedProposals: true, publishAgenda: true, startRegistration: true, viewSlides: true }
JavaScript
0
@@ -24,20 +24,19 @@ ission: -fals +tru e,%0A vot @@ -194,19 +194,20 @@ Agenda: -tru +fals e,%0A sta
55fff62f36a722583bce5a2fc897194dc564b217
negative tests
FizzBuzz/fizzbuzz.js
FizzBuzz/fizzbuzz.js
"use strict"; var assert = require('assert'); var fizz = function(v) { return v % 3 === 0; }; var buzz = function(v) { return v % 5 === 0; }; describe("fizzbuzz", function() { it("should fizz", function() { assert(fizz(3)); }); it("should buzz", function() { assert(!buzz(7)); }); });
JavaScript
0.999948
@@ -230,16 +230,38 @@ zz(3)); +%0A assert(!fizz(5)); %0A %7D) @@ -318,16 +318,38 @@ zz(7));%0A + assert(buzz(10));%0A %7D);%0A%7D)
0b55ffdeab384530ed6e174635e8124fa093c1e0
Remove redundant code from hapi17 consumer
lib/consumer/hapi17.js
lib/consumer/hapi17.js
var urlib = require('url') var qs = require('qs') var config = require('../config') var flows = { 1: require('../flow/oauth1'), 2: require('../flow/oauth2'), response: require('../response') } module.exports = function (_config) { var app = {} function register (server, options) { app.config = config.init(Object.keys(options).length ? options : _config) server.route({ method: ['GET', 'POST'], path: '/connect/{provider}/{override?}', handler: async (req, res) => { if (!(req.session || req.yar)) { throw new Error('Grant: register session plugin first') } var session = { provider: req.params.provider } if (req.params.override) { session.override = req.params.override } if (req.method === 'get' && Object.keys(req.query || {}).length) { var query = (parseInt(server.version.split('.')[0]) >= 12) ? qs.parse(urlib.parse(req.url, false).query) // #2985 : req.query session.dynamic = query } if (req.method === 'post' && Object.keys(req.payload || {}).length) { var payload = (parseInt(server.version.split('.')[0]) >= 12) ? qs.parse(req.payload) // #2985 : req.payload session.dynamic = payload } ;(req.session || req.yar).set('grant', session) return connect(req, res) } }) async function connect (req, res) { var grant = (req.session || req.yar).get('grant') var provider = config.provider(app.config, grant) var flow = flows[provider.oauth] var transport = (data) => { if (!provider.callback) { return res.response(qs.stringify(data)) } else if (!provider.transport || provider.transport === 'querystring') { return res.redirect((provider.callback || '') + '?' + qs.stringify(data)) } else if (provider.transport === 'session') { grant.response = data ;(req.session || req.yar).set('grant', grant) return res.redirect(provider.callback || '') } } var success = (url) => res.redirect(url) var error = (err) => transport({error: err.body}) if (/^1$/.test(provider.oauth)) { try { var {body} = await flow.request(provider) grant.request = body var url = await flow.authorize(provider, body) return success(url) } catch (err) { return error(err) } } else if (/^2$/.test(provider.oauth)) { try { grant.state = provider.state var url = await flow.authorize(provider) return success(url) } catch (err) { return error(err) } } else { return error({body: 'Grant: missing or misconfigured provider'}) } } server.route({ method: 'GET', path: '/connect/{provider}/callback', handler: async (req, res) => { var grant = (req.session || req.yar).get('grant') || {} var provider = config.provider(app.config, grant) var flow = flows[provider.oauth] var query = (parseInt(server.version.split('.')[0]) >= 12) ? qs.parse(urlib.parse(req.url, false).query) // #2985 : req.query var transport = (data) => { if (!provider.callback) { return res.response(qs.stringify(data)) } else if (!provider.transport || provider.transport === 'querystring') { return res.redirect((provider.callback || '') + '?' + qs.stringify(data)) } else if (provider.transport === 'session') { grant.response = data ;(req.session || req.yar).set('grant', grant) return res.redirect(provider.callback || '') } } var success = (data) => transport(data) var error = (err) => transport({error: err.body}) if (/^1$/.test(provider.oauth)) { try { var {body} = await flow.access(provider, grant.request, query) return success(flows.response(provider, body)) } catch (err) { return error(err) } } else if (/^2$/.test(provider.oauth)) { try { var {body} = await flow.access(provider, query, grant) return success(flows.response(provider, body)) } catch (err) { return error(err) } } else { return error({body: 'Grant: missing session or misconfigured provider'}) } } }) } app.pkg = require('../../package.json') app.register = register return app }
JavaScript
0.00819
@@ -889,69 +889,8 @@ ry = - (parseInt(server.version.split('.')%5B0%5D) %3E= 12)%0A ? qs. @@ -943,32 +943,8 @@ 985%0A - : req.query%0A @@ -1088,69 +1088,8 @@ ad = - (parseInt(server.version.split('.')%5B0%5D) %3E= 12)%0A ? qs. @@ -1120,34 +1120,8 @@ 985%0A - : req.payload%0A @@ -3049,67 +3049,8 @@ ry = - (parseInt(server.version.split('.')%5B0%5D) %3E= 12)%0A ? qs. @@ -3102,30 +3102,8 @@ 2985 -%0A : req.query %0A%0A
4cfeacb35c4786a1d005988c20ce96637161ebd6
Use 'beforeInput' event intead 'keyPress'; https://w3c.github.io/uievents/#event-type-keypress
src/components/CardNumberInput.js
src/components/CardNumberInput.js
import React from 'react'; import InputMask from 'inputmask-core'; import TextField from 'material-ui/TextField'; const ENTER_KEY = 'Enter'; const BACKSPACE_KEY = 'Backspace'; const KEYCODE_Y = 89; const KEYCODE_Z = 90; const PATTERN = '11-1111-11-11111'; class CardNumberInput extends React.Component { constructor() { super(); this.state = { isValid: false, text: '' } this.handlePaste = this.handlePaste.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.handleKeyPress = this.handleKeyPress.bind(this); this.handleChange = this.handleChange.bind(this); } componentWillMount() { const selection = this.props.value ? this.props.value.length : 0; let options = { pattern: PATTERN, placeholderChar: ' ', value: this.props.value, selection: { start: selection, end: selection } } this.mask = new InputMask(options); const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, _ => triggerOnchange(this.state, this.props)); } componentWillReceiveProps(nextProps) { if (this.props.value !== nextProps.value) { const selection = nextProps.value ? nextProps.value.length : 0; this.mask.setValue(nextProps.value); this.mask.setSelection({ start: selection, end: selection }) const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, _ => triggerOnchange(this.state, this.props)); } } handleChange(event) { const maskValue = this.mask.getValue() const elementValue = event.target.value; if (elementValue !== maskValue) { // Cut or delete operations will have shortened the value if (elementValue.length < maskValue.length) { const sizeDiff = maskValue.length - elementValue.length this.mask.setSelection(getElementSelection(event.target)); this.mask.selection.end = this.mask.selection.start + sizeDiff this.mask.backspace() } const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, _ => triggerOnchange(this.state, this.props)); } } handlePaste(event) { event.preventDefault(); this.mask.setSelection(getElementSelection(event.target)); let pastedValue = getTextFromClipboardData(event); if (this.mask.paste(pastedValue)) { const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, _ => triggerOnchange(this.state, this.props)); } } handleKeyDown(event) { if (isUndoEvent(event)) { event.preventDefault() if (this.mask.undo()) { const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, _ => triggerOnchange(this.state, this.props)); } return; } else if (isRedoEvent(event)) { event.preventDefault() if (this.mask.redo()) { const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, _ => triggerOnchange(this.state, this.props)); } return; } if (event.key === BACKSPACE_KEY) { event.preventDefault(); this.mask.setSelection(getElementSelection(event.target)); if (this.mask.backspace()) { const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, _ => triggerOnchange(this.state, this.props)); } } } handleKeyPress(event) { if (event.metaKey || event.altKey || event.ctrlKey || event.key === ENTER_KEY) { return } event.preventDefault(); this.mask.setSelection(getElementSelection(event.target)); if (this.mask.input(event.key)) { const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, _ => triggerOnchange(this.state, this.props)); } } render() { return <TextField type="text" {...this.props} floatingLabelText="Card Number" hintText={PATTERN.replace(/1/g, 'X') } size={this.mask.pattern.length} maxLength={this.mask.pattern.length} onChange={this.handleChange} onPaste={this.handlePaste} onKeyDown={this.handleKeyDown} onKeyPress={this.handleKeyPress} value={this.state.text} /> } } CardNumberInput.propTypes = { value: React.PropTypes.string, onChange: React.PropTypes.func } function getElementSelection(element) { return { start: element.selectionStart, end: element.selectionEnd } } function getDisplayMaskValue(mask) { return mask .getValue() .slice(0, mask.selection.end); } function isValidValue(value, mask) { return value && value !== mask.emptyValue && value.length === mask.pattern.length; } function triggerOnchange(state, props) { if (props.onChange) { props.onChange({ text: state.text, isValid: state.isValid }); } } function isUndoEvent(event) { return (event.ctrlKey || event.metaKey) && event.keyCode === (event.shiftKey ? KEYCODE_Y : KEYCODE_Z); } function isRedoEvent(event) { return (event.ctrlKey || event.metaKey) && event.keyCode === (event.shiftKey ? KEYCODE_Z : KEYCODE_Y); } function getTextFromClipboardData(event) { let result; // IE if (window.clipboardData) { result = window.clipboardData.getData('Text'); } else { result = (event.originalEvent || event).clipboardData.getData('text/plain'); } return result; } export default CardNumberInput;
JavaScript
0.000866
@@ -517,24 +517,27 @@ s.handle -KeyPress +BeforeInput = this. @@ -542,24 +542,27 @@ s.handle -KeyPress +BeforeInput .bind(th @@ -1705,24 +1705,25 @@ k.getValue() +; %0A const e @@ -3866,24 +3866,27 @@ handle -KeyPress +BeforeInput (event) @@ -4114,19 +4114,20 @@ t(event. -key +data )) %7B%0A @@ -4679,24 +4679,27 @@ on -KeyPress +BeforeInput =%7Bthis.h @@ -4707,16 +4707,19 @@ ndle -KeyPress +BeforeInput %7D%0A
f82ed6ff17abc2d8ad1ee10cc7a75c5bb7bc8243
Remove duplicated editLaneTitle propType
src/components/Lane/LaneHeader.js
src/components/Lane/LaneHeader.js
import React from 'react' import PropTypes from 'prop-types' import InlineInput from 'rt/widgets/InlineInput' import {Title, LaneHeader, RightContent } from 'rt/styles/Base' import LaneMenu from './LaneHeader/LaneMenu' const LaneHeaderComponent = ({ updateTitle, canAddLanes, onDelete, onDoubleClick, editLaneTitle, label, title, titleStyle, labelStyle, t, laneDraggable }) => { return ( <LaneHeader onDoubleClick={onDoubleClick} editLaneTitle={editLaneTitle}> <Title draggable={laneDraggable} style={titleStyle}> {editLaneTitle ? <InlineInput value={title} border placeholder={t('placeholder.title')} resize='vertical' onSave={updateTitle} /> : title } </Title> {label && ( <RightContent> <span style={labelStyle}>{label}</span> </RightContent> )} {canAddLanes && <LaneMenu t={t} onDelete={onDelete}/>} </LaneHeader> ) } LaneHeaderComponent.propTypes = { updateTitle: PropTypes.func, editLaneTitle: PropTypes.bool, canAddLanes: PropTypes.bool, laneDraggable: PropTypes.bool, label: PropTypes.string, title: PropTypes.string, onDelete: PropTypes.func, onDoubleClick: PropTypes.func, editLaneTitle: PropTypes.bool, t: PropTypes.func.isRequired } LaneHeaderComponent.defaultProps = { updateTitle: () => {}, editLaneTitle: false, canAddLanes: false } export default LaneHeaderComponent;
JavaScript
0
@@ -1198,41 +1198,8 @@ nc,%0A - editLaneTitle: PropTypes.bool,%0A t:
644fb2c2a1b34a501829ad18291cca6034d78d75
rename to "invite" and "locator" for clarity
src/components/NavTabs/NavTabs.js
src/components/NavTabs/NavTabs.js
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import { Map } from 'immutable'; import { Tab, Tabs } from 'material-ui/lib/tabs'; import classes from './NavTabs.css'; export class LoginView extends React.Component { static propTypes = { location: PropTypes.instanceOf(Map), push: PropTypes.func.isRequired }; render () { const { push, location } = this.props; const { basename, pathname } = location.toJS(); const tabsProps = { className: classes.self, onChange: (value) => push(basename + value), value: pathname }; if (process.env.USE_CASE === 'app') { return ( <Tabs {...tabsProps}> <Tab label='Register' value='register' /> <Tab label='Subscription' value='subscription' /> <Tab label='Search' value='search' /> </Tabs> ); } if (process.env.USE_CASE === 'manager') { return ( <Tabs {...tabsProps}> <Tab label='Register' value='register' /> <Tab label='Tags' value='things/tags' /> <Tab label='People' value='things/people' /> <Tab label='Readers' value='things/readers' /> <Tab label='Subscription' value='subscription' /> <Tab label='Search' value='search' /> </Tabs> ); } return <Tabs {...tabsProps} />; } } const mapStateToProps = (state) => ({ // this is not recommended, but I just need a quick hack for now location: state.getIn(['router', 'locationBeforeTransitions']) }); export default connect((mapStateToProps), { push })(LoginView);
JavaScript
0.000302
@@ -1243,36 +1243,30 @@ %3CTab label=' -Subscription +Invite ' value='sub @@ -1293,38 +1293,39 @@ %3CTab label=' -Search +Locator ' value='search'
7499436b89acf05f696b2f5a1abd0e936ac65bee
Implement card selection
src/components/ScrumPokerCards.js
src/components/ScrumPokerCards.js
"use strict"; import React, { Component } from "react"; import { StyleSheet, View, TouchableHighlight } from "react-native"; import _ from "lodash"; import Card from "./Card"; const CARD_VALUES = [ "0", "½", "1", "2", "3", "5", "8", "13", "20", "40", "100", "?", "∞", "☕", null ]; const CARDS_PER_ROW = 3; export default class ScrumPokerCards extends Component { constructor() { super(); this.state = { rows: _.chunk(CARD_VALUES, CARDS_PER_ROW), opacities: CARD_VALUES.map(() => 1), }; } render() { console.log("RENDER"); const rows = this.state.rows.map((row, i) => { const cards = row.map((cardValue, j) => { const idx = i * CARDS_PER_ROW + j; const opacity = this.state.opacities[idx]; console.log("RENDER", idx, opacity); return ( <TouchableHighlight key={ j } style={{ flex: 1 }} onPress={ this.onCardPressed.bind(this, idx) } > <Card style={{ opacity }} key={ cardValue } value={ cardValue } /> </TouchableHighlight> ); }); return ( <View key={ i } style={ styles.row }> { cards } </View> ) }); return ( <View style={ styles.container }> { rows } </View> ); } onCardPressed(idx) { console.log("HIDE", idx); const newState = _.cloneDeep(this.state); newState.opacities[idx] = 0; this.setState(newState); } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: "column", justifyContent: "space-between", }, row: { flex: 1, flexDirection: "row", justifyContent: "space-between", } });
JavaScript
0
@@ -428,16 +428,42 @@ ate = %7B%0A + selectedCard: null,%0A ro @@ -508,16 +508,16 @@ R_ROW),%0A - op @@ -603,16 +603,371 @@ NDER%22);%0A + if (this.state.selectedCard) %7B%0A return (%0A %3CView style=%7B styles.singleCardContainer %7D%3E%0A %3CTouchableHighlight%0A style=%7B%7B flex: 1 %7D%7D%0A onPress=%7B this.onCardPressed.bind(this, null) %7D%0A %3E%0A %3CCard value=%7B this.state.selectedCard %7D /%3E%0A %3C/TouchableHighlight%3E%0A %3C/View%3E%0A );%0A %7D%0A%0A cons @@ -1351,19 +1351,25 @@ d(this, -idx +cardValue ) %7D%0A @@ -1735,19 +1735,20 @@ Pressed( -idx +card ) %7B%0A @@ -1767,19 +1767,20 @@ %22HIDE%22, -idx +card );%0A%0A @@ -1838,26 +1838,27 @@ ate. -opacities%5Bidx%5D = 0 +selectedCard = card ;%0A%0A @@ -1892,16 +1892,16 @@ %0A %7D%0A%7D%0A%0A - const st @@ -1927,16 +1927,141 @@ reate(%7B%0A + singleCardContainer: %7B%0A flex: 1,%0A marginTop: 50,%0A marginBottom: 50,%0A marginLeft: 20,%0A marginRight: 20,%0A %7D,%0A contai
1020c4d209e482c209922b31692791f7a92e2dc8
add setImmediate so the maximum stack size is not exceeded
lib/db/sqljsAdapter.js
lib/db/sqljsAdapter.js
var async = require('async'); module.exports.createAdapter = function(filePath, callback) { var fs = require('fs'); var sqljs = require('sql.js'); fs.readFile(filePath, function(err, fileBuffer) { var db = new sqljs.Database(fileBuffer); var adapter = new Adapter(db); callback(err, adapter); }); } module.exports.createAdapterFromDb = function(db) { return new Adapter(db); } function Adapter(db) { this.db = db; } Adapter.prototype.getDBConnection = function () { return this.db; }; Adapter.prototype.get = function (sql, params, callback) { if (typeof params === 'function') { callback = params; params = []; } var statement = this.db.prepare(sql); statement.bind(params); var hasResult = statement.step(); var row; if (hasResult) { row = statement.getAsObject(); } statement.free(); callback(null, row); }; Adapter.prototype.prepare = function () { this.db.prepare.apply(this.db, arguments); }; Adapter.prototype.all = function (sql, params, callback) { var rows = []; this.each(sql, params, function(err, row, rowDone) { rows.push(row); rowDone(); }, function(err) { callback(err, rows); }); }; Adapter.prototype.each = function (sql, params, eachCallback, doneCallback) { if (typeof params === 'function') { doneCallback = eachCallback; eachCallback = params; params = []; } var statement = this.db.prepare(sql); statement.bind(params); async.whilst( function() { return statement.step(); }, function(callback) { var row = statement.getAsObject(); eachCallback(null, row, callback); }, function() { console.log('done'); statement.free(); doneCallback(); } ); };
JavaScript
0
@@ -1540,24 +1540,64 @@ callback) %7B%0A + async.setImmediate(function() %7B%0A var ro @@ -1627,24 +1627,26 @@ ct();%0A + eachCallback @@ -1668,16 +1668,26 @@ lback);%0A + %7D);%0A %7D,%0A
e8c4fd26c0d028462bb94304bdde17d9d1e53975
Fix for new value not beeing stored
lib/dummy-listeners.js
lib/dummy-listeners.js
if (!Object.prototype.addListener) { Object.defineProperty(Object.prototype, 'addListener', { enumerable: false, configurable: true, writable: false, value: function() { function addOneListener(obj, name, callback) { if (!obj._listeners_) { Object.defineProperty(obj, '_listeners_', { enumerable: false, configurable: true, writable: false, value: {} }); } if (!obj._listeners_[name]) { var descriptor = Object.getOwnPropertyDescriptor(obj, name); if (!descriptor) { descriptor = { enumerable: true, configurable: true, writable: true, value: undefined }; } if (!descriptor.configurable) throw 'It is not possible to add a listener to field ' + name; var field = { value: obj[name], callbacks: [] }; delete obj[name]; if (descriptor.value !== undefined || descriptor.writable) { descriptor.set = function(val) { field.value = val; return val; }; descriptor.get = function() { return field.value; }; delete descriptor.value; delete descriptor.writable; } var oldSetter = descriptor.set; descriptor.set = function(val) { var old = field.value; if (old === val) return old; val = oldSetter.call(obj, val); for (var i = 0; i < field.callbacks.length; ++i) field.callbacks[i](name, old, val); return val; }; obj._listeners_[name] = field; Object.defineProperty(obj, name, descriptor); } obj._listeners_[name].callbacks.push(callback); } if (arguments.length < 2) throw 'At least 2 args are needed: field name and callback'; var callback = arguments[arguments.length - 1]; if (typeof callback != 'function') throw 'The callback (last arg) must be a function (was "' + callback + '")'; for(var i = 0; i < arguments.length - 1; i++) addOneListener(this, arguments[i], callback); var obj = this; var args = arguments; return function() { obj['removeListener'].apply(obj, args); }; } }); } if (!Object.prototype.removeListener) { Object.defineProperty(Object.prototype, 'removeListener', { enumerable: false, configurable: true, writable: false, value: function() { function removeOneListener(obj, name, callback) { if (!obj._listeners_ || !obj._listeners_[name]) return false; var callbacks = obj._listeners_[name].callbacks; var index = callbacks.indexOf(callback); if (index < 0) return false; callbacks.splice(index, 1); return true; } if (arguments.length < 2) throw 'At least 2 args are needed: field name and callback'; var callback = arguments[arguments.length - 1]; if (typeof callback != 'function') throw 'The callback (last arg) must be a function (was "' + callback + '")'; for(var i = 0; i < arguments.length - 1; i++) removeOneListener(this, arguments[i], callback); } }); }
JavaScript
0.000001
@@ -1440,32 +1440,58 @@ call(obj, val);%0D +%0A%09%09%09%09%09%09field.value = val;%0D %0A%0D%0A%09%09%09%09%09%09for (va
9e133a8bc18f4f79428f636ed4540f433e9b5a52
Simplify editor registry destructor
lib/editor-registry.js
lib/editor-registry.js
'use babel' import {Emitter, CompositeDisposable} from 'atom' const EditorLinter = require('./editor-linter') export default class EditorRegistry { constructor() { this.emitter = new Emitter() this.subscriptions = new CompositeDisposable() this.editorLinters = new Map() this.subscriptions.add(this.emitter) } create(textEditor) { const editorLinter = new EditorLinter(textEditor) this.editorLinters.set(textEditor, editorLinter) this.emitter.emit('observe', editorLinter) editorLinter.onDidDestroy(() => this.editorLinters.delete(textEditor) ) return editorLinter } has(textEditor) { return this.editorLinters.has(textEditor) } forEach(textEditor) { this.editorLinters.forEach(textEditor) } ofPath(path) { for (let editorLinter of this.editorLinters) { if (editorLinter[0].getPath() === path) { return editorLinter[1] } } } ofTextEditor(textEditor) { return this.editorLinters.get(textEditor) } ofActiveTextEditor() { return this.ofTextEditor(atom.workspace.getActiveTextEditor()) } observe(callback) { this.forEach(callback) return this.emitter.on('observe', callback) } dispose() { this.subscriptions.dispose() this.editorLinters.forEach(function(editorLinter) { editorLinter.dispose() }) this.editorLinters.clear() } }
JavaScript
0
@@ -590,16 +590,57 @@ )%0A )%0A + this.subscriptions.add(editorLinter)%0A retu @@ -1299,100 +1299,8 @@ e()%0A - this.editorLinters.forEach(function(editorLinter) %7B%0A editorLinter.dispose()%0A %7D)%0A
ce727ba229a1cbc09da95728884d651e3883a815
handle paragraph formatting
src/main/resources/static/js/hogwild.js
src/main/resources/static/js/hogwild.js
$(document).ready(function() { $.getJSON("/app/story", function (data) { var entries = data.entries; for (var i = 0; i < entries.length; i++) { var entry = entries[i]; var container = $("<div>"); var heading = $("<h1>"); var body = $("<body>"); heading.text(entry.characterName); body.text(entry.body); container.append(heading); container.append(body); $("#story").append(container); } if(data.myTurn){ var form = $("<form><input type='text'></form>"); var submit = $("<a>Add</a>"); var edit = $("edit"); edit.append(form); edit.append(submit); submit.click(function(){ $.ajax({ type: "POST", url: "/app/story", data: JSON.stringify({"body":form.value()}), success: function(){}, dataType: "json" }); }) } }); });
JavaScript
0.000019
@@ -82,282 +82,936 @@ -var entries = data.entries;%0A for (var i = 0; i %3C entries.length; i++) %7B%0A var entry = entries%5Bi%5D;%0A var container = $(%22%3Cdiv%3E%22);%0A var heading = $(%22%3Ch1%3E%22);%0A var body = $(%22%3Cbody%3E%22);%0A heading.text(entry.characterName); +function toParagraphs(text)%7B%0A var lines = text.split(%22%5Cn%22);%0A var nonEmpty = %5B%5D;%0A for (var i = 0; i %3C lines.length; i++) %7B%0A var line = lines%5Bi%5D;%0A if(line && line.trim() !== %22%22)%7B%0A nonEmpty.push(line.trim());%0A %7D%0A %7D%0A return nonEmpty;%0A %7D%0A%0A var entries = data.entries;%0A for (var i = 0; i %3C entries.length; i++) %7B%0A var entry = entries%5Bi%5D;%0A var container = $(%22%3Cdiv%3E%22);%0A var heading = $(%22%3Ch1%3E%22);%0A var body = $(%22%3Cbody%3E%22);%0A heading.text(entry.characterName);%0A var bodyParagraphs = toParagraphs(enty.body);%0A for (var j = 0; j %3C bodyParagraphs.length; j++) %7B%0A var paragraph = bodyParagraphs%5Bj%5D;%0A var p = $(%22%3Cp%3E%22);%0A p.text(paragraph);%0A body.append(p);%0A %7D %0A
f7bf5b6c015dd75657903b68aaa4743ef0050646
create gulp build task, that builds everything required
ScrumPoker/gulpfile.js
ScrumPoker/gulpfile.js
var gulp = require("gulp"); var concat = require("gulp-concat"); var templateCache = require("gulp-angular-templatecache"); var minHtml = require("gulp-minify-html"); var sourcemap = require("gulp-sourcemaps"); var uglify = require("gulp-uglify"); gulp.task("script", function() { gulp.src([ "App/app.module.js", "App/**/*.module.js", "App/**/*.js" ]) .pipe(sourcemap.init()) .pipe(concat("app.js")) .pipe(uglify()) .pipe(sourcemap.write(".")) .pipe(gulp.dest(".")); }); gulp.task("templates", function() { gulp.src("partials/*.html") .pipe(minHtml()) .pipe(templateCache("templates.js", { standalone: true, root:"partials" })) .pipe(gulp.dest(".")); });
JavaScript
0
@@ -260,16 +260,17 @@ (%22script +s %22, funct @@ -752,28 +752,74 @@ .pipe(gulp.dest(%22.%22));%0A%7D);%0A +%0Agulp.task(%22build%22, %5B%22scripts%22, %22templates%22%5D);
eca8eee2bb4def206897e803c1253ae75d37d9e1
Use the username from db not the one entered by the user in tab title
src/main/resources/static/js/scripts.js
src/main/resources/static/js/scripts.js
$(document).ready(function () { 'use strict'; /***************************************/ /*** ROUTES ***/ /***************************************/ /*********************/ /** Root **/ /*********************/ crossroads.addRoute('/', function () { navigateTo('/login', 'Login') }, 100); /*********************/ /** Me **/ /*********************/ crossroads.addRoute('/me', function() { crossroads.parse(session.user.username); }, 100); /*********************/ /** Logout **/ /*********************/ crossroads.addRoute('/logout', function() { session.logout(); navigateTo('login', 'Login'); }, 100); /*********************/ /** Login **/ /*********************/ crossroads.addRoute('/login', function () { $('.sidebar').load('sidebar/not_logged_in.html'); $('.content').load('content/login.html', function () { if (session.authenticated) { console.info('already authenticated!, redirecting to profile...') return navigateTo(session.user.username, session.user.username) } if (window.loginMessage) { $('.error-list').append('<li class="error-list__item"><i class="error-list__item__icon fa fa-info-circle"></i><p class="error-list__item__text">' + window.loginMessage + '</p></li>'); window.loginMessage = null } $('.form--login').on('submit', function (e) { e.preventDefault() var username = $('.form__input[type=text]').val() var password = $('.form__input[type=password]').val() session.login(username, password) .then(function (user) { console.info('successfully authenticated, redirecting to profile...') navigateTo(username, username) }) .catch(function (error) { console.warn('bad credentials!') $('.error-list').append('<li class="error-list__item"><i class="error-list__item__icon fa fa-times-circle"></i><p class="error-list__item__text">Bad Credentials!</p></li>'); }) }) }); }, 100); /*********************/ /** Register **/ /*********************/ crossroads.addRoute('/register', function () { $('.sidebar').load('sidebar/not_logged_in.html'); $('.content').load('content/register.html', function () { if (session.authenticated) { console.info('already authenticated! no need to register - redirecting to profile...') return navigateTo(session.user.username, session.user.username) } $('.form--register').on('submit', function (e) { e.preventDefault() var username = $('.form__input[name=username]').val() var email = $('.form__input[name=email]').val() var password = $('.form__input[name=password]').val() var confirmation = $('.form__input[name=confirmation]').val() // Return error array as list items var errorArray = CheckFormInputRegister(email, password, confirmation, username); $('.error-list').empty(); $(errorArray).each(function(index, value){ $('.error-list').append('<li class="error-list__item"><i class="error-list__item__icon fa fa-times-circle" aria-hidden="true"></i><p class="error-list__item__text">' + value + '</p></li>') }); $('.error-list').slideDown(); if (errorArray.length == 0) { axios.post('/users', { username: username, password: password, email: email }) .then((res) => { console.log(res); window.loginMessage = "success, you can now login!" navigateTo('login', 'Login') }).catch((err) => { console.log(err) $('.error-list')[0].innerHTML = '<li class="error-list__item"><i class="error-list__item__icon fa fa-times-circle"></i><p class="error-list__item__text">' + err.response.data.message + '</p></li>'; }) } }) }); }, 100); /*********************/ /** Settings **/ /*********************/ crossroads.addRoute('/settings', function () { axios.get('/users/' + session.id) .then(function (data) { var user = data.data $('.sidebar').load('sidebar/logged_in.html'); $('.content').load('content/settings.html', function () { if (!session.authenticated) { console.info('How dare you access this page without authenticating, i will have to redirect you!'); return navigateTo('login', 'Login'); } $('#first_name')[0].value = user.firstname; $('#last_name')[0].value = user.lastname; $('#username')[0].value = user.username; $('#email')[0].value = user.email; $('#teamspeak')[0].value = user.teamspeak; $('#discord')[0].value = user.discord; $('#description')[0].value = user.description; $('#user_id')[0].value = user.id; $("#previewAvatar").attr("src", user.avatar); $("#avatar")[0].value = user.avatar; }); }) }, 100); /*********************/ /** Games **/ /*********************/ crossroads.addRoute('/games', function () { $('.sidebar').load(session.authenticated ? 'sidebar/logged_in.html' : 'sidebar/not_logged_in.html'); $('.content').load('content/games.html'); }, 100); /*********************/ /** Users **/ /*********************/ crossroads.addRoute('/users', function () { $('.sidebar').load(session.authenticated ? 'sidebar/logged_in.html' : 'sidebar/not_logged_in.html'); $('.content').load('content/users.html'); }, 100); /*********************/ /** Username **/ /*********************/ crossroads.addRoute('/{username}', function (username) { axios.get('/users?username=' + username).then(function (data) { var user = data.data[0] // HACK : THIS SHOULD CHANGE... window.profileUser = user $('.sidebar').load(session.authenticated ? 'sidebar/logged_in.html' : 'sidebar/not_logged_in.html'); $('.content').load('content/profile.html', function () { $('#username').text(user.username); $('#fullname').text(user.firstname) + ' ' + user.lastname; $('#email').text(user.email); $('#teamspeak').text(user.teamspeak); $('#discord').text(user.discord); $('#description').text(user.description); $('#level').text(user.level); $("#previewAvatar").attr("src", user.avatar); }); }) }, 1); /***************************************/ /*** Events ***/ /***************************************/ $('body').on('click', 'a', function (e) { var urlPath = $(this).attr('href'); e.preventDefault(); var title = $(this).text(); return History.pushState({ urlPath: urlPath }, title, urlPath); }); /***************************************/ /*** History ***/ /***************************************/ var History, State; History = window.History; if (History.enabled) { State = History.getState(); History.pushState({ urlPath: window.location.pathname }, $('title').text(), State.urlPath); } History.Adapter.bind(window, 'statechange', function () { return crossroads.parse(document.location.pathname); }) window.navigateTo = function navigateTo(urlPath, title = 'GameNation') { if (title) title = title + ' | GameNation' History.pushState({ urlPath: urlPath }, title, urlPath) } crossroads.parse(document.location.pathname); });
JavaScript
0.000002
@@ -2036,38 +2036,187 @@ -navigateTo(username, username) +axios.get('/users?username=' + username).then(function (data) %7B%0A navigateTo(username, data.data%5B0%5D.username)%0A %7D)%0A %0A
768765f6c85a108df658687aeede2e27c54cd2e3
html/js/shared
src/model/immutable/ContentBlockNode.js
src/model/immutable/ContentBlockNode.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 * @emails oncall+draft_js * * This file is a fork of ContentBlock adding support for nesting references by * providing links to children, parent, prevSibling, and nextSibling. * * This is unstable and not part of the public API and should not be used by * production systems. This file may be update/removed without notice. */ 'use strict'; import type {BlockNode, BlockNodeConfig, BlockNodeKey} from 'BlockNode'; import type {DraftBlockType} from 'DraftBlockType'; import type {DraftInlineStyle} from 'DraftInlineStyle'; const CharacterMetadata = require('CharacterMetadata'); const findRangesImmutable = require('findRangesImmutable'); const Immutable = require('immutable'); const {List, Map, OrderedSet, Record, Repeat} = Immutable; type ContentBlockNodeConfig = BlockNodeConfig & { children?: List<BlockNodeKey>, parent?: ?BlockNodeKey, prevSibling?: ?BlockNodeKey, nextSibling?: ?BlockNodeKey, }; const EMPTY_SET = OrderedSet(); const defaultRecord: ContentBlockNodeConfig = { parent: null, characterList: List(), data: Map(), depth: 0, key: '', text: '', type: 'unstyled', children: List(), prevSibling: null, nextSibling: null, }; const haveEqualStyle = ( charA: CharacterMetadata, charB: CharacterMetadata, ): boolean => charA.getStyle() === charB.getStyle(); const haveEqualEntity = ( charA: CharacterMetadata, charB: CharacterMetadata, ): boolean => charA.getEntity() === charB.getEntity(); const decorateCharacterList = ( config: ContentBlockNodeConfig, ): ContentBlockNodeConfig => { if (!config) { return config; } const {characterList, text} = config; if (text && !characterList) { config.characterList = List(Repeat(CharacterMetadata.EMPTY, text.length)); } return config; }; class ContentBlockNode extends Record(defaultRecord) implements BlockNode { constructor(props: ContentBlockNodeConfig = defaultRecord) { super(decorateCharacterList(props)); } getKey(): BlockNodeKey { return this.get('key'); } getType(): DraftBlockType { return this.get('type'); } getText(): string { return this.get('text'); } getCharacterList(): List<CharacterMetadata> { return this.get('characterList'); } getLength(): number { return this.getText().length; } getDepth(): number { return this.get('depth'); } getData(): Map<any, any> { return this.get('data'); } getInlineStyleAt(offset: number): DraftInlineStyle { const character = this.getCharacterList().get(offset); return character ? character.getStyle() : EMPTY_SET; } getEntityAt(offset: number): ?string { const character = this.getCharacterList().get(offset); return character ? character.getEntity() : null; } getChildKeys(): List<BlockNodeKey> { return this.get('children'); } getParentKey(): ?BlockNodeKey { return this.get('parent'); } getPrevSiblingKey(): ?BlockNodeKey { return this.get('prevSibling'); } getNextSiblingKey(): ?BlockNodeKey { return this.get('nextSibling'); } findStyleRanges( filterFn: (value: CharacterMetadata) => boolean, callback: (start: number, end: number) => void, ): void { findRangesImmutable( this.getCharacterList(), haveEqualStyle, filterFn, callback, ); } findEntityRanges( filterFn: (value: CharacterMetadata) => boolean, callback: (start: number, end: number) => void, ): void { findRangesImmutable( this.getCharacterList(), haveEqualEntity, filterFn, callback, ); } } module.exports = ContentBlockNode;
JavaScript
0.999931
@@ -2005,16 +2005,17 @@ extends +( Record(d @@ -2027,16 +2027,24 @@ tRecord) +: any)%0A impleme
db64f9361392fd988349fbd954e3bd692729bb00
Make insertIntoList strict-local
src/model/transaction/insertIntoList.js
src/model/transaction/insertIntoList.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 * @emails oncall+draft_js */ 'use strict'; import type {List} from 'immutable'; /** * Maintain persistence for target list when appending and prepending. */ function insertIntoList<T>( targetList: List<T>, toInsert: List<T>, offset: number, ): List<T> { if (offset === targetList.count()) { toInsert.forEach(c => { targetList = targetList.push(c); }); } else if (offset === 0) { toInsert.reverse().forEach(c => { targetList = targetList.unshift(c); }); } else { const head = targetList.slice(0, offset); const tail = targetList.slice(offset); targetList = head.concat(toInsert, tail).toList(); } return targetList; } module.exports = insertIntoList;
JavaScript
0.000007
@@ -200,16 +200,29 @@ * @flow + strict-local %0A * @ema @@ -418,16 +418,19 @@ rgetList +Arg : List%3CT @@ -484,16 +484,50 @@ st%3CT%3E %7B%0A + let targetList = targetListArg;%0A if (of
ae7da122d7d35e1da38280f12defd65a899859a1
fix session management
src/node/hooks/express/adminsettings.js
src/node/hooks/express/adminsettings.js
var path = require('path'); var eejs = require('ep_etherpad-lite/node/eejs'); var settings = require('ep_etherpad-lite/node/utils/Settings'); var installer = require('ep_etherpad-lite/static/js/pluginfw/installer'); var hooks = require("ep_etherpad-lite/static/js/pluginfw/hooks"); var fs = require('fs'); exports.expressCreateServer = function (hook_name, args, cb) { args.app.get('/admin/settings', function(req, res) { var render_args = { settings: "", search_results: {}, errors: [] }; res.send( eejs.require("ep_etherpad-lite/templates/admin/settings.html", render_args) ); }); } exports.socketio = function (hook_name, args, cb) { var io = args.io.of("/settings"); io.on('connection', function (socket) { console.warn ("The middleware now handles auth but I'm not convinced SocketIO is being responsible enough here so this needs reviewing before hitting master"); // if (!socket.handshake.session || !socket.handshake.session.user || !socket.handshake.session.user.is_admin) return; socket.on("load", function (query) { fs.readFile('settings.json', 'utf8', function (err,data) { if (err) { return console.log(err); } else { socket.emit("settings", {results: data}); } }); }); socket.on("saveSettings", function (settings) { fs.writeFile('settings.json', settings, function (err) { if (err) throw err; socket.emit("saveprogress", "saved"); }); }); socket.on("restartServer", function () { console.log("Admin request to restart server through a socket on /admin/settings"); settings.reloadSettings(); hooks.aCallAll("restartServer", {}, function () {}); }); }); }
JavaScript
0
@@ -756,196 +756,32 @@ -console.warn (%22The middleware now handles auth but I'm not convinced SocketIO is being responsible enough here so this needs reviewing before hitting master%22);%0A // if (!socket.handshake +if (!socket.conn.request .ses @@ -792,33 +792,36 @@ %7C%7C !socket. -handshake +conn.request .session.use @@ -837,17 +837,20 @@ ket. -handshake +conn.request .ses
42fe6a5a18ecea11e264d28259622a68884cc149
switch to v1 of oath url, no idea how this could have been working before
app/services/auth.js
app/services/auth.js
import Ember from 'ember'; const { inject, computed, RSVP, Logger, Service } = Ember; function objectToQueryParameters(obj) { return Object.keys(obj).map(key => { const value = obj[key]; return `${key}=${value}`; }).join('&'); } export default Service.extend({ ajax: inject.service(), // appId: '18758f68-8cf8-4f32-8785-059d4cd2e62e', appId: 'ec744ffe-d332-454a-9f13-b9f7ebe8b249', urls: { auth: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize', grant: 'https://login.microsoftonline.com/common/oauth2/v2.0/token' }, idToken: null, accessToken: null, init() { this._super(...arguments); // this.application = new window.Msal.UserAgentApplication(this.get('appId')); }, scope: computed(function () { return [ 'Calendars.ReadWrite', 'Contacts.ReadWrite', 'User.ReadBasic.All', 'User.ReadWrite', 'Mail.ReadWrite', 'Mail.Send' ]; }), authorizationUrl: computed('urls.auth', 'scope.[]', function () { const base = this.get('urls.auth'); const data = { client_id: this.get('appId'), redirect_uri: window.location.origin, response_type: 'code', scope: this.get('scope').join(' '), nonce: 'msft', response_mode: 'fragment' }; return `${base}/?${objectToQueryParameters(data)}`; }), login() { const deferred = RSVP.defer(); const url = this.get('authorizationUrl'); const popup = window.open(url, 'auth', 'scrollbars=no,menubar=no,width=800,height=600') const interval = window.setInterval(() => { try { const search = popup.window.location.hash; // const match = search.match(/id_token=(.*)&/); const match = search.match(/code=(.*)&/); if (match && match[1]) { popup.close(); window.clearInterval(interval); this.set('idToken', match[1]); deferred.resolve(match[1]); } } catch (e) { // ignore } }, 10); this.set('loginDeferred', deferred); return deferred.promise; }, silentLogin() { const accessToken = localStorage.getItem('accessToken'); if (!accessToken) { return RSVP.reject('no access token'); } this.set('accessToken', accessToken); return this.get('ajax').request('https://graph.microsoft.com/v1.0/me/', { headers: { Authorization: `Bearer ${accessToken}` } }).then(() => { Logger.info('logged in!'); }).catch(err => { this.set('accessToken', null); return RSVP.reject(err); }); }, exchangeCodeForToken(code) { const data = { code, client_id: this.get('appId'), scope: this.get('scope').join(' '), redirect_uri: window.location.origin, grant_type: 'authorization_code', client_secret: '0EcZvAiLDGuwdwvVtczMP0M' }; return this.get('ajax').post(this.get('urls.grant'), { contentType: 'application/x-www-form-urlencoded', data }) .then(res => { if (typeof res === 'string') { res = JSON.parse(res); } this.set('accessToken', res.access_token); window.localStorage.setItem('accessToken', res.access_token); }); } });
JavaScript
0
@@ -510,21 +510,16 @@ /oauth2/ -v2.0/ authoriz @@ -590,13 +590,8 @@ th2/ -v2.0/ toke @@ -1259,38 +1259,36 @@ window.location. -origin +href ,%0A re @@ -3059,32 +3059,84 @@ s.get('appId'),%0A + resource: 'https://graph.windows.net/',%0A scop @@ -3213,14 +3213,12 @@ ion. -origin +href ,%0A @@ -3293,31 +3293,52 @@ t: ' -0EcZvAiLDGuwdwvVtczMP0M +qGPJgoQgN7ZBc8iz65SVnD8qJ5gQGHh7q3y4rF0Kn/g= '%0A
8a1f972d7d0a5f300376501deb20b2d7d51c273a
Tweak message
app/skills/stream.js
app/skills/stream.js
const Twitter = require('twitter'); class Stream { constructor(controller) { this.controller = controller; this.client = new Twitter({ consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token_key: process.env.TWITTER_ACCESS_TOKEN, access_token_secret: process.env.TWITTER_ACCESS_SECRET, }); } run() { this.controller.hears('^start streaming(.*)$', 'direct_mention', (bot, msg) => { const query = msg.match[1].trim(); if (this.stream) { bot.reply(msg, `Already streaming by "${this.stream.query}" :no_mouth:`); return; } else if (query.length < 1) { bot.reply(msg, 'No filter specified :cry:\nUsage: start streaming "Twitter search query"') return; } bot.botkit.log('Streaming Query:', query); bot.reply(msg, `OK:ok_hand: Start streaming by ${query}`); this.startStreaming(bot, msg, query); }); this.controller.hears('stop streaming', 'direct_mention', (bot, msg) => { if (this.stream) { this.stream.destroy(); bot.reply(msg, `OK:ok_hand: Stop streaming by ${this.stream.query}`); this.stream = null; } else { bot.reply(msg, 'Stream is not found :no_mouth:'); } }); this.controller.hears('status', 'direct_mention', (bot, msg) => { if (this.stream) { bot.reply(msg, `Now streaming by ${this.stream.query} :surfer:`); } else { bot.reply(msg, 'No stream :no_mouth:'); } }); } startStreaming(bot, msg, track) { this.stream = this.client.stream('statuses/filter', { track }); this.stream.query = track; this.stream.on('data', (tweet) => { bot.reply(msg, { attachments: [ this.buildTweetAttachment(tweet), ], }); }); this.stream.on('error', (error) => { bot.botkit.log('Error: Twitter Stream ', error); }); } buildTweetAttachment(tweet) { return { author_name: `${tweet.user.name} @${tweet.user.screen_name}`, author_icon: tweet.user.profile_image_url_https, author_link: `https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`, text: tweet.text, footer: 'Twitter', footer_icon: 'https://a.slack-edge.com/6e067/img/services/twitter_pixel_snapped_32.png', ts: new Date(Date.parse(tweet.created_at)).getTime() / 1000, fallback: tweet.text, callback_id: tweet.id_str, actions: [ { name: 'like', text: 'Like', type: 'button', }, { name: 'retweet', text: 'Retweet', type: 'button', }, ], }; } } module.exports = Stream;
JavaScript
0
@@ -422,16 +422,17 @@ r.hears( +%5B '%5Estart @@ -444,15 +444,40 @@ ming + %22 (.*) +%22 $', + '%5Estart streaming$'%5D, 'di @@ -521,38 +521,108 @@ cons -t query = msg.match%5B1%5D.trim(); +ole.log(msg.match)%0A const query = msg.match%5B1%5D && msg.match%5B1%5D.trim();%0A console.log(query) %0A @@ -758,16 +758,26 @@ lse if ( +!query %7C%7C query.le @@ -783,17 +783,17 @@ ength %3C -1 +0 ) %7B%0A @@ -815,22 +815,21 @@ sg, 'No -filt +qu er +y specifi @@ -1258,32 +1258,33 @@ op streaming by +%22 $%7Bthis.stream.qu @@ -1283,24 +1283,25 @@ tream.query%7D +%22 %60);%0A @@ -1546,16 +1546,17 @@ ming by +%22 $%7Bthis.s @@ -1567,16 +1567,17 @@ m.query%7D +%22 :surfer
a17368efc279b49e22ac958528358b355febe7e3
Remove debug code
app/socket-bridge.js
app/socket-bridge.js
import debugLib from 'debug'; import socketIo from 'socket.io'; var debug = debugLib('socket-bridge'); export default function socketBridge(app) { var io = socketIo(app); var ansibleIo = io.of('/ansible'); var ansibleToPython = require('./ansible'); ansibleIo.on('connection', function (socket) { console.log('Socket.io connected to socket-bridge'); debug('Socket.io connected.'); ansibleToPython.on('message', function (data) { debug('Message frame ' + Date.now()); // Send on particular msg_type channel. if (data.header != null && data.header.msg_type != null) { if (data.header.msg_type == "UPDATE_PERIPHERAL"){ console.log("test");}; if (data.header.msg_type == "UPDATE_BATTERY") { console.log("test2");}; // socket.emit(data.header.msg_type, data); var unpackedMessage = data.content; unpackedMessage.type = data.header.msg_type; socket.send(unpackedMessage); debug('Passing data to client on event ' + data.header.msg_type + ':'); } else { console.log("Didn't get correct type!"); debug("Didn't get correct type!"); } }); socket.on('message', function (data) { ansibleToPython.send(data); debug('Passing data to runtime:'); debug(data); }); }); return io; }
JavaScript
0.000299
@@ -613,189 +613,8 @@ ) %7B%0A - if (data.header.msg_type == %22UPDATE_PERIPHERAL%22)%7B%0A console.log(%22test%22);%7D;%0A if (data.header.msg_type == %22UPDATE_BATTERY%22) %7B%0A console.log(%22test2%22);%7D;%0A
834357d245f5155a031a3db36693f3e8d293905b
Revert "Select menu options on mouse down"
Source/classes/Menu.js
Source/classes/Menu.js
/** * Menu */ Garnish.Menu = Garnish.Base.extend({ settings: null, $container: null, $options: null, $trigger: null, _windowWidth: null, _windowHeight: null, _windowScrollLeft: null, _windowScrollTop: null, _triggerOffset: null, _triggerWidth: null, _triggerHeight: null, _triggerOffsetRight: null, _triggerOffsetBottom: null, _menuWidth: null, _menuHeight: null, /** * Constructor */ init: function(container, settings) { this.setSettings(settings, Garnish.Menu.defaults); this.$container = $(container); this.$options = $(); this.addOptions(this.$container.find('a')); if (this.settings.attachToElement) { this.$trigger = $(this.settings.attachToElement); } // Prevent clicking on the container from hiding the menu this.addListener(this.$container, 'mousedown', function(ev) { ev.stopPropagation(); }); }, addOptions: function($options) { this.$options = this.$options.add($options); $options.data('menu', this); this.addListener($options, 'mousedown', 'selectOption'); }, setPositionRelativeToTrigger: function() { this._windowWidth = Garnish.$win.width(); this._windowHeight = Garnish.$win.height(); this._windowScrollLeft = Garnish.$win.scrollLeft(); this._windowScrollTop = Garnish.$win.scrollTop(); this._triggerOffset = this.$trigger.offset(); this._triggerWidth = this.$trigger.outerWidth(); this._triggerHeight = this.$trigger.outerHeight(); this._triggerOffsetRight = this._triggerOffset.left + this._triggerHeight; this._triggerOffsetBottom = this._triggerOffset.top + this._triggerHeight; this.$container.css('minWidth', 0); this.$container.css('minWidth', this._triggerWidth - (this.$container.outerWidth() - this.$container.width())); this._menuWidth = this.$container.outerWidth(); this._menuHeight = this.$container.outerHeight(); // Is there room for the menu below the trigger? var topClearance = this._triggerOffset.top - this._windowScrollTop, bottomClearance = this._windowHeight + this._windowScrollTop - this._triggerOffsetBottom; if (bottomClearance >= this._menuHeight || bottomClearance >= topClearance) { this.$container.css('top', this._triggerOffsetBottom); } else { this.$container.css('top', this._triggerOffset.top - this._menuHeight); } // Figure out how we're aliging it var align = this.$container.data('align'); if (align != 'left' && align != 'center' && align != 'right') { align = 'left'; } if (align == 'center') { this._alignCenter(); } else { // Figure out which options are actually possible var rightClearance = this._windowWidth + this._windowScrollLeft - (this._triggerOffset.left + this._menuWidth), leftClearance = this._triggerOffsetRight - this._menuWidth; if (align == 'right' && leftClearance >= 0 || rightClearance < 0) { this._alignRight(); } else { this._alignLeft(); } } delete this._windowWidth; delete this._windowHeight; delete this._windowScrollLeft; delete this._windowScrollTop; delete this._triggerOffset; delete this._triggerWidth; delete this._triggerHeight; delete this._triggerOffsetRight; delete this._triggerOffsetBottom; delete this._menuWidth; delete this._menuHeight; }, show: function() { // Move the menu to the end of the DOM this.$container.appendTo(Garnish.$bod) if (this.$trigger) { this.setPositionRelativeToTrigger(); } this.$container.velocity('stop'); this.$container.css({ opacity: 1, display: 'block' }); Garnish.escManager.register(this, 'hide'); }, hide: function() { this.$container.velocity('fadeOut', { duration: Garnish.FX_DURATION }, $.proxy(function() { this.$container.detach(); }, this)); Garnish.escManager.unregister(this); this.trigger('hide'); }, selectOption: function(ev) { this.settings.onOptionSelect(ev.currentTarget); this.trigger('optionselect', { selectedOption: ev.currentTarget }); this.hide(); }, _alignLeft: function() { this.$container.css({ left: this._triggerOffset.left, right: 'auto' }); }, _alignRight: function() { this.$container.css({ right: this._windowWidth - (this._triggerOffset.left + this._triggerWidth), left: 'auto' }); }, _alignCenter: function() { var left = Math.round((this._triggerOffset.left + this._triggerWidth / 2) - (this._menuWidth / 2)); if (left < 0) { left = 0; } this.$container.css('left', left); } }, { defaults: { attachToElement: null, onOptionSelect: $.noop } });
JavaScript
0
@@ -1008,25 +1008,21 @@ tions, ' -mousedown +click ', 'sele
3e04888ca631121900153f84acfe8575c9bde03f
Remove left-behind console log
src/components/popover/Popover.js
src/components/popover/Popover.js
import React, { PureComponent } from 'react'; import { createPortal } from 'react-dom'; import PropTypes from 'prop-types'; import cx from 'classnames'; import throttle from 'lodash.throttle'; import InjectOverlay from '../overlay'; import Transition from 'react-transition-group/Transition'; import ReactResizeDetector from 'react-resize-detector'; import { events } from '../utils'; import { calculatePositions } from './positionCalculation'; import ScrollContainer from '../scrollContainer'; import Box from '../box'; import theme from './theme.css'; const MAX_HEIGHT_DEFAULT = 240; class Popover extends PureComponent { popoverRoot = document.createElement('div'); state = { positioning: { left: 0, top: 0, arrowLeft: 0, arrowTop: 0, maxHeight: 'initial' } }; componentDidMount() { document.body.appendChild(this.popoverRoot); events.addEventsToWindow({ resize: this.setPlacementThrottled, scroll: this.setPlacementThrottled }); } componentWillUnmount() { events.removeEventsFromWindow({ resize: this.setPlacementThrottled, scroll: this.setPlacementThrottled }); document.body.removeChild(this.popoverRoot); } componentDidUpdate(prevProps) { if (this.props.active && prevProps !== this.props) { this.setPlacement(); } } setPlacement = () => { const { anchorEl, direction, position, offsetCorrection } = this.props; if (this.popoverNode) { this.setState({ positioning: calculatePositions(anchorEl, this.popoverNode, direction, position, offsetCorrection), }); } }; getMaxHeight = () => { const { fullHeight } = this.props; const { maxHeight } = this.state.positioning; console.log(maxHeight); if (!fullHeight && maxHeight > MAX_HEIGHT_DEFAULT) { return MAX_HEIGHT_DEFAULT; } return maxHeight; }; setPlacementThrottled = throttle(this.setPlacement, 250); render() { const { left, top, arrowLeft, arrowTop } = this.state.positioning; const { active, backdrop, children, className, color, footer, header, lockScroll, onOverlayClick, onEscKeyDown, onOverlayMouseDown, onOverlayMouseMove, onOverlayMouseUp, tint, } = this.props; if (!active) { return null; } const popover = ( <Transition timeout={0} in={active} appear> {state => { return ( <div className={cx(theme['wrapper'], theme[color], theme[tint], { [theme['is-entering']]: state === 'entering', [theme['is-entered']]: state === 'entered', })} > <InjectOverlay active={active} backdrop={backdrop} className={theme['overlay']} lockScroll={lockScroll} onClick={onOverlayClick} onEscKeyDown={onEscKeyDown} onMouseDown={onOverlayMouseDown} onMouseMove={onOverlayMouseMove} onMouseUp={onOverlayMouseUp} /> <div data-teamleader-ui={'popover'} className={cx(theme['popover'], className)} style={{ left: `${left}px`, top: `${top}px` }} ref={node => { this.popoverNode = node; }} > <div className={theme['arrow']} style={{ left: `${arrowLeft}px`, top: `${arrowTop}px` }} /> <Box display="flex"> <ScrollContainer className={theme['inner']} header={header} body={children} footer={footer} style={{ maxHeight: this.getMaxHeight() }} /> </Box> <ReactResizeDetector handleHeight handleWidth onResize={this.setPlacement} refreshMode="throttle" refreshRate={250} /> </div> </div> ); }} </Transition> ); return createPortal(popover, this.popoverRoot); } } Popover.propTypes = { /** The state of the Popover, when true the Popover is rendered otherwise it is not. */ active: PropTypes.bool, /** The Popovers anchor element. */ anchorEl: PropTypes.object, /** The background colour of the Overlay. */ backdrop: PropTypes.string, /** The component wrapped by the Popover. */ children: PropTypes.node, /** The class names for the wrapper to apply custom styling. */ className: PropTypes.string, /** The background colour of the Popover. */ color: PropTypes.oneOf(['aqua', 'gold', 'mint', 'neutral', 'ruby', 'teal', 'violet']), /** The direction in which the Popover is rendered, is overridden with the opposite direction if the Popover cannot be entirely displayed in the current direction. */ direction: PropTypes.oneOf(['north', 'south', 'east', 'west']), /** Node to render as the footer */ footer: PropTypes.node, /** Node to render as the header */ header: PropTypes.node, /** If true, the Popover stretches to fit its content vertically */ fullHeight: PropTypes.bool, /** The scroll state of the body, if true it will not be scrollable. */ lockScroll: PropTypes.bool, /** The amount of extra translation on the Popover (has no effect if position is "middle" or "center"). */ offsetCorrection: PropTypes.number, /** The function executed, when the "ESC" key is down. */ onEscKeyDown: PropTypes.func, /** The function executed, when the Overlay is clicked. */ onOverlayClick: PropTypes.func, /** The function executed, when the mouse is down on the Overlay. */ onOverlayMouseDown: PropTypes.func, /** The function executed, when the mouse is being moved over the Overlay. */ onOverlayMouseMove: PropTypes.func, /** The function executed, when the mouse is up on the Overlay. */ onOverlayMouseUp: PropTypes.func, /** The position in which the Popover is rendered, is overridden with the another position if the Popover cannot be entirely displayed in the current position. */ position: PropTypes.oneOf(['start', 'center', 'end']), /** The tint of the background colour of the Popover. */ tint: PropTypes.oneOf(['lightest', 'light', 'normal', 'dark', 'darkest']), }; Popover.defaultProps = { active: true, backdrop: 'dark', direction: 'south', fullHeight: true, color: 'neutral', lockScroll: true, offsetCorrection: 0, position: 'center', tint: 'lightest', }; export default Popover;
JavaScript
0
@@ -1671,37 +1671,8 @@ g;%0A%0A - console.log(maxHeight);%0A%0A
4160ffe7c23ec4488749a0965b95a96359247348
Remove display style instead of using inline-block for editing
opentreemap/treemap/js/src/inlineEditForm.js
opentreemap/treemap/js/src/inlineEditForm.js
"use strict"; var $ = require('jquery'); var Bacon = require('baconjs'); var _ = require('underscore'); var FH = require('./fieldHelpers'); // Requiring this module handles wiring up the browserified // baconjs to jQuery require('./baconUtils'); exports.init = function(options) { var updateUrl = options.updateUrl, form = options.form, edit = options.edit, save = options.save, cancel = options.cancel, displayFields = options.displayFields, editFields = options.editFields, validationFields = options.validationFields, editStream = $(edit).asEventStream('click').map('edit:start'), saveStream = $(save).asEventStream('click').map('save:start'), cancelStream = $(cancel).asEventStream('click').map('cancel'), actionStream = new Bacon.Bus(), actionToCssDisplay = function(actions, action) { return _.contains(actions, action) ? 'inline-block' : 'none'; }, actionToEditFieldCssDisplay = _.partial(actionToCssDisplay, ['edit:start', 'save:start', 'save:error']), actionToDisplayFieldCssDisplay = _.partial(actionToCssDisplay, ['idle', 'save:ok', 'cancel']), actionToValidationErrorCssDisplay = _.partial(actionToCssDisplay, ['save:error']), displayValuesToFormFields = function() { $(displayFields).each(function(index, el){ var field = $(el).attr('data-field'); var value = $(el).attr('data-value'); var input; if (field) { input = FH.getField($(editFields), field).find('input'); $(input).val(value); } }); }, formFieldsToDisplayValues = function() { $(editFields).each(function(index, el){ var field = $(el).attr('data-field'); var input, value, display; if (field) { input = FH.getField($(editFields), field).find('input'); value = input.val(); display = FH.getField($(displayFields), field); $(display).attr('data-value', value); $(display).html(value); } }); }, update = function(data) { return Bacon.fromPromise($.ajax({ url: updateUrl, type: 'PUT', contentType: "application/json", data: JSON.stringify(data) })); }, showValidationErrorsInline = function (errors) { _.each(errors, function (errorList, fieldName) { FH.getField($(validationFields), fieldName) .html(errorList.join(',')); }); }, isEditStart = function (action) { return action === 'edit:start'; }, responseStream = saveStream .map(FH.formToDictionary, $(form), $(editFields)) .flatMap(update) .mapError(function (e) { return e.responseJSON; }); responseStream.filter('.ok') .onValue(formFieldsToDisplayValues); responseStream.filter('.error') .map('.validationErrors') .onValue(showValidationErrorsInline); // TODO: Show success toast // TODO: Show error toast // TODO: Keep the details of showing toast out of // this module (use EventEmitter or callbacks) actionStream.plug(editStream); actionStream.plug(saveStream); actionStream.plug(cancelStream); actionStream.plug( responseStream.filter('.error').map('save:error') ); actionStream.plug( responseStream.filter('.ok').map('save:ok') ); actionStream.filter(isEditStart).onValue(displayValuesToFormFields); actionStream.map(actionToDisplayFieldCssDisplay) .toProperty('inline-block') .assign($(displayFields), "css", "display"); actionStream.map(actionToEditFieldCssDisplay) .toProperty('none') .assign($(editFields), "css", "display"); actionStream.map(actionToValidationErrorCssDisplay) .toProperty('none') .assign($(validationFields), "css", "display"); };
JavaScript
0
@@ -939,28 +939,16 @@ ion) ? ' -inline-block ' : 'non @@ -1022,33 +1022,32 @@ ionToCssDisplay, - %0A %5B'e @@ -1151,33 +1151,32 @@ ionToCssDisplay, - %0A %5B'i @@ -1278,17 +1278,16 @@ Display, - %0A @@ -1403,32 +1403,33 @@ ction(index, el) + %7B%0A @@ -2919,17 +2919,16 @@ %7D, - %0A%0A @@ -3981,20 +3981,8 @@ ty(' -inline-block ')%0A
7e668e1cb853a528c2bb2559fba18d06c996de37
Add files via upload (#9588)
editor/js/Menubar.View.js
editor/js/Menubar.View.js
/** * @author mrdoob / http://mrdoob.com/ */ Menubar.View = function ( editor ) { var container = new UI.Panel(); container.setClass( 'menu' ); var title = new UI.Panel(); title.setClass( 'title' ); title.setTextContent( 'View' ); container.add( title ); var options = new UI.Panel(); options.setClass( 'options' ); container.add( options ); // VR mode var option = new UI.Row(); option.setClass( 'option' ); option.setTextContent( 'VR mode' ); option.onClick( function () { if ( WEBVR.isAvailable() === true ) { editor.signals.enterVR.dispatch(); } else { alert( 'WebVR nor available' ); } } ); options.add( option ); return container; };
JavaScript
0
@@ -602,17 +602,17 @@ WebVR no -r +t availab
617e73ffb327f9ed5cb1043e5d3969eacdca261f
Remove isAuthenticated check from updateUser for now. This branch doesn't yet allow proper login, and this needs to be taken out for tests to pass.
src/controllers/userController.js
src/controllers/userController.js
'use strict'; /** * The controller for the user API * * * @module userController * @license MIT * @author yamikuronue */ /*Express typedefs*/ /** @typedef Request @type {object} @property {object} params - The parameters for the request / /** @typedef Response @type {object} @function send - The function to send data to the client @function status - Set the status code for the response */ const User = require('../model/User'); const debug = require('debug')('SockRPG:controller:User'); /** * Get all users in the system * @param {Request} _ Express' request object. Expects an ID under the params key * @param {Response} res Express' response object. * @returns {Promise} A promise that will resolve when the response has been sent. */ function getAllUsers(_, res) { return User.getAllUsers().then((data) => { res.send(data.map((user) => user.serialize())); }).catch((err) => { debug(`Error Retrieving Users: ${err.toString()}`); //TODO: Add Proper Logging res.status(500).send({error: err.toString()}); }); } /** * Get a single user. * @param {Request} req Express' request object. Expects an ID under the params key * @param {Response} res Express' response object. * @returns {Promise} A promise that will resolve when the response has been sent. */ function getUser(req, res) { const handleData = (user) => { if (Array.isArray(user)) { user = user[0]; //Only the first user } if (!user) { res.status(404); return; } res.send(user.serialize()); }; const handleError = (err) => { debug(`Error Retrieving User: ${err.toString()}`); //TODO: Add Proper Logging res.status(500).send({error: err.toString()}); }; //Check if the ID is a number if (Number.parseInt(req.params.id, 10) == req.params.id) { //eslint-disable-line eqeqeq return User.getUser(req.params.id).then(handleData).catch(handleError); //Otherwise it's a name } else if (req.params.id) { return User.getUserByName(req.params.id).then(handleData).catch(handleError); } //Fallthrough if we did neither: res.status(501).send({error: 'Missing ID'}); return Promise.resolve(); } /** * Add a user to the collection. * @param {Request} req Express' request object. Expects a body with a name parameter * @param {Response} res Express' response object. * @returns {Promise} A promise that will resolve when the response has been sent. */ function addUser(req, res) { return User.addUser(req.body).then((index) => { res.status(200).send({id: index[0]}).end(); }).catch((err) => { debug(`Error Adding User: ${err.toString()}`); //TODO: Add Proper Logging res.status(500).send({error: err.toString()}); }); } /** * Update a user * @param {Request} req Express' request object. Expects a body with data and an ID under the params key * @param {Response} res Express' response object. * @returns {Promise} A promise that will resolve when the response has been sent. */ function updateUser(req, res) { if (!req.isAuthenticated()) { res.status(401).end(); return null; } return User.getUser(req.params.id).then((user) => { user.Username = req.body.Username || user.Username; return user.save(); }).then(() => { res.status(200).end(); }).catch((err) => { debug(`Error Updating User: ${err.toString()}`); //TODO: Add Proper Logging // TODO: Remove switching on string in favor of better method if (err.toString().indexOf('No such') > -1) { res.status(404).send({error: err.toString()}); } else { res.status(500).send({error: err.toString()}); } }); } const controller = { getAllUsers: getAllUsers, getUser: getUser, addUser: addUser, updateUser: updateUser }; module.exports = controller;
JavaScript
0
@@ -2973,83 +2973,8 @@ ) %7B%0A -%09if (!req.isAuthenticated()) %7B%0A%09%09res.status(401).end();%0A%09%09return null;%0A%09%7D%0A%09 %0A%09re
759ebf6dbb2477aef1227fcc03c413cf19012529
remove waiting cursor after loading project
src/modules/savesettings/savesettings-directive.js
src/modules/savesettings/savesettings-directive.js
import './module.js'; angular.module('anol.savesettings') .directive('anolSavesettings', ['$templateRequest', '$compile', 'SaveSettingsService', 'ProjectSettings', 'NotificationService', function($templateRequest, $compile, SaveSettingsService, ProjectSettings, NotificationService) { return { restrict: 'A', template: function(tElement, tAttrs) { if (tAttrs.templateUrl) { return '<div></div>'; } return require('./templates/savemanager.html'); }, scope: { modalCallBack:'&' }, link: function(scope, element, attrs) { if (attrs.templateUrl && attrs.templateUrl !== '') { $templateRequest(attrs.templateUrl).then(function(html){ var template = angular.element(html); element.html(template); $compile(template)(scope); }); } var pageBody = angular.element(document).find('body'); scope.addWaiting = function() { pageBody.addClass('waiting'); }; scope.removeWaiting = function() { pageBody.removeClass('waiting'); }; scope.projectSettings = ProjectSettings; scope.close = function() { scope.modalCallBack(); }; scope.delete = function(id) { scope.addWaiting(); SaveSettingsService.delete(id).then(function(data) { NotificationService.addInfo(data.message); scope.removeWaiting(); }, function(data) { NotificationService.addError(data.message); scope.removeWaiting(); }); }; scope.save = function(name) { // load project name to overwrite if (angular.isUndefined(name) || scope.id) { angular.forEach(scope.projectSettings, function(value) { if (value.id == scope.id) { name = value.name; } }); } if (angular.isUndefined(name) || name == '') { return; } scope.addWaiting(); SaveSettingsService.save(name).then(function(data) { scope.modalCallBack(); NotificationService.addInfo(data.message); scope.removeWaiting(); }, function(data) { NotificationService.addError(data.message); scope.removeWaiting(); }); }; scope.load = function(id) { if (angular.isUndefined(id)) { return; } scope.addWaiting(); SaveSettingsService.load(id).then(function(data) { scope.modalCallBack(); NotificationService.addInfo(data.message); }, function(data) { NotificationService.addError(data.message); scope.removeWaiting(); }); }; } }; }]);
JavaScript
0.000001
@@ -3683,32 +3683,176 @@ (data.message);%0A + setTimeout(function() %7B%0A scope.removeWaiting();%0A %7D, 250);%0A
87a8540a4a85974b8bdf0a9fe0881f585894a111
set float to fixed if mobile
src/controls/CloseWindowButton.js
src/controls/CloseWindowButton.js
import $ from 'jquery' import { Control } from 'guide4you/src/controls/Control' import '../../less/closewindowbutton.less' /** * @typedef {g4uControlOptions} CloseWindowButtonOptions * @property {string} [label] */ /** * Close the window. This only works if the window was opened by javascript. */ export class CloseWindowButton extends Control { /** * @param {g4uControlOptions} options */ constructor (options = {}) { options.className = options.className || 'g4u-close-window-button' options.element = $('<div>')[0] super(options) /** * @type {string} * @private */ this.label_ = ('label' in options) ? this.getLocaliser().selectL10N(options.label) : this.getLocaliser().localiseUsingDictionary('CloseWindowButton label') let $button = $('<button>') .html(this.label_) .on('click', () => { window.close() }) this.get$Element().append($button) } }
JavaScript
0.000003
@@ -946,11 +946,141 @@ ton)%0A %7D +%0A%0A getFloat () %7B%0A if (this.getMap().get('mobile')) %7B%0A return 'fixed'%0A %7D else %7B%0A return super.getFloat()%0A %7D%0A %7D %0A%7D%0A
678da73aafaeebe40023c8202443094d86c8141f
Clean up unused vars
src/controls/trackpad-controls.js
src/controls/trackpad-controls.js
/** * 3dof (Gear VR, Daydream) controls for mobile. */ module.exports = AFRAME.registerComponent('trackpad-controls', { schema: { enabled: { default: true } }, init: function () { this.dVelocity = new THREE.Vector3(); this.zVel = 0; this.bindMethods(); }, play: function () { this.addEventListeners(); }, pause: function () { this.removeEventListeners(); this.dVelocity.set(0, 0, 0); }, remove: function () { this.pause(); }, addEventListeners: function () { const sceneEl = this.el.sceneEl; sceneEl.addEventListener('axismove', this.onAxisMove); sceneEl.addEventListener('trackpadtouchstart', this.onTouchStart); sceneEl.addEventListener('trackpadtouchend', this.onTouchEnd); }, removeEventListeners: function () { const sceneEl = this.el.sceneEl; sceneEl.removeEventListener('axismove', this.onAxisMove); sceneEl.removeEventListener('trackpadtouchstart', this.onTouchStart); sceneEl.removeEventListener('trackpadtouchend', this.onTouchEnd); }, isVelocityActive: function () { return this.data.enabled && this.isMoving; }, getVelocityDelta: function () { this.dVelocity.z = this.isMoving ? -this.zVel : 1; this.dVelocity.x = this.isMoving ? this.xVel : 1; return this.dVelocity.clone(); }, bindMethods: function () { this.onTouchStart = this.onTouchStart.bind(this); this.onTouchEnd = this.onTouchEnd.bind(this); this.onAxisMove = this.onAxisMove.bind(this); }, onTouchStart: function (e) { this.startingAxisData = []; e.preventDefault(); }, onTouchEnd: function (e) { this.startingAxisData = []; this.isMoving = false; e.preventDefault(); }, onAxisMove: function(e){ var axis_data = e.detail.axis; if(this.startingAxisData.length === 0){ this.startingAxisData[0] = axis_data[0] this.startingAxisData[1] = axis_data[1] } if(this.startingAxisData.length > 0){ var movingLeft = this.startingAxisData[0] > 0 && axis_data[0] < 0 var movingRight = this.startingAxisData[0] < 0 && axis_data[0] > 0 var movingForward = this.startingAxisData[1] > 0 && axis_data[1] < 0 var movingBackward = this.startingAxisData[1] < 0 && axis_data[1] > 0 var velX = axis_data[0] < this.startingAxisData[0] ? -1 : 1 var velZ = axis_data[1] < this.startingAxisData[1] ? 1 : -1 var absChangeZ = Math.abs(this.startingAxisData[1] - axis_data[1]) var absChangeX = Math.abs(this.startingAxisData[0] - axis_data[0]) if(absChangeZ > absChangeX) { this.xVel = 0; this.zVel = velZ; this.isMoving = true; }else{ this.zVel = 0; this.xVel = velX this.isMoving = true; } } } });
JavaScript
0.000001
@@ -1973,313 +1973,8 @@ 0)%7B%0A - var movingLeft = this.startingAxisData%5B0%5D %3E 0 && axis_data%5B0%5D %3C 0%0A var movingRight = this.startingAxisData%5B0%5D %3C 0 && axis_data%5B0%5D %3E 0%0A var movingForward = this.startingAxisData%5B1%5D %3E 0 && axis_data%5B1%5D %3C 0%0A var movingBackward = this.startingAxisData%5B1%5D %3C 0 && axis_data%5B1%5D %3E 0%0A%0A @@ -2102,17 +2102,16 @@ 1 : -1%0A%0A -%0A va
f04880a5d775c25c85b9c84eb63fad553dd6f9bc
Make datepicker update view after clearing selection
src/openlmis-form/openlmis-datepicker.directive.js
src/openlmis-form/openlmis-datepicker.directive.js
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  * See the GNU Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ (function() { 'use strict'; /** * @ngdoc directive * @restrict E * @name openlmis-form.directive:openlmisDatepicker * * @description * Directive allows to add date picker input. * * @example * To make this directive work only 'value' attribute is required, however there are more attributes to use. * In order to make datepicker input use id you can add 'input-id' attribute. * The 'change-method' attribute takes function that will be executed after datepicker value change. * Datepicker directive also can take max-date and min-date attributes. Their values can be set from other datepickers or manually. * ``` * <openlmis-datepicker * value="startDate" * input-id="datepicker-id" * change-method="afterChange()" * min-date="10/05/2016" * max-date="endDate"> * </openlmis-datepicker> * * <openlmis-datepicker * value="endDate"> * </openlmis-datepicker> * ``` */ angular .module('openlmis-form') .directive('openlmisDatepicker', datepicker); datepicker.$inject = ['$filter']; function datepicker($filter) { return { restrict: 'E', scope: { value: '=', inputId: '@?', minDate: '=?', maxDate: '=?', changeMethod: '=?', dateFormat: '=?' }, templateUrl: 'openlmis-form/openlmis-datepicker.html', controller: 'OpenlmisDatepickerController', controllerAs: 'vm', link: link }; function link(scope, element, attrs) { scope.$watch('value', function() { scope.dateString = $filter('openlmisDate')(scope.value); }); scope.clearSelection = function() { scope.value = undefined; scope.closePopover(); }; } } })();
JavaScript
0
@@ -1987,16 +1987,29 @@ $filter' +, '$document' %5D;%0A%0A%09fun @@ -2032,16 +2032,27 @@ ($filter +, $document ) %7B%0A @@ -2547,15 +2547,8 @@ ment -, attrs ) %7B%0A @@ -2774,16 +2774,562 @@ efined;%0A +%0A //This is to unselect value from datepicker view%0A //(Workaround for angular-strap bug - view isn't updated when value is undefined)%0A var primaryButtons = $document%5B0%5D.querySelectorAll('.btn-primary');%0A primaryButtons.forEach(function (button) %7B%0A var buttonElement = angular.element(button);%0A if (buttonElement.hasClass('btn-default')) %7B%0A buttonElement.removeClass('btn-primary');%0A %7D%0A %7D);%0A%0A
c1447d8991f7fda2b2d3b515e47cb595d841db7b
add host_tags support to default template data
src/util/lib/cosi/registration/setup/index.js
src/util/lib/cosi/registration/setup/index.js
"use strict"; /*eslint-env node, es6 */ /*eslint-disable no-magic-numbers, global-require, camelcase */ const assert = require("assert"); const fs = require("fs"); const os = require("os"); const path = require("path"); const url = require("url"); const api = require("circonusapi2"); const chalk = require("chalk"); const cosi = require(path.resolve(path.resolve(__dirname, "..", "..", "..", "cosi"))); const Broker = require(path.join(cosi.lib_dir, "broker")); const Metrics = require(path.join(cosi.lib_dir, "metrics")); const Registration = require(path.resolve(cosi.lib_dir, "registration")); const TemplateFetcher = require(path.join(cosi.lib_dir, "template", "fetch")); class Setup extends Registration { constructor(quiet) { super(quiet); this.regConfig = { broker: null, account: null, metricsFile: path.join(this.regDir, "setup-metrics.json"), cosiTags: [ "cosi:install", `distro:${this.cosiAPI.args.dist}-${this.cosiAPI.args.vers}`, `arch:${this.cosiAPI.args.arch}`, `os:${this.cosiAPI.args.type}` ], cosiNotes: `cosi:register,cosi_id:${this.cosiId}`, templateData: { host_name: this.customOptions.host_name ? this.customOptions.host_name : os.hostname(), host_target: this.customOptions.host_target ? this.customOptions.host_target : this._getDefaultHostIp(), host_vars: this.customOptions.host_vars ? this.customOptions.host_vars : {} } }; this.regConfig.templateData.host_vars.num_cpus = os.cpus().length; this.metricGroups = []; } setup() { console.log(chalk.bold("Registration Setup")); const self = this; this.once("verify.api", this.verifyCirconusAPI); this.once("verify.api.done", () => { self.emit("metrics.fetch"); }); this.once("metrics.fetch", this.fetchNADMetrics); this.once("metrics.fetch.save", this.saveMetrics); this.once("metrics.fetch.done", () => { self.emit("templates.fetch"); }); this.once("templates.fetch", this.fetchTemplates); this.once("templates.fetch.done", () => { self.emit("verify.broker"); }); this.once("verify.broker", this.verifyBroker); this.once("verify.broker.done", () => { self.emit("save.config"); }); this.once("save.config", this.saveRegConfig); this.emit("verify.api"); } verifyCirconusAPI() { console.log(chalk.blue(this.marker)); console.log("Verify Circonus API access"); const self = this; const apiKey = this.circonusAPI.key; const apiApp = this.circonusAPI.app; const apiURL = url.parse(this.circonusAPI.url); api.setup(apiKey, apiApp, apiURL); api.get("/account/current", null, (code, err, account) => { if (err) { self.emit("error", err); return; } if (code !== 200) { self.emit("error", new Error(`verifyAPI - API return code: ${code} ${err} ${account}`)); } console.log(chalk.green("API key verified"), "for account", account.name, account.description === null ? "" : `- ${account.description}`); let accountUrl = account._ui_base_url || "your_account_url"; if (accountUrl.substr(-1) === "/") { accountUrl = accountUrl.substr(0, accountUrl.length - 1); } self.regConfig.account = { name: account.name, uiUrl: accountUrl }; self.emit("verify.api.done"); }); } fetchNADMetrics() { console.log(chalk.blue(this.marker)); console.log("Fetch available metrics from NAD"); const self = this; const metrics = new Metrics(this.agentUrl); metrics.load((err) => { if (err) { self.emit("error", err); return; } console.log(chalk.green("Metrics loaded")); metrics.getMetricStats((metricStatsError, stats) => { if (metricStatsError) { self.emit("error", metricStatsError); } let totalMetrics = 0; for (const group in stats) { if (stats.hasOwnProperty(group)) { console.log(`\t ${group} has ${stats[group]} metrics`); totalMetrics += stats[group]; } } console.log(`Total metrics: ${totalMetrics}`); this.emit("metrics.fetch.save", metrics); }); }); } saveMetrics(metrics) { assert.equal(typeof metrics, "object", "metrics is required"); console.log("Saving available metrics"); const self = this; metrics.getMetrics((metricsError, agentMetrics) => { if (metricsError) { self.emit("error", metricsError); return; } fs.writeFile( self.regConfig.metricsFile, JSON.stringify(agentMetrics, null, 4), { encoding: "utf8", mode: 0o644, flag: "w" }, (saveError) => { if (saveError) { self.emit("error", saveError); return; } console.log(chalk.green("Metrics saved", self.regConfig.metricsFile)); self.emit("metrics.fetch.done"); } ); }); } fetchTemplates() { console.log(chalk.blue(this.marker)); console.log("Fetching templates"); const self = this; // DO NOT force in register, if templates have been provisioned, use them const templateFetch = new TemplateFetcher(false); templateFetch.all(this.quiet, (err, result) => { console.log(`Checked ${result.attempts}, fetched ${result.fetched}, errors ${result.error}`); if (err) { self.emit("error", err); return; } self.emit("templates.fetch.done"); }); } verifyBroker() { console.log(chalk.blue(this.marker)); console.log("Verify Circonus broker"); const self = this; const broker = new Broker(this.quiet); broker.getDefaultBroker((err, defaultBroker) => { if (err) { self.emit("error", err); return; } self.regConfig.broker = defaultBroker; self.emit("verify.broker.done"); }); } saveRegConfig() { console.log(chalk.blue(this.marker)); console.log("Save registration configuration"); const self = this; fs.writeFile( self.regConfigFile, JSON.stringify(this.regConfig, null, 4), { encoding: "utf8", mode: 0o644, flag: "w" }, (saveError) => { if (saveError) { self.emit("error", saveError); return; } console.log(chalk.green("Registration configuration saved", self.regConfigFile)); self.emit("setup.done"); this.emit("metrics.fetch.done"); } ); } _getDefaultHostIp() { const networkInterfaces = os.networkInterfaces(); for (const iface in networkInterfaces) { if (networkInterfaces.hasOwnProperty(iface)) { // for (const addr of networkInterfaces[iface]) { for (let i = 0; i < networkInterfaces[iface].length; i++) { const addr = networkInterfaces[iface][i]; if (!addr.internal && addr.family === "IPv4") { return addr.address; } } } } return "0.0.0.0"; } } module.exports = Setup;
JavaScript
0
@@ -1563,16 +1563,109 @@ ars : %7B%7D +,%0A host_tags: this.customOptions.host_tags ? this.customOptions.host_tags : %5B%5D %0A
8847f2db68ce91d4f85951573a3a9532a9d36746
Reset steps to increase smoothness
src/widgets/time-series/torque-header-view.js
src/widgets/time-series/torque-header-view.js
var cdb = require('cartodb.js'); var TorqueControlsView = require('./torque-controls-view'); var TorqueTimeInfoView = require('./torque-time-info-view'); var TimeSeriesHeaderView = require('./time-series-header-view'); var template = require('./torque-header-view.tpl'); /** * View for the header in the torque time-series view */ module.exports = cdb.core.View.extend({ className: 'CDB-Widget-header CDB-Widget-header--timeSeries CDB-Widget-contentSpaced', initialize: function () { this._dataviewModel = this.options.dataviewModel; this._torqueLayerModel = this.options.torqueLayerModel; this._rangeFilter = this._dataviewModel.filter; this._rangeFilter.bind('change', this.render, this); this.add_related_model(this._rangeFilter); }, render: function () { var showClearButton = true; this.clearSubViews(); this.$el.addClass(this.className); this.$el.html(template()); if (this._rangeFilter.isEmpty()) { this._appendView('.js-torque-controls', new TorqueControlsView({ torqueLayerModel: this._torqueLayerModel }) ); this._appendView('.js-torque-controls', new TorqueTimeInfoView({ dataviewModel: this._dataviewModel, torqueLayerModel: this._torqueLayerModel }) ); showClearButton = false; } this._createTimeSeriesHeaderView(showClearButton); return this; }, _createTimeSeriesHeaderView: function (showClearButton) { var headerView = new TimeSeriesHeaderView({ dataviewModel: this._dataviewModel, rangeFilter: this._dataviewModel.filter, showClearButton: showClearButton }); this._appendView('.js-time-series-header', headerView); this.listenTo(headerView, 'resetFilter', this._resetFilter); }, _resetFilter: function () { this._torqueLayerModel.resetRenderRange(); }, _appendView: function (selector, view) { this.addView(view); this.$(selector).append(view.render().el); } });
JavaScript
0.000001
@@ -1813,32 +1813,127 @@ : function () %7B%0A + // Move it to 0 so it doesn't stutter as much%0A this._torqueLayerModel.set(%7B step: 0 %7D);%0A this._torque
d8a17c9bc1f84633a9a70e582c48df06f281632d
Update Ashjrakamas.js
src/parser/shared/modules/items/bfa/Ashjrakamas.js
src/parser/shared/modules/items/bfa/Ashjrakamas.js
import React from 'react'; import SPELLS from 'common/SPELLS/index'; import ITEMS from 'common/ITEMS/index'; import Analyzer from 'parser/core/Analyzer'; import StatTracker from 'parser/shared/modules/StatTracker'; import UptimeIcon from 'interface/icons/Uptime'; import PrimaryStatIcon from 'interface/icons/PrimaryStat'; import ItemStatistic from 'interface/statistics/ItemStatistic'; import BoringItemValueText from 'interface/statistics/components/BoringItemValueText'; import { formatPercentage, formatNumber } from 'common/format'; import { TooltipElement } from 'common/Tooltip'; /** * Ashjra'kamas, Shroud of Resolve - * Equip: Your spells and abilities have a chance to increase your $pri by 1900 for 15 sec. */ const PROC_ADDED_ITEMLEVEL = 492; const STATS = 3648; class Ashjrakamas extends Analyzer { static dependencies = { statTracker: StatTracker, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasBack(ITEMS.ASHJRAKAMAS_SHROUD_OF_RESOLVE.id) && this.selectedCombatant.getItem(ITEMS.ASHJRAKAMAS_SHROUD_OF_RESOLVE.id).itemLevel >= PROC_ADDED_ITEMLEVEL; if (!this.active) { return; } // TODO check if this buff scales, hotfix notes make it sound static. //this.stats = calculatePrimaryStat(492, 3648, this.selectedCombatant.getItem(ITEMS.ASHJRAKAMAS_SHROUD_OF_RESOLVE.id).itemLevel); this.statTracker.add(SPELLS.DRACONIC_EMPOWERMENT.id, { intellect: STATS, strength: STATS, agility: STATS, }); } get totalBuffUptime() { return this.selectedCombatant.getBuffUptime(SPELLS.DRACONIC_EMPOWERMENT.id) / this.owner.fightDuration; } statistic() { return ( <ItemStatistic size="flexible" > <BoringItemValueText item={ITEMS.ASHJRAKAMAS_SHROUD_OF_RESOLVE}> <PrimaryStatIcon stat={this.selectedCombatant.spec.primaryStat} /> <TooltipElement content={( <div> <UptimeIcon /> {formatPercentage(this.totalBuffUptime, 2)}% uptime </div> )} > {formatNumber(this.totalBuffUptime * STATS)} <small>average {this.selectedCombatant.spec.primaryStat} gained</small></TooltipElement><br /> </BoringItemValueText> </ItemStatistic> ); } } export default Ashjrakamas;
JavaScript
0.000001
@@ -759,16 +759,21 @@ ;%0Aconst +PROC_ STATS = @@ -1170,217 +1170,8 @@ %7D%0A%0A - // TODO check if this buff scales, hotfix notes make it sound static.%0A //this.stats = calculatePrimaryStat(492, 3648, this.selectedCombatant.getItem(ITEMS.ASHJRAKAMAS_SHROUD_OF_RESOLVE.id).itemLevel);%0A%0A @@ -1242,16 +1242,21 @@ ellect: +PROC_ STATS,%0A @@ -1270,16 +1270,21 @@ rength: +PROC_ STATS,%0A @@ -1297,16 +1297,21 @@ gility: +PROC_ STATS,%0A @@ -1900,16 +1900,21 @@ ptime * +PROC_ STATS)%7D
ba2c65394f55bfb5c9938d1c20c94327d23f60a0
Work in progress
eln/ExpandableMolecule.js
eln/ExpandableMolecule.js
define([ 'src/util/api', 'src/util/ui', './libs' ], function (API, UI, libs) { var OCLE = libs.OCLE; class ExpandableMolecule { constructor(sample) { this.sample = sample; this.molfile = this.sample.$content.general.molfile + ''; this.idCode = OCLE.Molecule.fromMolfile(this.molfile).getIDCode(); this.expandedHydrogens = false; this.jsmeEditionMode = false; API.createData('editableMolfile', this.molfile).then( (editableMolfile) => { editableMolfile.onChange((event) => { // us this really a modification ? or a loop event ... // need to compare former oclID with new oclID var newMolecule = OCLE.Molecule.fromMolfile(event.target + ''); var idCode = newMolecule.getIDCode(); if (idCode != this.idCode) { this.idCode = idCode; this.molfile = event.target + ''; this.sample.setChildSync(['$content','general','molfile'], this.molfile); } else { console.log('no update'); } }); this.updateMolfiles(); this.toggleJSMEEdition(false); } ); } toggleJSMEEdition(force, noDepictUpdate) { if (force !== undefined && force === this.jsmeEditionMode) return; if (force === undefined) { this.jsmeEditionMode = !this.jsmeEditionMode; } else { this.jsmeEditionMode = force; } var prefs = { "prefs": [ "oldlook", "nozoom" ], "labelsize": "14", "bondwidth": "1", "defaultaction": "105", "highlightColor": "3", "outputResult": [ "yes" ] }; if (this.jsmeEditionMode) { API.getData("editableMolfile").triggerChange(); this.expandedHydrogens = false; } else { prefs.prefs.push('depict'); if (!noDepictUpdate) { this.expandedHydrogens = false; this.updateMolfiles(); API.createData("viewMolfile", this.viewMolfile); } } API.doAction('setJSMEPreferences', prefs) } setExpandedHydrogens(force) { if (force === undefined) { this.expandedHydrogens = !this.expandedHydrogens; } else { this.expandedHydrogens = force; } if (this.expandedHydrogens) { API.createData("viewMolfileExpandedH", this.viewMolfileExpandedH); this.toggleJSMEEdition(false, true); } else { API.createData("viewMolfile", this.viewMolfile); } } updateMolfiles() { // prevent the loop by checking actelionID var molecule = OCLE.Molecule.fromMolfile(this.molfile); this.viewMolfile = molecule.toVisualizerMolfile({ heavyAtomHydrogen: true }); molecule.addImplicitHydrogens(); this.viewMolfileExpandedH = molecule.toVisualizerMolfile(); } handleAction(action) { if (!action) return; switch (action.name) { case 'toggleJSMEEdition': this.toggleJSMEEdition(); break; case 'clearMolfile': var molfile = API.getData('editableMolfile'); molfile.setValue(''); break; case 'swapHydrogens': this.setExpandedHydrogens(); break; default: return false; } return true; } } return ExpandableMolecule; });
JavaScript
0.000003
@@ -1376,38 +1376,35 @@ this. -toggle +set JSMEEdition(fals @@ -1459,22 +1459,19 @@ -toggle +set JSMEEdit @@ -1474,20 +1474,20 @@ Edition( -forc +valu e, noDep @@ -1515,256 +1515,38 @@ -if (force !== undefined && force === this.jsmeEditionMode) return;%0A if (force === undefined) %7B%0A this.jsmeEditionMode = !this.jsmeEditionMode;%0A %7D else %7B%0A this.jsmeEditionMode = force;%0A %7D +this.jsmeEditionMode = value;%0A %0A @@ -2160,35 +2160,85 @@ (!noDepictUpdate -) %7B + && false) %7B // TODO when we should not updateMolfile %0A @@ -2848,38 +2848,35 @@ this. -toggle +set JSMEEdition(fals @@ -3558,22 +3558,19 @@ this. -toggle +set JSMEEdit @@ -3573,16 +3573,37 @@ Edition( +!this.jsmeEditionMode );%0A
c0ff96430274316b52fc291474fb908c9864233e
remove setTimeout
eln/ExpandableMolecule.js
eln/ExpandableMolecule.js
define([ 'src/util/api', 'src/util/ui', './libs' ], function (API, UI, libs) { var OCLE = libs.OCLE; class ExpandableMolecule { constructor(sample) { this.sample = sample; this.molfile = String(this.sample.getChildSync(['$content', 'general', 'molfile']) || ''); this.idCode = OCLE.Molecule.fromMolfile(this.molfile).getIDCode(); this.expandedHydrogens = false; this.jsmeEditionMode = false; API.createData('editableMolfile', this.molfile).then( (editableMolfile) => { editableMolfile.onChange((event) => { // us this really a modification ? or a loop event ... // need to compare former oclID with new oclID var newMolecule = OCLE.Molecule.fromMolfile(event.target + ''); var idCode = newMolecule.getIDCode(); if (idCode != this.idCode) { this.idCode = idCode; this.molfile = event.target + ''; this.sample.setChildSync(['$content','general','molfile'], this.molfile); } }); this.updateMolfiles(); this.setJSMEEdition(false); } ); } setJSMEEdition(value, noDepictUpdate) { this.jsmeEditionMode = value; var options = { prefs: [] }; if (this.jsmeEditionMode) { options.prefs.push('nodepict'); API.getData("editableMolfile").triggerChange(); this.expandedHydrogens = false; } else { options.prefs.push('depict'); if (!noDepictUpdate) { // TODO when we should not updateMolfile this.expandedHydrogens = false; this.updateMolfiles(); API.createData("viewMolfile", this.viewMolfile); } } API.doAction('setJSMEOptions', options) } setExpandedHydrogens(force) { if (force === undefined) { this.expandedHydrogens = !this.expandedHydrogens; } else { this.expandedHydrogens = force; } if (this.expandedHydrogens) { this.setJSMEEdition(false, true); setTimeout(() => { API.createData("viewMolfileExpandedH", this.viewMolfileExpandedH); }, 1000); } else { API.createData("viewMolfile", this.viewMolfile); } } updateMolfiles() { // prevent the loop by checking actelionID var molecule = OCLE.Molecule.fromMolfile(this.molfile); this.viewMolfile = molecule.toVisualizerMolfile({ heavyAtomHydrogen: true }); molecule.addImplicitHydrogens(); this.viewMolfileExpandedH = molecule.toVisualizerMolfile(); } handleAction(action) { if (!action) return; switch (action.name) { case 'toggleJSMEEdition': this.setJSMEEdition(!this.jsmeEditionMode); break; case 'clearMolfile': var molfile = API.getData('editableMolfile'); molfile.setValue(''); break; case 'swapHydrogens': this.setExpandedHydrogens(); break; default: return false; } return true; } } return ExpandableMolecule; });
JavaScript
0.000025
@@ -2487,47 +2487,8 @@ e);%0A - setTimeout(() =%3E %7B%0A @@ -2569,34 +2569,8 @@ dH); -%0A %7D, 1000); %0A%0A
50d3cd0a75ba83eaf4551d2e9de791319a311dbd
Handle 'no dashboard games' case gracefully
appsrc/util/fetch.js
appsrc/util/fetch.js
import invariant from 'invariant' import mklog from './log' const log = mklog('fetch') import {opts} from '../logger' import client from '../util/api' import {normalize, arrayOf} from './idealizr' import {game, user, collection, downloadKey} from './schemas' import {each, union, pluck, where, difference} from 'underline' export async function dashboardGames (market, credentials) { invariant(typeof market === 'object', 'dashboardGames has market') const {key, me} = credentials const api = client.withKey(key) const oldGameIds = market.getEntities('games')::where({userId: me.id})::pluck('id') const normalized = normalize(await api.myGames(), { games: arrayOf(game) }) // the 'myGames' endpoint doesn't set the userId // AND might return games you're not the user of normalized.entities.games::each((g) => { g.userId = g.userId || me.id }) normalized.entities.users = { [me.id]: me } normalized.entities.itchAppProfile = { myGames: { ids: normalized.entities.games::pluck('id') } } market.saveAllEntities(normalized) const newGameIds = normalized.entities.games::pluck('id') const goners = oldGameIds::difference(newGameIds) if (goners.length > 0) { market.deleteAllEntities({entities: {games: goners}}) } } export async function ownedKeys (market, credentials) { invariant(typeof market === 'object', 'dashboardGames has market') const {key} = credentials const api = client.withKey(key) let page = 0 while (true) { const response = await api.myOwnedKeys({page: page++}) if (response.ownedKeys.length === 0) { break } market.saveAllEntities(normalize(response, { ownedKeys: arrayOf(downloadKey) })) } } export async function collections (market, credentials) { invariant(typeof market === 'object', 'dashboardGames has market') const oldCollectionIds = market.getEntities('collections')::pluck('id') const prepareCollections = (normalized) => { const colls = market.getEntities('collections') normalized.entities.collections::each((coll, collId) => { const old = colls[collId] if (old) { coll.gameIds = old.gameIds::union(coll.gameIds) } }) return normalized } const {key} = credentials const api = client.withKey(key) const myCollectionsRes = normalize(await api.myCollections(), { collections: arrayOf(collection) }) market.saveAllEntities(prepareCollections(myCollectionsRes)) let newCollectionIds = myCollectionsRes.entities.collections::pluck('id') const goners = oldCollectionIds::difference(newCollectionIds) if (goners.length > 0) { market.deleteAllEntities({entities: {collections: goners}}) } } export async function collectionGames (market, credentials, collectionId) { invariant(typeof market === 'object', 'dashboardGames has market') invariant(typeof collectionId === 'number', 'dashboardGames has number collectionId') let collection = market.getEntities('collections')[collectionId] if (!collection) { log(opts, `collection not found: ${collectionId}, stack = ${(new Error()).stack}`) return } const api = client.withKey(credentials.key) let page = 1 let fetched = 0 let totalItems = 1 let fetchedGameIds = [] while (fetched < totalItems) { let res = await api.collectionGames(collectionId, page) totalItems = res.totalItems fetched = res.perPage * page const normalized = normalize(res, {games: arrayOf(game)}) const pageGameIds = normalized.entities.games::pluck('id') collection = { ...collection, gameIds: [ ...(collection.gameIds || []), ...pageGameIds ] } market.saveAllEntities({entities: {collections: {[collection.id]: collection}}}) fetchedGameIds = [ ...fetchedGameIds, ...pageGameIds ] market.saveAllEntities(normalized) page++ } // if games were removed remotely, they'll be removed locally at this step collection = { ...collection, gameIds: fetchedGameIds } market.saveAllEntities({entities: {collections: {[collection.id]: collection}}}) } export async function search (credentials, query) { invariant(typeof query === 'string', 'search has string query') const api = client.withKey(credentials.key) const gameResults = normalize(await api.searchGames(query), { games: arrayOf(game) }) const userResults = normalize(await api.searchUsers(query), { users: arrayOf(user) }) return { gameResults, userResults } } export async function gameLazily (market, credentials, gameId, opts = {}) { invariant(typeof market === 'object', 'gameLazily has market') invariant(typeof credentials === 'object', 'gameLazily has credentials') invariant(typeof gameId === 'number', 'gameLazily has gameId number') if (!opts.fresh) { let record = market.getEntities('games')[gameId] if (record) { return record } record = opts.game if (record) { return record } } const api = client.withKey(credentials.key) const response = normalize(await api.game(gameId), {game}) // TODO: re-use the 'user' this endpoint gives us? // thinking about layered markets, e.g.: // < looking for a user > // |-> [ query market - contains temporary data related to a search ] // |-> [ main market - contains persistent data (own games, owned games, games in collection) ] // at least, market shouldn't be a singleton return response.entities.games[gameId] } export async function userLazily (market, credentials, userId, opts = {}) { invariant(typeof market === 'object', 'userLazily has market') invariant(typeof credentials === 'object', 'userLazily has credentials') invariant(typeof userId === 'number', 'userLazily has userId number') if (!opts.fresh) { const record = market.getEntities('users')[userId] if (record) { return record } } const api = client.withKey(credentials.key) const response = normalize(await api.user(userId), {user}) return response.entities.users[userId] } export async function collectionLazily (market, credentials, collectionId, opts = {}) { invariant(typeof market === 'object', 'collectionLazily has market') invariant(typeof credentials === 'object', 'collectionLazily has credentials') invariant(typeof collectionId === 'number', 'collectionLazily has userId number') const oldRecord = market.getEntities('collections')[collectionId] if (!opts.fresh) { if (oldRecord) { return oldRecord } } const api = client.withKey(credentials.key) const response = normalize(await api.collection(collectionId), {collection}) return { ...oldRecord, ...response.entities.collections[collectionId] } } export default { dashboardGames, ownedKeys, collections, collectionGames, search, gameLazily, userLazily, collectionLazily }
JavaScript
0.000775
@@ -793,16 +793,91 @@ user of%0A + if (!normalized.entities.games) %7B%0A normalized.entities.games = %7B%7D%0A %7D%0A normal
e1594913c3947c76fb04b1952c25195a9c07512b
Update Kanban Visualization
src/routers/v1/finishing-printing/kanban-router.js
src/routers/v1/finishing-printing/kanban-router.js
var Manager = require("dl-module").managers.production.finishingPrinting.KanbanManager; var JwtRouterFactory = require("../../jwt-router-factory"); var resultFormatter = require("../../../result-formatter"); var db = require("../../../db"); var passport = require("../../../passports/jwt-passport"); const apiVersion = '1.0.0'; var handlePdfRequest = function (request, response, next) { var user = request.user; var id = request.params.id; var manager; db.get() .then(db => { manager = new Manager(db, user); return manager.getSingleByIdOrDefault(id); }) .then((kanban) => { var filename = kanban.productionOrder.orderNo + " - " + kanban.cart.cartNumber; manager.pdf(kanban) .then(kanbanDocBinary => { response.writeHead(200, { 'Content-Type': 'application/pdf', 'Content-Disposition': `attachment; filename=${filename}.pdf`, 'Content-Length': kanbanDocBinary.length }); response.end(kanbanDocBinary); }) .catch(e => { var error = resultFormatter.fail(apiVersion, 400, e); response.send(400, error); }); }); }; function getRouter() { var router = JwtRouterFactory(Manager, { version: apiVersion, defaultOrder: { "_updatedDate": -1 } }); var route = router.routes["get"].find(route => route.options.path === "/:id"); var originalHandler = route.handlers[route.handlers.length - 1]; route.handlers[route.handlers.length - 1] = function (request, response, next) { var isPDFRequest = (request.headers.accept || '').toString().indexOf("application/pdf") >= 0; if (isPDFRequest) { next(); } else { originalHandler(request, response, next); } }; route.handlers.push(handlePdfRequest); router.get("/read/visualization", passport, function (request, response, next) { var user = request.user; var query = request.query; query.filter = query.filter; query.select = query.select; db.get() .then(db => { manager = new Manager(db, user); return manager.readVisualization(query); }) .then(docs => { var result = resultFormatter.ok(apiVersion, 200, docs.data); delete docs.data; result.info = docs; return Promise.resolve(result); }) .then((result) => { response.send(result.statusCode, result); }) .catch((e) => { var statusCode = 500; if (e.name === "ValidationError") statusCode = 400; var error = resultFormatter.fail(apiVersion, statusCode, e); response.send(statusCode, error); }); }); router.put("/complete/:id", passport, (request, response, next) => { var user = request.user; var id = request.params.id; db.get() .then(db => { return Promise.resolve(new Manager(db, user)); }) .then((manager) => { return manager.getSingleByIdOrDefault(id) .then((doc) => { var result; if (!doc) { result = resultFormatter.fail(apiVersion, 404, new Error("data not found")); return Promise.resolve(result); } else { return manager.updateIsComplete(id) .then((docId) => { result = resultFormatter.ok(apiVersion, 204); return Promise.resolve(result); }); } }); }) .then((result) => { response.send(result.statusCode, result); }) .catch((e) => { var statusCode = 500; var error = resultFormatter.fail(apiVersion, statusCode, e); response.send(statusCode, error); }); }); return router; } module.exports = getRouter;
JavaScript
0
@@ -2264,16 +2264,51 @@ .select; +%0A query.order = query.order; %0A%0A
fcf678a93b675cc5f43f17ce14b80d04f597c7ad
Add a simple Flow example
WebClient/src/index.js
WebClient/src/index.js
import React from 'react' import { render } from 'react-dom' function Hello () { return <div>Hello React JSX World! powered by Babel</div> } render( <Hello />, document.getElementById('root') )
JavaScript
0
@@ -1,12 +1,22 @@ +// @flow%0A%0A import React @@ -81,16 +81,38 @@ Hello ( +%7Bname%7D: %7Bname: string%7D ) %7B%0A re @@ -131,41 +131,14 @@ llo -React JSX World! powered by Babel +%7Bname%7D %3C/di @@ -159,16 +159,29 @@ %3CHello + name='Pedro' /%3E,%0A d
670748f1006035f76a3c03d4d014d3ecce2f390f
Change from version to base path option
tools/scripts/build_api_docs_html_fragments.js
tools/scripts/build_api_docs_html_fragments.js
#!/usr/bin/env node /** * @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'; // MODULES // var join = require( 'path' ).join; var mkdir = require( 'fs' ).mkdirSync; var exists = require( '@stdlib/fs/exists' ).sync; var build = require( '@stdlib/_tools/docs/www/readme-fragment-file-tree' ); var stdlibPath = require( './stdlib_path.js' ); var stdlibVersion = require( './stdlib_version.js' ); var documentationPath = require( './api_docs_path.js' ); // MAIN // /** * Main execution sequence. * * @private */ function main() { var opts; var dir; dir = documentationPath(); if ( !exists( dir ) ) { mkdir( dir ); } opts = { 'version': 'v' + stdlibVersion(), 'dir': join( stdlibPath(), 'lib', 'node_modules' ), 'ignore': [ 'benchmark/**', 'bin/**', 'build/**', 'docs/**', 'etc/**', 'examples/**', 'reports/**', 'scripts/**', 'test/**', '**/_tools/**' ] }; build( dir, opts, done ); /** * Callback invoked upon completion. * * @private * @param {Error} [err] - error object * @throws {Error} unexpected error */ function done( err ) { if ( err ) { throw err; } console.log( 'Finished generating HTML fragments.' ); } } main();
JavaScript
0.000001
@@ -1211,19 +1211,26 @@ %0A%09%09' -version': ' +base': '/docs/api/ v' + @@ -1245,16 +1245,22 @@ ersion() + + '/' ,%0A%09%09'dir
f844f366fff47f8db44868d9dd7d0af70c824538
update jsdoc.js (#140)
packages/google-cloud-datalabeling/.jsdoc.js
packages/google-cloud-datalabeling/.jsdoc.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. // 'use strict'; module.exports = { opts: { readme: './README.md', package: './package.json', template: './node_modules/jsdoc-fresh', recurse: true, verbose: true, destination: './docs/' }, plugins: [ 'plugins/markdown', 'jsdoc-region-tag' ], source: { excludePattern: '(^|\\/|\\\\)[._]', include: [ 'build/src' ], includePattern: '\\.js$' }, templates: { copyright: 'Copyright 2018 Google, LLC.', includeDate: false, sourceFiles: false, systemName: '@google-cloud/datalabeling', theme: 'lumen' }, markdown: { idInHeadings: true } };
JavaScript
0
@@ -1040,9 +1040,9 @@ 201 -8 +9 Goo @@ -1165,16 +1165,71 @@ 'lumen' +,%0A default: %7B%0A %22outputSourceFiles%22: false%0A %7D %0A %7D,%0A
e85e2452adbb7d39b51b4189632fa0c785285451
Fix typo in custom click event
FastClick.js
FastClick.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Owner: mark@famo.us * @license MPL 2.0 * @copyright Famous Industries, Inc. 2014 */ define(function(require, exports, module) { /** * FastClick is an override shim which maps event pairs of * 'touchstart' and 'touchend' which differ by less than a certain * threshold to the 'click' event. * This is used to speed up clicks on some browsers. */ if (!window.CustomEvent) return; var clickThreshold = 300; var clickWindow = 500; var potentialClicks = {}; var recentlyDispatched = {}; var _now = Date.now; window.addEventListener('touchstart', function(event) { var timestamp = _now(); for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i]; potentialClicks[touch.identifier] = timestamp; } }); window.addEventListener('touchmove', function(event) { for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i]; delete potentialClicks[touch.identifier]; } }); window.addEventListener('touchend', function(event) { var currTime = _now(); for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i]; var startTime = potentialClicks[touch.identifier]; if (startTime && currTime - startTime < clickThreshold) { var clickEvt = new window.CustomEvent('click', { 'bubbles': true, 'details': touch }); recentlyDispatched[currTime] = event; event.target.dispatchEvent(clickEvt); } delete potentialClicks[touch.identifier]; } }); window.addEventListener('click', function(event) { var currTime = _now(); for (var i in recentlyDispatched) { var previousEvent = recentlyDispatched[i]; if (currTime - i < clickWindow) { if (event instanceof window.MouseEvent && event.target === previousEvent.target) event.stopPropagation(); } else delete recentlyDispatched[i]; } }, true); });
JavaScript
0.000003
@@ -1760,17 +1760,16 @@ 'detail -s ': touch
2e0d74287321ba074fb8dd0c1a110b7549e5c59b
Update documentation
Firestore.js
Firestore.js
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "_|Fire|get" }] */ /* globals FirestoreRequest_, createDocument_, deleteDocument_, getAuthToken_, getDocument_, getDocumentIds_, query_, updateDocument_ */ /** * Get an object that acts as an authenticated interface with a Firestore project. * * @param {string} email the user email address (for authentication) * @param {string} key the user private key (for authentication) * @param {string} projectId the Firestore project ID * @return {object} an authenticated interface with a Firestore project */ function getFirestore (email, key, projectId) { return new Firestore(email, key, projectId) } /** * An object that acts as an authenticated interface with a Firestore project. * * @constructor * @param {string} email the user email address (for authentication) * @param {string} key the user private key (for authentication) * @param {string} projectId the Firestore project ID * @return {object} an authenticated interface with a Firestore project */ var Firestore = function (email, key, projectId) { /** * The authentication token used for accessing Firestore. */ const authToken = getAuthToken_(email, key, 'https://oauth2.googleapis.com/token') const baseUrl = 'https://firestore.googleapis.com/v1beta1/projects/' + projectId + '/databases/(default)/documents/' /** * Get a document. * * @param {string} path the path to the document * @return {object} the document object */ this.getDocument = function (path) { const request = new FirestoreRequest_(baseUrl, authToken) return getDocument_(path, request) } /** * Get a list of all documents in a collection. * * @param {string} path the path to the collection * @return {object} an array of the documents in the collection */ this.getDocuments = function (path) { return this.query(path).execute() } /** * Get a list of all IDs of the documents in a path * * @param {string} path the path to the collection * @return {object} an array of IDs of the documents in the collection */ this.getDocumentIds = function (path) { const request = new FirestoreRequest_(baseUrl, authToken) return getDocumentIds_(path, request) } /** * Create a document with the given fields and an auto-generated ID. * * @param {string} path the path where the document will be written * @param {object} fields the document's fields * @return {object} the Document object written to Firestore */ this.createDocument = function (path, fields) { const request = new FirestoreRequest_(baseUrl, authToken) return createDocument_(path, fields, request) } /** * Update/patch a document at the given path with new fields. * * @param {string} path the path of the document to update. * If document name not provided, a random ID will be generated. * @param {object} fields the document's new fields * @param {boolean} if true, the update will use a mask * @return {object} the Document object written to Firestore */ this.updateDocument = function (path, fields, mask) { const request = new FirestoreRequest_(baseUrl, authToken) return updateDocument_(path, fields, request, mask) } /** * Run a query against the Firestore Database and * return an all the documents that match the query. * Must call .execute() to send the request. * * @param {string} path to query * @return {object} the JSON response from the GET request */ this.query = function (path) { const request = new FirestoreRequest_(baseUrl, authToken) return query_(path, request) } /** * Delete the Firestore document at the given path. * Note: this deletes ONLY this document, and not any subcollections. * * @param {string} path the path to the document to delete * @return {object} the JSON response from the DELETE request */ this.deleteDocument = function (path) { const request = new FirestoreRequest_(baseUrl, authToken) return deleteDocument_(path, request) } }
JavaScript
0
@@ -2985,16 +2985,21 @@ boolean%7D + mask if true
2e72d77362f4df18f09eabb8f2fb6f73310b953c
disable specific list view ui test due to failing in saucelabs until further research.
test/e2e/adminUI/group003List/uiTest001ListView.js
test/e2e/adminUI/group003List/uiTest001ListView.js
module.exports = { before: function (browser) { browser .url(browser.globals.adminUI.url) .waitForElementVisible('#signin-view') .setValue('input[name=email]', browser.globals.adminUI.login.email) .setValue('input[name=password]', browser.globals.adminUI.login.password) .click('button[type=submit]') .pause(browser.globals.defaultPauseTimeout) .url(browser.globals.adminUI.url) .waitForElementVisible('#home-view') .pause(browser.globals.defaultPauseTimeout) .click('#home-view > div > header > nav > div > ul.app-nav.app-nav--primary.app-nav--left > li:nth-child(2) > a') .waitForElementVisible('#list-view') .pause(browser.globals.defaultPauseTimeout) }, after: function (browser) { browser .click('#list-view > div > header > nav > div > ul.app-nav.app-nav--primary.app-nav--left > li.active > a') .waitForElementVisible('#list-view') .pause(browser.globals.defaultPauseTimeout) .click('#list-view > div > header > nav > div > ul.app-nav.app-nav--primary.app-nav--right > li:nth-child(2) > a') .pause(browser.globals.defaultPauseTimeout) .end(); }, 'List view must have a search bar': function (browser) { browser .click('#list-view > div > header > nav > div > ul.app-nav.app-nav--primary.app-nav--left > li.active > a') .waitForElementVisible('#list-view'); browser.expect.element('#list-view > div > div.keystone-body > div > div.ListHeader > div > div.InputGroup.ListHeader__bar > div.InputGroup_section.InputGroup_section--grow.ListHeader__search > input') .to.be.visible; }, 'List view must have a search button': function (browser) { browser.expect.element('#list-view > div > div.keystone-body > div > div.ListHeader > div > div.InputGroup.ListHeader__bar > div.InputGroup_section.InputGroup_section--grow.ListHeader__search > button') .to.be.visible; }, 'List view must have a filter input': function (browser) { browser.expect.element('#list-view > div > div.keystone-body > div > div.ListHeader > div > div.InputGroup.ListHeader__bar > div.InputGroup_section.ListHeader__filter') .to.be.visible; }, 'List view must have a column input': function (browser) { browser.expect.element('#list-view > div > div.keystone-body > div > div.ListHeader > div > div.InputGroup.ListHeader__bar > div.InputGroup_section.ListHeader__columns') .to.be.visible; }, 'List view must have a download input': function (browser) { browser.expect.element('#list-view > div > div.keystone-body > div > div.ListHeader > div > div.InputGroup.ListHeader__bar > div.InputGroup_section.ListHeader__download') .to.be.visible; }, 'List view must have an expand table width input': function (browser) { browser.expect.element('#list-view > div > div.keystone-body > div > div.ListHeader > div > div.InputGroup.ListHeader__bar > div.InputGroup_section.ListHeader__expand') .to.be.visible; }, 'List view must have a create list item button': function (browser) { browser.expect.element('#list-view > div > div.keystone-body > div > div.ListHeader > div > div.InputGroup.ListHeader__bar > div.InputGroup_section.ListHeader__create') .to.be.visible; }, 'List view must have a Showing N items label': function (browser) { browser.expect.element('#list-view > div > div.keystone-body > div > div.ListHeader > div > div:nth-child(4) > div > div') .to.be.visible; }, 'List view must have a name column header': function (browser) { browser.expect.element('#list-view > div > div.keystone-body > div > div:nth-child(2) > div > table > thead > tr > th:nth-child(1)') .to.be.visible; browser.expect.element('#list-view > div > div.keystone-body > div > div:nth-child(2) > div > table > thead > tr > th:nth-child(1)') .text.to.equal('Name'); }, 'List view must have an email column header': function (browser) { browser.expect.element('#list-view > div > div.keystone-body > div > div:nth-child(2) > div > table > thead > tr > th:nth-child(2)') .to.be.visible; browser.expect.element('#list-view > div > div.keystone-body > div > div:nth-child(2) > div > table > thead > tr > th:nth-child(2)') .text.to.equal('Email'); }, 'List view must have an Is Admin column header': function (browser) { browser.expect.element('#list-view > div > div.keystone-body > div > div:nth-child(2) > div > table > thead > tr > th:nth-child(3)') .to.be.visible; browser.expect.element('#list-view > div > div.keystone-body > div > div:nth-child(2) > div > table > thead > tr > th:nth-child(3)') .text.to.equal('Is Admin'); }, };
JavaScript
0
@@ -2639,32 +2639,34 @@ e.visible;%0A%09%7D,%0A%09 +// 'List view must @@ -2714,32 +2714,34 @@ on (browser) %7B%0A%09 +// %09browser.expect. @@ -2891,24 +2891,26 @@ __expand')%0A%09 +// %09%09%09 .to @@ -2915,32 +2915,34 @@ to.be.visible;%0A%09 +// %7D,%0A%09'List view m
afbb12aa87db3c8cca0b49725208a9d029d04311
fix tests
tests/acceptance/organization_admin/client-test.js
tests/acceptance/organization_admin/client-test.js
import { module, test } from 'qunit'; import { setupApplicationTest } from 'ember-qunit'; import { currentURL, visit } from '@ember/test-helpers'; import { authenticateSession } from 'ember-simple-auth/test-support'; module('Acceptance | organization_admin | client', function(hooks) { setupApplicationTest(hooks); test('visiting repository DataCite Journal', async function(assert) { await authenticateSession({ uid: 'datacite', name: 'DataCite', role_id: 'provider_admin', provider_id: 'datacite' }); await visit('/repositories/datacite.datacite'); assert.equal(currentURL(), '/repositories/datacite.datacite'); assert.dom('h2.work').hasText('DataCite'); assert.dom('li.nav-link.active a').hasText('Info'); }); test('visiting repository DataCite Journal settings', async function(assert) { await authenticateSession({ uid: 'datacite', name: 'DataCite', role_id: 'provider_admin', provider_id: 'datacite' }); await visit('/repositories/datacite.datacite/settings'); assert.equal(currentURL(), '/repositories/datacite.datacite/settings'); assert.dom('h2.work').hasText('DataCite'); assert.dom('li.nav-link.active a').hasText('Settings'); assert.dom('button#edit-repository').includesText('Update Repository'); assert.dom('button#delete-repository').includesText('Delete'); }); test('visiting repository DataCite Journal prefixes', async function(assert) { await authenticateSession({ uid: 'datacite', name: 'DataCite', role_id: 'provider_admin', provider_id: 'datacite' }); await visit('/repositories/datacite.datacite/prefixes'); assert.equal(currentURL(), '/repositories/datacite.datacite/prefixes'); assert.dom('h2.work').hasText('DataCite'); assert.dom('li.nav-link.active a').hasText('Prefixes'); }); test('visiting repository DataCite Journal dois', async function(assert) { await authenticateSession({ uid: 'datacite', name: 'DataCite', role_id: 'provider_admin', provider_id: 'datacite' }); await visit('/repositories/datacite.datacite/dois'); assert.equal(currentURL(), '/repositories/datacite.datacite/dois'); assert.dom('h2.work').hasText('DataCite'); assert.dom('li.nav-link.active a').hasText('DOIs'); assert.dom('h3.work').exists(); assert.dom('a#new-doi').doesNotExist(); assert.dom('a#upload-doi').doesNotExist(); assert.dom('a#transfer-dois').includesText('Transfer'); }); test('fail creating a new DOI for repository', async function(assert) { await authenticateSession({ uid: 'datacite', name: 'DataCite', role_id: 'provider_admin', provider_id: 'datacite' }); await visit('/repositories/datacite.datacite/dois'); assert.dom('new-doi').doesNotExist(); }); });
JavaScript
0.000001
@@ -689,36 +689,47 @@ asText('DataCite + Repository ');%0A - assert.dom(' @@ -1179,32 +1179,43 @@ asText('DataCite + Repository ');%0A assert.d @@ -1816,32 +1816,43 @@ asText('DataCite + Repository ');%0A assert.d @@ -2259,24 +2259,24 @@ ite/dois');%0A - assert.d @@ -2306,16 +2306,27 @@ DataCite + Repository ');%0A
b52a245bec966c71c2600552f594ae6a160d1470
add instance method scrollToRowKey unit test
tests/unit/specs/ve-table-instance-methods.spec.js
tests/unit/specs/ve-table-instance-methods.spec.js
import { mount } from "@vue/test-utils"; import veTable from "@/ve-table"; import { later, mockScrollTo } from "../util"; describe("veTable instance methods", () => { const TABLE_DATA = [ { name: "John", date: "1900-05-20", hobby: "coding and coding repeat", address: "No.1 Century Avenue, Shanghai", }, { name: "Dickerson", date: "1910-06-20", hobby: "coding and coding repeat", address: "No.1 Century Avenue, Beijing", }, { name: "Larsen", date: "2000-07-20", hobby: "coding and coding repeat", address: "No.1 Century Avenue, Chongqing", }, { name: "Geneva", date: "2010-08-20", hobby: "coding and coding repeat", address: "No.1 Century Avenue, Xiamen", }, { name: "Jami", date: "2020-09-20", hobby: "coding and coding repeat", address: "No.1 Century Avenue, Shenzhen", }, ]; const COLUMNS = [ { field: "name", key: "a", title: "Name", align: "center", }, { field: "date", key: "b", title: "Date", align: "left", }, { field: "hobby", key: "c", title: "Hobby", align: "right", }, { field: "address", key: "d", title: "Address" }, ]; it("scroll method", async () => { const wrapper = mount(veTable, { propsData: { columns: COLUMNS, tableData: TABLE_DATA, maxHeight: 50, }, }); await later(); const scrollToFn = mockScrollTo(); const option = { top: 100 }; wrapper.vm.scrollTo(option); expect(scrollToFn).toBeCalled(); expect(scrollToFn).toHaveBeenCalledWith(option); }); });
JavaScript
0
@@ -188,32 +188,55 @@ A = %5B%0A %7B%0A + rowkey: 0,%0A name @@ -241,24 +241,24 @@ me: %22John%22,%0A - @@ -391,32 +391,55 @@ %7D,%0A %7B%0A + rowkey: 1,%0A name @@ -598,32 +598,55 @@ %7D,%0A %7B%0A + rowkey: 2,%0A name @@ -804,32 +804,55 @@ %7D,%0A %7B%0A + rowkey: 3,%0A name @@ -1007,32 +1007,55 @@ %7D,%0A %7B%0A + rowkey: 4,%0A name @@ -1695,16 +1695,18 @@ (%22scroll +To method%22 @@ -2104,16 +2104,16 @@ lled();%0A - @@ -2168,13 +2168,738 @@ %0A %7D); +%0A%0A it(%22scrollToRowKey method%22, async () =%3E %7B%0A let warnSpy = jest.spyOn(console, %22warn%22).mockImplementation(() =%3E %7B%7D);%0A%0A const wrapper = mount(veTable, %7B%0A propsData: %7B%0A columns: COLUMNS,%0A tableData: TABLE_DATA,%0A maxHeight: 50,%0A rowKeyFieldName: %22rowkey%22,%0A %7D,%0A %7D);%0A%0A await later();%0A%0A const scrollToFn = mockScrollTo();%0A%0A const option = %7B top: 100 %7D;%0A%0A wrapper.vm.scrollToRowKey(%7B rowKey: %22%22 %7D);%0A expect(warnSpy).toBeCalledWith(%60Row key can't be empty!%60);%0A%0A wrapper.vm.scrollToRowKey(%7B rowKey: 2 %7D);%0A expect(scrollToFn).toBeCalled();%0A%0A warnSpy.mockRestore();%0A %7D); %0A%7D);%0A
2daf2104593281ac80405c479c279ec9435a6991
Use radius and location type as part of cache key
Maps/Nearby.js
Maps/Nearby.js
// @flow import { DownloadResult, downloadManager } from '../HTTP.js' import { buildURL } from '../URLs.js' import { parseBar } from './PlaceInfo.js' import { config } from '../Config.js' import type { Int, Float } from '../Types.js' import type { Key, Coords, PlaceID } from './MapStore.js' import type { Bar, Photo } from '../Bar/Bar.js' /*********************************************************************/ export type SearchResponse = { htmlAttrib: Array<string>, nextToken: string, results: Array<Bar>, } // export type MarkerInfo = { // coords: Coords, // placeID: PlaceID, // } /*********************************************************************/ const BaseURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json" const noResults = { htmlAttrib: [], nextToken: null, results: [], } export const searchNearby = async ( apiKey : Key, coords : Coords, radius : Int, locationType : string, includeOpenNowOnly = true, ) : Promise<DownloadResult<SearchResponse>> => { const params = { key: apiKey, // rankby: 'distance', radius: radius, location: `${coords.latitude},${coords.longitude}`, type: locationType, } if (includeOpenNowOnly) params.opennow = true const url = buildURL(BaseURL, params) const key = `qd:maps:search:lat=${coords.latitude},lon=${coords.longitude}` console.log("fetching from Nearby with key", key) const options = { method: 'GET' } const jsonDownloadResult = await downloadManager.fetchJSON( key, url, options, config.nearbyCacheInfo) return jsonDownloadResult.update(parseResponse) } export const fetchMore = async ( apiKey : Key, prevResponse : SearchResponse ) : Promise<DownloadResult<SearchResponse>> => { if (!prevResponse.next_page_token) return noResults const url = buildURL(BaseURL, { key: apiKey, next_page_token: prevResponse.next_page_token, }) } /* See https://developers.google.com/places/web-service/search for the response structure */ const parseResponse = (doc) : SearchResponse => { return { 'htmlAttrib': doc.html_attribution, 'nextToken': doc.next_page_token, 'results': doc.results.map(parseBar), } }
JavaScript
0
@@ -1492,16 +1492,62 @@ ngitude%7D +,radius=$%7Bradius%7D,locationType=$%7BlocationType%7D %60%0A co
44f8bf0627a4a3bfa1378bcc322967af6692f711
allow custom smtp configs
packages/isomorphic-core/src/auth-helpers.js
packages/isomorphic-core/src/auth-helpers.js
const _ = require('underscore') const Joi = require('joi'); const IMAPErrors = require('./imap-errors') const IMAPConnection = require('./imap-connection') const imapSmtpSettings = Joi.object().keys({ imap_host: [Joi.string().ip().required(), Joi.string().hostname().required()], imap_port: Joi.number().integer().required(), imap_username: Joi.string().required(), imap_password: Joi.string().required(), smtp_host: [Joi.string().ip().required(), Joi.string().hostname().required()], smtp_port: Joi.number().integer().required(), smtp_username: Joi.string().required(), smtp_password: Joi.string().required(), ssl_required: Joi.boolean().required(), }).required(); const resolvedGmailSettings = Joi.object().keys({ xoauth2: Joi.string().required(), expiry_date: Joi.number().integer().required(), }).required(); const office365Settings = Joi.object().keys({ name: Joi.string().required(), type: Joi.string().valid('office365').required(), email: Joi.string().required(), password: Joi.string().required(), username: Joi.string().required(), }).required(); const USER_ERRORS = { AUTH_500: "Please contact support@nylas.com. An unforeseen error has occurred.", IMAP_AUTH: "Incorrect username or password", IMAP_RETRY: "We were unable to reach your mail provider. Please try again.", } function credentialsForProvider({provider, settings, email}) { if (provider === "gmail") { const connectionSettings = { imap_username: email, imap_host: 'imap.gmail.com', imap_port: 993, smtp_username: email, smtp_host: 'smtp.gmail.com', smtp_port: 465, ssl_required: true, } const connectionCredentials = { xoauth2: settings.xoauth2, expiry_date: settings.expiry_date, } return {connectionSettings, connectionCredentials} } else if (provider === "imap") { const connectionSettings = _.pick(settings, [ 'imap_host', 'imap_port', 'smtp_host', 'smtp_port', 'ssl_required', ]); const connectionCredentials = _.pick(settings, [ 'imap_username', 'imap_password', 'smtp_username', 'smtp_password', ]); return {connectionSettings, connectionCredentials} } else if (provider === "office365") { const connectionSettings = { imap_host: 'outlook.office365.com', imap_port: 993, ssl_required: true, smtp_custom_config: { host: 'smtp.office365.com', port: 587, secure: false, tls: {ciphers: 'SSLv3'}, }, } const connectionCredentials = { imap_username: email, imap_password: settings.password, smtp_username: email, smtp_password: settings.password, } return {connectionSettings, connectionCredentials} } throw new Error(`Invalid provider: ${provider}`) } module.exports = { imapAuthRouteConfig() { return { description: 'Authenticates a new account.', tags: ['accounts'], auth: false, validate: { payload: { email: Joi.string().email().required(), name: Joi.string().required(), provider: Joi.string().valid('imap', 'gmail', 'office365').required(), settings: Joi.alternatives().try(imapSmtpSettings, office365Settings, resolvedGmailSettings), }, }, } }, imapAuthHandler(upsertAccount) { return (request, reply) => { const dbStub = {}; const connectionChecks = []; const {email, provider, name} = request.payload; const {connectionSettings, connectionCredentials} = credentialsForProvider(request.payload) connectionChecks.push(IMAPConnection.connect({ settings: Object.assign({}, connectionSettings, connectionCredentials), logger: request.logger, db: dbStub, })); Promise.all(connectionChecks).then((conns) => { for (const conn of conns) { if (conn) { conn.end(); } } const accountParams = { name: name, provider: provider, emailAddress: email, connectionSettings: connectionSettings, } return upsertAccount(accountParams, connectionCredentials) }) .then(({account, token}) => { const response = account.toJSON(); response.account_token = token.value; return reply(JSON.stringify(response)); }) .catch((err) => { request.logger.error(err) if (err instanceof IMAPErrors.IMAPAuthenticationError) { return reply({message: USER_ERRORS.IMAP_AUTH, type: "api_error"}).code(401); } if (err instanceof IMAPErrors.RetryableError) { return reply({message: USER_ERRORS.IMAP_RETRY, type: "api_error"}).code(408); } return reply({message: USER_ERRORS.AUTH_500, type: "api_error"}).code(500); }) } }, }
JavaScript
0
@@ -621,16 +621,52 @@ ired(),%0A + smtp_custom_config: Joi.object(),%0A ssl_re @@ -2026,16 +2026,38 @@ quired', + 'smtp_custom_config', %0A %5D);
67cb107510cb1384593f1d5898738abffce8bebd
update unit tests
test/api/controllers/serverController.test.js
test/api/controllers/serverController.test.js
const Promise = require('bluebird'), should = require('should'), sinon = require('sinon'), ServerController = require('../../../lib/api/controllers/serverController'), Request = require('kuzzle-common-objects').Request, KuzzleMock = require('../../mocks/kuzzle.mock'), sandbox = sinon.sandbox.create(); describe('Test: server controller', () => { let serverController, kuzzle, foo = {foo: 'bar'}, index = '%text', collection = 'unit-test-serverController', request; beforeEach(() => { const data = { controller: 'server', index, collection }; kuzzle = new KuzzleMock(); serverController = new ServerController(kuzzle); request = new Request(data); }); afterEach(() => { sandbox.restore(); }); describe('#getStats', () => { it('should trigger the plugin manager and return a proper response', () => { return serverController.getStats(request) .then(response => { should(kuzzle.statistics.getStats).be.calledOnce(); should(kuzzle.statistics.getStats).be.calledWith(request); should(response).be.instanceof(Object); should(response).match(foo); }); }); }); describe('#getLastStats', () => { it('should trigger the proper methods and return a valid response', () => { return serverController.getLastStats(request) .then(response => { should(kuzzle.statistics.getLastStats).be.calledOnce(); should(response).be.instanceof(Object); should(response).match(foo); }); }); }); describe('#getAllStats', () => { it('should trigger the proper methods and return a valid response', () => { return serverController.getAllStats(request) .then(response => { should(kuzzle.statistics.getAllStats).be.calledOnce(); should(response).be.instanceof(Object); should(response).match(foo); }); }); }); describe('#adminExists', () => { it('should call search with right query', () => { return serverController.adminExists() .then(() => { should(kuzzle.internalEngine.bootstrap.adminExists).be.calledOnce(); }); }); it('should return false if there is no result', () => { kuzzle.internalEngine.bootstrap.adminExists.returns(Promise.resolve(false)); return serverController.adminExists() .then((response) => { should(response).match({ exists: false }); }); }); it('should return true if there is result', () => { kuzzle.internalEngine.bootstrap.adminExists.returns(Promise.resolve(true)); return serverController.adminExists() .then((response) => { should(response).match({ exists: true }); }); }); }); describe('#now', () => { it('should resolve to a number', () => { return serverController.now(request) .then(response => { should(response).be.instanceof(Object); should(response).not.be.undefined(); should(response.now).not.be.undefined().and.be.a.Number(); }); }); }); describe('#info', () => { it('should return a properly formatted server information object', () => { class Foo { constructor() { this.qux = 'not a function'; this.baz = function () {}; } _privateMethod() {} publicMethod() {} } kuzzle.funnel.controllers = { foo: new Foo() }; kuzzle.funnel.pluginsControllers = { foobar: { _privateMethod: function () {}, publicMethod: function () {}, anotherMethod: function () {}, notAnAction: 3.14 } }; kuzzle.config.http.routes.push({verb: 'foo', action: 'publicMethod', controller: 'foo', url: '/u/r/l'}); kuzzle.pluginsManager.routes = [{verb: 'bar', action: 'publicMethod', controller: 'foobar', url: '/foobar'}]; return serverController.info() .then(response => { should(response).be.instanceof(Object); should(response).not.be.null(); should(response.serverInfo).be.an.Object(); should(response.serverInfo.kuzzle).be.and.Object(); should(response.serverInfo.kuzzle.version).be.a.String(); should(response.serverInfo.kuzzle.api).be.an.Object(); should(response.serverInfo.kuzzle.api.routes).match({ foo: { publicMethod: { action: 'publicMethod', controller: 'foo', http: { url: '/u/r/l', verb: 'FOO' } }, baz: { action: 'baz', controller: 'foo' } }, foobar: { publicMethod: { action: 'publicMethod', controller: 'foobar', http: { url: '/foobar', verb: 'BAR' } }, anotherMethod: { action: 'anotherMethod', controller: 'foobar' } } }); should(response.serverInfo.kuzzle.plugins).be.an.Object(); should(response.serverInfo.kuzzle.system).be.an.Object(); should(response.serverInfo.services).be.an.Object(); }); }); it('should reject an error in case of error', () => { kuzzle.services.list.broker.getInfos.returns(Promise.reject(new Error('foobar'))); return should(serverController.info()).be.rejected(); }); }); });
JavaScript
0
@@ -4980,24 +4980,31 @@ url: ' +_plugin /foobar',%0A
8c1c22488114ca0d2c1265c462397a54ba8b8173
fix resolveComponentPath to handle global & linked installs
packages/mjml-core/src/helpers/mjmlconfig.js
packages/mjml-core/src/helpers/mjmlconfig.js
import path from 'path' import fs from 'fs' import { registerComponent } from '../components' export function readMjmlConfig(configPathOrDir = process.cwd()) { let componentRootPath = process.cwd() let mjmlConfigPath = configPathOrDir try { mjmlConfigPath = path.basename(configPathOrDir) === '.mjmlconfig' ? path.resolve(configPathOrDir) : path.resolve(configPathOrDir, '.mjmlconfig') componentRootPath = path.dirname(mjmlConfigPath) const mjmlConfig = JSON.parse(fs.readFileSync(path.resolve(mjmlConfigPath), 'utf8')) return { mjmlConfig, componentRootPath } } catch (e) { if (e.code !== 'ENOENT') { console.log('Error reading mjmlconfig : ', e) // eslint-disable-line no-console } return { mjmlConfig: { packages: [] }, mjmlConfigPath, componentRootPath } } } export function resolveComponentPath(compPath, componentRootPath) { if (!compPath) { return null } if (!compPath.startsWith('.') && !path.isAbsolute(compPath)) { try { return require.resolve(compPath) } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') { console.log('Error resolving custom component path : ', e) // eslint-disable-line no-console return null } // if we get a 'MODULE_NOT_FOUND' error try again with relative path: return resolveComponentPath(`./${compPath}`, componentRootPath) } } return require.resolve(path.resolve(componentRootPath, compPath)) } export function registerCustomComponent(comp, registerCompFn = registerComponent) { if (comp instanceof Function) { registerCompFn(comp) } else { const compNames = Object.keys(comp) // this approach handles both an array and an object (like the mjml-accordion default export) compNames.forEach(compName => { registerCustomComponent(comp[compName], registerCompFn) }) } } export default function registerCustomComponents(configPathOrDir = process.cwd(), registerCompFn = registerComponent) { const { mjmlConfig: { packages }, componentRootPath } = readMjmlConfig(configPathOrDir) packages.forEach(compPath => { const resolvedPath = resolveComponentPath(compPath, componentRootPath) if (resolvedPath) { try { const requiredComp = require(resolvedPath) // eslint-disable-line global-require, import/no-dynamic-require registerCustomComponent(requiredComp.default || requiredComp, registerCompFn) } catch (e) { if (e.code !== 'ENOENT') { console.log('Error when registering custom component : ', resolvedPath, e) // eslint-disable-line no-console } else { console.log('Missing or unreadable custom component : ', resolvedPath) // eslint-disable-line no-console } } } }) }
JavaScript
0
@@ -1239,17 +1239,14 @@ // - if we g -e +o t a @@ -1273,39 +1273,296 @@ rror - try again with relative +%0A try %7B%0A // try again as relative path to node_modules: (this may be necessary if mjml is intalled globally or by npm link)%0A return resolveComponentPath(%60./node_modules/$%7BcompPath%7D%60, componentRootPath)%0A %7D catch (e) %7B%0A // try again as a plain local path:%0A + @@ -1623,24 +1623,32 @@ ntRootPath)%0A + %7D%0A %7D%0A %7D%0A @@ -2363,21 +2363,59 @@ %3E %7B%0A -const +let resolvedPath = compPath%0A try %7B%0A resolve @@ -2472,24 +2472,26 @@ otPath)%0A + if (resolved @@ -2498,28 +2498,16 @@ Path) %7B%0A - try %7B%0A @@ -2699,32 +2699,38 @@ rCompFn)%0A %7D +%0A %7D catch (e) %7B%0A @@ -2722,26 +2722,24 @@ catch (e) %7B%0A - if (e. @@ -2735,33 +2735,33 @@ if (e.code -! += == 'ENOENT') %7B%0A @@ -2751,30 +2751,61 @@ === 'ENOENT' + %7C%7C e.code !== 'MODULE_NOT_FOUND' ) %7B%0A - cons @@ -2817,30 +2817,29 @@ og(' -Error when registering +Missing or unreadable cus @@ -2869,19 +2869,16 @@ lvedPath -, e ) // esl @@ -2911,18 +2911,16 @@ e%0A - - %7D else %7B @@ -2920,18 +2920,16 @@ else %7B%0A - @@ -2941,37 +2941,38 @@ le.log(' -Missing or unreadable +Error when registering custom @@ -2990,32 +2990,35 @@ ', resolvedPath +, e ) // eslint-disa @@ -3041,18 +3041,8 @@ ole%0A - %7D%0A
d9b9355ecd653daafdd5d6e2b1521e9e76dc16c1
Add support for ES6 in a pre-bundle state
packages/olo-gulp-helpers/helpers/scripts.js
packages/olo-gulp-helpers/helpers/scripts.js
"use strict"; const fs = require("fs"); const path = require("path"); const process = require("process"); const gulp = require("gulp"); const eslint = require("gulp-eslint"); const concat = require("gulp-concat"); const sourcemaps = require("gulp-sourcemaps"); const uglify = require("gulp-uglify"); const rev = require("gulp-rev"); const babel = require("gulp-babel"); const gulpif = require("gulp-if"); const plumber = require("gulp-plumber"); const teamcityESLintFormatter = require("eslint-teamcity"); const webpackStream = require("webpack-stream"); const webpack = require("webpack"); const tslint = require("gulp-tslint"); const _ = require("lodash"); const WebpackMd5Hash = require("webpack-md5-hash"); const Server = require("karma").Server; function lintJavaScript(scripts) { return gulp .src(scripts) .pipe(eslint()) .pipe( eslint.format( process.env.TEAMCITY_VERSION ? teamcityESLintFormatter : undefined ) ) .pipe(eslint.failAfterError()); } function lintTypeScript(scripts, projectRoot) { return gulp .src(scripts) .pipe( tslint({ formatter: process.env.TEAMCITY_VERSION ? "tslint-teamcity-reporter" : undefined, formattersDirectory: process.env.TEAMCITY_VERSION ? projectRoot + "/node_modules/tslint-teamcity-reporter/" : undefined }) ) .pipe(tslint.report()); } function createBundle( bundleName, bundleFiles, outputPath, currentDirectory, watchMode ) { console.log("Creating script bundle: " + bundleName); return gulp .src(bundleFiles) .pipe(gulpif(watchMode, plumber())) .pipe(sourcemaps.init()) .pipe(babel()) .pipe(uglify()) .pipe(concat({ path: bundleName, cwd: currentDirectory })) .pipe(rev()) .pipe(sourcemaps.write(".")) .pipe(gulp.dest(outputPath)); } function createWebpackManifestWriter(bundleName, watchMode) { return stats => { if ( !watchMode && stats.compilation.errors && stats.compilation.errors.length ) { console.error("Failed to generate webpack: " + bundleName); stats.compilation.errors.forEach(error => { console.error("in " + error.file + ":"); console.error(error.message); }); throw new Error("Error generating webpack"); } // TODO: introduce a file lock here to avoid any concurrency issues (for now we just process these serially) const manifestPath = path.join(process.cwd(), "rev-manifest.json"); const hashedFileName = Object.keys(stats.compilation.assets).filter(key => key.endsWith(".js") )[0]; const manifestContents = fs.existsSync(manifestPath) ? JSON.parse(fs.readFileSync(manifestPath, "utf8")) : {}; manifestContents[bundleName] = hashedFileName; fs.writeFileSync( manifestPath, JSON.stringify(manifestContents, null, " ") ); }; } function createWebpackConfig( bundleName, entryScriptPath, watchMode, additionalWebpackConfig ) { const webpackConfig = additionalWebpackConfig || {}; const baseName = bundleName.replace(/(.*)\..*$/, "$1"); const loaders = _.concat( [ { test: /\.ts(x?)$/, loaders: ["ts-loader"] } ], webpackConfig.loaders || [] ); const output = Object.assign({}, webpackConfig.output || {}, { filename: baseName + "-[chunkhash].js" }); return { devtool: "source-map", entry: { bundle: entryScriptPath }, output: output, watch: watchMode, module: { loaders: loaders }, externals: webpackConfig.externals, plugins: _.chain(webpackConfig.plugins || []) .concat([ new WebpackMd5Hash(), new webpack.NoEmitOnErrorsPlugin(), new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify( process.env.TEAMCITY_VERSION ? "production" : "development" ) } }), process.env.TEAMCITY_VERSION && new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: true }), function() { this.plugin( "done", createWebpackManifestWriter(bundleName, watchMode) ); } ]) .without(undefined) .value(), resolve: { extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".jsx"] } }; } function createWebpackBundle( bundleName, entryScriptPath, outputPath, watchMode, additionalWebpackConfig ) { console.log("Creating webpack script bundle: " + bundleName); const webpackConfig = createWebpackConfig( bundleName, entryScriptPath, watchMode, additionalWebpackConfig ); return gulp .src(entryScriptPath) .pipe(gulpif(watchMode, plumber())) .pipe(webpackStream(webpackConfig)) .pipe(gulp.dest(outputPath)); } function runKarmaTests(config, callback) { new Server( { basePath: "", frameworks: config.frameworks, files: config.files, preprocessors: { "**/*.ts": ["webpack"], "**/*.tsx": ["webpack"] }, webpack: { plugins: config.webpack.plugins || [], module: { loaders: config.webpack.loaders || [], noParse: [/[\/\\]sinon\.js/] }, resolve: { extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".jsx"], alias: { sinon: "sinon/pkg/sinon.js" } }, externals: config.webpack.externals }, reporters: [process.env.TEAMCITY_VERSION ? "teamcity" : "mocha"], mochaReporter: { output: "autowatch" }, port: 9876, colors: true, autoWatch: true, browsers: ["PhantomJS"], concurrency: Infinity, singleRun: !config.watch }, callback ).start(); } module.exports = { lintJavaScript: lintJavaScript, lintTypeScript: lintTypeScript, createBundle: createBundle, createWebpackBundle: createWebpackBundle, runKarmaTests: runKarmaTests };
JavaScript
0
@@ -1683,16 +1683,108 @@ e(babel( +%7B%0A presets: %5B%22es2015%22%5D // ensure that uglify does not choke on potential es6 code%0A %7D ))%0A .
c53ebc50ee2dcd35b5f4f4662876dbc43f3b58b9
Rename variables
src/botPage/bot/Interpreter.js
src/botPage/bot/Interpreter.js
import JSInterpreter from 'js-interpreter'; import { observer as globalObserver } from 'binary-common-utils/lib/observer'; import { createScope } from './CliTools'; import Interface from './Interface'; const unrecoverableErrors = ['InsufficientBalance', 'CustomLimitsReached']; const botInitialized = bot => bot && bot.tradeEngine.options; const botStarted = bot => botInitialized(bot) && bot.tradeEngine.tradeOptions; const shouldRestartOnError = (bot, e = {}) => unrecoverableErrors.includes(e.name) && botInitialized(bot) && bot.tradeEngine.options.shouldRestartOnError; const timeMachineEnabled = bot => botInitialized(bot) && bot.tradeEngine.options.timeMachineEnabled; export default class Interpreter { constructor() { this.init(); } init() { this.$scope = createScope(); this.bot = new Interface(this.$scope); this.stopped = false; this.$scope.observer.register('REVERT', watchName => this.revert(watchName === 'before' ? this.beforeState : this.duringState) ); } run(code) { const initFunc = (interpreter, scope) => { const BotIf = this.bot.getInterface('Bot'); const ticksIf = this.bot.getTicksInterface(); const { alert, prompt, sleep, console: customConsole } = this.bot.getInterface(); interpreter.setProperty(scope, 'console', interpreter.nativeToPseudo(customConsole)); interpreter.setProperty(scope, 'alert', interpreter.nativeToPseudo(alert)); interpreter.setProperty(scope, 'prompt', interpreter.nativeToPseudo(prompt)); const pseudoBotIf = interpreter.nativeToPseudo(BotIf); Object.entries(ticksIf).forEach(([name, f]) => interpreter.setProperty(pseudoBotIf, name, this.createAsync(interpreter, f)) ); interpreter.setProperty( pseudoBotIf, 'start', interpreter.nativeToPseudo((...args) => { const { start } = BotIf; if (shouldRestartOnError(this.bot)) { this.startState = interpreter.takeStateSnapshot(); } start(...args); }) ); interpreter.setProperty(pseudoBotIf, 'purchase', this.createAsync(interpreter, BotIf.purchase)); interpreter.setProperty(pseudoBotIf, 'sellAtMarket', this.createAsync(interpreter, BotIf.sellAtMarket)); interpreter.setProperty(scope, 'Bot', pseudoBotIf); interpreter.setProperty( scope, 'watch', this.createAsync(interpreter, watchName => { const { watch } = this.bot.getInterface(); if (timeMachineEnabled(this.bot)) { const snapshot = this.interpreter.takeStateSnapshot(); if (watchName === 'before') { this.beforeState = snapshot; } else { this.duringState = snapshot; } } return watch(watchName); }) ); interpreter.setProperty(scope, 'sleep', this.createAsync(interpreter, sleep)); }; return new Promise((resolve, reject) => { const onError = e => { if (this.stopped) { return; } if (!shouldRestartOnError(this.bot, e.name) || !botStarted(this.bot)) { reject(e); return; } globalObserver.emit('Error', e); const { initArgs, tradeOptions } = this.bot.tradeEngine; this.stop(); this.init(); this.$scope.observer.register('Error', onError); this.bot.tradeEngine.init(...initArgs); this.bot.tradeEngine.start(tradeOptions); this.revert(this.startState); }; this.$scope.observer.register('Error', onError); this.interpreter = new JSInterpreter(code, initFunc); this.onFinish = resolve; this.loop(); }); } loop() { if (this.stopped || !this.interpreter.run()) { this.onFinish(this.interpreter.pseudoToNative(this.interpreter.value)); } } revert(state) { this.interpreter.restoreStateSnapshot(state); // eslint-disable-next-line no-underscore-dangle this.interpreter.paused_ = false; this.loop(); } stop() { this.$scope.api.disconnect(); globalObserver.emit('bot.stop'); this.stopped = true; } createAsync(interpreter, func) { return interpreter.createAsyncFunction((...args) => { const callback = args.pop(); func(...args.map(arg => interpreter.pseudoToNative(arg))) .then(rv => { callback(interpreter.nativeToPseudo(rv)); this.loop(); }) .catch(e => this.$scope.observer.emit('Error', e)); }); } }
JavaScript
0.000003
@@ -453,13 +453,21 @@ t, e +rrorName = -%7B%7D +'' ) =%3E @@ -471,16 +471,17 @@ =%3E%0A +! unrecove @@ -502,18 +502,21 @@ cludes(e -.n +rrorN ame) &&
467a4fc68453eb098f8bb1f5bad4a893c0b71048
Fix boolean logic in loadFull invocation
src/bundles/rollbar.snippet.js
src/bundles/rollbar.snippet.js
/* globals __DEFAULT_ROLLBARJS_URL__ */ /* globals _rollbarConfig */ var RollbarShim = require('../shim').Rollbar; var snippetCallback = require('../snippet_callback'); _rollbarConfig.rollbarJsUrl = _rollbarConfig.rollbarJsUrl || __DEFAULT_ROLLBARJS_URL__; var shim = RollbarShim.init(window, _rollbarConfig); var callback = snippetCallback(shim, _rollbarConfig); shim.loadFull(window, document, !!_rollbarConfig.async, _rollbarConfig, callback);
JavaScript
0.000008
@@ -397,10 +397,46 @@ nt, -!! +_rollbarConfig.async === undefined %7C%7C _rol
aef7b12c2cef8faf1d8647388676830f0e48b7ef
add style to MultiselectTag.js
packages/react-widgets/src/MultiselectTag.js
packages/react-widgets/src/MultiselectTag.js
import cn from 'classnames' import React from 'react' import PropTypes from 'prop-types' import Button from './Button' class MultiselectTag extends React.Component { static propTypes = { id: PropTypes.string, clearTagIcon: PropTypes.node, onRemove: PropTypes.func.isRequired, focused: PropTypes.bool, disabled: PropTypes.bool, readOnly: PropTypes.bool, label: PropTypes.string, value: PropTypes.any, } handleRemove = event => { const { value, disabled, onRemove } = this.props if (!disabled) onRemove(value, event) } renderDelete() { const { label, disabled, readOnly, clearTagIcon } = this.props return ( <Button variant={null} onClick={this.handleRemove} className="rw-multiselect-tag-btn" disabled={disabled || readOnly} label={label || 'Remove item'} > {clearTagIcon} </Button> ) } render() { const { id, className, children, focused, disabled } = this.props return ( <div id={id} role="option" className={cn( className, 'rw-multiselect-tag', disabled && 'rw-state-disabled', focused && !disabled && 'rw-state-focus' )} > <span className="rw-multiselect-tag-label">{children}</span> {this.renderDelete()} </div> ) } } export default MultiselectTag
JavaScript
0
@@ -25,34 +25,8 @@ es'%0A -import React from 'react'%0A impo @@ -56,16 +56,41 @@ -types'%0A +import React from 'react' %0Aimport @@ -981,16 +981,23 @@ disabled +, style %7D = thi @@ -1236,16 +1236,17 @@ e-focus' +, %0A @@ -1249,16 +1249,38 @@ )%7D%0A + style=%7Bstyle%7D%0A %3E%0A
fb5488decad38f2fb6baaa722a4330369b95eaa4
Fix spawn module require in rear-server-scripts init
packages/rear-server-scripts/scripts/init.js
packages/rear-server-scripts/scripts/init.js
const fs = require('fs-extra'); const path = require('path'); const logger = require('rear-logger')('rear-server-scripts-init'); const spawn = require('child_process').spawn; module.exports = init; /////////////////////// function init(root, appName, origin, verbose, useYarn, template) { prepareProject(root); copyTemplate(root, origin, template); installDependencies(root, useYarn, verbose); } function prepareProject(root) { const appPackage = require(path.join(root, 'package.json')); appPackage.dependencies = appPackage.dependencies || {}; appPackage.devDependencies = appPackage.devDependencies || {}; appPackage.scripts = { start: 'rear start', build: 'rear build', test: 'rear test', eject: 'rear eject', }; fs.writeFileSync( path.join(root, 'package.json'), JSON.stringify(appPackage, null, 2) ); const readmeExists = fs.existsSync(path.join(root, 'README.md')); if (readmeExists) { fs.renameSync( path.join(root, 'README.md'), path.join(root, 'README.old.md') ); } } function copyTemplate(root, origin, template) { const ownPackagePath = path.join(__dirname, '..', 'package.json'); const ownPackageName = require(ownPackagePath).name; const ownPath = path.join(root, 'node_modules', ownPackageName); const templatePath = template ? path.resolve(origin, template) : path.join(ownPath, 'template'); if (fs.existsSync(templatePath)) { fs.copySync(templatePath, root); } else { logger.error( `Could not locate supplied template: %c${templatePath}`, 'green' ); return; } fs.move( path.join(root, 'gitignore'), path.join(root, '.gitignore'), [], err => { if (err) { // Append if there's already a `.gitignore` file there if (err.code === 'EEXIST') { const data = fs.readFileSync(path.join(props.app.path, 'gitignore')); fs.appendFileSync(path.join(props.app.path, '.gitignore'), data); fs.unlinkSync(path.join(props.app.path, 'gitignore')); } else { throw err; } } } ); } function installDependencies(root, useYarn, verbose) { let command; let args; if (useYarn) { command = 'yarnpkg'; args = ['add']; } else { command = 'npm'; args = ['install', '--save', verbose && '--verbose'].filter(e => e); } args.push('rear-core', 'rear-logger'); // Install additional template dependencies, if present const templateDependenciesPath = path.join(root, '.template.dependencies.json'); if (fs.existsSync(templateDependenciesPath)) { const templateDependencies = require(templateDependenciesPath).dependencies; args = args.concat( Object.keys(templateDependencies).map(key => { return `${key}@${templateDependencies[key]}`; }) ); fs.unlinkSync(templateDependenciesPath); } logger.info(`Installing dependencies using ${command}...`); const proc = spawn.sync(command, args, { stdio: 'inherit' }); if (proc.status !== 0) { logger.error(`\`${command} ${args.join(' ')}\` failed`); return; } }
JavaScript
0
@@ -133,16 +133,20 @@ st spawn +Sync = requi @@ -170,16 +170,20 @@ ').spawn +Sync ;%0A%0Amodul @@ -2959,18 +2959,17 @@ = spawn -.s +S ync(comm
9d7e2254c57d99f87c8f984be5a2ce228a44a1a3
Use env vars by default instead of 'CHANGE_ME'
packages/tux-scripts/template/new/src/app.js
packages/tux-scripts/template/new/src/app.js
import React from 'react' import createContentfulAdapter from 'tux-adapter-contentful' import tux from './middleware/tux' import history from 'react-chain-history' import createReactChain from 'react-chain' import Home from './home' import './index.css' const publicUrl = process.env.PUBLIC_URL ? process.env.PUBLIC_URL : process.env.SERVER ? 'https://localhost:3000' : `${location.protocol}//${location.host}/` // Get your Contentful tokens from https://app.contentful.com/account/profile/developers/applications const adapter = createContentfulAdapter({ space: 'CHANGE_ME', accessToken: 'CHANGE_ME', clientId: 'CHANGE_ME', redirectUri: publicUrl, }) export default createReactChain() .chain(history()) .chain(tux({ adapter })) .chain(() => () => <Home />)
JavaScript
0
@@ -441,14 +441,34 @@ ful -tokens +clientId (application Uid) fro @@ -591,72 +591,149 @@ ce: -'CHANGE_ME',%0A accessToken: 'CHANGE_ME',%0A clientId: 'CHANGE_ME' +process.env.TUX_CONTENTFUL_SPACE_ID,%0A accessToken: process.env.TUX_CONTENTFUL_ACCESS_TOKEN,%0A clientId: process.env.TUX_CONTENTFUL_CLIENT_ID ,%0A
605f57f681e4f94297167b5800756d2c0e8722fd
Update tests for Home View
tests/routes/Home/components/HomeView.spec.js
tests/routes/Home/components/HomeView.spec.js
import React from 'react' import { HomeView } from 'routes/Home/components/HomeView' import { render } from 'enzyme' describe('(View) Home', () => { let _component beforeEach(() => { _component = render(<HomeView />) }) it('Renders a welcome message', () => { const welcome = _component.find('h4') expect(welcome).to.exist expect(welcome.text()).to.match(/Welcome!/) }) it('Renders an awesome duck image', () => { const duck = _component.find('img') expect(duck).to.exist expect(duck.attr('alt')).to.match(/This is a duck, because Redux!/) }) })
JavaScript
0
@@ -310,9 +310,13 @@ d('h -4 +eader ')%0A @@ -384,16 +384,23 @@ ch(/ -Welcome! +About Max Rojas /)%0A @@ -423,28 +423,27 @@ rs a -n awesome duck image + bio of the painter ', ( @@ -459,20 +459,19 @@ const -duck +bio = _comp @@ -486,11 +486,9 @@ nd(' -img +p ')%0A @@ -497,20 +497,19 @@ expect( -duck +bio ).to.exi @@ -526,66 +526,61 @@ ect( -duck.attr('alt')).to.match(/This is a duck, because Redux! +bio.find('strong').text()).to.match(/Max Rojas Vargas /)%0A
78ea1cd9b62f00747beb24b884e0d69a43e6b52e
Remove unused import
tests/smoke-tests/readerPresenterSmokeTest.js
tests/smoke-tests/readerPresenterSmokeTest.js
const Endless = imports.gi.Endless; const EosKnowledge = imports.gi.EosKnowledge; const EosKnowledgeSearch = imports.EosKnowledgeSearch; const Gio = imports.gi.Gio; const Gtk = imports.gi.Gtk; const Lang = imports.lang; // Load and register the GResource which has content for this app let resource = Gio.Resource.load('tests/test-content/test-content.gresource'); resource._register(); let resource_path = Gio.File.new_for_uri('resource:///com/endlessm/thrones'); // Mock out the engine so that we aren't looking for an eos-thrones database let mock_engine = new EosKnowledgeSearch.Engine(); mock_engine.get_object_by_id = function () {}; mock_engine.get_objects_by_query = function (query, callback) { const OBJECTS = [ { title: 'Article One', authors: ['Plward11'], published: 'September 30, 2014', ekn_id: 'about:blank', html: '<a href="http://www.google.com">Google</a>' }, { title: 'Article Two', authors: ['Ffarfan'], ekn_id: 'about:blank', }, { title: 'Article Three', published: 'September 30, 2014', ekn_id: 'about:blank', }, { title: 'Article Four (Cheese)', published: 'February 13, 2015', synopsis: 'Cheese is really expensive in Canada...', authors: ['Ptomato'], ekn_id: 'about:blank', } ]; callback(undefined, OBJECTS.slice(0, query.limit).map((props) => { let authors = props.authors; delete props.authors; let model = new EosKnowledgeSearch.ArticleObjectModel(props); if (authors) model.set_authors(authors); return model; })); }; mock_engine.get_xapian_uri = function () {}; const TestApplication = new Lang.Class({ Name: 'TestApplication', Extends: Endless.Application, _init: function (props) { this.parent(props); }, vfunc_startup: function () { this.parent(); let [success, app_json, len, etag] = resource_path.get_child('app.json') .load_contents(null); let presenter = new EosKnowledge.Reader.Presenter(JSON.parse(app_json), { engine: mock_engine, application: this, }); presenter.desktop_launch(0); }, }); let app = new TestApplication({ application_id: 'com.endlessm.knowledge.readerPresenterSmokeTest', flags: Gio.ApplicationFlags.FLAGS_NONE, }); app.run(ARGV);
JavaScript
0
@@ -162,36 +162,8 @@ io;%0A -const Gtk = imports.gi.Gtk;%0A cons
d404b07560e35f5288681f4084091c73231aba75
Tweak spacing
toolkits/landcover/test/helpers/test-image.js
toolkits/landcover/test/helpers/test-image.js
/** * @license * 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. */ // Maximum number of constant images to fetch when processing test data // collections. var MAX_TEST_COLLECTION_SIZE = 15; /** * Returns a single constant ee.Image comprised of the bands and values in the * specified dictionary. * * @param {*} values A dictionary containing band names as keys and * corresponding numeric values. The values are used to build an ee.Image * with a single constant value in each respective band. * @param {string} startDate An optional start date for the image, in YYYY-MM-DD * format. * @returns {!ee.Image} */ var create = function(values, startDate) { var image = ee.Dictionary(values).toImage().int64(); if (startDate) { image = image.set('system:time_start', ee.Date(startDate).millis()); } return image; }; /** * Reduces the specified constant ee.Image to a dictionary with one key per * band. * * @param {!ee.Image} image A constant ee.Image (an image with a single value). * @returns {*} A dictionary keyed by band name. */ var reduceConstant = function(image) { return ee.Image(image) .reduceRegion(ee.Reducer.first(), ee.Geometry.Point(0, 0), 1); }; /** * Reduces a collection of constant ee.Image instances to a list of * dictionaries keyed by band. * * @param {!ee.ImageCollection} collection A collection containing only constant * ee.Image instances (images with a single value). * @returns {Array} An array of dictionaries keyed by band name. */ var reduceConstants = function(collection) { return collection.toList(MAX_TEST_COLLECTION_SIZE).map(reduceConstant); }; exports.create = create; exports.reduceConstant = reduceConstant; exports.reduceConstants = reduceConstants;
JavaScript
0.000001
@@ -724,16 +724,17 @@ E = 15;%0A +%0A /**%0A * R
7f522d8cbf244b71c36a22e3bcce6b060dc887d0
Add CSS classes to items for better customizability
accessibility.cloud.js
accessibility.cloud.js
import Mustache from 'mustache'; import humanizeString from 'humanize-string'; function formatName(name) { return humanizeString(name).replace(/^Rating /, ''); } function formatValue(value) { if (value === true) return 'Yes'; if (value === false) return 'No'; return value; } function formatRating(rating) { const between0and5 = Math.floor(Math.min(1, Math.max(0, rating)) * 5); const stars = '★★★★★'.slice(5 - between0and5); return `<span class="stars">${stars}</span> <span class="numeric">${between0and5}/5</span>`; } function recursivelyRenderProperties(element) { if ($.isArray(element)) { return `<ul class="ac-list">${element.map(e => `<li>${recursivelyRenderProperties(e)}</li>`).join('')}</ul>`; } else if ($.isPlainObject(element)) { const listElements = $.map(element, (value, key) => { if ($.isArray(value) || $.isPlainObject(value)) { if (key === 'areas' && value.length === 1) { return recursivelyRenderProperties(value[0]); } return `<li class="ac-group"><span class='subtle'>${formatName(key)}</span> ${recursivelyRenderProperties(value)}</li>`; } if (key.startsWith('rating')) { return `<li class="ac-rating">${formatName(key)}: ${formatRating(parseFloat(value))}</li>`; } return `<li>${formatName(key)}: ${formatValue(value)}</li>`; }); return `<ul class="ac-group">${listElements.join('')}</ul>`; } return element; } function isAccessible(place) { return place.accessibility && place.accessibility.accessibleWith && place.accessibility.accessibleWith.wheelchair; } const AccessibilityCloud = { apiDomain: 'https://www.accessibility.cloud', getPlacesAround(parameters) { return $.ajax({ dataType: 'json', url: `${this.apiDomain}/place-infos?includeRelated=source`, data: parameters, headers: { Accept: 'application/json', 'X-Token': this.token, }, }); }, resultsTemplate() { // eslint-disable-next-line no-multi-str return `<ul class="ac-result-list" role="treegrid"> \ {{#places}} \ {{#properties}} \ <li class="ac-result {{isAccessibleClass}}" role="gridcell" aria-expanded="false"> \ <div class="ac-summary"> \ <img src="${this.apiDomain}/icons/categories/{{category}}.svg" role="presentation" class="ac-result-icon"> \ <header class="ac-result-name" role="heading">{{name}}</header> \ <div class="ac-result-distance">{{formattedDistance}}</div> \ <div class="ac-result-category">{{humanizedCategory}}</div> \ <a href="{{infoPageUrl}}" class="ac-result-link">{{sourceName}}</a> \ <div class="ac-result-accessibility-summary">{{accessibilitySummary}}</div> \ <div class="ac-result-accessibility-details ac-hidden">{{{formattedAccessibility}}}</div> \ </div> \ </li> \ {{/properties}} \ {{/places}} \ </ul>`; }, renderPlaces(element, places, related) { if (!$(element).length) { // console.error('Could not render results, element not found.'); return; } if (places && places.length) { $(element).html(Mustache.render(this.resultsTemplate(), { places, humanizedCategory() { return humanizeString(this.category); }, formattedDistance() { return `${Math.round(this.distance)}m`; }, formattedAccessibility() { return recursivelyRenderProperties(this.accessibility); }, isAccessibleClass() { return isAccessible(this) ? 'is-accessible' : ''; }, accessibilitySummary() { if (isAccessible(this)) { return 'Accessible with wheelchair'; } return 'Not accessible with wheelchair'; }, sourceName() { const source = related.sources && related.sources[this.sourceId]; return source && (source.shortName || source.name); }, })); // prevent slideToggle for link $('li.ac-result a').click(event => event.stopPropagation()); $('li.ac-result').click(event => $(event.target) .parent() .find('.ac-result-accessibility-details') .first() .slideToggle()); } else { $(element).html('<div class="ac-no-results">No results.</div>'); } }, renderSourcesAndLicenses(element, sources, licenses) { const links = Object.keys(sources).map((sourceId) => { const source = sources[sourceId]; const license = licenses[source.licenseId]; const licenseURL = `${this.apiDomain}/browse/licenses/${license._id}`; const sourceURL = source.originWebsiteURL || `${this.apiDomain}/browse/sources/${source._id}`; return `<a href="${sourceURL}">${(source.shortName || source.name)}</a> (<a href="${licenseURL}">${(license.shortName || license.name)}</a>)`; }); if (links.length) { $(element).append(`<p class="ac-licenses">Source: ${links.join(', ')}</p>`); } }, loadAndRenderPlaces(element, parameters) { return this.getPlacesAround(parameters) .done((response) => { this.renderPlaces(element, response.features, response.related); this.renderSourcesAndLicenses( element, response.related.sources, response.related.licenses, ); }) .fail((error) => { let message = 'No error message'; if (error) { try { message = JSON.parse(error.responseText).error.reason; } catch (e) { message = `${error.statusText}<br>${error.responseText}`; } } $(element).html(`<div class="ac-error">Could not load data:${message}</div>`); }); }, }; export default AccessibilityCloud;
JavaScript
0
@@ -1296,16 +1296,43 @@ urn %60%3Cli + class=%22ac-$%7Btypeof value%7D%22 %3E$%7Bforma
91db4d03f9eec41876c7fe5e3ffcdf42ab0bb267
Fix lp:1302500 by evaluating an empty context to avoid error
web_context_tunnel/static/src/js/context_tunnel.js
web_context_tunnel/static/src/js/context_tunnel.js
openerp.web_context_tunnel = function(instance) { instance.web.form.FormWidget.prototype.build_context = function() { var v_context = false; var fields_values = false; // instead of using just the attr context, we merge any attr starting with context for (var key in this.node.attrs) { if (key.substring(0, 7) === "context") { if (!v_context) { fields_values = this.field_manager.build_eval_context(); v_context = new instance.web.CompoundContext(this.node.attrs[key]).set_eval_context(fields_values); } else { v_context = new instance.web.CompoundContext(this.node.attrs[key], v_context).set_eval_context(fields_values); } } } if (!v_context) { v_context = (this.field || {}).context || {}; } return v_context; }; }; // vim:et fdc=0 fdl=0:
JavaScript
0
@@ -883,16 +883,85 @@ %7C%7C %7B%7D;%0A + v_context = new instance.web.CompoundContext(v_context);%0A
f349f5c37f2f6b19b951eb23b527493e88154e74
use Object.assign
src/browser/worker/process/background.js
src/browser/worker/process/background.js
import extend from 'extend'; import Image from '../../../image/Image'; const defaultOptions = { regression: { kernelType: 'polynomial', kernelOptions: { degree: 2, constant: 1 } }, threshold: 0.02, roi: { minSurface: 100, positive: false }, sampling: 20, include: [] }; function run(image, options, onStep) { options = extend({}, defaultOptions, options); const manager = this.manager; if (Array.isArray(image)) { return Promise.all(image.map(function (img) { const run = runOnce(manager, img, options); if (typeof onStep === 'function') { run.then(onStep); } return run; })); } else { return runOnce(manager, image, options); } } function runOnce(manager, image, options) { return manager.post('data', [image, options]).then(function (response) { for (let i in response) { response[i] = new Image(response[i]); } return response; }); } function work() { worker.on('data', function (send, image, options) { image = new IJS(image); const result = {}; const toTransfer = []; const grey = image.grey(); const sobel = grey.sobelFilter(); maybeInclude('sobel', sobel); const mask = sobel.level().mask({ threshold: options.threshold }); maybeInclude('mask', mask); const roiManager = sobel.getRoiManager(); roiManager.fromMask(mask); const realMask = roiManager.getMask(options.roi); maybeInclude('realMask', realMask); const pixels = grey.getPixelsGrid({ sampling: options.sampling, mask: realMask }); const background = image.getBackground(pixels.xyS, pixels.zS, options.regression); maybeInclude('background', background); const corrected = image.subtract(background); result.result = corrected; toTransfer.push(corrected.data.buffer); send(result, toTransfer); function maybeInclude(name, image) { if (options.include.includes(name)) { result[name] = image; toTransfer.push(image.data.buffer); } } }); } const background = { run, work }; export default background;
JavaScript
0.000051
@@ -1,34 +1,4 @@ -import extend from 'extend';%0A%0A impo @@ -321,14 +321,21 @@ s = -extend +Object.assign (%7B%7D,