<commit_before>import {customElement, bindable, inject, computedFrom, LogManager} from 'aurelia-framework';
import {CurrencyCode} from '../../util/common-models';
import {Stamps} from '../../services/stamps';
import {Countries} from '../../services/countries';
import {Preferences} from '../../services/preferences';
import {EventAggregator} from 'aurelia-event-aggregator';
import {EventNames} from '../../events/event-names';
import {EventManaged} from '../../events/event-managed';
import _ from 'lodash';
import moment from 'moment';

const logger = LogManager.getLogger('stamp-editor');

const PreferredValues = [
    {key: 'countryRef', category: 'stamps', type: Number},
    {key: 'catalogueRef', category: 'stamps', type: Number, model: ['activeCatalogueNumber']},
    {key: 'condition', category: 'stamps', type: Number, model: ['activeCatalogueNumber', 'ownership']},
    {key: 'albumRef', category: 'stamps', type: Number, model: ['ownership']},
    {key: 'sellerRef', category: 'stamps', type: Number, model: ['ownership']},
    {key: 'grade', category: 'stamps', type: Number, model: ['ownership']}
];

function createCatalogueNumber() {
    return {
        id: 0,
        catalogueRef: -1,
        value: 0.0,
        number: '',
        active: true,
        unknown: false
    };
}

function createOwnership() {
    return {
        id: 0,
        albumRef: -1,
        code: CurrencyCode.USD.description,
        purchased: moment(new Date()).format('YYYY-MM-DDT00:00:00Z'),
        pricePaid: 0.0
    };
}

@customElement('stamp-editor')
@bindable('model')
@inject(EventAggregator, Stamps, Countries, Preferences)
export class StampEditorComponent extends EventManaged {

    createMode = false;
    usedInlineImagePath = false;
    preferences = [];
    duplicateModel;

    constructor(eventBus, stampService, countryService, preferenceService) {
        super(eventBus);
        this.stampService = stampService;
        this.countryService = countryService;
        this.preferenceService = preferenceService;
    }

    attached() {
        this.setPreferences();
        this.subscribe(EventNames.checkExists, this.checkExists.bind(this));
        this.subscribe(EventNames.calculateImagePath, this.calculateImagePath.bind(this));
        this.subscribe(EventNames.convert, this.convertToStamp.bind(this));
        this.subscribe(EventNames.changeEditMode, this.changeEditMode.bind(this));
    }

    changeEditMode(mode) {
        if( this.createMode === true && (mode === 'wantList' || mode === 'stamp') ) {
            this.duplicateModel.wantList = !this.duplicateModel.wantList;
            this.duplicateModel.stampOwnership = [];
            if( !this.duplicateModel.wantList ) {
                this.duplicateModel.stampOwnership.push(createOwnership());
            }
        } else if ( this.createMode === false && mode === 'create' ) {
            this.eventBus.publish(EventNames.stampCreate);
        }

    }

    convertToStamp(m) {
        if (this.duplicateModel.id === 0 && m && this.createMode === true) {
            this.duplicateModel = m;
            this.duplicateModel.stampOwnership = [];
            this.duplicateModel.stampOwnership.push(createOwnership());
        }
    }

    calculateImagePath() {
        _.debounce(function (self) {
            var m = self.duplicateModel;
            if( self.createMode === true && m.wantList === false && m.stampOwnerships && m.stampOwnerships.length > 0 ) {
                var cn = m.activeCatalogueNumber;
                if( m.countryRef > 0 && cn.number !== '') {
                    var country = self.countryService.getById( m.countryRef );
                    if( country ) {
                        var path = country.name + '/';
                        if( !self.usedInlineImagePath && (cn.condition === 2 || cn.condition === 3) ) {
                            path += 'used/';
                        }
                        path += cn.number + '.jpg';
                        var owner = _.first(m.stampOwnerships);
                        owner.img = path;
                    }
                }
            }
        }, 500)(this);
    }

    checkExists() {
        _.debounce(function (self) {
            if (self.duplicateModel.countryRef > 0 && self.duplicateModel.activeCatalogueNumber) {
                var cn = self.duplicateModel.activeCatalogueNumber;
                if (cn.catalogueRef > 0 && cn.number && cn.number !== '') {
                    var opts = {
                        $filter: '((countryRef eq ' + self.duplicateModel.countryRef + ') and (catalogueRef eq ' + cn.catalogueRef + ') and (number eq \'' + cn.number + '\'))'
                    };
                    self.stampService.find(opts).then(results => {
                        if (results.models.length > 0) {
                            self.processExistenceResults(results.models);
                        }
                    });
                }
            }
        }, 500)(this);
    }

    processExistenceResults(models) {
        _.remove(models, {id: this.duplicateModel.id});
        if (models.length > 0) {
            var index = _.findIndex(models, {wantList: true});
            var wantList = ( index >= 0 );
            var obj = {
                convert: wantList,
                conversionModel: ( index >= 0 ) ? models[index] : undefined
            };
            this.eventBus.publish(EventNames.conflictExists, obj);
        }
    }

    setPreferences() {
        var self = this;
        this.preferenceService.find().then(results => {
            self.preferences = results.models;
            self.processPreferences();
        });
    }

    processPreferences() {
        if (this.preferences.length > 0) {
            var p = _.findWhere(this.preferences, { name: 'usedInlineImagePath', category: 'stamps'});
            this.usedInlineImagePath = ( p && p.value === 'true');
            if( this.duplicateModel.id <= 0 ) {
                PreferredValues.forEach(function (pref) {
                    var prefValue = _.findWhere(this.preferences, {name: pref.key, category: pref.category});
                    if (prefValue) {
                        var value = prefValue.value;
                        if (pref.type === Number) {
                            value = +value;
                        }
                        var m = this.duplicateModel;
                        if (pref.model) {
                            pref.model.forEach(function (key) {
                                if (key === "activeCatalogueNumber") {
                                    m = this.activeCatalogueNumber;
                                } else if (key === "ownership") {
                                    m = this.ownership;
                                }
                                if (m) {
                                    m[pref.key] = value;
                                }
                            }, this);
                        } else if (m) {
                            m[pref.key] = value;
                        } else {
                            logger.error("The model was not defined");
                        }
                    }
                }, this);
            }
        }
    }

    save(keepOpen) {
        if (this.validate()) {
            this.stampService.save(this.duplicateModel).then(stamp => {
                this.eventBus.publish(EventNames.stampSaved, { stamp: stamp, remainOpen: keepOpen });
            }).catch(err => {
                logger.error(err);
            });
        }
    }

    cancel() {
        this.eventBus.publish(EventNames.stampEditorCancel);
    }

    saveAndNew() {
        this.save(true);
    }

    validate() {
        return true;
    }

    modelChanged(newValue) {
        this.createMode = (newValue && newValue.id <= 0);
        if (newValue) {
            this.duplicateModel = _.clone(newValue, true);
            if( this.preferenceService.loaded ) {
                this.processPreferences();
            }
        } else {
            this.duplicateModel = null;
        }

    }

    @computedFrom('duplicateModel')
    get ownership() {
        if (!this.duplicateModel) {
            return undefined;
        }
        var owners = this.duplicateModel.stampOwnerships;
        var owner;
        if( this.duplicateModel.wantList === false ) {
            if (!owners) {
                this.duplicateModel.stampOwnerships = [];
                owner = createOwnership();
                this.duplicateModel.stampOwnerships.push(owner);
            } else if (this.duplicateModel.stampOwnerships.length > 0) {
                owner = _.first(this.duplicateModel.stampOwnerships);
            } else {
                owner = createOwnership();
                this.duplicateModel.stampOwnerships.push(owner);
            }
        }
        return owner;
    }

    /**
     * Will lazily retrieve the active catalogue number from the stamp model.  If one does not exist
     * will create the catalogue numbers array and create an initial catalogue number to put in it.
     *
     * This will be a computed property on model.  It will only calculate if model is updated.
     *
     * @returns {Object} The active catalogue number.
     */
    @computedFrom('duplicateModel')
    get activeCatalogueNumber() {
        if (!this.duplicateModel) {
            return undefined;
        }
        var activeNumber = this.duplicateModel.activeCatalogueNumber;
        if (!activeNumber) {
            if (!this.duplicateModel.catalogueNumbers) {
                this.duplicateModel.catalogueNumbers = [];
            } else {
                activeNumber = _.findWhere(this.duplicateModel.catalogueNumbers, {active: true});
            }
            if (!activeNumber) {
                activeNumber = createCatalogueNumber();
                this.duplicateModel.catalogueNumbers.push(activeNumber);
            }
            this.duplicateModel.activeCatalogueNumber = activeNumber;
        }
        return activeNumber;
    }
}
<commit_msg>reset stamp fields on a save + new<commit_after>import {customElement, bindable, inject, computedFrom, LogManager} from 'aurelia-framework';
import {CurrencyCode} from '../../util/common-models';
import {Stamps} from '../../services/stamps';
import {Countries} from '../../services/countries';
import {Preferences} from '../../services/preferences';
import {EventAggregator} from 'aurelia-event-aggregator';
import {EventNames} from '../../events/event-names';
import {EventManaged} from '../../events/event-managed';
import _ from 'lodash';
import moment from 'moment';

const logger = LogManager.getLogger('stamp-editor');

const PreferredValues = [
    {key: 'countryRef', category: 'stamps', type: Number},
    {key: 'catalogueRef', category: 'stamps', type: Number, model: ['activeCatalogueNumber']},
    {key: 'condition', category: 'stamps', type: Number, model: ['activeCatalogueNumber', 'ownership']},
    {key: 'albumRef', category: 'stamps', type: Number, model: ['ownership']},
    {key: 'sellerRef', category: 'stamps', type: Number, model: ['ownership']},
    {key: 'grade', category: 'stamps', type: Number, model: ['ownership']}
];

function createCatalogueNumber() {
    return {
        id: 0,
        catalogueRef: -1,
        value: 0.0,
        number: '',
        active: true,
        unknown: false
    };
}

function createOwnership() {
    return {
        id: 0,
        albumRef: -1,
        code: CurrencyCode.USD.description,
        purchased: moment(new Date()).format('YYYY-MM-DDT00:00:00Z'),
        pricePaid: 0.0
    };
}

@customElement('stamp-editor')
@bindable('model')
@inject(EventAggregator, Stamps, Countries, Preferences)
export class StampEditorComponent extends EventManaged {

    createMode = false;
    usedInlineImagePath = false;
    preferences = [];
    duplicateModel;

    constructor(eventBus, stampService, countryService, preferenceService) {
        super(eventBus);
        this.stampService = stampService;
        this.countryService = countryService;
        this.preferenceService = preferenceService;
    }

    attached() {
        this.setPreferences();
        this.subscribe(EventNames.checkExists, this.checkExists.bind(this));
        this.subscribe(EventNames.calculateImagePath, this.calculateImagePath.bind(this));
        this.subscribe(EventNames.convert, this.convertToStamp.bind(this));
        this.subscribe(EventNames.changeEditMode, this.changeEditMode.bind(this));
    }

    changeEditMode(mode) {
        if( this.createMode === true && (mode === 'wantList' || mode === 'stamp') ) {
            this.duplicateModel.wantList = !this.duplicateModel.wantList;
            this.duplicateModel.stampOwnership = [];
            if( !this.duplicateModel.wantList ) {
                this.duplicateModel.stampOwnership.push(createOwnership());
            }
        } else if ( this.createMode === false && mode === 'create' ) {
            this.eventBus.publish(EventNames.stampCreate);
        }

    }

    convertToStamp(m) {
        if (this.duplicateModel.id === 0 && m && this.createMode === true) {
            this.duplicateModel = m;
            this.duplicateModel.stampOwnership = [];
            this.duplicateModel.stampOwnership.push(createOwnership());
        }
    }

    calculateImagePath() {
        _.debounce(function (self) {
            var m = self.duplicateModel;
            if( self.createMode === true && m.wantList === false && m.stampOwnerships && m.stampOwnerships.length > 0 ) {
                var cn = m.activeCatalogueNumber;
                if( m.countryRef > 0 && cn.number !== '') {
                    var country = self.countryService.getById( m.countryRef );
                    if( country ) {
                        var path = country.name + '/';
                        if( !self.usedInlineImagePath && (cn.condition === 2 || cn.condition === 3) ) {
                            path += 'used/';
                        }
                        path += cn.number + '.jpg';
                        var owner = _.first(m.stampOwnerships);
                        owner.img = path;
                    }
                }
            }
        }, 500)(this);
    }

    checkExists() {
        _.debounce(function (self) {
            if (self.duplicateModel.countryRef > 0 && self.duplicateModel.activeCatalogueNumber) {
                var cn = self.duplicateModel.activeCatalogueNumber;
                if (cn.catalogueRef > 0 && cn.number && cn.number !== '') {
                    var opts = {
                        $filter: '((countryRef eq ' + self.duplicateModel.countryRef + ') and (catalogueRef eq ' + cn.catalogueRef + ') and (number eq \'' + cn.number + '\'))'
                    };
                    self.stampService.find(opts).then(results => {
                        if (results.models.length > 0) {
                            self.processExistenceResults(results.models);
                        }
                    });
                }
            }
        }, 500)(this);
    }

    processExistenceResults(models) {
        _.remove(models, {id: this.duplicateModel.id});
        if (models.length > 0) {
            var index = _.findIndex(models, {wantList: true});
            var wantList = ( index >= 0 );
            var obj = {
                convert: wantList,
                conversionModel: ( index >= 0 ) ? models[index] : undefined
            };
            this.eventBus.publish(EventNames.conflictExists, obj);
        }
    }

    setPreferences() {
        var self = this;
        this.preferenceService.find().then(results => {
            self.preferences = results.models;
            self.processPreferences();
        });
    }

    processPreferences() {
        if (this.preferences.length > 0) {
            var p = _.findWhere(this.preferences, { name: 'usedInlineImagePath', category: 'stamps'});
            this.usedInlineImagePath = ( p && p.value === 'true');
            if( this.duplicateModel.id <= 0 ) {
                PreferredValues.forEach(function (pref) {
                    var prefValue = _.findWhere(this.preferences, {name: pref.key, category: pref.category});
                    if (prefValue) {
                        var value = prefValue.value;
                        if (pref.type === Number) {
                            value = +value;
                        }
                        var m = this.duplicateModel;
                        if (pref.model) {
                            pref.model.forEach(function (key) {
                                if (key === "activeCatalogueNumber") {
                                    m = this.activeCatalogueNumber;
                                } else if (key === "ownership") {
                                    m = this.ownership;
                                }
                                if (m) {
                                    m[pref.key] = value;
                                }
                            }, this);
                        } else if (m) {
                            m[pref.key] = value;
                        } else {
                            logger.error("The model was not defined");
                        }
                    }
                }, this);
            }
        }
    }

    save(keepOpen) {
        if (this.validate()) {
            this.stampService.save(this.duplicateModel).then(stamp => {
                this.eventBus.publish(EventNames.stampSaved, { stamp: stamp, remainOpen: keepOpen });
                if( keepOpen) {
                    this.resetModel();
                }
            }).catch(err => {
                logger.error(err);
            });
        }
    }

    cancel() {
        this.eventBus.publish(EventNames.stampEditorCancel);
    }

    saveAndNew() {
        this.save(true);
    }

    validate() {
        return true;
    }

    resetModel() {
        this.duplicateModel.id = 0;
        this.duplicateModel.rate = "";
        this.duplicateModel.description = "";
        this.resetCatalogueNumber();
        this.resetOwnership();
        this.model = this.duplicateModel;
    }

    resetCatalogueNumber() {
        let cn = this.activeCatalogueNumber
        cn.id = 0;
        cn.number = "";
        cn.unknown = false;
        cn.nospace = false;
        cn.value = 0;
    }

    resetOwnership() {
        let owner = this.ownership;
        if( owner ) {
            owner.notes = undefined;
            owner.cert = false;
            owner.certImg = undefined;
            owner.defects = 0;
            owner.deception = 0;
        }
    }

    modelChanged(newValue) {
        this.createMode = (newValue && newValue.id <= 0);
        if (newValue) {
            this.duplicateModel = _.clone(newValue, true);
            if( this.preferenceService.loaded ) {
                this.processPreferences();
            }
        } else {
            this.duplicateModel = null;
        }

    }

    @computedFrom('duplicateModel')
    get ownership() {
        if (!this.duplicateModel) {
            return undefined;
        }
        var owners = this.duplicateModel.stampOwnerships;
        var owner;
        if( this.duplicateModel.wantList === false ) {
            if (!owners) {
                this.duplicateModel.stampOwnerships = [];
                owner = createOwnership();
                this.duplicateModel.stampOwnerships.push(owner);
            } else if (this.duplicateModel.stampOwnerships.length > 0) {
                owner = _.first(this.duplicateModel.stampOwnerships);
            } else {
                owner = createOwnership();
                this.duplicateModel.stampOwnerships.push(owner);
            }
        }
        return owner;
    }

    /**
     * Will lazily retrieve the active catalogue number from the stamp model.  If one does not exist
     * will create the catalogue numbers array and create an initial catalogue number to put in it.
     *
     * This will be a computed property on model.  It will only calculate if model is updated.
     *
     * @returns {Object} The active catalogue number.
     */
    @computedFrom('duplicateModel')
    get activeCatalogueNumber() {
        if (!this.duplicateModel) {
            return undefined;
        }
        var activeNumber = this.duplicateModel.activeCatalogueNumber;
        if (!activeNumber) {
            if (!this.duplicateModel.catalogueNumbers) {
                this.duplicateModel.catalogueNumbers = [];
            } else {
                activeNumber = _.findWhere(this.duplicateModel.catalogueNumbers, {active: true});
            }
            if (!activeNumber) {
                activeNumber = createCatalogueNumber();
                this.duplicateModel.catalogueNumbers.push(activeNumber);
            }
            this.duplicateModel.activeCatalogueNumber = activeNumber;
        }
        return activeNumber;
    }
}
<|endoftext|>


<commit_before>/*
Copyright 2017 New Vector 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.
*/

import React from 'react';
import PropTypes from 'prop-types';
import { MatrixClient } from 'matrix-js-sdk';
import GeminiScrollbar from 'react-gemini-scrollbar';
import TagOrderStore from '../../stores/TagOrderStore';

import GroupActions from '../../actions/GroupActions';

import sdk from '../../index';
import dis from '../../dispatcher';
import { _t } from '../../languageHandler';

import { Droppable } from 'react-beautiful-dnd';

const TagPanel = React.createClass({
    displayName: 'TagPanel',

    contextTypes: {
        matrixClient: PropTypes.instanceOf(MatrixClient),
    },

    getInitialState() {
        return {
            orderedTags: [],
            selectedTags: [],
        };
    },

    componentWillMount: function() {
        this.unmounted = false;
        this.context.matrixClient.on("Group.myMembership", this._onGroupMyMembership);
        this.context.matrixClient.on("sync", this.onClientSync);

        this._tagOrderStoreToken = TagOrderStore.addListener(() => {
            if (this.unmounted) {
                return;
            }
            this.setState({
                orderedTags: TagOrderStore.getOrderedTags() || [],
                selectedTags: TagOrderStore.getSelectedTags(),
            });
        });
        // This could be done by anything with a matrix client
        dis.dispatch(GroupActions.fetchJoinedGroups(this.context.matrixClient));
    },

    componentWillUnmount() {
        this.unmounted = true;
        this.context.matrixClient.removeListener("Group.myMembership", this._onGroupMyMembership);
        this.context.matrixClient.removeListener("sync", this.onClientSync);
        if (this._filterStoreToken) {
            this._filterStoreToken.remove();
        }
    },

    _onGroupMyMembership() {
        if (this.unmounted) return;
        dis.dispatch(GroupActions.fetchJoinedGroups(this.context.matrixClient));
    },

    onClientSync(syncState, prevState) {
        // Consider the client reconnected if there is no error with syncing.
        // This means the state could be RECONNECTING, SYNCING or PREPARED.
        const reconnected = syncState !== "ERROR" && prevState !== syncState;
        if (reconnected) {
            // Load joined groups
            dis.dispatch(GroupActions.fetchJoinedGroups(this.context.matrixClient));
        }
    },

    onClick(e) {
        dis.dispatch({action: 'deselect_tags'});
    },

    onCreateGroupClick(ev) {
        ev.stopPropagation();
        dis.dispatch({action: 'view_create_group'});
    },

    onClearFilterClick(ev) {
        dis.dispatch({action: 'deselect_tags'});
    },

    render() {
        const GroupsButton = sdk.getComponent('elements.GroupsButton');
        const DNDTagTile = sdk.getComponent('elements.DNDTagTile');
        const AccessibleButton = sdk.getComponent('elements.AccessibleButton');

        const tags = this.state.orderedTags.map((tag, index) => {
            return <DNDTagTile
                key={tag}
                tag={tag}
                index={index}
                selected={this.state.selectedTags.includes(tag)}
            />;
        });

        const clearButton = this.state.selectedTags.length > 0 ?
             :

;

        return

            <AccessibleButton className="mx_TagPanel_clearButton" onClick={this.onClearFilterClick}>
                { clearButton }
            </AccessibleButton>

            <GeminiScrollbar
                className="mx_TagPanel_scroller"
                autoShow={true}
                onClick={this.onClick}
            >
                <Droppable
                    droppableId="tag-panel-droppable"
                    type="draggable-TagTile"
                >
                    { (provided, snapshot) => (

                                { tags }
                                { provided.placeholder }

                    ) }
                </Droppable>
            </GeminiScrollbar>

                <GroupsButton tooltip={true} />

;
    },
});
export default TagPanel;
<commit_msg>s/autoShow/autoshow/<commit_after>/*
Copyright 2017 New Vector 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.
*/

import React from 'react';
import PropTypes from 'prop-types';
import { MatrixClient } from 'matrix-js-sdk';
import GeminiScrollbar from 'react-gemini-scrollbar';
import TagOrderStore from '../../stores/TagOrderStore';

import GroupActions from '../../actions/GroupActions';

import sdk from '../../index';
import dis from '../../dispatcher';
import { _t } from '../../languageHandler';

import { Droppable } from 'react-beautiful-dnd';

const TagPanel = React.createClass({
    displayName: 'TagPanel',

    contextTypes: {
        matrixClient: PropTypes.instanceOf(MatrixClient),
    },

    getInitialState() {
        return {
            orderedTags: [],
            selectedTags: [],
        };
    },

    componentWillMount: function() {
        this.unmounted = false;
        this.context.matrixClient.on("Group.myMembership", this._onGroupMyMembership);
        this.context.matrixClient.on("sync", this.onClientSync);

        this._tagOrderStoreToken = TagOrderStore.addListener(() => {
            if (this.unmounted) {
                return;
            }
            this.setState({
                orderedTags: TagOrderStore.getOrderedTags() || [],
                selectedTags: TagOrderStore.getSelectedTags(),
            });
        });
        // This could be done by anything with a matrix client
        dis.dispatch(GroupActions.fetchJoinedGroups(this.context.matrixClient));
    },

    componentWillUnmount() {
        this.unmounted = true;
        this.context.matrixClient.removeListener("Group.myMembership", this._onGroupMyMembership);
        this.context.matrixClient.removeListener("sync", this.onClientSync);
        if (this._filterStoreToken) {
            this._filterStoreToken.remove();
        }
    },

    _onGroupMyMembership() {
        if (this.unmounted) return;
        dis.dispatch(GroupActions.fetchJoinedGroups(this.context.matrixClient));
    },

    onClientSync(syncState, prevState) {
        // Consider the client reconnected if there is no error with syncing.
        // This means the state could be RECONNECTING, SYNCING or PREPARED.
        const reconnected = syncState !== "ERROR" && prevState !== syncState;
        if (reconnected) {
            // Load joined groups
            dis.dispatch(GroupActions.fetchJoinedGroups(this.context.matrixClient));
        }
    },

    onClick(e) {
        dis.dispatch({action: 'deselect_tags'});
    },

    onCreateGroupClick(ev) {
        ev.stopPropagation();
        dis.dispatch({action: 'view_create_group'});
    },

    onClearFilterClick(ev) {
        dis.dispatch({action: 'deselect_tags'});
    },

    render() {
        const GroupsButton = sdk.getComponent('elements.GroupsButton');
        const DNDTagTile = sdk.getComponent('elements.DNDTagTile');
        const AccessibleButton = sdk.getComponent('elements.AccessibleButton');

        const tags = this.state.orderedTags.map((tag, index) => {
            return <DNDTagTile
                key={tag}
                tag={tag}
                index={index}
                selected={this.state.selectedTags.includes(tag)}
            />;
        });

        const clearButton = this.state.selectedTags.length > 0 ?
             :

;

        return

            <AccessibleButton className="mx_TagPanel_clearButton" onClick={this.onClearFilterClick}>
                { clearButton }
            </AccessibleButton>

            <GeminiScrollbar
                className="mx_TagPanel_scroller"
                autoshow={true}
                onClick={this.onClick}
            >
                <Droppable
                    droppableId="tag-panel-droppable"
                    type="draggable-TagTile"
                >
                    { (provided, snapshot) => (

                                { tags }
                                { provided.placeholder }

                    ) }
                </Droppable>
            </GeminiScrollbar>

                <GroupsButton tooltip={true} />

;
    },
});
export default TagPanel;
<|endoftext|>


<commit_before>"use strict";

var P = require('bluebird');
var uuid = require('cassandra-uuid').TimeUuid;
var preq = require('preq');

var HyperSwitch = require('hyperswitch');
var HTTPError = HyperSwitch.HTTPError;
var URI = HyperSwitch.URI;

var mwUtil = require('../lib/mwUtil');

var spec = HyperSwitch.utils.loadSpec(__dirname + '/key_rev_value.yaml');

function ArchivalBucket(options) {
}

ArchivalBucket.prototype._latestName = function(bucket) {
    return bucket + '.latest';
};

ArchivalBucket.prototype._archiveName = function(bucket) {
    return bucket + '.archive';
};

ArchivalBucket.prototype.createBucket = function(hyper, req) {
    var self = this;
    var rp = req.params;
    return P.join(
        hyper.put({
            uri: new URI([rp.domain, 'sys', 'key_value', self._latestName(rp.bucket)]),
            headers: req.headers,
            body: req.body
        }),
        hyper.put({
            uri: new URI([rp.domain, 'sys', 'key_rev_value', self._archiveName(rp.bucket)]),
            headers: req.headers,
            body: req.body
        })
    )
    .then(function() {
        return { status: 201 }; });
};

ArchivalBucket.prototype.getRevision = function(hyper, req) {
    var self = this;
    var rp = req.params;
    var latestRequestPath = [rp.domain, 'sys', 'key_value', self._latestName(rp.bucket), rp.key];
    if (rp.tid) {
        latestRequestPath.push(rp.tid);
    }
    return hyper.get({
        uri: new URI(latestRequestPath),
        headers: req.headers
    })
    .then(function(res) {
        if (rp.revision) {
            var etagInfo = mwUtil.parseETag(res.headers.etag);
            if (Number.parseInt(etagInfo.rev) !== Number.parseInt(rp.revision)
                || (rp.tid && rp.tid !== etagInfo.tid)) {
                throw new HTTPError({ status: 404 });
            }
        }
        return res;
    })
    .catch({ status: 404 }, function() {
        var olderRequestPath = [rp.domain, 'sys', 'key_rev_value',
                self._archiveName(rp.bucket), rp.key];
        if (rp.revision) {
            olderRequestPath.push('' + rp.revision);
            if (rp.tid) {
                olderRequestPath.push(rp.tid);
            }
        }
        return hyper.get({
            uri: new URI(olderRequestPath),
            headers: req.headers
        });
    });
};

ArchivalBucket.prototype.listRevisions = function(hyper, req) {
    var self = this;
    var rp = req.params;
    return hyper.get({
        uri: new URI([rp.domain, 'sys', 'key_rev_value', self._archiveName(rp.bucket), rp.key, '']),
        query: req.query
    });
};

ArchivalBucket.prototype._updateNewerRev = function(hyper, req, rev, tid) {
    var self = this;
    var rp = req.params;
    var headers = req.headers || {};
    headers.etag = headers.etag || mwUtil.makeETag(rev, tid);

    return hyper.get({
        uri: new URI([rp.domain, 'sys', 'key_value', self._latestName(rp.bucket), rp.key])
    })
    .catch({ status: 404 }, function() { /* Ignore */ })
    .then(function(res) {
        if (res) {
            var etagInfo = mwUtil.parseETag(res.headers.etag);
            if (Number.parseInt(etagInfo.rev) > Number.parseInt(rp.revision)) {
                return P.resolve({ status: 200 });
            }
        }
        hyper.put({
            uri: new URI([rp.domain, 'sys', 'key_value', self._latestName(rp.bucket), rp.key]),
            headers: headers,
            body: req.body
        });
    });
};

ArchivalBucket.prototype.putRevision = function(hyper, req) {
    var self = this;
    var rp = req.params;

    var rev = mwUtil.parseRevision(rp.revision, 'key_rev_large_value');
    var tid = rp.tid && mwUtil.coerceTid(rp.tid, 'key_rev_large_value') || uuid.now().toString();

    var headers = req.headers || {};
    headers.etag = headers.etag || mwUtil.makeETag(rev, tid);
    return P.join(
        hyper.put({
            uri: new URI([rp.domain, 'sys', 'key_rev_value',
                self._archiveName(rp.bucket), rp.key, '' + rev, tid]),
            headers: headers,
            body: req.body
        }),
        self._updateNewerRev(hyper, req, rev, tid)
    )
    .spread(function(res1) { return res1; });
};

module.exports = function(options) {
    var archivalBucket = new ArchivalBucket(options);

    return {
        spec: spec, // Re-export from spec module
        operations: {
            createBucket: archivalBucket.createBucket.bind(archivalBucket),
            listRevisions: archivalBucket.listRevisions.bind(archivalBucket),
            getRevision: archivalBucket.getRevision.bind(archivalBucket),
            putRevision: archivalBucket.putRevision.bind(archivalBucket)
        }
    };
};
<commit_msg>Updated the archival bucket name<commit_after>"use strict";

var P = require('bluebird');
var uuid = require('cassandra-uuid').TimeUuid;
var preq = require('preq');

var HyperSwitch = require('hyperswitch');
var HTTPError = HyperSwitch.HTTPError;
var URI = HyperSwitch.URI;

var mwUtil = require('../lib/mwUtil');

var spec = HyperSwitch.utils.loadSpec(__dirname + '/key_rev_value.yaml');

function ArchivalBucket(options) {
}

ArchivalBucket.prototype._latestName = function(bucket) {
    return bucket + '.latest';
};

ArchivalBucket.prototype._archiveName = function(bucket) {
    return bucket;
};

ArchivalBucket.prototype.createBucket = function(hyper, req) {
    var self = this;
    var rp = req.params;
    return P.join(
        hyper.put({
            uri: new URI([rp.domain, 'sys', 'key_value', self._latestName(rp.bucket)]),
            headers: req.headers,
            body: req.body
        }),
        hyper.put({
            uri: new URI([rp.domain, 'sys', 'key_rev_value', self._archiveName(rp.bucket)]),
            headers: req.headers,
            body: req.body
        })
    )
    .then(function() {
        return { status: 201 }; });
};

ArchivalBucket.prototype.getRevision = function(hyper, req) {
    var self = this;
    var rp = req.params;
    var latestRequestPath = [rp.domain, 'sys', 'key_value', self._latestName(rp.bucket), rp.key];
    if (rp.tid) {
        latestRequestPath.push(rp.tid);
    }
    return hyper.get({
        uri: new URI(latestRequestPath),
        headers: req.headers
    })
    .then(function(res) {
        if (rp.revision) {
            var etagInfo = mwUtil.parseETag(res.headers.etag);
            if (parseInt(etagInfo.rev) !== parseInt(rp.revision)
                || (rp.tid && rp.tid !== etagInfo.tid)) {
                throw new HTTPError({ status: 404 });
            }
        }
        return res;
    })
    .catch({ status: 404 }, function() {
        var olderRequestPath = [rp.domain, 'sys', 'key_rev_value',
                self._archiveName(rp.bucket), rp.key];
        if (rp.revision) {
            olderRequestPath.push('' + rp.revision);
            if (rp.tid) {
                olderRequestPath.push(rp.tid);
            }
        }
        return hyper.get({
            uri: new URI(olderRequestPath),
            headers: req.headers
        });
    });
};

ArchivalBucket.prototype.listRevisions = function(hyper, req) {
    var self = this;
    var rp = req.params;
    return hyper.get({
        uri: new URI([rp.domain, 'sys', 'key_rev_value', self._archiveName(rp.bucket), rp.key, '']),
        query: req.query
    });
};

ArchivalBucket.prototype._updateNewerRev = function(hyper, req, rev, tid) {
    var self = this;
    var rp = req.params;
    var headers = req.headers || {};
    headers.etag = headers.etag || mwUtil.makeETag(rev, tid);

    return hyper.get({
        uri: new URI([rp.domain, 'sys', 'key_value', self._latestName(rp.bucket), rp.key])
    })
    .catch({ status: 404 }, function() { /* Ignore */ })
    .then(function(res) {
        if (res) {
            var etagInfo = mwUtil.parseETag(res.headers.etag);
            if (Number.parseInt(etagInfo.rev) > Number.parseInt(rp.revision)) {
                return P.resolve({ status: 200 });
            }
        }
        hyper.put({
            uri: new URI([rp.domain, 'sys', 'key_value', self._latestName(rp.bucket), rp.key]),
            headers: headers,
            body: req.body
        });
    });
};

ArchivalBucket.prototype.putRevision = function(hyper, req) {
    var self = this;
    var rp = req.params;

    var rev = mwUtil.parseRevision(rp.revision, 'key_rev_large_value');
    var tid = rp.tid && mwUtil.coerceTid(rp.tid, 'key_rev_large_value') || uuid.now().toString();

    var headers = req.headers || {};
    headers.etag = headers.etag || mwUtil.makeETag(rev, tid);
    return P.join(
        hyper.put({
            uri: new URI([rp.domain, 'sys', 'key_rev_value',
                self._archiveName(rp.bucket), rp.key, '' + rev, tid]),
            headers: headers,
            body: req.body
        }),
        self._updateNewerRev(hyper, req, rev, tid)
    )
    .spread(function(res1) { return res1; });
};

module.exports = function(options) {
    var archivalBucket = new ArchivalBucket(options);

    return {
        spec: spec, // Re-export from spec module
        operations: {
            createBucket: archivalBucket.createBucket.bind(archivalBucket),
            listRevisions: archivalBucket.listRevisions.bind(archivalBucket),
            getRevision: archivalBucket.getRevision.bind(archivalBucket),
            putRevision: archivalBucket.putRevision.bind(archivalBucket)
        }
    };
};
<|endoftext|>


<commit_before>import { EventDispatcher } from '../core/EventDispatcher.js';
import {
	MirroredRepeatWrapping,
	ClampToEdgeWrapping,
	RepeatWrapping,
	LinearEncoding,
	UnsignedByteType,
	RGBAFormat,
	LinearMipmapLinearFilter,
	LinearFilter,
	UVMapping
} from '../constants.js';
import { MathUtils } from '../math/MathUtils.js';
import { Vector2 } from '../math/Vector2.js';
import { Matrix3 } from '../math/Matrix3.js';
import { ImageUtils } from '../extras/ImageUtils.js';

let textureId = 0;

class Texture extends EventDispatcher {

	constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) {

		super();

		Object.defineProperty( this, 'id', { value: textureId ++ } );
		Object.defineProperty( this, 'isTexture', { value: true } );
		Object.defineProperty( this, 'DEFAULT_IMAGE', { value: undefined } );
		Object.defineProperty( this, 'DEFAULT_MAPPING', { value: UVMapping } );

		this.uuid = MathUtils.generateUUID();

		this.name = '';

		this.image = image;
		this.mipmaps = [];

		this.mapping = mapping;

		this.wrapS = wrapS;
		this.wrapT = wrapT;

		this.magFilter = magFilter;
		this.minFilter = minFilter;

		this.anisotropy = anisotropy;

		this.format = format;
		this.internalFormat = null;
		this.type = type;

		this.offset = new Vector2( 0, 0 );
		this.repeat = new Vector2( 1, 1 );
		this.center = new Vector2( 0, 0 );
		this.rotation = 0;

		this.matrixAutoUpdate = true;
		this.matrix = new Matrix3();

		// Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
		//
		// Also changing the encoding after already used by a Material will not automatically make the Material
		// update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
		this.encoding = encoding;

		this.generateMipmaps = true;
		this.premultiplyAlpha = false;
		this.flipY = true;
		this.unpackAlignment = 4;	// valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)

		// Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
		//
		// Also changing the encoding after already used by a Material will not automatically make the Material
		// update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
		this.encoding = encoding !== undefined ? encoding : LinearEncoding;

		this.version = 0;
		this.onUpdate = null;

	}

	updateMatrix() {

		this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );

	}

	clone() {

		return new this.constructor().copy( this );

	}

	copy( source ) {

		this.name = source.name;

		this.image = source.image;
		this.mipmaps = source.mipmaps.slice( 0 );

		this.mapping = source.mapping;

		this.wrapS = source.wrapS;
		this.wrapT = source.wrapT;

		this.magFilter = source.magFilter;
		this.minFilter = source.minFilter;

		this.anisotropy = source.anisotropy;

		this.format = source.format;
		this.internalFormat = source.internalFormat;
		this.type = source.type;

		this.offset.copy( source.offset );
		this.repeat.copy( source.repeat );
		this.center.copy( source.center );
		this.rotation = source.rotation;

		this.matrixAutoUpdate = source.matrixAutoUpdate;
		this.matrix.copy( source.matrix );

		this.generateMipmaps = source.generateMipmaps;
		this.premultiplyAlpha = source.premultiplyAlpha;
		this.flipY = source.flipY;
		this.unpackAlignment = source.unpackAlignment;
		this.encoding = source.encoding;

		return this;

	}

	toJSON( meta ) {

		const isRootObject = ( meta === undefined || typeof meta === 'string' );

		if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {

			return meta.textures[ this.uuid ];

		}

		const output = {

			metadata: {
				version: 4.5,
				type: 'Texture',
				generator: 'Texture.toJSON'
			},

			uuid: this.uuid,
			name: this.name,

			mapping: this.mapping,

			repeat: [ this.repeat.x, this.repeat.y ],
			offset: [ this.offset.x, this.offset.y ],
			center: [ this.center.x, this.center.y ],
			rotation: this.rotation,

			wrap: [ this.wrapS, this.wrapT ],

			format: this.format,
			type: this.type,
			encoding: this.encoding,

			minFilter: this.minFilter,
			magFilter: this.magFilter,
			anisotropy: this.anisotropy,

			flipY: this.flipY,

			premultiplyAlpha: this.premultiplyAlpha,
			unpackAlignment: this.unpackAlignment

		};

		if ( this.image !== undefined ) {

			// TODO: Move to THREE.Image

			const image = this.image;

			if ( image.uuid === undefined ) {

				image.uuid = MathUtils.generateUUID(); // UGH

			}

			if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {

				let url;

				if ( Array.isArray( image ) ) {

					// process array of images e.g. CubeTexture

					url = [];

					for ( let i = 0, l = image.length; i < l; i ++ ) {

						// check cube texture with data textures

						if ( image[ i ].isDataTexture ) {

							url.push( serializeImage( image[ i ].image ) );

						} else {

							url.push( serializeImage( image[ i ] ) );

						}

					}

				} else {

					// process single image

					url = serializeImage( image );

				}

				meta.images[ image.uuid ] = {
					uuid: image.uuid,
					url: url
				};

			}

			output.image = image.uuid;

		}

		if ( ! isRootObject ) {

			meta.textures[ this.uuid ] = output;

		}

		return output;

	}

	dispose() {

		this.dispatchEvent( { type: 'dispose' } );

	}

	transformUv( uv ) {

		if ( this.mapping !== UVMapping ) return uv;

		uv.applyMatrix3( this.matrix );

		if ( uv.x < 0 || uv.x > 1 ) {

			switch ( this.wrapS ) {

				case RepeatWrapping:

					uv.x = uv.x - Math.floor( uv.x );
					break;

				case ClampToEdgeWrapping:

					uv.x = uv.x < 0 ? 0 : 1;
					break;

				case MirroredRepeatWrapping:

					if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {

						uv.x = Math.ceil( uv.x ) - uv.x;

					} else {

						uv.x = uv.x - Math.floor( uv.x );

					}

					break;

			}

		}

		if ( uv.y < 0 || uv.y > 1 ) {

			switch ( this.wrapT ) {

				case RepeatWrapping:

					uv.y = uv.y - Math.floor( uv.y );
					break;

				case ClampToEdgeWrapping:

					uv.y = uv.y < 0 ? 0 : 1;
					break;

				case MirroredRepeatWrapping:

					if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {

						uv.y = Math.ceil( uv.y ) - uv.y;

					} else {

						uv.y = uv.y - Math.floor( uv.y );

					}

					break;

			}

		}

		if ( this.flipY ) {

			uv.y = 1 - uv.y;

		}

		return uv;

	}

	set needsUpdate( value ) {

		if ( value === true ) this.version ++;

	}

	serializeImage( image ) {

		if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
      ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
      ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {

			// default images

			return ImageUtils.getDataURL( image );

		} else {

			if ( image.data ) {

				// images of DataTexture

				return {
					data: Array.prototype.slice.call( image.data ),
					width: image.width,
					height: image.height,
					type: image.data.constructor.name
				};

			} else {

				console.warn( 'THREE.Texture: Unable to serialize Texture.' );
				return {};

			}

		}

	}

}

export { Texture };
<commit_msg>serializeImage -> this.serializeImage<commit_after>import { EventDispatcher } from '../core/EventDispatcher.js';
import {
	MirroredRepeatWrapping,
	ClampToEdgeWrapping,
	RepeatWrapping,
	LinearEncoding,
	UnsignedByteType,
	RGBAFormat,
	LinearMipmapLinearFilter,
	LinearFilter,
	UVMapping
} from '../constants.js';
import { MathUtils } from '../math/MathUtils.js';
import { Vector2 } from '../math/Vector2.js';
import { Matrix3 } from '../math/Matrix3.js';
import { ImageUtils } from '../extras/ImageUtils.js';

let textureId = 0;

class Texture extends EventDispatcher {

	constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) {

		super();

		Object.defineProperty( this, 'id', { value: textureId ++ } );
		Object.defineProperty( this, 'isTexture', { value: true } );
		Object.defineProperty( this, 'DEFAULT_IMAGE', { value: undefined } );
		Object.defineProperty( this, 'DEFAULT_MAPPING', { value: UVMapping } );

		this.uuid = MathUtils.generateUUID();

		this.name = '';

		this.image = image;
		this.mipmaps = [];

		this.mapping = mapping;

		this.wrapS = wrapS;
		this.wrapT = wrapT;

		this.magFilter = magFilter;
		this.minFilter = minFilter;

		this.anisotropy = anisotropy;

		this.format = format;
		this.internalFormat = null;
		this.type = type;

		this.offset = new Vector2( 0, 0 );
		this.repeat = new Vector2( 1, 1 );
		this.center = new Vector2( 0, 0 );
		this.rotation = 0;

		this.matrixAutoUpdate = true;
		this.matrix = new Matrix3();

		// Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
		//
		// Also changing the encoding after already used by a Material will not automatically make the Material
		// update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
		this.encoding = encoding;

		this.generateMipmaps = true;
		this.premultiplyAlpha = false;
		this.flipY = true;
		this.unpackAlignment = 4;	// valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)

		// Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
		//
		// Also changing the encoding after already used by a Material will not automatically make the Material
		// update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
		this.encoding = encoding !== undefined ? encoding : LinearEncoding;

		this.version = 0;
		this.onUpdate = null;

	}

	updateMatrix() {

		this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );

	}

	clone() {

		return new this.constructor().copy( this );

	}

	copy( source ) {

		this.name = source.name;

		this.image = source.image;
		this.mipmaps = source.mipmaps.slice( 0 );

		this.mapping = source.mapping;

		this.wrapS = source.wrapS;
		this.wrapT = source.wrapT;

		this.magFilter = source.magFilter;
		this.minFilter = source.minFilter;

		this.anisotropy = source.anisotropy;

		this.format = source.format;
		this.internalFormat = source.internalFormat;
		this.type = source.type;

		this.offset.copy( source.offset );
		this.repeat.copy( source.repeat );
		this.center.copy( source.center );
		this.rotation = source.rotation;

		this.matrixAutoUpdate = source.matrixAutoUpdate;
		this.matrix.copy( source.matrix );

		this.generateMipmaps = source.generateMipmaps;
		this.premultiplyAlpha = source.premultiplyAlpha;
		this.flipY = source.flipY;
		this.unpackAlignment = source.unpackAlignment;
		this.encoding = source.encoding;

		return this;

	}

	toJSON( meta ) {

		const isRootObject = ( meta === undefined || typeof meta === 'string' );

		if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {

			return meta.textures[ this.uuid ];

		}

		const output = {

			metadata: {
				version: 4.5,
				type: 'Texture',
				generator: 'Texture.toJSON'
			},

			uuid: this.uuid,
			name: this.name,

			mapping: this.mapping,

			repeat: [ this.repeat.x, this.repeat.y ],
			offset: [ this.offset.x, this.offset.y ],
			center: [ this.center.x, this.center.y ],
			rotation: this.rotation,

			wrap: [ this.wrapS, this.wrapT ],

			format: this.format,
			type: this.type,
			encoding: this.encoding,

			minFilter: this.minFilter,
			magFilter: this.magFilter,
			anisotropy: this.anisotropy,

			flipY: this.flipY,

			premultiplyAlpha: this.premultiplyAlpha,
			unpackAlignment: this.unpackAlignment

		};

		if ( this.image !== undefined ) {

			// TODO: Move to THREE.Image

			const image = this.image;

			if ( image.uuid === undefined ) {

				image.uuid = MathUtils.generateUUID(); // UGH

			}

			if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {

				let url;

				if ( Array.isArray( image ) ) {

					// process array of images e.g. CubeTexture

					url = [];

					for ( let i = 0, l = image.length; i < l; i ++ ) {

						// check cube texture with data textures

						if ( image[ i ].isDataTexture ) {

							url.push( this.serializeImage( image[ i ].image ) );

						} else {

							url.push( this.serializeImage( image[ i ] ) );

						}

					}

				} else {

					// process single image

					url = this.serializeImage( image );

				}

				meta.images[ image.uuid ] = {
					uuid: image.uuid,
					url: url
				};

			}

			output.image = image.uuid;

		}

		if ( ! isRootObject ) {

			meta.textures[ this.uuid ] = output;

		}

		return output;

	}

	dispose() {

		this.dispatchEvent( { type: 'dispose' } );

	}

	transformUv( uv ) {

		if ( this.mapping !== UVMapping ) return uv;

		uv.applyMatrix3( this.matrix );

		if ( uv.x < 0 || uv.x > 1 ) {

			switch ( this.wrapS ) {

				case RepeatWrapping:

					uv.x = uv.x - Math.floor( uv.x );
					break;

				case ClampToEdgeWrapping:

					uv.x = uv.x < 0 ? 0 : 1;
					break;

				case MirroredRepeatWrapping:

					if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {

						uv.x = Math.ceil( uv.x ) - uv.x;

					} else {

						uv.x = uv.x - Math.floor( uv.x );

					}

					break;

			}

		}

		if ( uv.y < 0 || uv.y > 1 ) {

			switch ( this.wrapT ) {

				case RepeatWrapping:

					uv.y = uv.y - Math.floor( uv.y );
					break;

				case ClampToEdgeWrapping:

					uv.y = uv.y < 0 ? 0 : 1;
					break;

				case MirroredRepeatWrapping:

					if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {

						uv.y = Math.ceil( uv.y ) - uv.y;

					} else {

						uv.y = uv.y - Math.floor( uv.y );

					}

					break;

			}

		}

		if ( this.flipY ) {

			uv.y = 1 - uv.y;

		}

		return uv;

	}

	set needsUpdate( value ) {

		if ( value === true ) this.version ++;

	}

	serializeImage( image ) {

		if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
      ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
      ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {

			// default images

			return ImageUtils.getDataURL( image );

		} else {

			if ( image.data ) {

				// images of DataTexture

				return {
					data: Array.prototype.slice.call( image.data ),
					width: image.width,
					height: image.height,
					type: image.data.constructor.name
				};

			} else {

				console.warn( 'THREE.Texture: Unable to serialize Texture.' );
				return {};

			}

		}

	}

}

export { Texture };
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import Well from 'react-bootstrap/lib/Well';
import Alert from 'react-bootstrap/lib/Alert';
import { Draft, Editor, EditorState, ContentState, RichUtils, convertFromRaw, convertToRaw } from 'draft-js';
import CodeUtils from 'draft-js-code';
import { stateToHTML } from 'draft-js-export-html';
import Helmet from 'react-helmet';
import cookie from 'react-cookie';
import superagent from 'superagent';
import { connect } from 'react-redux';
import { Link } from 'react-router';
require('./Community.scss');

var PrismDecorator = require('draft-js-prism');

import { getBlogEntries } from '../../redux/actions/getBlogEntriesActions';

@connect((store) => {
  return {
    activateNewUserState: store.activateNewUser.userStatus,
    getBlogEntriesState: store.getBlogEntries.articleList,
  };
})

export default class RichEditorExample extends Component {
  constructor(props) {
    super(props);
    var decorator = new PrismDecorator();
    this.state = {editorState: EditorState.createEmpty(decorator)};

    this.focus = () => this.refs.editor.focus();
    this.onChange = (editorState) => this.setState({editorState});

    this.handleKeyCommand = (command) => this._handleKeyCommand(command);
    this.onTab = (e) => this._onTab(e);
    this.handleReturn = (e) => this._handleReturn(e);
    //this.keyBindingFn = (e) => this._keyBindingFn(e);

    this.toggleBlockType = (type) => this._toggleBlockType(type);
    this.toggleInlineStyle = (style) => this._toggleInlineStyle(style);
  }

  componentDidMount() {
    superagent
    .post('/community')
    .send({ loadStatus: 1 })
    .set('Accept', 'application/json')
    .end((error, res) => {
      if (res.body.status === 1) {
        this.props.dispatch(getBlogEntries(res.body.blogArticles));
      }
    });
  }

  _handleKeyCommand(command) {
    const {editorState} = this.state;
    const newState = RichUtils.handleKeyCommand(editorState, command);
    if (newState) {
      this.onChange(newState);
      return true;
    }
    return false;
}

  /*_keyBindingFn(e) {
      var editorState = this.state.editorState;
      var command;

      if (CodeUtils.hasSelectionInBlock(editorState)) {
          command = CodeUtils.getKeyBinding(e);
      }
      if (command) {
          return command;
      }

      return Draft.getDefaultKeyBinding(e);
  }*/

  _handleReturn(e) {
      var editorState = this.state.editorState;

      if (!CodeUtils.hasSelectionInBlock(editorState)) {
          return;
      }
      this.onChange(
          CodeUtils.handleReturn(e, editorState)
      );
      return true;
  }

  _onTab(e) {
    /*const maxDepth = 4;
    this.onChange(RichUtils.onTab(e, this.state.editorState, maxDepth));*/
    var editorState = this.state.editorState;
    if (!CodeUtils.hasSelectionInBlock(editorState)) {
        return;
    }
    this.onChange(
        CodeUtils.handleTab(e, editorState)
    );
  }

  _toggleBlockType(blockType) {
    this.onChange(
      RichUtils.toggleBlockType(
        this.state.editorState,
        blockType
      )
    );
  }

  _toggleInlineStyle(inlineStyle) {
    this.onChange(
      RichUtils.toggleInlineStyle(
        this.state.editorState,
        inlineStyle
      )
    );
  }

  saveDataToDatabase() {
    const titelData = this.refs.titel.value;
    const markupData = stateToHTML(this.state.editorState.getCurrentContent());
    const userEmail = cookie.load('ck_email');

    if(titelData.length > 2 && titelData.length < 60){
      if (markupData.length > 40) {
        this.refs.titel.value = '';
        superagent
        .post('/community')
        .send({ loadStatus: 0, markupData: markupData, titelData: titelData, userEmail: userEmail })
        .set('Accept', 'application/json')
        .end((error, res) => {
          if (res.body.status === 1) {
            this.props.dispatch(getBlogEntries(res.body.blogArticles));

            /* Clear editor state */
            const editorState = EditorState.push(this.state.editorState, ContentState.createFromText(''));
            this.setState({ editorState });
          }
        });
      } else{
        console.log("Minimum 40 Zeichen bei Markup Daten!");
      }
    } else{
      console.log("Minimum 3 Zeichen & maximal 60 Zeichen für Titel!");
    }
  }

  render() {
    const {draftjsStatus, draftjsMsg, editorState} = this.state;
    const { activateNewUserState, getBlogEntriesState } = this.props;
    //const styles = require('./Community.scss');

    let className = 'RichEditor-editor';
    var contentState = editorState.getCurrentContent();
    if (!contentState.hasText()) {
      if (contentState.getBlockMap().first().getType() !== 'unstyled') {
        className += ' RichEditor-hidePlaceholder';
      }
    }

    let blogContentDef = '';
    /*getBlogEntriesState.articles.sort(function(a, b){
        return b.unixtime-a.unixtime
    });*/
    getBlogEntriesState.articles.forEach(function(entry){
      blogContentDef += '

' + entry.titel + '

' + entry.markup + '
Author: ' + entry.userEmail + ' | ' + entry.timeFormatted + '
';
    });

    return (

Community

        <Helmet title="Community"/>
        {(activateNewUserState.activatedUser === true && activateNewUserState.loggedInUser === true) || (cookie.load('ck_userLoggedIn') === true && cookie.load('ck_activation') === true) ?

          <form className="community-title-form form-inline">

              <input type="text" ref="titel" name="titel" id="titel" placeholder="Titel" className="titleStyle form-control"/>

          </form>

          <BlockStyleControls
            editorState={editorState}
            onToggle={this.toggleBlockType}
            />
          <InlineStyleControls
            editorState={editorState}
            onToggle={this.toggleInlineStyle}
            />

            <Editor
              blockStyleFn={getBlockStyle}
              customStyleMap={styleMap}
              editorState={editorState}
              handleKeyCommand={this.handleKeyCommand}
              handleReturn={this.handleReturn}
              onChange={this.onChange}
              //keyBindingFn={this.keyBindingFn}
              onTab={this.onTab}
              placeholder=""
              ref="editor"
              spellCheck={true}
              />

        <button className="btn btn-primary" onClick={this.saveDataToDatabase.bind(this)}>Speichern</button>

        :
        <Alert bsStyle="warning">Wenn du selbst Beiträge erfassen möchtest, erstelle jetzt <Link to="/registrieren">hier</Link> deinen eigenen Account.</Alert>
        }

    );
  }
}

 const styleMap = {
   CODE: {
     backgroundColor: 'rgba(0, 0, 0, 0.05)',
     fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace',
     fontSize: 16,
     padding: 2,
   },
 };

 function getBlockStyle(block) {
   switch (block.getType()) {
     case 'blockquote': return 'RichEditor-blockquote';
     case 'code-block': return 'language-css';
     default: return null;
   }
 }

 class StyleButton extends Component {
   constructor() {
     super();
     this.onToggle = (e) => {
       e.preventDefault();
       this.props.onToggle(this.props.style);
     };
   }

   render() {
     let className = 'RichEditor-styleButton';
     if (this.props.active) {
       className += ' RichEditor-activeButton';
     }

     return (

         {this.props.label}

     );
   }
 }

 const BLOCK_TYPES = [
   /*{label: 'H1', style: 'header-one'},
   {label: 'H2', style: 'header-two'},
   {label: 'H3', style: 'header-four'},*/
   {label: 'Headline', style: 'header-three'},
   /*{label: 'H5', style: 'header-five'},
   {label: 'H6', style: 'header-six'},*/
   {label: 'Blockquote', style: 'blockquote'},
   {label: 'UL', style: 'unordered-list-item'},
   {label: 'OL', style: 'ordered-list-item'},
   {label: 'Code Block', style: 'code-block'},
 ];

 const BlockStyleControls = (props) => {
   const {editorState} = props;
   const selection = editorState.getSelection();
   const blockType = editorState
     .getCurrentContent()
     .getBlockForKey(selection.getStartKey())
     .getType();

   return (

       {BLOCK_TYPES.map((type) =>


<commit_before>var unirest = require('unirest');
var moment = require('moment');

var studentSchedules = [];
var numStudents = 0;

/*

{
    className: [
        {
            section: CMSC132-0101
            times: [
                {
                    days: MWF,
                    start: fdsa,
                    end: fewage
                },
                ...
            ]
        },
        ...
    ],
    ...
}

*/

function testFunction(classNames, callback) {
    let innerFlag = 0;
    let sections = [];
    let classes = {};
    for (let k = 0; k < classNames.length; k++) {
        console.log("Querying " + classNames[k]);
        unirest
        .get('http://api.umd.io/v0/courses/' + classNames[k])
        .end((response) => {
            sections = response.body['sections'];
            //console.log(response.body['sections']);
            var className = response.body['course_id'];

            if (sections == undefined) {
                callback({type: 'error', message: response.body['message']});
                return;
            }

            innerFlag += sections.length;
            classes[className] = [];
            sections.map(function(section) {
                unirest
                .get('http://api.umd.io/v0/courses/sections/' + section)
                .end(function(response) {
                    //console.log(response.body);
                    //console.log(response.body['section_id']);
                    //console.log(response.body['meetings'][0]['start_time']);
                    //console.log(response.body['meetings'][0]['end_time']);

                    var sectionName = response.body['section_id'];
                    var meetingTimes = [];
                    if (response.body['meetings'] == undefined) {
                        return;
                    }
                    response.body['meetings'].map((meeting) => {
                        var startTime = meeting['start_time'];
                        if (startTime == "")
                            return;

                        var endTime = meeting['end_time']
                        var startTimeFormatted = moment(startTime, ["h:mmA"]).format("HHmm");
                        var endTimeFormatted = moment(endTime, ["h:mmA"]).format("HHmm");
                        //console.log(response.body['meetings'][0]['days']);

                        var dayString = meeting['days'].toString();
                        for (let i = 0; i < dayString.length; i++) {
                            var dayChar = "";
                            if (dayString[i] != 'T') {
                                dayChar = dayString[i];
                            } else {
                                dayChar = dayString[i] + dayString[i + 1];
                                i++;
                            }
                            var sectionObj = {
                                days: dayChar,
                                start: startTimeFormatted,
                                end: endTimeFormatted
                            }
                            //console.log(sectionObj);

                            meetingTimes.push(sectionObj);
                        }
                    });

                    classes[className].push({
                        section: sectionName,
                        times: meetingTimes
                    });

                    innerFlag--;
                    if (innerFlag == 0) {
                        //console.log(classes)
                        validateFirst(classes, callback);
                        //return classes;
                    }
                });
            });
        });
    }
};

function debug(classes1) {
    for (let c in classes1) {
        console.log(c);
        classes1[c].forEach((section) => {
            console.log(section);
        })
    }
}

// Contains functions to help filter one person
function validateFirst(classes1, callback) {
    var goodOnes = [];
    var notPossible = false;
    var isFirst = true;

    //Go through all classes
    for (let c in classes1) {
        var newGoodOnes = [];
        //console.log("Class");
        //console.log(c);
        //Give classname c, get all of c's sections as an array
        //each section is passed in the forEach
        classes1[c].forEach((section) => {
            var foundMatch = false;
            //sections for the first class, add them all to goodOnes
            if (isFirst) {
                //console.log("First");
                var tmp = [];
                tmp.push(section);
                goodOnes.push(tmp);
                //console.log(goodOnes.length);
            } else {
                //Current set of already compatible section times in goodOnes
                //console.log(goodOnes.length);
                goodOnes.forEach((goodSchedule) => {
                    //no conflicts with this combination
                    if (!hasConflict(section, goodSchedule)) {
                        var combined = goodSchedule.concat(section); //add section number that fits
                        newGoodOnes.push(combined); //now add the sections to the newGoodOnes
                        foundMatch = true;
                    }
                });
            }
            //console.log("After");

        });
        if (!isFirst) {
            goodOnes = newGoodOnes;
        }
        //console.log(goodOnes);
        isFirst = false;

    }
    //console.log(goodOnes)
    studentSchedules.push(goodOnes);
    if (studentSchedules.length == numStudents)
        schedulesLoaded(callback);
}

//Determines if a meeting conflicts with a set of already validated meetings
function hasConflict(curr, sections) {
    let returnValue = false;
    for (let section of sections) {
        for (let st of section.times) {
            for (let currTimesObj of curr.times) {
                if (currTimesObj.days == st.days) {
                    //console.log('\n---\n' + curr.section + ' - ' + section.section);
                    //console.log(st.days);
                    //console.log(currTimesObj.start + " vs. " + st.start);
                    if ((currTimesObj.start >= st.start && currTimesObj.start <= st.end) || (currTimesObj.end >= st.start && currTimesObj.end <= st.end)) {
                        //returnValue = true;
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

function schedulesLoaded(callback) {
    //console.log(studentSchedules[0]);
    //console.log("\n=====\n");
    //console.log(studentSchedules[1]);
    getOverlaps(studentSchedules[0], studentSchedules[1], callback);
}

function getOverlaps(scheduleArr1, scheduleArr2, callback) {
    //schedules is an array of "schedule"
    //A schedule is an array of sections
    var absoluteMax = 1;
    var perfectPairs = [];
    //Go through all schedules in first student

    scheduleArr1.forEach((schedule1) => {
        scheduleArr2.forEach((schedule2) => {
            var localMax = numClassesInCommon(schedule1, schedule2);
            console.log(localMax + "don't worry, its loading :)");

            if (localMax < absoluteMax) {
                return; //no classes in common so move on to next schedule2
            }
            else if (localMax == absoluteMax) {
                perfectPairs.push(makePair(schedule1, schedule2));
            }
            else { //case when localMax > absMax, it's the new absMax
                absoluteMax = localMax;
                perfectPairs = []; //empty to make room
                perfectPairs.push(makePair(schedule1, schedule2));
            }
        });

    });

    callback(perfectPairs.splice(0, 25), absoluteMax);
    /*
    perfectPairs.forEach((p) => {
        console.log("\n=====\ns1");
        for (var x = 0; x < p.s1.length; x++) {
            console.log("Section: " + p.s1[x].section);
            console.log(p.s1[x].times);
        }
        console.log("\ns2");
        for (var x = 0; x < p.s2.length; x++) {
            console.log("Section: " + p.s2[x].section);
            console.log(p.s2[x].times);
        }

    });
    */

}

function numClassesInCommon(schedule1, schedule2) {
    var common = 0; // # of classes in common
    schedule1.forEach((section1) => {      // Each section in the first student's schedule
        schedule2.forEach((section2) => {  // Each section in the second student's schedule
            if (section1.section === section2.section) // Compare the names
                common++;
        });
    });
    return common;
}

function makePair(schedule1, schedule2) {
    var pair = {};
    pair.s1 = schedule1;
    pair.s2 = schedule2;
    return pair;
}

function getCommonSections(schedule1, schedule2) {
    var common = [];

    schedule1.forEach((section1) => { //go thrru 1's sections
        schedule2.forEach((section2) => {//compare each 1's section with all 2's sections
            if (section1.section === section2.section) {
                common.push(section1); //if a section matches
            }
        });
    });

    return common;
}

module.exports = function(s1, s2, callback) {
    var StudentClasses = [s1, s2];
    numStudents = StudentClasses.length;

    for (let i = 0; i < StudentClasses.length; i++) {
        testFunction(StudentClasses[i], callback);
    }
}
<commit_msg>updating umd.io calls to https<commit_after>var unirest = require('unirest');
var moment = require('moment');

var studentSchedules = [];
var numStudents = 0;

/*

{
    className: [
        {
            section: CMSC132-0101
            times: [
                {
                    days: MWF,
                    start: fdsa,
                    end: fewage
                },
                ...
            ]
        },
        ...
    ],
    ...
}

*/

function testFunction(classNames, callback) {
    let innerFlag = 0;
    let sections = [];
    let classes = {};
    for (let k = 0; k < classNames.length; k++) {
        console.log("Querying " + classNames[k]);
        unirest
        .get('https://api.umd.io/v0/courses/' + classNames[k])
        .end((response) => {
            sections = response.body['sections'];
            //console.log(response.body['sections']);
            var className = response.body['course_id'];

            if (sections == undefined) {
                callback({type: 'error', message: response.body['message']});
                return;
            }

            innerFlag += sections.length;
            classes[className] = [];
            sections.map(function(section) {
                unirest
                .get('https://api.umd.io/v0/courses/sections/' + section)
                .end(function(response) {
                    //console.log(response.body);
                    //console.log(response.body['section_id']);
                    //console.log(response.body['meetings'][0]['start_time']);
                    //console.log(response.body['meetings'][0]['end_time']);

                    var sectionName = response.body['section_id'];
                    var meetingTimes = [];
                    if (response.body['meetings'] == undefined) {
                        return;
                    }
                    response.body['meetings'].map((meeting) => {
                        var startTime = meeting['start_time'];
                        if (startTime == "")
                            return;

                        var endTime = meeting['end_time']
                        var startTimeFormatted = moment(startTime, ["h:mmA"]).format("HHmm");
                        var endTimeFormatted = moment(endTime, ["h:mmA"]).format("HHmm");
                        //console.log(response.body['meetings'][0]['days']);

                        var dayString = meeting['days'].toString();
                        for (let i = 0; i < dayString.length; i++) {
                            var dayChar = "";
                            if (dayString[i] != 'T') {
                                dayChar = dayString[i];
                            } else {
                                dayChar = dayString[i] + dayString[i + 1];
                                i++;
                            }
                            var sectionObj = {
                                days: dayChar,
                                start: startTimeFormatted,
                                end: endTimeFormatted
                            }
                            //console.log(sectionObj);

                            meetingTimes.push(sectionObj);
                        }
                    });

                    classes[className].push({
                        section: sectionName,
                        times: meetingTimes
                    });

                    innerFlag--;
                    if (innerFlag == 0) {
                        //console.log(classes)
                        validateFirst(classes, callback);
                        //return classes;
                    }
                });
            });
        });
    }
};

function debug(classes1) {
    for (let c in classes1) {
        console.log(c);
        classes1[c].forEach((section) => {
            console.log(section);
        })
    }
}

// Contains functions to help filter one person
function validateFirst(classes1, callback) {
    var goodOnes = [];
    var notPossible = false;
    var isFirst = true;

    //Go through all classes
    for (let c in classes1) {
        var newGoodOnes = [];
        //console.log("Class");
        //console.log(c);
        //Give classname c, get all of c's sections as an array
        //each section is passed in the forEach
        classes1[c].forEach((section) => {
            var foundMatch = false;
            //sections for the first class, add them all to goodOnes
            if (isFirst) {
                //console.log("First");
                var tmp = [];
                tmp.push(section);
                goodOnes.push(tmp);
                //console.log(goodOnes.length);
            } else {
                //Current set of already compatible section times in goodOnes
                //console.log(goodOnes.length);
                goodOnes.forEach((goodSchedule) => {
                    //no conflicts with this combination
                    if (!hasConflict(section, goodSchedule)) {
                        var combined = goodSchedule.concat(section); //add section number that fits
                        newGoodOnes.push(combined); //now add the sections to the newGoodOnes
                        foundMatch = true;
                    }
                });
            }
            //console.log("After");

        });
        if (!isFirst) {
            goodOnes = newGoodOnes;
        }
        //console.log(goodOnes);
        isFirst = false;

    }
    //console.log(goodOnes)
    studentSchedules.push(goodOnes);
    if (studentSchedules.length == numStudents)
        schedulesLoaded(callback);
}

//Determines if a meeting conflicts with a set of already validated meetings
function hasConflict(curr, sections) {
    let returnValue = false;
    for (let section of sections) {
        for (let st of section.times) {
            for (let currTimesObj of curr.times) {
                if (currTimesObj.days == st.days) {
                    //console.log('\n---\n' + curr.section + ' - ' + section.section);
                    //console.log(st.days);
                    //console.log(currTimesObj.start + " vs. " + st.start);
                    if ((currTimesObj.start >= st.start && currTimesObj.start <= st.end) || (currTimesObj.end >= st.start && currTimesObj.end <= st.end)) {
                        //returnValue = true;
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

function schedulesLoaded(callback) {
    //console.log(studentSchedules[0]);
    //console.log("\n=====\n");
    //console.log(studentSchedules[1]);
    getOverlaps(studentSchedules[0], studentSchedules[1], callback);
}

function getOverlaps(scheduleArr1, scheduleArr2, callback) {
    //schedules is an array of "schedule"
    //A schedule is an array of sections
    var absoluteMax = 1;
    var perfectPairs = [];
    //Go through all schedules in first student

    scheduleArr1.forEach((schedule1) => {
        scheduleArr2.forEach((schedule2) => {
            var localMax = numClassesInCommon(schedule1, schedule2);
            console.log(localMax + "don't worry, its loading :)");

            if (localMax < absoluteMax) {
                return; //no classes in common so move on to next schedule2
            }
            else if (localMax == absoluteMax) {
                perfectPairs.push(makePair(schedule1, schedule2));
            }
            else { //case when localMax > absMax, it's the new absMax
                absoluteMax = localMax;
                perfectPairs = []; //empty to make room
                perfectPairs.push(makePair(schedule1, schedule2));
            }
        });

    });

    callback(perfectPairs.splice(0, 25), absoluteMax);
    /*
    perfectPairs.forEach((p) => {
        console.log("\n=====\ns1");
        for (var x = 0; x < p.s1.length; x++) {
            console.log("Section: " + p.s1[x].section);
            console.log(p.s1[x].times);
        }
        console.log("\ns2");
        for (var x = 0; x < p.s2.length; x++) {
            console.log("Section: " + p.s2[x].section);
            console.log(p.s2[x].times);
        }

    });
    */

}

function numClassesInCommon(schedule1, schedule2) {
    var common = 0; // # of classes in common
    schedule1.forEach((section1) => {      // Each section in the first student's schedule
        schedule2.forEach((section2) => {  // Each section in the second student's schedule
            if (section1.section === section2.section) // Compare the names
                common++;
        });
    });
    return common;
}

function makePair(schedule1, schedule2) {
    var pair = {};
    pair.s1 = schedule1;
    pair.s2 = schedule2;
    return pair;
}

function getCommonSections(schedule1, schedule2) {
    var common = [];

    schedule1.forEach((section1) => { //go thrru 1's sections
        schedule2.forEach((section2) => {//compare each 1's section with all 2's sections
            if (section1.section === section2.section) {
                common.push(section1); //if a section matches
            }
        });
    });

    return common;
}

module.exports = function(s1, s2, callback) {
    var StudentClasses = [s1, s2];
    numStudents = StudentClasses.length;

    for (let i = 0; i < StudentClasses.length; i++) {
        testFunction(StudentClasses[i], callback);
    }
}
<|endoftext|>


<commit_before>function check_login() {
    var username = $('#log_username_field').val();
    var pass = $('#log_pass_field').val();
    if (!username && !pass) {
        return false;
    }
    var data = {
        'login': username,
        'pass': pass,
        'cb_csrf_secured': $('#cb_csrf_secured').val()
    }
    var request = $.ajax({
        type: 'POST',
        url: 'http://localhost/Codeigniter-Social-Network/ajax/login',
        data: data,
        dataType: 'json',
        encode: true
    }).done(function(data, e) {
        $('#cb_csrf_secured').val(data.cb_csrf_secured);
        if (data.error) {
            $('p#login_errors').text(data.error);
            e.preventDefault();
            return false;
        } else {
            location.reload();
            e.preventDefault();
            return false;
        }
    });
};<commit_msg>Added Login & Logout Functionality<commit_after>function check_login() {
    var username = $('#log_username_field').val();
    var pass = $('#log_pass_field').val();
    if (!username && !pass) {
        return false;
    }
    var data = {
        'login': username,
        'pass': pass,
        'cb_csrf_secured': $('#cb_csrf_secured').val()
    }
    var request = $.ajax({
        type: 'POST',
        url: 'YOUR BASE URL/ajax/login',
        data: data,
        dataType: 'json',
        encode: true
    }).done(function(data, e) {
        $('#cb_csrf_secured').val(data.cb_csrf_secured);
        if (data.error) {
            $('p#login_errors').text(data.error);
            e.preventDefault();
            return false;
        } else {
            location.reload();
            e.preventDefault();
            return false;
        }
    });
};<|endoftext|>


<commit_before>(function() {

  // TODO: Pass USB vendor and product ID filter when supported by Chrome.
  //       - maybe not? We might want to connect to a non-official Espruino board
  // TODO: Use device name when/if supported

  function getStatus(ignoreSettings) {
    if (typeof navigator == "undefined") {
      return {warning:"Not running in a browser"};
    }
    if (!navigator.serial) {
      if (Espruino.Core.Utils.isChrome())
        return {error:`Chrome currently requires <code>chrome://flags/#enable-experimental-web-platform-features</code> to be enabled.`};
      else if (Espruino.Core.Utils.isFirefox())
        return {error:`Firefox doesn't support Web Serial - try using Chrome`};
      else
        return {error:"No navigator.serial. Do you have a supported browser?"};
    }
    if (window && window.location && window.location.protocol=="http:" &&
        window.location.hostname!="localhost") {
      return {error:"Serving off HTTP (not HTTPS)"};
    }
    if (!ignoreSettings && !Espruino.Config.WEB_SERIAL)
      return {warning:`"Web Serial" disabled in settings`};
    return true;
  }

  var OK = true;
  var testedCompatibility = false;
  /// List of previously paired devices that we could reconnect to without the chooser
  var pairedDevices = [];

  var serialPort;
  var serialPortReader;
  var connectionDisconnectCallback;

  function init() {
    Espruino.Core.Config.add("WEB_SERIAL", {
      section : "Communications",
      name : "Connect over Serial (Web Serial)",
      descriptionHTML : 'Allow connection to Espruino from the Web Browser via Serial. The API must currently be enabled by pasting chrome://flags#enable-experimental-web-platform-features into the address bar and clicking Enable',
      type : "boolean",
      defaultValue : true,
    });
    // If we're ok and have the getDevices extension, use it to remember previously paired devices
    if (getStatus(true)===true && navigator.serial.getPorts) {
      console.log("Serial> serial.getPorts exists - grab known devices");
      navigator.serial.getPorts().then(devices=>{
        pairedDevices = devices;
      });
    }
  }

  function getSerialDeviceInfo(device) {
    var idx = pairedDevices.indexOf(device);
    var deviceInfo = { path : "webserial:"+(idx>=0?idx:""), type : "usb", description : "Previously connected device"};
    if (device.getInfo) {
      var info = device.getInfo();
      if (info.usbVendorId && info.usbProductId) {
        deviceInfo.path = "webserial:"+(63356+info.usbVendorId).toString(16).substr(-4)+":"+(63356+info.usbProductId).toString(16).substr(-4);
      }
    }
    return deviceInfo;
  }

  function getPorts(callback) {
    if (!testedCompatibility) {
      testedCompatibility = true;
      if (getStatus(true)!==true)
        OK = false;
    }
    if (Espruino.Config.WEB_SERIAL && OK) {
      var list = [{path:'Web Serial', description:'Serial', type : "serial", promptsUser:true}];
      pairedDevices.forEach(function(dev) {
        list.push(getSerialDeviceInfo(dev));
      });
      callback(list, true/*instantPorts*/);
    } else
      callback(undefined, true/*instantPorts*/);
  }

  function openSerial(path, openCallback, receiveCallback, disconnectCallback) {
    var promise;
    // Check for pre-paired devices
    serialPort = pairedDevices.find(dev=>getSerialDeviceInfo(dev).path == path);
    if (serialPort) {
      console.log("Serial> Pre-paired Web Serial device already found");
      promise = Promise.resolve(serialPort);
    } else {
      console.log("Serial> Starting device chooser");
      promise = navigator.serial.requestPort({});
    }
    promise.then(function(port) {
      Espruino.Core.Status.setStatus("Connecting to serial port");
      serialPort = port;
      var br = parseInt(Espruino.Config.BAUD_RATE);
      return port.open({ baudrate: br/*old*/, baudRate: br/*new*/ });
    }).then(function () {
      function readLoop() {
        serialPortReader = serialPort.readable.getReader();
        serialPortReader.read().then(function ({ value, done }) {
          serialPortReader.releaseLock();
          if (value) {
            receiveCallback(value.buffer);
          }
          if (done) {
            disconnectCallback();
          } else {
            readLoop();
          }
        });
      }
      readLoop();
      Espruino.Core.Status.setStatus("Serial connected. Receiving data...");
      if (!pairedDevices.includes(serialPort))
        pairedDevices.push(serialPort);

      openCallback({ portName : getSerialDeviceInfo(serialPort).path });
    }).catch(function(error) {
      console.log('Serial> ERROR: ' + error);
      disconnectCallback();
    });
  }

  function closeSerial() {
    if (serialPort) {
      serialPortReader.cancel().then(function() {
        serialPort.close();
        serialPort = undefined;
        serialPortReader = undefined;
      });
    }
    if (connectionDisconnectCallback) {
      connectionDisconnectCallback();
      connectionDisconnectCallback = undefined;
    }
  }

  function writeSerial(data, callback) {
    var writer = serialPort.writable.getWriter();
    writer.write(Espruino.Core.Utils.stringToArrayBuffer(data)).then(function() {
      callback();
    }).catch(function(error) {
      console.log('Serial> SEND ERROR: ' + error);
      closeSerial();
    });
    writer.releaseLock();
  }

  // ----------------------------------------------------------

  Espruino.Core.Serial.devices.push({
    "name" : "Web Serial",
    "init" : init,
    "getStatus": getStatus,
    "getPorts": getPorts,
    "open": openSerial,
    "write": writeSerial,
    "close": closeSerial,
  });
})();
<commit_msg>Ensure `navigator.serial.getPorts` errors don't break other plugins<commit_after>(function() {

  // TODO: Pass USB vendor and product ID filter when supported by Chrome.
  //       - maybe not? We might want to connect to a non-official Espruino board
  // TODO: Use device name when/if supported

  function getStatus(ignoreSettings) {
    if (typeof navigator == "undefined") {
      return {warning:"Not running in a browser"};
    }
    if (getPortsErrorMessage!==undefined) {
      return {error:getPortsErrorMessage};
    }
    if (!navigator.serial) {
      if (Espruino.Core.Utils.isChrome())
        return {error:`Chrome currently requires <code>chrome://flags/#enable-experimental-web-platform-features</code> to be enabled.`};
      else if (Espruino.Core.Utils.isFirefox())
        return {error:`Firefox doesn't support Web Serial - try using Chrome`};
      else
        return {error:"No navigator.serial. Do you have a supported browser?"};
    }
    if (window && window.location && window.location.protocol=="http:" &&
        window.location.hostname!="localhost") {
      return {error:"Serving off HTTP (not HTTPS)"};
    }
    if (!ignoreSettings && !Espruino.Config.WEB_SERIAL)
      return {warning:`"Web Serial" disabled in settings`};
    return true;
  }

  var OK = true;
  var getPortsErrorMessage = undefined;
  var testedCompatibility = false;
  /// List of previously paired devices that we could reconnect to without the chooser
  var pairedDevices = [];

  var serialPort;
  var serialPortReader;
  var connectionDisconnectCallback;

  function init() {
    Espruino.Core.Config.add("WEB_SERIAL", {
      section : "Communications",
      name : "Connect over Serial (Web Serial)",
      descriptionHTML : 'Allow connection to Espruino from the Web Browser via Serial. The API must currently be enabled by pasting chrome://flags#enable-experimental-web-platform-features into the address bar and clicking Enable',
      type : "boolean",
      defaultValue : true,
    });
    // If we're ok and have the getDevices extension, use it to remember previously paired devices
    if (getStatus(true)===true && navigator.serial.getPorts) {
      console.log("Serial> serial.getPorts exists - grab known devices");
      navigator.serial.getPorts().then(devices=>{
        pairedDevices = devices;
      }, err=>{
        getPortsErrorMessage = err.toString();
        console.log("Serial> "+err.toString());
      });
    }
  }

  function getSerialDeviceInfo(device) {
    var idx = pairedDevices.indexOf(device);
    var deviceInfo = { path : "webserial:"+(idx>=0?idx:""), type : "usb", description : "Previously connected device"};
    if (device.getInfo) {
      var info = device.getInfo();
      if (info.usbVendorId && info.usbProductId) {
        deviceInfo.path = "webserial:"+(63356+info.usbVendorId).toString(16).substr(-4)+":"+(63356+info.usbProductId).toString(16).substr(-4);
      }
    }
    return deviceInfo;
  }

  function getPorts(callback) {
    if (!testedCompatibility) {
      testedCompatibility = true;
      if (getStatus(true)!==true)
        OK = false;
    }
    if (Espruino.Config.WEB_SERIAL && OK) {
      var list = [{path:'Web Serial', description:'Serial', type : "serial", promptsUser:true}];
      pairedDevices.forEach(function(dev) {
        list.push(getSerialDeviceInfo(dev));
      });
      callback(list, true/*instantPorts*/);
    } else
      callback(undefined, true/*instantPorts*/);
  }

  function openSerial(path, openCallback, receiveCallback, disconnectCallback) {
    var promise;
    // Check for pre-paired devices
    serialPort = pairedDevices.find(dev=>getSerialDeviceInfo(dev).path == path);
    if (serialPort) {
      console.log("Serial> Pre-paired Web Serial device already found");
      promise = Promise.resolve(serialPort);
    } else {
      console.log("Serial> Starting device chooser");
      promise = navigator.serial.requestPort({});
    }
    promise.then(function(port) {
      Espruino.Core.Status.setStatus("Connecting to serial port");
      serialPort = port;
      var br = parseInt(Espruino.Config.BAUD_RATE);
      return port.open({ baudrate: br/*old*/, baudRate: br/*new*/ });
    }).then(function () {
      function readLoop() {
        serialPortReader = serialPort.readable.getReader();
        serialPortReader.read().then(function ({ value, done }) {
          serialPortReader.releaseLock();
          if (value) {
            receiveCallback(value.buffer);
          }
          if (done) {
            disconnectCallback();
          } else {
            readLoop();
          }
        });
      }
      readLoop();
      Espruino.Core.Status.setStatus("Serial connected. Receiving data...");
      if (!pairedDevices.includes(serialPort))
        pairedDevices.push(serialPort);

      openCallback({ portName : getSerialDeviceInfo(serialPort).path });
    }).catch(function(error) {
      console.log('Serial> ERROR: ' + error);
      disconnectCallback();
    });
  }

  function closeSerial() {
    if (serialPort) {
      serialPortReader.cancel().then(function() {
        serialPort.close();
        serialPort = undefined;
        serialPortReader = undefined;
      });
    }
    if (connectionDisconnectCallback) {
      connectionDisconnectCallback();
      connectionDisconnectCallback = undefined;
    }
  }

  function writeSerial(data, callback) {
    var writer = serialPort.writable.getWriter();
    writer.write(Espruino.Core.Utils.stringToArrayBuffer(data)).then(function() {
      callback();
    }).catch(function(error) {
      console.log('Serial> SEND ERROR: ' + error);
      closeSerial();
    });
    writer.releaseLock();
  }

  // ----------------------------------------------------------

  Espruino.Core.Serial.devices.push({
    "name" : "Web Serial",
    "init" : init,
    "getStatus": getStatus,
    "getPorts": getPorts,
    "open": openSerial,
    "write": writeSerial,
    "close": closeSerial,
  });
})();
<|endoftext|>


<commit_before>var servico = require('./servico'),
	http = require('http'),
	app = servico();

http.createServer(app).listen(app.get('porta'), function () {
	console.log('Aplicação escutando na porta', app.get('porta'));
});<commit_msg>adiciona variavel de ambiente para ip do servidor<commit_after>var servico = require('./servico'),
	http = require('http'),
	app = servico();

var ipaddr  = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port    = parseInt(process.env.OPENSHIFT_NODEJS_PORT) || 8080;

http.createServer(app).listen(port, ipaddr, function () {
	console.log('Aplicação escutando na porta', app.get('porta'));
});<|endoftext|>


<commit_before>module.exports = Object.freeze({
  SERVER_NAME: 'Obsidian Bears',
  TEXT_CHANNEL: 'hubot-songlist',
  VOICE_CHANNEL: 'Hubot\'s DJ Booth',

  STATUS_DELAY_TIME: 3000,
  STREAM_VOLUME: 0.5
});
<commit_msg>Lower streaming volume<commit_after>module.exports = Object.freeze({
  SERVER_NAME: 'Obsidian Bears',
  TEXT_CHANNEL: 'hubot-songlist',
  VOICE_CHANNEL: 'Hubot\'s DJ Booth',

  STATUS_DELAY_TIME: 3000,
  STREAM_VOLUME: 0.2
});
<|endoftext|>


<commit_before>//app-specific sentence

module.exports = {
  debug : true,
  slackChannel : "#football",
  serverPort : 8080,
  pingInteralInMilliseconds : 1000, // * 60, // server main loop interval. 6 hours
  postBeforeTheMatch : true,
  postAfterTheMatch : true,
  preMatchWindowInMinutes: 5, // time before the match in minutes when we are ready to rant
  preMatchWindowCloseTimeInMinutesBeforeMatch: 1, //time before the match in minutes when ranting closes
  postMatchWindowInHours: 2,  // time after then match in hours when we are ready to rant
  postMatchWindowCloseTimeInHoursAfterMatch: 6 // time after the match in hours when rant window closes
};
<commit_msg>forgot to turn off the debugger<commit_after>//app-specific sentence

module.exports = {
  debug : false,
  slackChannel : "#football",
  serverPort : 8080,
  pingInteralInMilliseconds : 1000 * 60, // server main loop interval. 6 hours
  postBeforeTheMatch : true,
  postAfterTheMatch : true,
  preMatchWindowInMinutes: 5, // time before the match in minutes when we are ready to rant
  preMatchWindowCloseTimeInMinutesBeforeMatch: 1, //time before the match in minutes when ranting closes
  postMatchWindowInHours: 2,  // time after then match in hours when we are ready to rant
  postMatchWindowCloseTimeInHoursAfterMatch: 6 // time after the match in hours when rant window closes
};
<|endoftext|>


<commit_before>var config = {};

config.db = "";

module.exports = config;
<commit_msg>Add dev config<commit_after>var config = {};

config.db = 'mongodb://localhost/crawlr-dev';
config.sessionCookie = {
    maxAge: 8640000,
    httpOnly: true,
    secure: false
};
config.sessionSecret = 'TRASHDUMPYARD';
config.sessionKey = 'sessionId';
config.sessionCollection = 'sessions';

module.exports = config;
<|endoftext|>