<commit_before>var tswcalc = tswcalc || {};

tswcalc.import = function() {

    var start = function(vars) {
        for (var slotId in vars) {
            if (vars.hasOwnProperty(slotId)) {
                splitVars = vars[slotId].split(',');
                updateSlot(slotId, splitVars);
            }
        }
        tswcalc.summary.updateAllStats();
    };

    var updateSlot = function(slotId, values) {
        var slotObj = tswcalc.slots[slotId];
        slotObj.ql('10.' + values[0]);
        if(slotObj.isWeapon()) {
            slotObj.wtype(tswcalc.data.wtype_mapping.to_name[values[1]]);
            slotObj.el.wtype.change();
        } else {
            slotObj.role(tswcalc.data.role_mapping.to_stat[values[1]]);
        }
        slotObj.glyphQl('10.' + values[2]);
        slotObj.primaryGlyph(tswcalc.data.stat_mapping.to_stat[values[3]]);
        slotObj.secondaryGlyph(tswcalc.data.stat_mapping.to_stat[values[4]]);
        slotObj.el.btn.primary[values[5]].click();
        slotObj.el.btn.secondary[values[6]].click();
        // support signets
        if (typeof values[7] !== 'undefined' && typeof values[8] !== 'undefined') {
            if (values[8] >= 80) {
                slotObj.el.btn.nyraid.prop('disabled', false);
                slotObj.el.btn.nyraid.prop('checked', true);
                slotObj.el.btn.nyraid.change();
            } else {
                var signetQuality = tswcalc.data.signet_quality_mapping.to_name[values[7]];
                var signetId = values[8] != '0' ? values[8] : 'none';
                checkIfNyRaidItemAndEnableCheckButton(slotId);
                changeSignet(slotId, signetQuality, signetId);
            }
        } else {
            checkIfNyRaidItemAndEnableCheckButton(slotId);
            changeSignet(slotId, 'none', 'none');
        }
    };

    var checkIfNyRaidItemAndEnableCheckButton = function(slotId) {
        var slotObj = tswcalc.slots[slotId];
        if (isAllowedNyRaidItem(slotId)) {
            slotObj.el.btn.nyraid.prop('disabled', false);
        }
    };

    var changeSignet = function(slotId, quality, id) {
        var slotObj = tswcalc.slots[slotId];
        slotObj.signetQuality(quality);
        slotObj.signetId(id);
        slotObj.el.signetId.change();
    };

    var isAllowedNyRaidItem = function(slotId) {
        var slotObj = tswcalc.slots[slotId];
        return !slotObj.isWeapon() && typeof tswcalc.data.ny_raid_items[slotId][slotObj.role()] !== 'undefined';
    };

    var oPublic = {
        start: start
    };

    return oPublic;
}();<commit_msg>Fixed correct import of woodcutters<commit_after>var tswcalc = tswcalc || {};

tswcalc.import = function() {

    var start = function(vars) {
        for (var slotId in vars) {
            if (vars.hasOwnProperty(slotId)) {
                splitVars = vars[slotId].split(',');
                updateSlot(slotId, splitVars);
            }
        }
        tswcalc.summary.updateAllStats();
    };

    var updateSlot = function(slotId, values) {
        var slotObj = tswcalc.slots[slotId];
        slotObj.ql('10.' + values[0]);
        if(slotObj.isWeapon()) {
            slotObj.wtype(tswcalc.data.wtype_mapping.to_name[values[1]]);
            slotObj.el.wtype.change();
        } else {
            slotObj.role(tswcalc.data.role_mapping.to_stat[values[1]]);
        }
        slotObj.glyphQl('10.' + values[2]);
        slotObj.primaryGlyph(tswcalc.data.stat_mapping.to_stat[values[3]]);
        slotObj.secondaryGlyph(tswcalc.data.stat_mapping.to_stat[values[4]]);
        slotObj.el.btn.primary[values[5]].click();
        slotObj.el.btn.secondary[values[6]].click();
        // support signets
        if (typeof values[7] !== 'undefined' && typeof values[8] !== 'undefined') {
            if(values[8] >= 90) {
                slotObj.el.btn.woodcutters.prop('disabled', false);
                slotObj.el.btn.woodcutters.prop('checked', true);
                slotObj.el.btn.woodcutters.change();
            } else if (values[8] >= 80 && values[8] < 90) {
                slotObj.el.btn.nyraid.prop('disabled', false);
                slotObj.el.btn.nyraid.prop('checked', true);
                slotObj.el.btn.nyraid.change();
            } else {
                var signetQuality = tswcalc.data.signet_quality_mapping.to_name[values[7]];
                var signetId = values[8] != '0' ? values[8] : 'none';
                changeSignet(slotId, signetQuality, signetId);
            }
        } else {
            changeSignet(slotId, 'none', 'none');
        }
        checkIfNyRaidItemAndEnableCheckButton(slotId);
        checkIfWoodcutterNecklaceAndEnableCheckbutton(slotId);
    };

    var checkIfNyRaidItemAndEnableCheckButton = function(slotId) {
        var slotObj = tswcalc.slots[slotId];
        if (isAllowedNyRaidItem(slotId)) {
            slotObj.el.btn.nyraid.prop('disabled', false);
        }
    };

    var checkIfWoodcutterNecklaceAndEnableCheckbutton = function(slotId) {
        if(slotId == "neck") {
            var slotObj = tswcalc.slots[slotId];
            slotObj.el.btn.woodcutters.prop('disabled', false);
        }
    };

    var changeSignet = function(slotId, quality, id) {
        var slotObj = tswcalc.slots[slotId];
        slotObj.signetQuality(quality);
        slotObj.signetId(id);
        slotObj.el.signetId.change();
    };

    var isAllowedNyRaidItem = function(slotId) {
        var slotObj = tswcalc.slots[slotId];
        return !slotObj.isWeapon() && typeof tswcalc.data.ny_raid_items[slotId][slotObj.role()] !== 'undefined';
    };

    var oPublic = {
        start: start
    };

    return oPublic;
}();<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/shim/AudioContext"], function(Tone){

	if (Tone.supported){

		//fixes safari only bug which is still present in 11
		var ua = navigator.userAgent.toLowerCase();
		var isSafari = ua.indexOf("safari") !== -1 && ua.indexOf("chrome") === -1;
		if (isSafari){

			var WaveShaperNode = function(context){

				this._internalNode = this.input = this.output = context._native_createWaveShaper();

				this._curve = null;

				for (var prop in this._internalNode){
					this._defineProperty(this._internalNode, prop);
				}
			};

			Object.defineProperty(WaveShaperNode.prototype, "curve", {
				get : function(){
					return this._curve;
				},
				set : function(curve){
					this._curve = curve;
					var array = new Float32Array(curve.length+1);
					array.set(curve, 1);
					array[0] = curve[0];
					this._internalNode.curve = array;
				}
			});

			WaveShaperNode.prototype._defineProperty = function(context, prop){
				if (Tone.isUndef(this[prop])){
					Object.defineProperty(this, prop, {
						get : function(){
							if (typeof context[prop] === "function"){
								return context[prop].bind(context);
							} else {
								return context[prop];
							}
						},
						set : function(val){
							context[prop] = val;
						}
					});
				}
			};

			AudioContext.prototype._native_createWaveShaper = AudioContext.prototype.createWaveShaper;
			AudioContext.prototype.createWaveShaper = function(){
				return new WaveShaperNode(this);
			};
		}
	}

});
<commit_msg>using 'includes' instead of 'indexOf'<commit_after>define(["Tone/core/Tone", "Tone/shim/AudioContext"], function(Tone){

	if (Tone.supported){

		//fixes safari only bug which is still present in 11
		var ua = navigator.userAgent.toLowerCase();
		var isSafari = ua.includes("safari") && !ua.includes("chrome");
		if (isSafari){

			var WaveShaperNode = function(context){

				this._internalNode = this.input = this.output = context._native_createWaveShaper();

				this._curve = null;

				for (var prop in this._internalNode){
					this._defineProperty(this._internalNode, prop);
				}
			};

			Object.defineProperty(WaveShaperNode.prototype, "curve", {
				get : function(){
					return this._curve;
				},
				set : function(curve){
					this._curve = curve;
					var array = new Float32Array(curve.length+1);
					array.set(curve, 1);
					array[0] = curve[0];
					this._internalNode.curve = array;
				}
			});

			WaveShaperNode.prototype._defineProperty = function(context, prop){
				if (Tone.isUndef(this[prop])){
					Object.defineProperty(this, prop, {
						get : function(){
							if (typeof context[prop] === "function"){
								return context[prop].bind(context);
							} else {
								return context[prop];
							}
						},
						set : function(val){
							context[prop] = val;
						}
					});
				}
			};

			AudioContext.prototype._native_createWaveShaper = AudioContext.prototype.createWaveShaper;
			AudioContext.prototype.createWaveShaper = function(){
				return new WaveShaperNode(this);
			};
		}
	}

});
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Nov 17 2014 13:59:51 GMT+0000 (GMT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: './',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha'],

    // list of files / patterns to load in the browser
    files: [
      '../../static/scripts/vendor/polyfills/bind.js',
      '../../static/scripts/vendor/sinon.js',
      '../../static/scripts/vendor/chai.js',
      '../../static/scripts/vendor/promise.js',
      'lib/errors.js',
      'lib/tab-store.js',
      'lib/tab-state.js',
      'lib/tab-error-cache.js',
      'lib/sidebar-injector.js',
      'lib/browser-action.js',
      'lib/help-page.js',
      'lib/hypothesis-chrome-extension.js',
      'test/*-test.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true
  });
};
<commit_msg>Get Promise explicitly through requires<commit_after>// Karma configuration
// Generated on Mon Nov 17 2014 13:59:51 GMT+0000 (GMT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: './',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha'],

    // list of files / patterns to load in the browser
    files: [
      '../../../node_modules/es6-promise/dist/es6-promise.js',
      '../../static/scripts/vendor/polyfills/bind.js',
      '../../static/scripts/vendor/sinon.js',
      '../../static/scripts/vendor/chai.js',
      'lib/errors.js',
      'lib/tab-store.js',
      'lib/tab-state.js',
      'lib/tab-error-cache.js',
      'lib/sidebar-injector.js',
      'lib/browser-action.js',
      'lib/help-page.js',
      'lib/hypothesis-chrome-extension.js',
      'test/*-test.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true
  });
};
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import R from 'ramda';
import { connect } from 'react-redux';
import { Field, formValueSelector, reduxForm } from 'redux-form';
import Select from 'react-select';

import PLACEHOLDER from '../../../configurations/placeholders.config';

import transformFormValues from '../../../helpers/transformFormValues';
import block from '../../../helpers/bem-cn';
import checkOnPattern from '../../../helpers/pattern-check';
import parse from '../../../helpers/parse-value';
import optionsTransformer from '../../../helpers/optionsTransformer';

import Section from '../../Layout/Section/Section';
import Row from '../../Layout/Row/Row';
import Title from '../../Layout/Title/Title';
import Input from '../../inputs/Input';
import Radio from '../../inputs/Radio/Radio';
import Label from '../../labels/Label';
import Hint from '../../labels/Hint/Hint';
import SimpleSelect from '../../selects/SimpleSelect/SimpleSelect';
import MultiSelect from '../../selects/MultiSelect/MultiSelect';
import TagSelect from '../../selects/TagSelect/TagSelect';
import OAuthEndpoints from './partials/OAuthEndpoints/OAuthEndpoints';
import OAuthClientEndpoints from './partials/OAuthClientEndpoints/OAuthClientEndpoints';
import JWTStrategyOptions from './partials/JWTStrategyOptions/JWTStrategyOptions';

import HeadersSection from '../../forms/plugins/RequestTransformer/HeadersSection/HeadersSection';
import QueryStringSection from '../../forms/plugins/RequestTransformer/QueryStringSection/QueryStringSection';

import Button from '../../buttons/Button';
import RenderPlugins from '../../forms/plugins/RenderPlugins';

const b = block('j-api-form');
const row = block('j-row');
const col = block('j-col');
const grid = block('j-grid');

const propTypes = {
    schema: PropTypes.object.isRequired,
    handleSubmit: PropTypes.func.isRequired,
    initialValues: PropTypes.object.isRequired,
};

class OAuthServerForm extends PureComponent {
    state = {
        tabs: [
            'oAuth Endpoints',
            'oAuth Client Endpoints',
        ],
        activeTab: 0,
        strategy: {},
    };

    handleTabSwitch = idx => this.setState(prevState => ({ activeTab: idx }));

    render() {
        const {
            editing,
            handleSubmit,
            schema,
            initialValues,
        } = this.props;
        const createOptions = (list1, list2) => {
            const combinedListOfUnitsAndLabels = R.zip(list1, list2);

            return combinedListOfUnitsAndLabels.map(item => ({
                label: item[1],
                value: item[0],
            }));
        };
        const createStrategyOptions = (list) => {
            const names = list.map(item => item.name);
            const combinedListOfUnitsAndLabels = R.zip(list, names);

            return combinedListOfUnitsAndLabels.map(item => ({
                label: item[1],
                value: item[1],
                settings: item[0],
            }));
        };
        const ifEditing = (yes, no) => R.ifElse(
            () => editing,
            (yes, no) => yes,
            (yes, no) => no,
        );

        const renderTabs = () => {
            const first = 'oAuth Endpoints';
            const second = 'oAuth Client Endpoints';

            return (

                        {
                            this.state.tabs.map((item, idx) =>
                                <Button
                                    key={item}
                                    mod={`${this.state.activeTab === idx ? 'primary' : 'white'}`}
                                    onClick={() => this.handleTabSwitch(idx)}
                                    type="button"
                                >
                                    {item}
                                </Button>
                            )
                        }

                            <OAuthEndpoints
                                endpoints={initialValues.oauth_endpoints}
                                schema={schema}
                                change={this.props.change}
                                category={'oauth_endpoints'}
                                initialValues={initialValues}
                            />

                            <OAuthClientEndpoints
                                endpoints={initialValues.oauth_client_endpoints}
                                schema={schema}
                                change={this.props.change}
                                category={'oauth_client_endpoints'}
                                initialValues={initialValues}
                            />

            );
        };

        const renderJWTStrategy = () => (

                <Row className={b('row')()} fullwidth>
                    <JWTStrategyOptions
                        name="token_strategy.settings"
                        title="JWT settings"
                    />
                </Row>

        );

        const renderIntrospectionStrategy = () => (

                    <Row col>

                            Auth Header Type
                            <Field
                                type="text"
                                name="token_strategy.settings.auth_header_type"
                                placeholder=""
                                component={Input}
                            />

                    </Row>

                    <Row col>
                        Use OAuth Header?
                        <Row className={b('radio-wrap')()}>
                            <Row className={b('radio')()}>
                                <Field
                                    name="token_strategy.settings.use_oauth_header"
                                    component={Radio}
                                    value={'true'}
                                    type="radio"
                                    id="use-aouth-header-is-active"
                                />
                                Yes
                            </Row>
                            <Row className={b('radio')()}>
                                <Field
                                    name="token_strategy.settings.use_oauth_header"
                                    component={Radio}
                                    value={'false'}
                                    type="radio"
                                    id="use-aouth-header-is-not-active"
                                />
                                No
                            </Row>
                        </Row>
                    </Row>

        );

        const renderStrategy = (name) => {
            switch (name) {
                case 'jwt': {
                    return renderJWTStrategy();
                }
                case 'introspection': {
                    return renderIntrospectionStrategy();
                }
                default:
                    return null;
            }
        };

        const handleChangeStrategy = value => {
            this.setState(() => ({
                strategy: {
                    name: value.value,
                    settings: value.settings,
                }
            }), () => this.props.change('token_strategy.name', value.value));
        };

        return (
            <form className={b} onSubmit={handleSubmit}>

                    <Row>
                        <Title>
                            {
                                ifEditing()(
                                    `Edit ${initialValues.name}`,
                                    'Create New oAuth Server')
                            }
                        </Title>
                    </Row>

1. General

                        <Row className={b('row')()} fullwidth>
                            <Row col>
                                oAuth Server Name
                                <Field
                                    name="name"
                                    type="text"
                                    component={Input}
                                    disabled={editing}
                                />
                                <Hint>Must be unique</Hint>
                            </Row>
                        </Row>

2. Cors meta

                                <Row col>
                                    Is Enabled?
                                    <Row className={b('radio-wrap')()}>
                                        <Row className={b('radio')()}>
                                            <Field
                                                name="cors_meta.enabled"
                                                component={Radio}
                                                value={'true'}
                                                type="radio"
                                                id="cors-meta-is-active"
                                            />
                                            Yes
                                        </Row>
                                        <Row className={b('radio')()}>
                                            <Field
                                                name="cors_meta.enabled"
                                                component={Radio}
                                                value={'false'}
                                                type="radio"
                                                id="cors-meta-is-not-active"
                                            />
                                            No
                                        </Row>
                                    </Row>
                                </Row>

                                    Domains
                                    <Field
                                        name="cors_meta.domains"
                                        type="text"
                                        edit={false}
                                        value="cors_meta.domains"
                                        options={optionsTransformer(schema.cors_meta.domains)}
                                        component={TagSelect}
                                    />
                                    <Hint>A list of all domains from which the endpoint will accept requests</Hint>

                                    Methods
                                    <Field
                                        name="cors_meta.methods"
                                        type="text"
                                        edit={false}
                                        value="cors_meta.methods"
                                        options={optionsTransformer(schema.cors_meta.methods)}
                                        component={MultiSelect}
                                    />
                                    <Hint>HTTP methods that are supported for the endpoint.</Hint>

                                    Request Headers
                                    <Field
                                        name="cors_meta.request_headers"
                                        type="text"
                                        edit={false}
                                        value="cors_meta.request_headers"
                                        placeholder={PLACEHOLDER.REQUEST_HEADERS}
                                        options={optionsTransformer(schema.cors_meta.request_headers)}
                                        component={TagSelect}
                                    />
                                    <Hint>Value(s) for the Access-Control-Allow-Headers header.</Hint>

                                    Exposed Headers
                                    <Field
                                        name="cors_meta.exposed_headers"
                                        type="text"
                                        edit={false}
                                        value="cors_meta.exposed_headers"
                                        placeholder={PLACEHOLDER.EXPOSED_HEADERS}
                                        options={optionsTransformer(schema.cors_meta.exposed_headers)}
                                        component={TagSelect}
                                    />
                                    <Hint>Value for the Access-Control-Expose-Headers header.</Hint>

3. Rate limit

                                    Limit Value
                                    <Field
                                        type="number"
                                        name="rate_limit.limit.value"
                                        placeholder=""
                                        component={Input}
                                    />

                                    Limit Unit
                                    <Field
                                        name="rate_limit.limit.unit"
                                        type="text"
                                        searchable={false}
                                        clearable={false}
                                        options={createOptions(schema.rate_limit.limit.units, schema.rate_limit.limit.labels)}
                                        component={SimpleSelect}
                                    />

                                Is Enabled?
                                <Row className={b('radio-wrap')()}>
                                    <Row className={b('radio')()}>
                                        <Field
                                            name="rate_limit.enabled"
                                            component={Radio}
                                            value={'true'}
                                            type="radio"
                                            id="rate-limit-is-active"
                                        />
                                        Yes
                                    </Row>
                                    <Row className={b('radio')()}>
                                        <Field
                                            name="rate_limit.enabled"
                                            component={Radio}
                                            value={'false'}
                                            type="radio"
                                            id="rate-limit-is-not-active"
                                        />
                                        No
                                    </Row>
                                </Row>

4. Token strategy

                                <Select
                                    className="j-select"
                                    name="token_strategy.name"
                                    options={createStrategyOptions(schema.token_strategy.strategies)}
                                    onChange={handleChangeStrategy}
                                    value={this.state.strategy.name}
                                    searchable={false}
                                    clearable={false}
                                />

                        { renderStrategy(this.state.strategy.name) }

                        { renderTabs() }

                <Row className={b('row',{ 'button-row': true })()}>
                    <Button
                        type="submit"
                        mod="primary"
                    >
                        Create oAuth Server
                    </Button>
                </Row>
            </form>
        );
    }
};

OAuthServerForm.propTypes = propTypes;

const selector = formValueSelector('oAuthServerForm');

const form = reduxForm({
    form: 'oAuthServerForm',
    enableReinitialize: true, // this is needed!!
})(OAuthServerForm);

export default connect(
    state => {
        return {
            keepDirtyOnReinitialize: false,
        };
    },
    null,
)(form);
<commit_msg>basic rendering of cors_meta<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import R from 'ramda';
import { connect } from 'react-redux';
import { Field, formValueSelector, reduxForm } from 'redux-form';
import Select from 'react-select';

import PLACEHOLDER from '../../../configurations/placeholders.config';

import transformFormValues from '../../../helpers/transformFormValues';
import block from '../../../helpers/bem-cn';
import checkOnPattern from '../../../helpers/pattern-check';
import parse from '../../../helpers/parse-value';
import optionsTransformer from '../../../helpers/optionsTransformer';

import Section from '../../Layout/Section/Section';
import Row from '../../Layout/Row/Row';
import Title from '../../Layout/Title/Title';
import Input from '../../inputs/Input';
import Radio from '../../inputs/Radio/Radio';
import Label from '../../labels/Label';
import Hint from '../../labels/Hint/Hint';
import SimpleSelect from '../../selects/SimpleSelect/SimpleSelect';
import MultiSelect from '../../selects/MultiSelect/MultiSelect';
import TagSelect from '../../selects/TagSelect/TagSelect';
import OAuthEndpoints from './partials/OAuthEndpoints/OAuthEndpoints';
import OAuthClientEndpoints from './partials/OAuthClientEndpoints/OAuthClientEndpoints';
import JWTStrategyOptions from './partials/JWTStrategyOptions/JWTStrategyOptions';

import HeadersSection from '../../forms/plugins/RequestTransformer/HeadersSection/HeadersSection';
import QueryStringSection from '../../forms/plugins/RequestTransformer/QueryStringSection/QueryStringSection';

import Button from '../../buttons/Button';
import RenderPlugins from '../../forms/plugins/RenderPlugins';

const b = block('j-api-form');
const row = block('j-row');
const col = block('j-col');
const grid = block('j-grid');

const propTypes = {
    schema: PropTypes.object.isRequired,
    handleSubmit: PropTypes.func.isRequired,
    initialValues: PropTypes.object.isRequired,
};

class OAuthServerForm extends PureComponent {
    state = {
        tabs: [
            'oAuth Endpoints',
            'oAuth Client Endpoints',
        ],
        activeTab: 0,
        strategy: {},
    };

    handleTabSwitch = idx => this.setState(prevState => ({ activeTab: idx }));

    render() {
        const {
            editing,
            handleSubmit,
            schema,
            initialValues,
        } = this.props;
        // console.clear();
        console.error('Initial:: ', initialValues);

        const createOptions = (list1, list2) => {
            const combinedListOfUnitsAndLabels = R.zip(list1, list2);

            return combinedListOfUnitsAndLabels.map(item => ({
                label: item[1],
                value: item[0],
            }));
        };
        const createStrategyOptions = (list) => {
            const names = list.map(item => item.name);
            const combinedListOfUnitsAndLabels = R.zip(list, names);

            return combinedListOfUnitsAndLabels.map(item => ({
                label: item[1],
                value: item[1],
                settings: item[0],
            }));
        };
        const ifEditing = (yes, no) => R.ifElse(
            () => editing,
            (yes, no) => yes,
            (yes, no) => no,
        );

        const renderTabs = () => {
            const first = 'oAuth Endpoints';
            const second = 'oAuth Client Endpoints';

            return (

                        {
                            this.state.tabs.map((item, idx) =>
                                <Button
                                    key={item}
                                    mod={`${this.state.activeTab === idx ? 'primary' : 'white'}`}
                                    onClick={() => this.handleTabSwitch(idx)}
                                    type="button"
                                >
                                    {item}
                                </Button>
                            )
                        }

                            <OAuthEndpoints
                                endpoints={initialValues.oauth_endpoints}
                                schema={schema}
                                change={this.props.change}
                                category={'oauth_endpoints'}
                                initialValues={initialValues}
                            />

                            <OAuthClientEndpoints
                                endpoints={initialValues.oauth_client_endpoints}
                                schema={schema}
                                change={this.props.change}
                                category={'oauth_client_endpoints'}
                                initialValues={initialValues}
                            />

            );
        };

        const renderJWTStrategy = () => (

                <Row className={b('row')()} fullwidth>
                    <JWTStrategyOptions
                        name="token_strategy.settings"
                        title="JWT settings"
                    />
                </Row>

        );

        const renderIntrospectionStrategy = () => (

                    <Row col>

                            Auth Header Type
                            <Field
                                type="text"
                                name="token_strategy.settings.auth_header_type"
                                placeholder=""
                                component={Input}
                            />

                    </Row>

                    <Row col>
                        Use OAuth Header?
                        <Row className={b('radio-wrap')()}>
                            <Row className={b('radio')()}>
                                <Field
                                    name="token_strategy.settings.use_oauth_header"
                                    component={Radio}
                                    value={'true'}
                                    type="radio"
                                    id="use-aouth-header-is-active"
                                />
                                Yes
                            </Row>
                            <Row className={b('radio')()}>
                                <Field
                                    name="token_strategy.settings.use_oauth_header"
                                    component={Radio}
                                    value={'false'}
                                    type="radio"
                                    id="use-aouth-header-is-not-active"
                                />
                                No
                            </Row>
                        </Row>
                    </Row>

        );

        const renderStrategy = (name) => {
            switch (name) {
                case 'jwt': {
                    return renderJWTStrategy();
                }
                case 'introspection': {
                    return renderIntrospectionStrategy();
                }
                default:
                    return null;
            }
        };

        const handleChangeStrategy = value => {
            this.setState(() => ({
                strategy: {
                    name: value.value,
                    settings: value.settings,
                }
            }), () => this.props.change('token_strategy.name', value.value));
        };

        const getValues = key => initialValues.cors_meta[key];

        return (
            <form className={b} onSubmit={handleSubmit}>

                    <Row>
                        <Title>
                            {
                                ifEditing()(
                                    `Edit ${initialValues.name}`,
                                    'Create New oAuth Server')
                            }
                        </Title>
                    </Row>

1. General

                        <Row className={b('row')()} fullwidth>
                            <Row col>
                                oAuth Server Name
                                <Field
                                    name="name"
                                    type="text"
                                    component={Input}
                                    disabled={editing}
                                />
                                <Hint>Must be unique</Hint>
                            </Row>
                        </Row>

2. Cors meta

                                <Row col>
                                    Is Enabled?
                                    <Row className={b('radio-wrap')()}>
                                        <Row className={b('radio')()}>
                                            <Field
                                                name="cors_meta.enabled"
                                                component={Radio}
                                                value={'true'}
                                                type="radio"
                                                id="cors-meta-is-active"
                                            />
                                            Yes
                                        </Row>
                                        <Row className={b('radio')()}>
                                            <Field
                                                name="cors_meta.enabled"
                                                component={Radio}
                                                value={'false'}
                                                type="radio"
                                                id="cors-meta-is-not-active"
                                            />
                                            No
                                        </Row>
                                    </Row>
                                </Row>

                                    Domains
                                    <Field
                                        name="cors_meta.domains"
                                        type="text"
                                        edit={editing}
                                        value={() => getValues('domains')}
                                        options={optionsTransformer(schema.cors_meta.domains)}
                                        component={TagSelect}
                                    />
                                    <Hint>A list of all domains from which the endpoint will accept requests</Hint>

                                    Methods
                                    <Field
                                        name="cors_meta.methods"
                                        type="text"
                                        edit={editing}
                                        value={() => getValues('methods')}
                                        options={optionsTransformer(schema.cors_meta.methods)}
                                        component={MultiSelect}
                                    />
                                    <Hint>HTTP methods that are supported for the endpoint.</Hint>

                                    Request Headers
                                    <Field
                                        name="cors_meta.request_headers"
                                        type="text"
                                        edit={editing}
                                        value={() => getValues('request_headers')}
                                        placeholder={PLACEHOLDER.REQUEST_HEADERS}
                                        options={optionsTransformer(schema.cors_meta.request_headers)}
                                        component={TagSelect}
                                    />
                                    <Hint>Value(s) for the Access-Control-Allow-Headers header.</Hint>

                                    Exposed Headers
                                    <Field
                                        name="cors_meta.exposed_headers"
                                        type="text"
                                        edit={editing}
                                        value={() => getValues('exposed_headers')}
                                        placeholder={PLACEHOLDER.EXPOSED_HEADERS}
                                        options={optionsTransformer(schema.cors_meta.exposed_headers)}
                                        component={TagSelect}
                                    />
                                    <Hint>Value for the Access-Control-Expose-Headers header.</Hint>

3. Rate limit

                                    Limit Value
                                    <Field
                                        type="number"
                                        name="rate_limit.limit.value"
                                        placeholder=""
                                        component={Input}
                                    />

                                    Limit Unit
                                    <Field
                                        name="rate_limit.limit.unit"
                                        type="text"
                                        searchable={false}
                                        clearable={false}
                                        options={createOptions(schema.rate_limit.limit.units, schema.rate_limit.limit.labels)}
                                        component={SimpleSelect}
                                    />

                                Is Enabled?
                                <Row className={b('radio-wrap')()}>
                                    <Row className={b('radio')()}>
                                        <Field
                                            name="rate_limit.enabled"
                                            component={Radio}
                                            value={'true'}
                                            type="radio"
                                            id="rate-limit-is-active"
                                        />
                                        Yes
                                    </Row>
                                    <Row className={b('radio')()}>
                                        <Field
                                            name="rate_limit.enabled"
                                            component={Radio}
                                            value={'false'}
                                            type="radio"
                                            id="rate-limit-is-not-active"
                                        />
                                        No
                                    </Row>
                                </Row>

4. Token strategy

                                <Select
                                    className="j-select"
                                    name="token_strategy.name"
                                    options={createStrategyOptions(schema.token_strategy.strategies)}
                                    onChange={handleChangeStrategy}
                                    value={this.state.strategy.name}
                                    searchable={false}
                                    clearable={false}
                                />

                        { renderStrategy(this.state.strategy.name) }

                        { renderTabs() }

                <Row className={b('row',{ 'button-row': true })()}>
                    <Button
                        type="submit"
                        mod="primary"
                    >
                        Create oAuth Server
                    </Button>
                </Row>
            </form>
        );
    }
};

OAuthServerForm.propTypes = propTypes;

const selector = formValueSelector('oAuthServerForm');

const form = reduxForm({
    form: 'oAuthServerForm',
    enableReinitialize: true, // this is needed!!
})(OAuthServerForm);

export default connect(
    state => {
        return {
            keepDirtyOnReinitialize: false,
        };
    },
    null,
)(form);
<|endoftext|>


<commit_before>import { sealTxByKeystore, sealTxByTrezor } from "../utils/sealer"
import { verifyNonce } from "../utils/validators"
import store from "../store"
import { doTransaction, doApprovalTransaction, saveRawExchangeTransaction, throwErrorSignExchangeTransaction } from "../actions/exchangeActions"
import { doTransaction as doTransactionTransfer, saveRawTransferTransaction, throwErrorSignTransferTransaction } from "../actions/transferActions"
import constants from "../services/constants"
import Rate from "./rate"

export function sendEtherFromWallet(
  id, ethereum, account, sourceToken, sourceAmount,
  destAddress, nonce, gas, gasPrice, keystring,
  password, callback, wallet) {

  var txData = ethereum.executeWalletData(
    wallet.address, destAddress, sourceAmount, "")
  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: wallet.address,
    value: 0,
    data: txData,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }
  const tx = sealTxByKeystore(txParams, keystring, password)
  store.dispatch(doTransactionTransfer(id, ethereum, tx, callback))
}

export function sendTokenFromWallet(
  id, ethereum, account, sourceToken, sourceAmount,
  destAddress, nonce, gas, gasPrice, keystring,
  password, callback, wallet) {

  var sendTokenData = ethereum.sendTokenData(
    sourceToken, sourceAmount, destAddress)
  var txData = ethereum.executeWalletData(
    wallet.address, sourceToken, 0, sendTokenData)
  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: wallet.address,
    value: 0,
    data: txData,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }
  const tx = sealTxByKeystore(txParams, keystring, password)
  store.dispatch(doTransactionTransfer(id, ethereum, tx, callback))
}

export function sendEtherFromAccount(
  id, ethereum, account, sourceToken, sourceAmount,
  destAddress, nonce, gas, gasPrice, keystring, accountType,
  password, callback) {

  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: destAddress,
    value: sourceAmount,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }
  switch (accountType) {
    case "keystore":
      const tx = sealTxByKeystore(txParams, keystring, password)
      store.dispatch(doTransactionTransfer(id, ethereum, tx, callback))
      break
    case "trezor":
      txParams.address_n = keystring
      sealTxByTrezor(txParams, (tx) => {
        store.dispatch(saveRawTransferTransaction(tx))
      }, (error) => {
        store.dispatch(throwErrorSignTransferTransaction(error))
      })
      break
  }
}

export function sendTokenFromAccount(
  id, ethereum, account, sourceToken, sourceAmount,
  destAddress, nonce, gas, gasPrice, keystring, accountType,
  password, callback) {

  var txData = ethereum.sendTokenData(
    sourceToken, sourceAmount, destAddress)
  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: sourceToken,
    value: '0x0',
    data: txData,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }

  switch (accountType) {
    case "keystore":
      const tx = sealTxByKeystore(txParams, keystring, password)
      store.dispatch(doTransactionTransfer(id, ethereum, tx, callback))
      break
    case "trezor":
      txParams.address_n = keystring
      sealTxByTrezor(txParams, (tx) => {
        store.dispatch(saveRawTransferTransaction(tx))
      }, (error) => {
        store.dispatch(throwErrorSignTransferTransaction(error))
      })
      break
  }

}

export function etherToOthersFromAccount(
  id, ethereum, account, sourceToken, sourceAmount, destToken,
  destAddress, maxDestAmount, minConversionRate,
  throwOnFailure, nonce, gas, gasPrice, keystring, accountType,
  password, callback) {

  var txData = ethereum.exchangeData(
    sourceToken, sourceAmount, destToken, destAddress,
    maxDestAmount, minConversionRate, throwOnFailure)
  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: ethereum.networkAddress,
    value: sourceAmount,
    data: txData,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }
  switch (accountType) {
    case "keystore":
      var tx = sealTxByKeystore(txParams, keystring, password)
      store.dispatch(doTransaction(id, ethereum, tx, callback))
      break
    case "trezor":
      txParams.address_n = keystring
      sealTxByTrezor(txParams, (tx) => {
        store.dispatch(saveRawExchangeTransaction(tx))
      }, (error) => {
        store.dispatch(throwErrorSignExchangeTransaction(error))
      })
      break
  }
  //const tx = sealTxByKeystore(txParams, keystring, password)

}

export function tokenToOthersFromAccount(
  id, ethereum, account, sourceToken, sourceAmount, destToken,
  destAddress, maxDestAmount, minConversionRate,
  throwOnFailure, nonce, gas, gasPrice, keystring, accountType,
  password, callback) {

  const approvalData = ethereum.approveTokenData(sourceToken, sourceAmount)
  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: sourceToken,
    value: 0,
    data: approvalData,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }
  switch (accountType) {
    case "keystore":
      const approvalTx = sealTxByKeystore(txParams, keystring, password)
      store.dispatch(
        doApprovalTransaction(id, ethereum, approvalTx, (hash) => {
          const exchangeData = ethereum.exchangeData(
            sourceToken, sourceAmount, destToken, destAddress,
            maxDestAmount, minConversionRate, throwOnFailure)
          const newNonce = verifyNonce(nonce, 1)
          const exchangeTxParams = {
            nonce: newNonce,
            gasPrice: gasPrice,
            gasLimit: gas,
            to: ethereum.networkAddress,
            value: 0,
            data: exchangeData,
            // EIP 155 chainId - mainnet: 1, ropsten: 3
            chainId: 42
          }
          const exchangeTx = sealTxByKeystore(exchangeTxParams, keystring, password)
          console.log(exchangeTx)
          store.dispatch(doTransaction(id, ethereum, exchangeTx, callback))
        }))
      break
    case "trezor":

      break
  }

}

export function fetchRate(ethereum, source, dest, reserve, callback) {
  ethereum.getRate(source.address, dest.address, reserve.index,
    (result) => {
      callback(new Rate(
        source, dest, reserve,
        result[0], result[1], result[2]))
    })
}

export function fetchRatePromise(ethereum, source, dest, reserve) {
  return new Promise((resolve, reject) => {
    ethereum.getRate(source.address, dest.address, reserve.index,
      (result) => {
        resolve(new Rate(
          source.name,
          source.symbol,
          source.icon,
          source.address,
          result[0],
          result[2]
        ))
      })
  })
}
<commit_msg>add tranfer ledger<commit_after>import { sealTxByKeystore, sealTxByTrezor, sealTxByLedger } from "../utils/sealer"
import { verifyNonce } from "../utils/validators"
import store from "../store"
import { doTransaction, doApprovalTransaction, saveRawExchangeTransaction, throwErrorSignExchangeTransaction } from "../actions/exchangeActions"
import { doTransaction as doTransactionTransfer, saveRawTransferTransaction, throwErrorSignTransferTransaction } from "../actions/transferActions"
import constants from "../services/constants"
import Rate from "./rate"

export function sendEtherFromWallet(
  id, ethereum, account, sourceToken, sourceAmount,
  destAddress, nonce, gas, gasPrice, keystring,
  password, callback, wallet) {

  var txData = ethereum.executeWalletData(
    wallet.address, destAddress, sourceAmount, "")
  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: wallet.address,
    value: 0,
    data: txData,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }
  const tx = sealTxByKeystore(txParams, keystring, password)
  store.dispatch(doTransactionTransfer(id, ethereum, tx, callback))
}

export function sendTokenFromWallet(
  id, ethereum, account, sourceToken, sourceAmount,
  destAddress, nonce, gas, gasPrice, keystring,
  password, callback, wallet) {

  var sendTokenData = ethereum.sendTokenData(
    sourceToken, sourceAmount, destAddress)
  var txData = ethereum.executeWalletData(
    wallet.address, sourceToken, 0, sendTokenData)
  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: wallet.address,
    value: 0,
    data: txData,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }
  const tx = sealTxByKeystore(txParams, keystring, password)
  store.dispatch(doTransactionTransfer(id, ethereum, tx, callback))
}

export function sendEtherFromAccount(
  id, ethereum, account, sourceToken, sourceAmount,
  destAddress, nonce, gas, gasPrice, keystring, accountType,
  password, callback) {

  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: destAddress,
    value: sourceAmount,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }
  switch (accountType) {
    case "keystore":
      const tx = sealTxByKeystore(txParams, keystring, password)
      store.dispatch(doTransactionTransfer(id, ethereum, tx, callback))
      break
    case "trezor":
      txParams.address_n = keystring
      sealTxByTrezor(txParams, (tx) => {
        store.dispatch(saveRawTransferTransaction(tx))
      }, (error) => {
        store.dispatch(throwErrorSignTransferTransaction(error))
      })
      break
    case "ledger":
      txParams.address_n = keystring
      sealTxByLedger(txParams, (tx) => {
        store.dispatch(saveRawTransferTransaction(tx))
      }, (error) => {
        store.dispatch(throwErrorSignTransferTransaction(error))
      })
      break
  }
}

export function sendTokenFromAccount(
  id, ethereum, account, sourceToken, sourceAmount,
  destAddress, nonce, gas, gasPrice, keystring, accountType,
  password, callback) {

  var txData = ethereum.sendTokenData(
    sourceToken, sourceAmount, destAddress)
  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: sourceToken,
    value: '0x0',
    data: txData,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }

  switch (accountType) {
    case "keystore":
      const tx = sealTxByKeystore(txParams, keystring, password)
      store.dispatch(doTransactionTransfer(id, ethereum, tx, callback))
      break
    case "trezor":
      txParams.address_n = keystring
      sealTxByTrezor(txParams, (tx) => {
        store.dispatch(saveRawTransferTransaction(tx))
      }, (error) => {
        store.dispatch(throwErrorSignTransferTransaction(error))
      })
      break
    case "ledger":
      txParams.address_n = keystring
      sealTxByLedger(txParams, (tx) => {
        console.log(tx)
        store.dispatch(saveRawTransferTransaction(tx))
      }, (error) => {
        store.dispatch(throwErrorSignTransferTransaction(error))
      })
      break
  }

}

export function etherToOthersFromAccount(
  id, ethereum, account, sourceToken, sourceAmount, destToken,
  destAddress, maxDestAmount, minConversionRate,
  throwOnFailure, nonce, gas, gasPrice, keystring, accountType,
  password, callback) {

  var txData = ethereum.exchangeData(
    sourceToken, sourceAmount, destToken, destAddress,
    maxDestAmount, minConversionRate, throwOnFailure)
  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: ethereum.networkAddress,
    value: sourceAmount,
    data: txData,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }
  switch (accountType) {
    case "keystore":
      var tx = sealTxByKeystore(txParams, keystring, password)
      store.dispatch(doTransaction(id, ethereum, tx, callback))
      break
    case "trezor":
      txParams.address_n = keystring
      sealTxByTrezor(txParams, (tx) => {
        store.dispatch(saveRawExchangeTransaction(tx))
      }, (error) => {
        store.dispatch(throwErrorSignExchangeTransaction(error))
      })
      break
  }
  //const tx = sealTxByKeystore(txParams, keystring, password)

}

export function tokenToOthersFromAccount(
  id, ethereum, account, sourceToken, sourceAmount, destToken,
  destAddress, maxDestAmount, minConversionRate,
  throwOnFailure, nonce, gas, gasPrice, keystring, accountType,
  password, callback) {

  const approvalData = ethereum.approveTokenData(sourceToken, sourceAmount)
  const txParams = {
    nonce: nonce,
    gasPrice: gasPrice,
    gasLimit: gas,
    to: sourceToken,
    value: 0,
    data: approvalData,
    // EIP 155 chainId - mainnet: 1, ropsten: 3
    chainId: 42
  }
  switch (accountType) {
    case "keystore":
      const approvalTx = sealTxByKeystore(txParams, keystring, password)
      store.dispatch(
        doApprovalTransaction(id, ethereum, approvalTx, (hash) => {
          const exchangeData = ethereum.exchangeData(
            sourceToken, sourceAmount, destToken, destAddress,
            maxDestAmount, minConversionRate, throwOnFailure)
          const newNonce = verifyNonce(nonce, 1)
          const exchangeTxParams = {
            nonce: newNonce,
            gasPrice: gasPrice,
            gasLimit: gas,
            to: ethereum.networkAddress,
            value: 0,
            data: exchangeData,
            // EIP 155 chainId - mainnet: 1, ropsten: 3
            chainId: 42
          }
          const exchangeTx = sealTxByKeystore(exchangeTxParams, keystring, password)
          console.log(exchangeTx)
          store.dispatch(doTransaction(id, ethereum, exchangeTx, callback))
        }))
      break
    case "trezor":

      break
  }

}

export function fetchRate(ethereum, source, dest, reserve, callback) {
  ethereum.getRate(source.address, dest.address, reserve.index,
    (result) => {
      callback(new Rate(
        source, dest, reserve,
        result[0], result[1], result[2]))
    })
}

export function fetchRatePromise(ethereum, source, dest, reserve) {
  return new Promise((resolve, reject) => {
    ethereum.getRate(source.address, dest.address, reserve.index,
      (result) => {
        resolve(new Rate(
          source.name,
          source.symbol,
          source.icon,
          source.address,
          result[0],
          result[2]
        ))
      })
  })
}
<|endoftext|>


<commit_before>// Karma configuration

'use strict';

module.exports = function (config) {

	config.set({

		// base path, that will be used to resolve files and exclude
		basePath: './src/',

		// testing framework to use (jasmine/mocha/qunit/...)
		frameworks: ['jasmine', 'karma-typescript'],

		files: [
			'../node_modules/angular/angular.js',
			'../node_modules/angular-mocks/angular-mocks.js',
			'../node_modules/angular-sanitize/angular-sanitize.js',
			'../node_modules/i18next/i18next.js',
			'../node_modules/i18next-xhr-backend/i18nextXHRBackend.js',
			'../node_modules/i18next-sprintf-postprocessor/i18nextSprintfPostProcessor.js',

			{ pattern: './*.ts', included: true },

		],

		preprocessors: {
			'./**/!(*spec).ts': ['karma-typescript', 'coverage'],
			'./*.spec.ts': ['karma-typescript']
		},

		reporters: ["progress", "karma-typescript"],

		karmaTypescriptConfig: {
			tsconfig: "../tsconfig-karma.json"
		},

		// list of files to exclude
		exclude: [],

		// web server port
		port: 9876,

		// cli runner port
		runnerPort: 9100,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		singleRun: true,

		browsers: ['Chrome'],

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 60000

	});
};
<commit_msg>use chrome headless<commit_after>// Karma configuration

'use strict';

module.exports = function (config) {

	config.set({

		// base path, that will be used to resolve files and exclude
		basePath: './src/',

		// testing framework to use (jasmine/mocha/qunit/...)
		frameworks: ['jasmine', 'karma-typescript'],

		files: [
			'../node_modules/angular/angular.js',
			'../node_modules/angular-mocks/angular-mocks.js',
			'../node_modules/angular-sanitize/angular-sanitize.js',
			'../node_modules/i18next/i18next.js',
			'../node_modules/i18next-xhr-backend/i18nextXHRBackend.js',
			'../node_modules/i18next-sprintf-postprocessor/i18nextSprintfPostProcessor.js',

			{ pattern: './*.ts', included: true },

		],

		preprocessors: {
			'./**/!(*spec).ts': ['karma-typescript', 'coverage'],
			'./*.spec.ts': ['karma-typescript']
		},

		reporters: ["progress", "karma-typescript"],

		karmaTypescriptConfig: {
			tsconfig: "../tsconfig-karma.json"
		},

		// list of files to exclude
		exclude: [],

		// web server port
		port: 9876,

		// cli runner port
		runnerPort: 9100,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		singleRun: true,

		browsers: ['ChromeHeadless'],

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 60000

	});
};
<|endoftext|>


<commit_before>class jfMultiDropdownController {
	/* @ngInject */
	constructor($scope, $filter, $element) {

		this.$scope = $scope;
		this.$element = $element;

		this.filter = $filter('filter');
		this.opened = false;

		this.singleSelectionIndex = -1;

		this.handleOutsideClick();

		this.$scope.$watch('jfMultiDropdown.items', (newVal, oldVal) => {
			if (newVal) {
				this.sortItems();
				if (this.singleSelection) {
					this.items.forEach((item, index) => item.$id = index);
					let disabled = _.filter(this.items, item => item.disabled);
					disabled.forEach(item => item.isSelected = false);
					let selected = _.filter(this.items, item => item.isSelected);
					if (selected.length > 1) {
						selected.slice(1).forEach(item => item.isSelected = false);
					}
					if (selected.length) {
						this.singleSelectionIndex = selected[0].$id;
					}
				}
			}
		});

		this.$scope.$watch('jfMultiDropdown.dropdownOpened', (val) => {
			if (val === true) {
				if (!this.items) {
					return;
				}
				this.opened = true;
				this.filterText = '';
			}
			else if (val === false) {
				this.opened = false;
				this.filterText = '';
			}
			else {

			}
		});
	}

	sendOpenStateChange() {
		if (this.onOpenStateChange) {
			this.onOpenStateChange({opened: this.opened});
		}
	}

	handleOutsideClick() {
		let handler = (e) => {
			let outside = !$(e.target).parents('.jf-multi-dropdown').length || $(e.target).parents(
				'.jf-multi-dropdown')[0] !== $(this.$element).find('.jf-multi-dropdown')[0];
			if (outside) {
				this.opened = false;
				this.sendOpenStateChange();
				this.sortItems();
			}
			this.$scope.$apply();
		};
		$(document).on('click', handler);
		this.$scope.$on('$destroy', () => {
			$(document).off('click', handler);
		});
	}

	getSelectedForTitle() {
		let selected = _.filter(this.items, (item) => item.isSelected);
		selected = _.map(selected, s => s.selectedText || s.text);
		return selected.join(', ');
	}

	onClick() {
		if (this.disabled !== true) {
			if (!this.items) {
				return;
			}
			this.opened = !this.opened;
			this.sendOpenStateChange();
			if (!this.opened) {
				this.sortItems();
			}
			this.filterText = '';

		}

	}

	onSingleSelection() {
		this.items.forEach((item) => {
			if (!item.disabled) {
				item.isSelected = false;
			}
		});
		let selected = _.find(this.items, item => item.$id == this.singleSelectionIndex);
		selected.isSelected = true;
		this.applyChanges();
	}

	getSelectedCount() {
		let selected = _.filter(this.items, (item) => item.isSelected && !item.isAllToggleCheckbox);
		return selected.length;
	}

	applyChanges() {
		if (this.onChange) {
			this.onChange();
		}
	}

	selectedItems() {
		let selected = _.filter(this.items, (item) => item.isSelected);
		selected = _.map(selected, 'text');
		return selected;
	}

	sortItems() {
		if (this.noSelectedFirst) {
			return;
		}
		if (!this.items) {
			return;
		}
		let selected = this.noSort ? _.filter(this.items, (item) => item.isSelected) : _.sortBy(
			_.filter(this.items, (item) => item.isSelected), 'text');
		let unSelected = this.noSort ? _.filter(this.items, (item) => !item.isSelected) : _.sortBy(
			_.filter(this.items, (item) => !item.isSelected), 'text');
		this.lastSelectedIndex = selected.length - 1;
		let combined = selected.concat(unSelected);
		this.items.splice.apply(this.items, [0, this.items.length].concat(combined));
	}

	selectAll() {
		this.filter(this.items, this.filterText).forEach((item) => {
			if (!item.disabled) {
				item.isSelected = true;
			}
		});
		this.applyChanges();
	}

	unSelectAll() {
		this.filter(this.items, this.filterText).forEach((item) => {
			if (!item.disabled) {
				item.isSelected = false;
			}
		});
		this.applyChanges();
		this.singleSelectionIndex = -1;
	}

	onSelection() {
		this.applyChanges();
	}

	clearSelection() {
		if (this.textInputs) {
			_.forEach(this.items, (item) => {
				item.inputTextValue = '';
			});
		}
		this.unSelectAll();
	}

}

export function jfMultiDropdown() {
	return {
		controller: jfMultiDropdownController,
		controllerAs: 'jfMultiDropdown',
		bindToController: true,
		scope: {
			title: '@',
			label: '@',
			filterPlaceholder: '@',
			noItemsMessage: '@',
			items: '=',
			disabled: '=?',
			onChange: '&?',
			noSort: '=?',
			onOpenStateChange: '&?',
			dropdownOpened: '=',
			showSelected: '@',
			showLabelCounter: '@',
			noFilter: '=?',
			noSelectedFirst: '=?',
			singleSelection: '=?',
			textInputs: '<?',
			borderless: '<?'
		},
		templateUrl: 'directives/jf_multi_dropdown/jf_multi_dropdown.html'
	};
}<commit_msg>JFUIE-2: jf-multi-dropdown: Disable 'clear all' button when component is disabled<commit_after>class jfMultiDropdownController {
	/* @ngInject */
	constructor($scope, $filter, $element) {

		this.$scope = $scope;
		this.$element = $element;

		this.filter = $filter('filter');
		this.opened = false;

		this.singleSelectionIndex = -1;

		this.handleOutsideClick();

		this.$scope.$watch('jfMultiDropdown.items', (newVal, oldVal) => {
			if (newVal) {
				this.sortItems();
				if (this.singleSelection) {
					this.items.forEach((item, index) => item.$id = index);
					let disabled = _.filter(this.items, item => item.disabled);
					disabled.forEach(item => item.isSelected = false);
					let selected = _.filter(this.items, item => item.isSelected);
					if (selected.length > 1) {
						selected.slice(1).forEach(item => item.isSelected = false);
					}
					if (selected.length) {
						this.singleSelectionIndex = selected[0].$id;
					}
				}
			}
		});

		this.$scope.$watch('jfMultiDropdown.dropdownOpened', (val) => {
			if (val === true) {
				if (!this.items) {
					return;
				}
				this.opened = true;
				this.filterText = '';
			}
			else if (val === false) {
				this.opened = false;
				this.filterText = '';
			}
			else {

			}
		});
	}

	sendOpenStateChange() {
		if (this.onOpenStateChange) {
			this.onOpenStateChange({opened: this.opened});
		}
	}

	handleOutsideClick() {
		let handler = (e) => {
			let outside = !$(e.target).parents('.jf-multi-dropdown').length || $(e.target).parents(
				'.jf-multi-dropdown')[0] !== $(this.$element).find('.jf-multi-dropdown')[0];
			if (outside) {
				this.opened = false;
				this.sendOpenStateChange();
				this.sortItems();
			}
			this.$scope.$apply();
		};
		$(document).on('click', handler);
		this.$scope.$on('$destroy', () => {
			$(document).off('click', handler);
		});
	}

	getSelectedForTitle() {
		let selected = _.filter(this.items, (item) => item.isSelected);
		selected = _.map(selected, s => s.selectedText || s.text);
		return selected.join(', ');
	}

	onClick() {
		if (this.disabled !== true) {
			if (!this.items) {
				return;
			}
			this.opened = !this.opened;
			this.sendOpenStateChange();
			if (!this.opened) {
				this.sortItems();
			}
			this.filterText = '';

		}

	}

	onSingleSelection() {
		this.items.forEach((item) => {
			if (!item.disabled) {
				item.isSelected = false;
			}
		});
		let selected = _.find(this.items, item => item.$id == this.singleSelectionIndex);
		selected.isSelected = true;
		this.applyChanges();
	}

	getSelectedCount() {
		let selected = _.filter(this.items, (item) => item.isSelected && !item.isAllToggleCheckbox);
		return selected.length;
	}

	applyChanges() {
		if (this.onChange) {
			this.onChange();
		}
	}

	selectedItems() {
		let selected = _.filter(this.items, (item) => item.isSelected);
		selected = _.map(selected, 'text');
		return selected;
	}

	sortItems() {
		if (this.noSelectedFirst) {
			return;
		}
		if (!this.items) {
			return;
		}
		let selected = this.noSort ? _.filter(this.items, (item) => item.isSelected) : _.sortBy(
			_.filter(this.items, (item) => item.isSelected), 'text');
		let unSelected = this.noSort ? _.filter(this.items, (item) => !item.isSelected) : _.sortBy(
			_.filter(this.items, (item) => !item.isSelected), 'text');
		this.lastSelectedIndex = selected.length - 1;
		let combined = selected.concat(unSelected);
		this.items.splice.apply(this.items, [0, this.items.length].concat(combined));
	}

	selectAll() {
		if (this.disabled) return;
		this.filter(this.items, this.filterText).forEach((item) => {
			if (!item.disabled) {
				item.isSelected = true;
			}
		});
		this.applyChanges();
	}

	unSelectAll() {
        if (this.disabled) return;
		this.filter(this.items, this.filterText).forEach((item) => {
			if (!item.disabled) {
				item.isSelected = false;
			}
		});
		this.applyChanges();
		this.singleSelectionIndex = -1;
	}

	onSelection() {
		this.applyChanges();
	}

	clearSelection() {
        if (this.disabled) return;
        if (this.textInputs) {
			_.forEach(this.items, (item) => {
				item.inputTextValue = '';
			});
		}
		this.unSelectAll();
	}

}

export function jfMultiDropdown() {
	return {
		controller: jfMultiDropdownController,
		controllerAs: 'jfMultiDropdown',
		bindToController: true,
		scope: {
			title: '@',
			label: '@',
			filterPlaceholder: '@',
			noItemsMessage: '@',
			items: '=',
			disabled: '=?',
			onChange: '&?',
			noSort: '=?',
			onOpenStateChange: '&?',
			dropdownOpened: '=',
			showSelected: '@',
			showLabelCounter: '@',
			noFilter: '=?',
			noSelectedFirst: '=?',
			singleSelection: '=?',
			textInputs: '<?',
			borderless: '<?'
		},
		templateUrl: 'directives/jf_multi_dropdown/jf_multi_dropdown.html'
	};
}<|endoftext|>


<commit_before>'use strict';
const expect = require('chai').expect;
const Internet = require('../../src/faker/internet');
const data = require('../../data/internet.json');
const nameData = require('../../data/name.json');

describe('Internet', () => {
  describe('#email', () => {
    it('should return a email', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.email()).to.be.oneOf(data['emails']);
      });
    });
  });

  describe('#freeEmail', () => {
    it('should return a freeEmail', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.freeEmail()).to.be.oneOf(data['freeEmails']);
      });
    });
  });

  describe('#safeEmail', () => {
    it('should return a safeEmail', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.safeEmail()).to.be.oneOf(data['safeEmails']);
      });
    });
  });

  describe('#userName', () => {
    it('should return a userName', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.userName()).to.be.oneOf(data['userNames']);
      });
    });
  });

  describe('#password', () => {
    it('should return a password', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.password()).to.match(/^[a-zA-Z0-9]+$/);
      });
    });

    it('should return a password between 8 and 16 alphanumeric characters by default', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.password()).to.match(/^[a-zA-Z0-9]{8,16}$/);
      });
    });

    it('should return a lowercase password when mixCase is false', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.password(8, 16, false)).to.match(/^[a-z0-9]+$/);
      });
    });

    it('should return a password with special characters when specialChars is true', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.password(128, 128, true, true)).to.match(/[\!\@\#\$\%\^\&\*]/);
      });
    });
  });

  describe('#domainName', () => {
    it('should return a domainName', () => {
      [...Array(100).keys()].forEach(_ => {
        const domainName = Internet.domainName();
        expect(domainName.split('.')[0]).to.be.oneOf(nameData['lastNames']);
        expect(domainName.split('.')[1]).to.be.oneOf(data['domainSuffixes']);
      });
    });
  });

  describe('#fixUmlauts', () => {
    it('should replace ä with ae', () => {
      expect(Internet.fixUmlauts('ä')).to.eql('ae');
    });

    it('should replace ö with oe', () => {
      expect(Internet.fixUmlauts('ö')).to.eql('oe');
    });

    it('should replace ü with ue', () => {
      expect(Internet.fixUmlauts('ü')).to.eql('ue');
    });
  });

  describe('#domainWord', () => {
    it('should return a domainWord', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.domainWord()).to.be.oneOf(nameData['lastNames']);
      });
    });
  });

  describe('#domainSuffix', () => {
    it('should return a domainSuffix', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.domainSuffix()).to.be.oneOf(data['domainSuffixes']);
      });
    });
  });

  describe('#ipV4_address', () => {
    it('should return a ipV4_address', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.ipV4_address()).to.be.oneOf(data['ipV4_addresses']);
      });
    });
  });

  describe('#privateIpV4_address', () => {
    it('should return a privateIpV4_address', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.privateIpV4_address()).to.be.oneOf(data['privateIpV4_addresses']);
      });
    });
  });

  describe('#publicIpV4_address', () => {
    it('should return a publicIpV4_address', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.publicIpV4_address()).to.be.oneOf(data['publicIpV4_addresses']);
      });
    });
  });

  describe('#ipV4_cidr', () => {
    it('should return a ipV4_cidr', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.ipV4_cidr()).to.be.oneOf(data['ipV4_cidrs']);
      });
    });
  });

  describe('#ipV6_address', () => {
    it('should return a ipV6_address', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.ipV6_address()).to.be.oneOf(data['ipV6_addresses']);
      });
    });
  });

  describe('#ipV6_cidr', () => {
    it('should return a ipV6_cidr', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.ipV6_cidr()).to.be.oneOf(data['ipV6_cidrs']);
      });
    });
  });

  describe('#macAddress', () => {
    it('should return a macAddress', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.macAddress()).to.be.oneOf(data['macAddresses']);
      });
    });
  });

  describe('#url', () => {
    it('should return a url', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.url()).to.be.oneOf(data['urls']);
      });
    });
  });

  describe('#slug', () => {
    it('should return a slug', () => {
      [...Array(100).keys()].forEach(_ => {
        // expect(Internet.slug()).to.be.oneOf(data['slugs']);
      });
    });
  });
});
<commit_msg>Cleaned up tests that have not been implemented yet.<commit_after>'use strict';
const expect = require('chai').expect;
const Internet = require('../../src/faker/internet');
const data = require('../../data/internet.json');
const nameData = require('../../data/name.json');

describe('Internet', () => {
  describe('#email', () => {
  });

  describe('#freeEmail', () => {
  });

  describe('#safeEmail', () => {
  });

  describe('#userName', () => {
  });

  describe('#password', () => {
    it('should return a password', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.password()).to.match(/^[a-zA-Z0-9]+$/);
      });
    });

    it('should return a password between 8 and 16 alphanumeric characters by default', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.password()).to.match(/^[a-zA-Z0-9]{8,16}$/);
      });
    });

    it('should return a lowercase password when mixCase is false', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.password(8, 16, false)).to.match(/^[a-z0-9]+$/);
      });
    });

    it('should return a password with special characters when specialChars is true', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.password(128, 128, true, true)).to.match(/[\!\@\#\$\%\^\&\*]/);
      });
    });
  });

  describe('#domainName', () => {
    it('should return a domainName', () => {
      [...Array(100).keys()].forEach(_ => {
        const domainName = Internet.domainName();
        expect(domainName.split('.')[0]).to.be.oneOf(nameData['lastNames']);
        expect(domainName.split('.')[1]).to.be.oneOf(data['domainSuffixes']);
      });
    });
  });

  describe('#fixUmlauts', () => {
    it('should replace ä with ae', () => {
      expect(Internet.fixUmlauts('ä')).to.eql('ae');
    });

    it('should replace ö with oe', () => {
      expect(Internet.fixUmlauts('ö')).to.eql('oe');
    });

    it('should replace ü with ue', () => {
      expect(Internet.fixUmlauts('ü')).to.eql('ue');
    });
  });

  describe('#domainWord', () => {
    it('should return a domainWord', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.domainWord()).to.be.oneOf(nameData['lastNames']);
      });
    });
  });

  describe('#domainSuffix', () => {
    it('should return a domainSuffix', () => {
      [...Array(100).keys()].forEach(_ => {
        expect(Internet.domainSuffix()).to.be.oneOf(data['domainSuffixes']);
      });
    });
  });

  describe('#ipV4_address', () => {
  });

  describe('#privateIpV4_address', () => {
  });

  describe('#publicIpV4_address', () => {
  });

  describe('#ipV4_cidr', () => {
  });

  describe('#ipV6_address', () => {
  });

  describe('#ipV6_cidr', () => {
  });

  describe('#macAddress', () => {
  });

  describe('#url', () => {
  });

  describe('#slug', () => {
  });
});
<|endoftext|>


<commit_before>//Import bedJS
var bedJS = require('../index.js');

//Test function
var Test =
{
	//Show bed file
	ShowBED: function(bed)
	{
		//Read the full file
		for(var i = 0; i < bed.length; i++)
		{
			//Show in console
			console.log(JSON.stringify(bed[i]));
		}
	},

	//Test read a file
	Read: function()
	{
		//Read the test file
		var bed = bedJS.Read('./test.bed');

		//Show the bed header
		console.log('>> Bed in JSON:');

		//Show the bed
		Test.ShowBED(bed);
	},

	//Test collapse by name
	CollapseByName: function()
	{
		//Read the test file
		var bed = bedJS.Read('./test.bed');

		//Collapse BED regions by name
		var collapsed = bedJS.Collapse.ByName(bed);

		//Show the collapsed regions
		console.log('>> Collapse BED by region name');

		//Show the bed
		Test.ShowBED(collapsed);
	},

	//Test collapse by region
	CollapseByRegion: function()
	{
		//Read the test file
		var bed = bedJS.Read('./test.bed');

		//Collapse BED regions by name
		var collapsed = bedJS.Collapse.ByRegion(bed);

		//Show the collapsed regions
		console.log('>> Collapse BED by region');

		//Show the bed
		Test.ShowBED(collapsed);
	},

	//Index a fasta file
	IndexFasta: function()
	{
		//Reference fasta
		var reference = './getfasta.fa';

		//Index the reference file
		bedJS.Fasta.Index(reference);
	},

	//Get from fasta file
	GetFasta: function()
	{
		//Reference fasta
		var reference = './getfasta.fa';

		//Bed with region
		var bed = './getfasta.bed';

		//Read the bed file
		var bedContent = bedJS.Read(bed);

		//Get fasta sequence
		var fasta = bedJS.Fasta.Get(reference, bedContent);

		//Show in console
		for(var i = 0; i < fasta.length; i++)
		{
			//Get the bed region
			var region = bedContent[i];

			//Show region
			console.log('Region:' + region.chromosome + ':' + region.start + '-' + region.end);

			//Show expected and generated
			console.log('Expected: ' + region.name + '   Generated: ' + fasta[i].sequence);
		}
	}

};

//Exports to node
module.exports = Test;
<commit_msg>test/test.js: minor update<commit_after>//Import bedJS
var bedJS = require('../index.js');

//Test object
var Test = {};

//Show bed file
Test.showBED = function(bed)
{
  //Read the full file
  for(var i = 0; i < bed.length; i++)
  {
    //Show in console
    console.log(JSON.stringify(bed[i]));
  }

  //Exit
  return;
};

//Test read a file
Test.read = function()
{
  //Read the test file
  var bed = bedJS.Read('./test.bed');

  //Show the bed header
  console.log('>> Bed in JSON:');

  //Show the bed
  Test.showBED(bed);

  //Exit
  return;
};

//Test collapse by name
Test.collapseByName = function()
{
  //Read the test file
  var bed = bedJS.Read('./test.bed');

  //Collapse BED regions by name
  var collapsed = bedJS.Collapse.ByName(bed);

  //Show the collapsed regions
  console.log('>> Collapse BED by region name');

  //Show the bed
  Test.showBED(collapsed);

  //Exit
  return;
};

//Test collapse by region
Test.collapseByRegion = function()
{
  //Read the test file
  var bed = bedJS.Read('./test.bed');

  //Collapse BED regions by name
  var collapsed = bedJS.Collapse.ByRegion(bed);

  //Show the collapsed regions
  console.log('>> Collapse BED by region');

  //Show the bed
  Test.showBED(collapsed);

  //Exit
  return;
};

//Index a fasta file
Test.indexFasta = function()
{
  //Reference fasta
  var reference = './getfasta.fa';

  //Index the reference file
  bedJS.Fasta.Index(reference);

  //Exit
  return;
},

//Get from fasta file
Test.getFasta = function()
{
  //Reference fasta
  var reference = './getfasta.fa';

  //Bed with region
  var bed = './getfasta.bed';

  //Read the bed file
  var bedContent = bedJS.Read(bed);

  //Get fasta sequence
  var fasta = bedJS.Fasta.Get(reference, bedContent);

  //Show in console
  for(var i = 0; i < fasta.length; i++)
  {
    //Get the bed region
    var region = bedContent[i];

    //Show region
    console.log('Region:' + region.chromosome + ':' + region.start + '-' + region.end);

    //Show expected and generated
    console.log('Expected: ' + region.name + '   Generated: ' + fasta[i].sequence);
  }

  //Exit
  return;
};

//Exports to node
module.exports = Test;
<|endoftext|>


<commit_before>export class Notification {
  /**
   * @typedef NotificationData
   * @property {boolean} [read]
   * @property {string} title
   * @property {string} message
   * @property {('basic'|'sms')} [type='basic']
   * @property {number} [date]
   * @property {object} [metadata]
   */

  /**
   *
   * @param {NotificationData} data
   */
  constructor(data) {
    this.read = 'read' in data ? data.read : false;
    this.title = data.title;
    this.message = data.message;
    this.date = 'date' in data ? data.date : null;
    this.metadata = 'metadata' in data ? data.metadata : '';
    this.id = this.title + this.message + this.date + JSON.stringify(this.metadata);
  }

  /**
   * Converts the notification to a JSON object
   * @return {object}
   */
  toJSON() {
    return {
      read: this.read,
      title: this.title,
      message: this.message,
      date: this.date,
      metadata: this.metadata,
    };
  }

  static fromJSON(json) {
    return new Notification(json);
  }
}
<commit_msg>Add progress property<commit_after>export class Notification {
  /**
   * @typedef NotificationData
   * @property {boolean} [read]
   * @property {string} title
   * @property {string} message
   * @property {('basic'|'sms')} [type='basic']
   * @property {number} [date]
   * @property {number} [progress]
   * @property {object} [metadata]
   */

  /**
   *
   * @param {NotificationData} data
   */
  constructor(data) {
    this.read = 'read' in data ? data.read : false;
    this.title = data.title;
    this.message = data.message;
    this.date = 'date' in data ? data.date : null;
    this.progress = data.progress;
    this.metadata = 'metadata' in data ? data.metadata : '';
    this.id = this.title + this.message + this.date + JSON.stringify(this.metadata);
  }

  /**
   * Converts the notification to a JSON object
   * @return {object}
   */
  toJSON() {
    return {
      read: this.read,
      title: this.title,
      message: this.message,
      date: this.date,
      metadata: this.metadata,
    };
  }

  static fromJSON(json) {
    return new Notification(json);
  }
}
<|endoftext|>


<commit_before>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'client/bower_components/jquery/dist/jquery.js',
      'client/bower_components/angular/angular.js',
      'client/bower_components/angular-mocks/angular-mocks.js',
      'client/bower_components/angular-resource/angular-resource.js',
      'client/bower_components/angular-cookies/angular-cookies.js',
      'client/bower_components/angular-sanitize/angular-sanitize.js',
      'client/bower_components/angular-route/angular-route.js',
      'client/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      'client/bower_components/lodash/dist/lodash.compat.js',
      'client/bower_components/angular-socket-io/socket.js',
      'client/app/app.js',
      'client/app/app.coffee',
      'client/app/**/*.js',
      'client/app/**/*.coffee',
      'client/components/**/*.js',
      'client/components/**/*.coffee',
      'client/app/**/*.jade',
      'client/components/**/*.jade',
      'client/app/**/*.html',
      'client/components/**/*.html'
    ],

    preprocessors: {
      '**/*.jade': 'ng-jade2js',
      '**/*.html': 'html2js',
      '**/*.coffee': 'coffee',
    },

    ngHtml2JsPreprocessor: {
      stripPrefix: 'client/'
    },

    ngJade2JsPreprocessor: {
      stripPrefix: 'client/'
    },

    // list of files / patterns to exclude
    exclude: [],

    // web server port
    port: 8080,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Firefox'],// ['PhantomJS'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
<commit_msg>Added firefox and chrome in karma test runner.<commit_after>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'client/bower_components/jquery/dist/jquery.js',
      'client/bower_components/angular/angular.js',
      'client/bower_components/angular-mocks/angular-mocks.js',
      'client/bower_components/angular-resource/angular-resource.js',
      'client/bower_components/angular-cookies/angular-cookies.js',
      'client/bower_components/angular-sanitize/angular-sanitize.js',
      'client/bower_components/angular-route/angular-route.js',
      'client/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      'client/bower_components/lodash/dist/lodash.compat.js',
      'client/bower_components/angular-socket-io/socket.js',
      'client/app/app.js',
      'client/app/app.coffee',
      'client/app/**/*.js',
      'client/app/**/*.coffee',
      'client/components/**/*.js',
      'client/components/**/*.coffee',
      'client/app/**/*.jade',
      'client/components/**/*.jade',
      'client/app/**/*.html',
      'client/components/**/*.html'
    ],

    preprocessors: {
      '**/*.jade': 'ng-jade2js',
      '**/*.html': 'html2js',
      '**/*.coffee': 'coffee',
    },

    ngHtml2JsPreprocessor: {
      stripPrefix: 'client/'
    },

    ngJade2JsPreprocessor: {
      stripPrefix: 'client/'
    },

    // list of files / patterns to exclude
    exclude: [],

    // web server port
    port: 8080,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Firefox','Chrome'],// ['PhantomJS'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
<|endoftext|>


<commit_before>/* globals magazineBuilder */

(function(window, $, app) {
    function NewElement() {

        // Add the new element to the DOM
        this.addToDom = function($elements) {
            var $content = app.Page.getContent();

            // If a slug exists, add the new element after the slug, else add it to the top of the page
            var $slug = app.Slug.findSlug();

            if ($slug.length) {
                $slug.after($elements);
            } else {
                $elements.prependTo($content);
            }

            // Deselect all other elements
            app.ContentEditor.deselectAll();

            // Apply edit interactions to the new element.
            app.ContentEditor.applyInteractions($elements);

            // Select the new Element
            app.ContentEditor.select($elements);
        };

        // Create New Text Element
        this.newText = function() {
            var $newDiv = $('
', {
                class: 'span-12 textAlignCenter push-down-18 push-right-18 editable resizable draggable ui-selectee'
            });
            $newDiv.text('NEW EMPTY TEXT ELEMENT');
            addToDom($newDiv);
        };

        // Create New Image Element
        this.newImage = function() {
            var $newDiv = $('
', {
                class: 'span-12 textAlignCenter push-down-18 push-right-18 resizable draggable ui-selectee'
            });

            $newDiv.append('');
            console.log("img = " + $newDiv);
            addToDom($newDiv);
        };

        // Create New CTA Element
        this.newCTA = function() {
            var $newDiv = $('
', {
                class: 'btnShopThe span-12 textAlignCenter push-down-18 push-right-18 editable resizable draggable ui-selectee'
            });

            // --> create new element and then .appenTo($newDiv)
            $newDiv.append('SHOP THE SELECTION');
            addToDom($newDiv);
        };
    }

    app.modules.NewElement = NewElement;
})(window, jQuery, MagTool);
<commit_msg>Fix New Element.<commit_after>/* globals magazineBuilder */

(function(window, $, app) {
    function NewElement() {

        // Add the new element to the DOM
        var addToDom = function($elements) {
            var $content = app.Page.getContent();

            // If a slug exists, add the new element after the slug, else add it to the top of the page
            var $slug = app.Slug.findSlug();

            if ($slug.length) {
                $slug.after($elements);
            } else {
                $elements.prependTo($content);
            }

            // Deselect all other elements
            app.ContentEditor.deselectAll();

            // Apply edit interactions to the new element.
            app.ContentEditor.applyInteractions($elements);

            // Select the new Element
            app.ContentEditor.select($elements);
        };

        // Create New Text Element
        this.newText = function() {
            var $newDiv = $('
', {
                class: 'span-12 textAlignCenter push-down-18 push-right-18 editable resizable draggable ui-selectee'
            });
            $newDiv.text('NEW EMPTY TEXT ELEMENT');
            addToDom($newDiv);
        };

        // Create New Image Element
        this.newImage = function() {
            var $newDiv = $('
', {
                class: 'span-12 textAlignCenter push-down-18 push-right-18 resizable draggable ui-selectee'
            });

            $newDiv.append('');
            console.log("img = " + $newDiv);
            addToDom($newDiv);
        };

        // Create New CTA Element
        this.newCTA = function() {
            var $newDiv = $('
', {
                class: 'btnShopThe span-12 textAlignCenter push-down-18 push-right-18 editable resizable draggable ui-selectee'
            });

            // --> create new element and then .appenTo($newDiv)
            $newDiv.append('SHOP THE SELECTION');
            addToDom($newDiv);
        };
    }

    app.modules.NewElement = NewElement;
})(window, jQuery, MagTool);
<|endoftext|>