<commit_before>/*
 * Copyright 2015-2016 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html} from "/web_modules/lit-element.js";
import UtilsNew from "../../../utilsNew.js";
import "./variant-interpreter-qc-alignment-stats.js";
import "./variant-interpreter-qc-variant-stats.js";

class VariantInterpreterQcOverview extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            clinicalAnalysisId: {
                type: String
            },
            clinicalAnalysis: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = "vcis-" + UtilsNew.randomString(6);

        this._config = this.getDefaultConfig();
    }

    connectedCallback() {
        super.connectedCallback();

        this._config = {...this.getDefaultConfig(), ...this.config};
    }

    updated(changedProperties) {
        // if (changedProperties.has("opencgaSession")) {
        //     this.opencgaSessionObserver();
        // }
        if (changedProperties.has("clinicalAnalysisId")) {
            this.clinicalAnalysisIdObserver();
        }

        if (changedProperties.has("config")) {
            this._config = {...this.getDefaultConfig(), ...this.config};
        }
    }

    clinicalAnalysisIdObserver() {
        if (this.opencgaSession && this.clinicalAnalysisId) {
            this.opencgaSession.opencgaClient.clinical().info(this.clinicalAnalysisId, {study: this.opencgaSession.study.fqn})
                .then(response => {
                    this.clinicalAnalysis = response.responses[0].results[0];
                    this.requestUpdate();
                })
                .catch(response => {
                    console.error("An error occurred fetching clinicalAnalysis: ", response);
                });
        }
    }

    getDefaultConfig() {
        return {
            title: "QC Summary",
            icon: "",
            display: {
                collapsable: true,
                showTitle: false,
                labelWidth: 2,
                defaultValue: "-",
                defaultLayout: "horizontal"
            },
            sections: [
                {
                    title: "Summary",
                    collapsed: false,
                    elements: [
                        {
                            name: "Analysis ID",
                            field: "id"
                        },
                        {
                            name: "Proband",
                            field: "proband.id",
                            type: "custom",
                            display: {
                                render: probandId => html`<strong>${probandId}</strong>`
                            }
                        },
                        {
                            name: "Disorder",
                            field: "disorder",
                            type: "custom",
                            display: {
                                render: disorder => {
                                    let id = disorder.id;
                                    if (disorder.id.startsWith("OMIM:")) {
                                        id = html`<a href="https://omim.org/entry/${disorder.id.split(":")[1]}" target="_blank">${disorder.id}</a>`;
                                    }
                                    return html`${disorder.name || "-"} (${id})`
                                },
                            }
                        },
                        {
                            name: "Analysis Type",
                            field: "type"
                        },
                    ]
                },
            ]
        }
    }

    /*getVariantConfig() {
        return {
            title: "Variant",
            icon: "",
            display: {
                collapsable: true,
                showTitle: false,
                labelWidth: 2,
                defaultValue: "-",
                defaultLayout: "horizontal"
            },
            sections: [
                {
                    title: "Variant Stats",
                    display: {
                        visible: data => data.type === "FAMILY",
                    },
                    elements: [
                        {
                            name: "Proband Stats",
                            // field: "proband.id",
                            type: "custom",
                            showLabel: false,
                            display: {
                                width: 12,
                                render: data => {
                                    console.log("data",data)
                                    if (data.proband && data.proband.samples && data.proband.samples.length > 0) {
                                        const stats = data.proband.samples[0].annotationSets.find( annotationSet => annotationSet.id === "opencga_sample_variant_stats");
                                        if(!stats) {
                                            console.error("Sample variant stats unavailable")
                                        }
                                        return html`
                                            <sample-variant-stats-view .opencgaSession="${this.opencgaSession}" .sampleVariantStats="${stats?.annotations}"> </sample-variant-stats-view>
                                        `;
                                    }
                                },
                            }
                        },
                    ]
                },
                {
                    title: "Files",
                    elements: [
                        {
                            name: "File",
                            field: "files",
                            type: "list",
                            display: {
                                contentLayout: "bullets",
                                template: "${name}"
                            }
                        }
                    ]
                }
            ]
        }
    }*/

    onSideNavClick(e) {
        e.preventDefault();

        // Remove button focus highlight
        e.target.blur();

        // Remove selected active button
        document.querySelector(".side-nav-active").classList.add("side-nav");
        document.querySelector(".side-nav-active").classList.remove("side-nav-active");
        document.querySelectorAll(".tab-content").forEach(value => value.style.display = "none");

        let option = e.currentTarget.dataset.id;
        document.getElementById(this._prefix + option).classList.remove("side-nav");
        document.getElementById(this._prefix + option).classList.add("side-nav-active");
        document.getElementById(this._prefix + option + "Content").style.display = "block";
    }

    render() {
        // Check Project exists
        if (!this.opencgaSession.project) {
            return html`

No public projects available to browse. Please login to continue

            `;
        }

        return html`

Overview

                            <button id="${this._prefix}Summary" type="button" class="list-group-item side-nav-active"
                                  data-id="Summary" @click="${this.onSideNavClick}">Summary</button>
                            <button id="${this._prefix}VariantStats" type="button" class="list-group-item side-nav"
                                  data-id="VariantStats" @click="${this.onSideNavClick}">Variant Stats</button>
                            <button id="${this._prefix}AlignmentStats" type="button" class="list-group-item side-nav"
                                  data-id="AlignmentStats" @click="${this.onSideNavClick}">Alignment Stats</button>
                            <button id="${this._prefix}GeneCoverageStats" type="button" class="list-group-item side-nav"
                                  data-id="GeneCoverageStats" @click="${this.onSideNavClick}">Gene Coverage Stats</button>
                            <button id="${this._prefix}MendelianErrorsContent" type="button" class="list-group-item side-nav"
                                  data-id="MendelianErrors" @click="${this.onSideNavClick}">Mendelian Errors</button>

                                <data-form .data=${this.clinicalAnalysis} .config="${this._config}"></data-form>

                                <variant-interpreter-qc-variant-stats     .opencgaSession=${this.opencgaSession}
                                                                        .clinicalAnalysis="${this.clinicalAnalysis}">
                                </variant-interpreter-qc-variant-stats>

Alignment Stats

                                <variant-interpreter-qc-alignment-stats .opencgaSession=${this.opencgaSession}
                                                                        .clinicalAnalysis="${this.clinicalAnalysis}">
                                </variant-interpreter-qc-alignment-stats>

Gene Coverage Stats

Alignment QC

                                <alignment-stats-view .opencgaSession=${this.opencgaSession} .alignmentStats="${this.alignmentStats}"></alignment-stats-view>

        `;
    }

}

customElements.define("variant-interpreter-qc-overview", VariantInterpreterQcOverview);
<commit_msg>wc: new QC components<commit_after>/*
 * Copyright 2015-2016 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html} from "/web_modules/lit-element.js";
import UtilsNew from "../../../utilsNew.js";
import "./variant-interpreter-qc-summary.js";
import "./variant-interpreter-qc-variant-stats.js";
import "./variant-interpreter-qc-alignment-stats.js";

class VariantInterpreterQcOverview extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            clinicalAnalysisId: {
                type: String
            },
            clinicalAnalysis: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = "vcis-" + UtilsNew.randomString(6);

        this._config = this.getDefaultConfig();
    }

    connectedCallback() {
        super.connectedCallback();

        this._config = {...this.getDefaultConfig(), ...this.config};
    }

    updated(changedProperties) {
        // if (changedProperties.has("opencgaSession")) {
        //     this.opencgaSessionObserver();
        // }
        if (changedProperties.has("clinicalAnalysisId")) {
            this.clinicalAnalysisIdObserver();
        }

        if (changedProperties.has("config")) {
            this._config = {...this.getDefaultConfig(), ...this.config};
        }
    }

    clinicalAnalysisIdObserver() {
        if (this.opencgaSession && this.clinicalAnalysisId) {
            this.opencgaSession.opencgaClient.clinical().info(this.clinicalAnalysisId, {study: this.opencgaSession.study.fqn})
                .then(response => {
                    this.clinicalAnalysis = response.responses[0].results[0];
                    this.requestUpdate();
                })
                .catch(response => {
                    console.error("An error occurred fetching clinicalAnalysis: ", response);
                });
        }
    }

    getDefaultConfig() {
        return {
            title: "QC Summary",
            icon: "",
            display: {
                collapsable: true,
                showTitle: false,
                labelWidth: 2,
                defaultValue: "-",
                defaultLayout: "horizontal"
            },
            sections: [
                {
                    title: "Summary",
                    collapsed: false,
                    elements: [
                        {
                            name: "Analysis ID",
                            field: "id"
                        },
                        {
                            name: "Proband",
                            field: "proband.id",
                            type: "custom",
                            display: {
                                render: probandId => html`<strong>${probandId}</strong>`
                            }
                        },
                        {
                            name: "Disorder",
                            field: "disorder",
                            type: "custom",
                            display: {
                                render: disorder => {
                                    let id = disorder.id;
                                    if (disorder.id.startsWith("OMIM:")) {
                                        id = html`<a href="https://omim.org/entry/${disorder.id.split(":")[1]}" target="_blank">${disorder.id}</a>`;
                                    }
                                    return html`${disorder.name || "-"} (${id})`
                                },
                            }
                        },
                        {
                            name: "Analysis Type",
                            field: "type"
                        },
                    ]
                },
            ]
        }
    }

    /*getVariantConfig() {
        return {
            title: "Variant",
            icon: "",
            display: {
                collapsable: true,
                showTitle: false,
                labelWidth: 2,
                defaultValue: "-",
                defaultLayout: "horizontal"
            },
            sections: [
                {
                    title: "Variant Stats",
                    display: {
                        visible: data => data.type === "FAMILY",
                    },
                    elements: [
                        {
                            name: "Proband Stats",
                            // field: "proband.id",
                            type: "custom",
                            showLabel: false,
                            display: {
                                width: 12,
                                render: data => {
                                    console.log("data",data)
                                    if (data.proband && data.proband.samples && data.proband.samples.length > 0) {
                                        const stats = data.proband.samples[0].annotationSets.find( annotationSet => annotationSet.id === "opencga_sample_variant_stats");
                                        if(!stats) {
                                            console.error("Sample variant stats unavailable")
                                        }
                                        return html`
                                            <sample-variant-stats-view .opencgaSession="${this.opencgaSession}" .sampleVariantStats="${stats?.annotations}"> </sample-variant-stats-view>
                                        `;
                                    }
                                },
                            }
                        },
                    ]
                },
                {
                    title: "Files",
                    elements: [
                        {
                            name: "File",
                            field: "files",
                            type: "list",
                            display: {
                                contentLayout: "bullets",
                                template: "${name}"
                            }
                        }
                    ]
                }
            ]
        }
    }*/

    onSideNavClick(e) {
        e.preventDefault();

        // Remove button focus highlight
        e.target.blur();

        // Remove selected active button
        document.querySelector(".side-nav-active").classList.add("side-nav");
        document.querySelector(".side-nav-active").classList.remove("side-nav-active");
        document.querySelectorAll(".tab-content").forEach(value => value.style.display = "none");

        let option = e.currentTarget.dataset.id;
        document.getElementById(this._prefix + option).classList.remove("side-nav");
        document.getElementById(this._prefix + option).classList.add("side-nav-active");
        document.getElementById(this._prefix + option + "Content").style.display = "block";
    }

    render() {
        // Check Project exists
        if (!this.opencgaSession.project) {
            return html`

No public projects available to browse. Please login to continue

            `;
        }

        return html`

Overview

                            <button id="${this._prefix}Summary" type="button" class="list-group-item side-nav-active"
                                  data-id="Summary" @click="${this.onSideNavClick}">Summary</button>
                            <button id="${this._prefix}VariantStats" type="button" class="list-group-item side-nav"
                                  data-id="VariantStats" @click="${this.onSideNavClick}">Variant Stats</button>
                            <button id="${this._prefix}MendelianErrorsContent" type="button" class="list-group-item side-nav"
                                  data-id="MendelianErrors" @click="${this.onSideNavClick}">Mendelian Errors</button>
                            <button id="${this._prefix}AlignmentStats" type="button" class="list-group-item side-nav"
                                  data-id="AlignmentStats" @click="${this.onSideNavClick}">Alignment Stats</button>
                            <button id="${this._prefix}GeneCoverageStats" type="button" class="list-group-item side-nav"
                                  data-id="GeneCoverageStats" @click="${this.onSideNavClick}">Gene Coverage Stats</button>

                                <variant-interpreter-qc-summary .opencgaSession=${this.opencgaSession}
                                                                .clinicalAnalysis=${this.clinicalAnalysis}
                                                                .config="${this._config}">
                                </variant-interpreter-qc-summary>

                                <variant-interpreter-qc-variant-stats     .opencgaSession=${this.opencgaSession}
                                                                        .clinicalAnalysis="${this.clinicalAnalysis}">
                                </variant-interpreter-qc-variant-stats>

Alignment Stats

                                <variant-interpreter-qc-alignment-stats .opencgaSession=${this.opencgaSession}
                                                                        .clinicalAnalysis="${this.clinicalAnalysis}">
                                </variant-interpreter-qc-alignment-stats>

Gene Coverage Stats

Alignment QC

                                <alignment-stats-view .opencgaSession=${this.opencgaSession} .alignmentStats="${this.alignmentStats}"></alignment-stats-view>

        `;
    }

}

customElements.define("variant-interpreter-qc-overview", VariantInterpreterQcOverview);
<|endoftext|>


<commit_before>import $ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import Promise from 'bluebird';

Promise.config({
  cancellation: true,
});

import App from './app.jsx';
import * as Api from './api';
import { ApiError } from './utils/http';

var initializationEl = document.querySelector('#initialization');
var progressBarEl = initializationEl.querySelector('.progress-bar');
var progress = +progressBarEl.getAttribute('aria-valuenow');

function incrementProgressBar(gotoPercent) {
  progress = Math.min(gotoPercent || (progress + 20), 100); // cap to 100%
  progressBarEl.style.width = `${progress}%`;
  progressBarEl.setAttribute('aria-valuenow', progress);
  progressBarEl.querySelector('span').textContent = `${progress}% Complete`;
}

function renderApp() {
  incrementProgressBar(100);
  initializationEl.classList.add('done');
  initializationEl.addEventListener('transitionend', function() { initializationEl.remove(); });

  const appElement = document.querySelector('#app');

  ReactDOM.render(App, appElement);

  $('#screen').css('padding-top', $('#header-main').height() + 10);
}

export default function startApp() {
  incrementProgressBar(25);
  // Load user.
  var userPromise = Api.getCurrentUser();

  userPromise.then(() => {
    incrementProgressBar(50);
    // Check permissions?

    // Get lookups.
    var citiesPromise = Api.getCities();
    var districtsPromise = Api.getDistricts();
    var regionsPromise = Api.getRegions();
    var schoolDistrictsPromise = Api.getSchoolDistricts();
    var serviceAreasPromise = Api.getServiceAreas();

    return Promise.all([citiesPromise, districtsPromise, regionsPromise, schoolDistrictsPromise, serviceAreasPromise]).then(() => {
      incrementProgressBar(75);
      // Wrapping in a setTimeout to silence an error from Bluebird's promise lib about API requests
      // made inside of component{Will,Did}Mount.
      setTimeout(renderApp, 0);
    });
  }).catch(err => {
    showError(err);
  });
}

function showError(err) {
  progressBarEl.classList.add('progress-bar-danger');
  progressBarEl.classList.remove('active');
  console.error(err);
  var errorMessage = String(err);
  if (err instanceof ApiError) {
    errorMessage = err.message;
  }

  ReactDOM.render((

Error loading application

{errorMessage}

  ), document.getElementById('init-error'));
}

window.onload = startApp;
<commit_msg>HETS-19 fix for client<commit_after>import $ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import Promise from 'bluebird';

Promise.config({
  cancellation: true,
});

import App from './app.jsx';
import * as Api from './api';
import { ApiError } from './utils/http';

var initializationEl = document.querySelector('#initialization');
var progressBarEl = initializationEl.querySelector('.progress-bar');
var progress = +progressBarEl.getAttribute('aria-valuenow');

function incrementProgressBar(gotoPercent) {
  progress = Math.min(gotoPercent || (progress + 20), 100); // cap to 100%
  progressBarEl.style.width = `${progress}%`;
  progressBarEl.setAttribute('aria-valuenow', progress);
  progressBarEl.querySelector('span').textContent = `${progress}% Complete`;
}

function renderApp() {
  incrementProgressBar(100);
  initializationEl.classList.add('done');
  initializationEl.addEventListener('transitionend', function() { initializationEl.remove(); });

  const appElement = document.querySelector('#app');

  ReactDOM.render(App, appElement);

  $('#screen').css('padding-top', $('#header-main').height() + 10);
}

export default function startApp() {
  incrementProgressBar(25);
  // Load user.
  var userPromise = Api.getCurrentUser();

  userPromise.then(() => {
    incrementProgressBar(50);
    // Check permissions?

    // Get lookups.
    var citiesPromise = Api.getCities();
    var districtsPromise = Api.getDistricts();
    var regionsPromise = Api.getRegions();
    var serviceAreasPromise = Api.getServiceAreas();

    return Promise.all([citiesPromise, districtsPromise, regionsPromise, serviceAreasPromise]).then(() => {
      incrementProgressBar(75);
      // Wrapping in a setTimeout to silence an error from Bluebird's promise lib about API requests
      // made inside of component{Will,Did}Mount.
      setTimeout(renderApp, 0);
    });
  }).catch(err => {
    showError(err);
  });
}

function showError(err) {
  progressBarEl.classList.add('progress-bar-danger');
  progressBarEl.classList.remove('active');
  console.error(err);
  var errorMessage = String(err);
  if (err instanceof ApiError) {
    errorMessage = err.message;
  }

  ReactDOM.render((

Error loading application

{errorMessage}

  ), document.getElementById('init-error'));
}

window.onload = startApp;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types'
import SelectField from 'react-md/lib/SelectFields';
import Radio from 'react-md/lib/SelectionControls/Radio';
import Switch from 'react-md/lib/SelectionControls/Switch';
import Divider from 'react-md/lib/Dividers';
import axios from 'axios'
import { API_ROOT } from '../middleware/api';

class AddAttribute extends Component {
  constructor(props) {
    super(props);
    this.state = {
      relation: '',
      attribute: '',
      attributes: [],
      negated: false
    };
    this.setRelation = this.setRelation.bind(this);
    this.setAttribute = this.setAttribute.bind(this);
    this._handleInlineChange = this._handleInlineChange.bind(this);
  }
  setRelation(newValue, newActiveIndex, event) {
    console.log(newValue, newActiveIndex, event);
    const relation = newValue;
    this.setState({ relation })

    // With the relation type chosen, we can query the backend
    console.log(relation)
    axios.get(API_ROOT + `get_attribute_values/type/` + relation)
      .then(res => {
        const attributes = res.data.sort();
        this.setState({ attributes });
      });

    // callback to set state in upper level
    this.props.handleChange(relation, event, this.props.groupIndex, this.props.attributeIndex, "relation");
  }
  setAttribute(newValue, newActiveIndex, event) {
    console.log(newValue, newActiveIndex, event);
    const attribute = newValue;
    this.setState({ attribute })

    // callback to set state in upper level
    this.props.handleChange(attribute, event, this.props.groupIndex, this.props.attributeIndex, "attribute");
  }
  _handleInlineChange(e) {
   // Basically how the `SelectionControlGroup` works
   this.setState({ inlineValue: e.target.value });
   console.log(e)
   console.log(e.target.id)

   // callback
   this.props.handleChange(e.target.id, event, this.props.groupIndex, this.props.attributeIndex, "logical");
 }
 _handleChangeNegated = (negated, event) => {
    this.setState({ negated });
    this.props.handleChange(negated, event, this.props.groupIndex, this.props.attributeIndex, "negated");
  };
  render(){
    const { inlineValue, negated } = this.state;
    return (

        <fieldset>
          <fieldset>
            <legend className="md-subheading-1">Negation:</legend>
            <Switch id="switch3" name="controlledSwitch" label="Negate" checked={negated} onChange={this._handleChangeNegated} />
          </fieldset>
          <legend className="md-subheading-1">Define a relation:</legend>
          <fieldset>
            <legend className="md-subheading-1">Select Attribute:</legend>
            <SelectField
              id="relations"
              label="Relations"
              placeholder="Select a Relation"
              position={SelectField.Positions.BELOW}
              menuItems={this.props.relations}
              className="md-cell"
              helpOnFocus
              helpText="Relations are descriptors about specific attributes."
              onChange={this.setRelation}
              required
            />
            <SelectField
              id="attributes"
              label="Attributes"
              placeholder="Select an Attribute"
              position={SelectField.Positions.BELOW}
              menuItems={this.state.attributes}
              className="md-cell"
              helpOnFocus
              helpText="An attribute is a specific instance of a relation type. For example, O157 is an attribute of relation O-Type."
              onChange={this.setAttribute}
              required
            />
          </fieldset>
          <fieldset onChange={this._handleInlineChange}>
            <legend className="md-subheading-1">Linked By:</legend>
            <Radio
              id="AND"
              inline
              name="inlineRadios"
              value="A"
              label="AND"
              checked={inlineValue === 'A'}
            />
            <Radio
              id="OR"
              inline
              name="inlineRadios"
              value="B"
              label="OR"
              checked={inlineValue === 'B'}
            />
          </fieldset>
          <Divider />
        </fieldset>

    )
  }
}

AddAttribute.propTypes = {
  handleChange: PropTypes.func
}

export default AddAttribute;
<commit_msg>DEL: some state in AddAttribute.js that overlapped with GroupsForm. Left some state vars that are required by react-md to render updates to user<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types'
import SelectField from 'react-md/lib/SelectFields';
import Radio from 'react-md/lib/SelectionControls/Radio';
import Switch from 'react-md/lib/SelectionControls/Switch';
import Divider from 'react-md/lib/Dividers';
import axios from 'axios'
import { API_ROOT } from '../middleware/api';

class AddAttribute extends Component {
  constructor(props) {
    super(props);
    this.state = {
      attributes: [],
    };
    this.setRelation = this.setRelation.bind(this);
    this.setAttribute = this.setAttribute.bind(this);
    this._handleInlineChange = this._handleInlineChange.bind(this);
  }
  setRelation(newValue, newActiveIndex, event) {
    console.log(newValue, newActiveIndex, event);
    const relation = newValue;

    // With the relation type chosen, we can query the backend
    console.log(relation)
    axios.get(API_ROOT + `get_attribute_values/type/` + relation)
      .then(res => {
        const attributes = res.data.sort();
        this.setState({ attributes });
      });

    // callback to set state in upper level
    this.props.handleChange(relation, event, this.props.groupIndex, this.props.attributeIndex, "relation");
  }
  setAttribute(newValue, newActiveIndex, event) {
    console.log(newValue, newActiveIndex, event);
    const attribute = newValue;

    // callback to set state in upper level
    this.props.handleChange(attribute, event, this.props.groupIndex, this.props.attributeIndex, "attribute");
  }
  _handleInlineChange(e) {
   // Basically how the `SelectionControlGroup` works
   this.setState({ inlineValue: e.target.value });
   console.log(e)
   console.log(e.target.id)

   // callback
   this.props.handleChange(e.target.id, event, this.props.groupIndex, this.props.attributeIndex, "logical");
 }
 _handleChangeNegated = (negated, event) => {
    this.props.handleChange(negated, event, this.props.groupIndex, this.props.attributeIndex, "negated");
  };
  render(){
    const { inlineValue, negated } = this.state;
    return (

        <fieldset>
          <fieldset>
            <legend className="md-subheading-1">Negation:</legend>
            <Switch id="switch3" name="controlledSwitch" label="Negate" checked={negated} onChange={this._handleChangeNegated} />
          </fieldset>
          <legend className="md-subheading-1">Define a relation:</legend>
          <fieldset>
            <legend className="md-subheading-1">Select Attribute:</legend>
            <SelectField
              id="relations"
              label="Relations"
              placeholder="Select a Relation"
              position={SelectField.Positions.BELOW}
              menuItems={this.props.relations}
              className="md-cell"
              helpOnFocus
              helpText="Relations are descriptors about specific attributes."
              onChange={this.setRelation}
              required
            />
            <SelectField
              id="attributes"
              label="Attributes"
              placeholder="Select an Attribute"
              position={SelectField.Positions.BELOW}
              menuItems={this.state.attributes}
              className="md-cell"
              helpOnFocus
              helpText="An attribute is a specific instance of a relation type. For example, O157 is an attribute of relation O-Type."
              onChange={this.setAttribute}
              required
            />
          </fieldset>
          <fieldset onChange={this._handleInlineChange}>
            <legend className="md-subheading-1">Linked By:</legend>
            <Radio
              id="AND"
              inline
              name="inlineRadios"
              value="A"
              label="AND"
              checked={inlineValue === 'A'}
            />
            <Radio
              id="OR"
              inline
              name="inlineRadios"
              value="B"
              label="OR"
              checked={inlineValue === 'B'}
            />
          </fieldset>
          <Divider />
        </fieldset>

    )
  }
}

AddAttribute.propTypes = {
  handleChange: PropTypes.func
}

export default AddAttribute;
<|endoftext|>


<commit_before>var benchmark = require('benchmark')

exports.suite = function () {
  var suite = new benchmark.Suite()
  process.nextTick(function () {
    suite
      .on('error', function (event) {
        console.error(event.target.error.stack)
      })
      .on('cycle', function (event) {
        console.log(String(event.target))
      })
      .on('complete', function () {
        console.log('Fastest is ' + this.filter('fastest').pluck('name'))
      })
      .run({ async: true })
  })
  return suite
}
<commit_msg>fix benchmark for v2<commit_after>var benchmark = require('benchmark')

exports.suite = function () {
  var suite = new benchmark.Suite()
  process.nextTick(function () {
    suite
      .on('error', function (event) {
        console.error(event.target.error.stack)
      })
      .on('cycle', function (event) {
        console.log(String(event.target))
      })
      .on('complete', function () {
        console.log('Fastest is ' + this.filter('fastest').map('name'))
      })
      .run({ async: true })
  })
  return suite
}
<|endoftext|>


<commit_before>function (doc) {
    // this is a direct port of the python case.xform.extract_case_blocks function
    var relevantDocTypes = [
        "XFormInstance", "XFormError", "XFormDuplicate",
        "XFormDeprecated", "SubmissionErrorLog", "XFormArchived"
    ];
    var deviceReportXmlns = "http://code.javarosa.org/devicereport";

    var shouldLook = function (doc) {
        return (relevantDocTypes.indexOf(doc.doc_type) !== -1 &&
            !(doc.xmlns === deviceReportXmlns ||
              doc['@xmlns'] === deviceReportXmlns)
        );

    };

    function typeOf(value) {
        // todo: this function now lives in 3 places in couch. any way to deduplicate?
        var s = typeof value;
        if (s === 'object') {
            if (value) {
                if (Object.prototype.toString.call(value) == '[object Array]') {
                    s = 'array';
                }
            } else {
                s = 'null';
            }
        }
        return s;
    }

    function isArray(obj) {
        return typeOf(obj) === "array";
    }

    function isObject(obj) {
        return typeOf(obj) === "object";
    }

    var emitCaseBlocksIn = function (subdoc) {

        var getCaseId = function (caseBlock) {
            return caseBlock['case_id'] || caseBlock['@case_id'] || null;
        };

        var emitIfId = function (caseBlock) {
            caseId = getCaseId(caseBlock);
            if (caseId) {
                emit([caseId, doc._id], null);
            }
        }

        var prop, i, caseId;

        if (isArray(subdoc)) {
            for (i = 0; i < subdoc.length; i++) {
                emitCaseBlocksIn(subdoc[i]);
            }
        } else if (isObject(subdoc)) {
            for (prop in subdoc) {
                if (subdoc.hasOwnProperty(prop)) {
                    if (prop === 'case') {
                        var caseOrCaseList = subdoc[prop];
                        if (isArray(caseOrCaseList)) {
                            for (i = 0; i < caseOrCaseList.length; i++) {
                                emitIfId(caseOrCaseList[i]);
                            }
                        } else {
                            emitIfId(caseOrCaseList);
                        }
                    }
                    else {
                        // recurse through sub properties
                        emitCaseBlocksIn(subdoc[prop]);
                    }
                }
            }
        }
    };
    if (shouldLook(doc)) {
        log('looking in ' + doc._id);
        emitCaseBlocksIn(doc);
    }
}
<commit_msg>remove log statement<commit_after>function (doc) {
    // this is a direct port of the python case.xform.extract_case_blocks function
    var relevantDocTypes = [
        "XFormInstance", "XFormError", "XFormDuplicate",
        "XFormDeprecated", "SubmissionErrorLog", "XFormArchived"
    ];
    var deviceReportXmlns = "http://code.javarosa.org/devicereport";

    var shouldLook = function (doc) {
        return (relevantDocTypes.indexOf(doc.doc_type) !== -1 &&
            !(doc.xmlns === deviceReportXmlns ||
              doc['@xmlns'] === deviceReportXmlns)
        );

    };

    function typeOf(value) {
        // todo: this function now lives in 3 places in couch. any way to deduplicate?
        var s = typeof value;
        if (s === 'object') {
            if (value) {
                if (Object.prototype.toString.call(value) == '[object Array]') {
                    s = 'array';
                }
            } else {
                s = 'null';
            }
        }
        return s;
    }

    function isArray(obj) {
        return typeOf(obj) === "array";
    }

    function isObject(obj) {
        return typeOf(obj) === "object";
    }

    var emitCaseBlocksIn = function (subdoc) {

        var getCaseId = function (caseBlock) {
            return caseBlock['case_id'] || caseBlock['@case_id'] || null;
        };

        var emitIfId = function (caseBlock) {
            caseId = getCaseId(caseBlock);
            if (caseId) {
                emit([caseId, doc._id], null);
            }
        }

        var prop, i, caseId;

        if (isArray(subdoc)) {
            for (i = 0; i < subdoc.length; i++) {
                emitCaseBlocksIn(subdoc[i]);
            }
        } else if (isObject(subdoc)) {
            for (prop in subdoc) {
                if (subdoc.hasOwnProperty(prop)) {
                    if (prop === 'case') {
                        var caseOrCaseList = subdoc[prop];
                        if (isArray(caseOrCaseList)) {
                            for (i = 0; i < caseOrCaseList.length; i++) {
                                emitIfId(caseOrCaseList[i]);
                            }
                        } else {
                            emitIfId(caseOrCaseList);
                        }
                    }
                    else {
                        // recurse through sub properties
                        emitCaseBlocksIn(subdoc[prop]);
                    }
                }
            }
        }
    };
    if (shouldLook(doc)) {
        emitCaseBlocksIn(doc);
    }
}
<|endoftext|>


<commit_before>/*
Copyright 2012 Twitter, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * This module defines the Table view which generates a dynamic tabular view of a Workflow's jobs.
 */
define(['jquery', 'd3', '../core', './core'], function($, d3, Ambrose, View) {
  // Table ctor
  var Table = View.Table = function(workflow, container) {
    return new View.Table.fn.init(workflow, container);
  };

  /**
   * Table prototype.
   */
  Table.fn = Table.prototype = {
    /**
     * Constructor.
     *
     * @param workflow the Workflow instance to bind to.
     * @param container the DOM element in which to render the view.
     */
    init: function(workflow, container) {
      this.workflow = workflow;
      this.container = $(container);
      this.initTable();
      var self = this;
      workflow.on('jobsLoaded', function(event, data) {
        self.handleJobsLoaded(event, data);
      });
      workflow.on('jobStarted jobProgress jobComplete jobFailed', function(event, data) {
        self.handleJobUpdated(event, data);
      });
      workflow.on('jobSelected jobMouseOver', function(event, job, prev) {
        if (job != null) self.handleJobUpdated(event, job);
        if (prev != null) self.handleJobUpdated(event, prev);
      });
    },

    initTable: function() {
      $('
'
        + '

'
        + '#	'
        + 'Identifier	'
        + 'Status	'
        + 'Aliases	'
        + 'Features	'
        + 'Mappers	'
        + 'Reducers	'
        + '

'
        + '
')
        .appendTo(this.container.empty())
        .append(this.tbody = $('
'));
    },

    handleJobsLoaded: function(event, data) {
      this.loadTable(data);
    },

    handleJobUpdated: function(event, data) {
      this.updateTableRow(data);
    },

    selectRows: function(jobs) {
      // select rows and bind to jobs data
      return d3.select(this.tbody.get(0)).selectAll('tr')
        .data(jobs, function(job) { return job.id; });
    },

    removeRows: function(tr) {
      // remove rows for missing jobs data
      tr.exit().remove();
    },

    createRows: function(tr) {
      // create rows for new jobs data
      tr = tr.enter().append('tr');
      tr.append('td').attr('class', 'job-num')
        .text(function(job) { return 1 + (job.topologicalIndex || job.index); });
      tr.append('td').attr('class', 'job-id')
        .append('a').attr('class', 'job-url')
        .attr('target', '_blank')
        .attr('href', 'javascript:void(0);');
      tr.append('td').attr('class', 'job-status')
      tr.append('td').attr('class', 'job-aliases')
      tr.append('td').attr('class', 'job-features')
      tr.append('td').attr('class', 'job-mappers')
      tr.append('td').attr('class', 'job-reducers');
    },

    updateRows: function(tr, duration) {
      // update mutable row properties
      duration = duration || 250;
      tr.transition().duration(duration)
        .style('background-color', function(job) {
          if (job.mouseover) return d3.rgb(98, 98, 196).brighter();
          if (job.selected) return d3.rgb(98, 98, 196);
          if (job.status == 'RUNNING') return d3.rgb(98, 196, 98).brighter();
          if (job.status == 'COMPLETE') return d3.rgb(98, 196, 98);
          if (job.status == 'FAILED') return d3.rgb(196, 98, 98);
          return null;
        });
      tr.selectAll('a.job-url')
        .attr('href', function(job) { return job.trackingUrl || 'javascript:void(0);'; })
        .text(function(job) { return job.id; });
      tr.selectAll('td.job-status')
        .text(function (job) { Ambrose.nullToEmpty(job.status); });
      tr.selectAll('td.job-aliases')
        .text(function (job) { Ambrose.commaDelimit(job.aliases); });
      tr.selectAll('td.job-features')
        .text(function (job) { Ambrose.commaDelimit(job.features); });
      tr.selectAll('td.job-mappers')
        .text(function (job) { Ambrose.taskProgressMessage(job.totalMappers, job.mapProgress); });
      tr.selectAll('td.job-reducers')
        .text(function (job) { Ambrose.taskProgressMessage(job.totalReducers, job.reduceProgress); });
    },

    loadTableD3: function(jobs) {
      var tr = this.selectRows(jobs);
      this.removeRows(tr);
      this.createRows(tr);
      this.updateRows(tr);
    },

    updateTableRowD3: function(job) {
      this.updateRows(this.selectRows([job]));
    },

    loadTable: function(jobs) {
      var self = this;
      var tbody = this.tbody.empty();
      this.rows = {};
      $.each(jobs, function(i, job) {
        var tr = $('
'
          + '' + (i + 1) + '	'
          + '	'
          + ''
          + ''
          + ''
          + ''
          + ''
          + '
')
          .appendTo(tbody)
          .on('click', function() { self.workflow.selectJob(job); })
          .on('mouseover', function() { self.workflow.mouseOverJob(job); })
          .on('mouseout', function() { self.workflow.mouseOverJob(null); });
        self.rows[job.id] = tr;
        self.updateTableRow(job, tr);
      });
    },

    updateTableRow: function(job, tr) {
      // find job row
      if (tr == null) {
        tr = this.rows[job.id];
        if (tr == null) {
          console.error("No row for job id '" + job.id + "' exists");
          return;
        }
      }
      // update data
      $('.job-url', tr).text(job.id).attr('href', job.trackingUrl);
      $('.job-status', tr).text(Ambrose.nullToEmpty(job.status));
      $('.job-alias', tr).text(Ambrose.commaDelimit(job.aliases));
      $('.job-feature', tr).text(Ambrose.commaDelimit(job.features));
      $('.job-mappers', tr).text(Ambrose.taskProgressMessage(job.totalMappers, job.mapProgress));
      $('.job-reducers', tr).text(Ambrose.taskProgressMessage(job.totalReducers, job.reduceProgress));
      // update css
      tr.removeClass();
      if (job.mouseover) tr.addClass('mouseover');
      if (job.selected) tr.addClass('selected');
      if (job.status == 'FAILED') tr.addClass('error');
      if (job.status == 'COMPLETE') tr.addClass('success');
    },
  };

  // bind prototype to ctor
  Table.fn.init.prototype = Table.fn;
  return Table;
});
<commit_msg>Updates table view to use d3<commit_after>/*
Copyright 2012 Twitter, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * This module defines the Table view which generates a dynamic tabular view of a Workflow's jobs.
 */
define(['jquery', 'd3', '../core', './core'], function($, d3, Ambrose, View) {
  // Table ctor
  var Table = View.Table = function(workflow, container) {
    return new View.Table.fn.init(workflow, container);
  };

  /**
   * Table prototype.
   */
  Table.fn = Table.prototype = {
    /**
     * Constructor.
     *
     * @param workflow the Workflow instance to bind to.
     * @param container the DOM element in which to render the view.
     */
    init: function(workflow, container) {
      this.workflow = workflow;
      this.container = $(container);
      this.initTable();
      var self = this;
      workflow.on('jobsLoaded', function(event, jobs) {
        self.loadTable(jobs);
      });
      workflow.on('jobStarted jobProgress jobComplete jobFailed', function(event, job) {
        self.updateTableRows([job], 350);
      });
      workflow.on('jobSelected jobMouseOver', function(event, job, prev) {
        var jobs = [];
        if (prev != null) jobs.push(prev);
        if (job != null) jobs.push(job);
        self.updateTableRows(jobs);
      });
    },

    initTable: function() {
      $('
'
        + '

'
        + '#	'
        + 'Identifier	'
        + 'Status	'
        + 'Aliases	'
        + 'Features	'
        + 'Mappers	'
        + 'Reducers	'
        + '

'
        + '
')
        .appendTo(this.container.empty())
        .append(this.tbody = $('
'));
    },

    loadTable: function(jobs) {
      var tr = this.selectRows(jobs);
      this.removeRows(tr);
      this.createRows(tr);
      this.updateRows(tr);
    },

    updateTableRows: function(jobs, duration) {
      this.updateRows(this.selectRows(jobs), duration);
    },

    selectRows: function(jobs) {
      // select rows and bind to jobs data
      return d3.select(this.tbody.get(0)).selectAll('tr')
        .data(jobs, function(job) { return job.id; });
    },

    removeRows: function(tr) {
      // remove rows for missing jobs data
      tr.exit().remove();
    },

    createRows: function(tr) {
      // create rows for new jobs data
      tr = tr.enter().append('tr');
      tr.style('background-color', 'white');
      tr.append('td').attr('class', 'job-num')
        .text(function(job) { return 1 + (job.topologicalIndex || job.index); });
      tr.append('td').attr('class', 'job-id')
        .append('a').attr('class', 'job-url')
        .attr('target', '_blank')
        .attr('href', 'javascript:void(0);');
      tr.append('td').attr('class', 'job-status')
      tr.append('td').attr('class', 'job-aliases')
      tr.append('td').attr('class', 'job-features')
      tr.append('td').attr('class', 'job-mappers')
      tr.append('td').attr('class', 'job-reducers');
      var self = this;
      tr.on('mouseover', function(job) { self.workflow.mouseOverJob(job); })
        .on('mouseout', function(job) { self.workflow.mouseOverJob(null); })
        .on('click', function(job) { self.workflow.selectJob(job); });
    },

    updateRows: function(tr, duration) {
      // update mutable row properties
      if (duration) tr = tr.transition().duration(duration);
      tr.style('background-color', function(job) {
          if (job.mouseover) return d3.rgb(98, 98, 196).brighter();
          if (job.selected) return d3.rgb(98, 98, 196);
          if (job.status == 'RUNNING') return d3.rgb(98, 196, 98).brighter();
          if (job.status == 'COMPLETE') return d3.rgb(98, 196, 98);
          if (job.status == 'FAILED') return d3.rgb(196, 98, 98);
          return 'white';
        });
      tr.selectAll('a.job-url')
        .attr('href', function(job) { return job.trackingUrl || 'javascript:void(0);'; })
        .text(function(job) { return job.id; });
      tr.selectAll('td.job-status')
        .text(function (job) { Ambrose.nullToEmpty(job.status); });
      tr.selectAll('td.job-aliases')
        .text(function (job) { Ambrose.commaDelimit(job.aliases); });
      tr.selectAll('td.job-features')
        .text(function (job) { Ambrose.commaDelimit(job.features); });
      tr.selectAll('td.job-mappers')
        .text(function (job) { Ambrose.taskProgressMessage(job.totalMappers, job.mapProgress); });
      tr.selectAll('td.job-reducers')
        .text(function (job) { Ambrose.taskProgressMessage(job.totalReducers, job.reduceProgress); });
    },
  };

  // bind prototype to ctor
  Table.fn.init.prototype = Table.fn;
  return Table;
});
<|endoftext|>


<commit_before>var http = require('http');

var server = http.createServer(function (request, response) {
	response.writeHead(200, { "Content-Type": "text/plain" });
	response.end("Hello World\n");
});

server.listen(8000);
console.log("Server running at http://localhost:8000/");<commit_msg>Pull port from environment<commit_after>var http = require('http');

var server = http.createServer(function (request, response) {
	response.writeHead(200, { "Content-Type": "text/plain" });
	response.end("Hello World\n");
});

var port = process.env.port || 8080;
server.listen(port);
console.log("Server running at http://localhost:" + port);<|endoftext|>


<commit_before>/*
 * Tangram
 * Copyright 2009 Baidu Inc. All rights reserved.
 */

///import baidu.fn;

/**
 * 包装函数的返回值，使其在能按照index指定的方式返回。
如果其值为-1，直接返回返回值。
如果其值为0，返回"返回值"的包装结果。
 如果其值大于0，返回第i个位置的参数的包装结果（从1开始计数）
 * @author berg
 * @name baidu.fn.wrapReturnValue
 * @function
 * @grammar baidu.fn.wrapReturnValue(func, wrapper, mode)
 * @param {function} func    需要包装的函数
 * @param {function} wrapper 包装器
 * @param {number} 包装第几个参数
 * @version 1.3.5
 * @return {function} 包装后的函数
 */
baidu.fn.wrapReturnValue = function (func, wrapper, mode) {
    mode = mode | 0;
    return function(){
        var ret = func.apply(this, arguments);

        if(mode > 0){
            return new wrapper(arguments[mode - 1]);
        }
        if(!mode){
            return new wrapper(ret);
        }
        return ret;
    }
};
<commit_msg>修改wrapReturnValue的逻辑顺序 [Change] 按照输入习惯将mode为0的排在前面提前处理以提高性能 baidu.fn.wrapReturnValue : 将判断mode为0的值提前<commit_after>/*
 * Tangram
 * Copyright 2009 Baidu Inc. All rights reserved.
 */

///import baidu.fn;

/**
 * 包装函数的返回值，使其在能按照index指定的方式返回。
如果其值为-1，直接返回返回值。
如果其值为0，返回"返回值"的包装结果。
 如果其值大于0，返回第i个位置的参数的包装结果（从1开始计数）
 * @author berg
 * @name baidu.fn.wrapReturnValue
 * @function
 * @grammar baidu.fn.wrapReturnValue(func, wrapper, mode)
 * @param {function} func    需要包装的函数
 * @param {function} wrapper 包装器
 * @param {number} mode 包装第几个参数
 * @version 1.3.5
 * @return {function} 包装后的函数
 */
baidu.fn.wrapReturnValue = function (func, wrapper, mode) {
    mode = mode | 0;
    return function(){
        var ret = func.apply(this, arguments);
        if(!mode){
            return new wrapper(ret);
        }
        if(mode > 0){
            return new wrapper(arguments[mode - 1]);
        }
        return ret;
    }
};
<|endoftext|>


<commit_before>var _ = require('underscore');
require('./test/environment');
var Context = require('./src/template/template_context');
var compiler = require('./precompile/tungsten_template/inline');
var Timer = require('./src/debug/timer');

// Using simplified lookup functions
Context.setAdapterFunctions({
  initialize: function(view, parentContext) {
    if (view == null) {
      view = {};
    }
    this.parent = parentContext;
  },
  lookupValue: function(view, name) {
    var value = null;
    if (view && view[name] != null) {
      value = view[name];
    }

    if (typeof value === 'function') {
      value = value.call(view);
    }
    return value;
  }
});

function getTemplate(templateStr, partials) {
  return compiler(templateStr || '', partials || {});
}

// Sample template with most Mustache features
// Section - Array
// Partial
// Static attribute
// Dynamic attribute
// Escaped text
// Unescaped text with HTML
var template = getTemplate('<select>\r\n{{#options}}  {{> option}}{{/option}}</select>', {
  option: '<option value="{{index}}" {{#even}}class="even"{{/even}} {{^even}}class="odd "{{/even}}>{{text}} {{nothing}} {{{raw_html}}} {{{raw_text}}}</option>\r\n'
});
var data = {
  raw_html: 'test &',
  raw_text: 'test',
  nothing: undefined,
  options: _.map(new Array(1000), function(v, i) {
    return {
      index: i,
      text: '"' + i + '"',
      even: i % 2 === 0
    };
  })
};

// Average render time over ten runs
// Using timer to grab any other timer data that is set
var t = new Timer('perf_run');
for (var i = 0; i < 10; i++) {
  template.toVdom(data);
  t.log('rendered');
}<commit_msg>Correcting template error<commit_after>var _ = require('underscore');
require('./test/environment');
var Context = require('./src/template/template_context');
var compiler = require('./precompile/tungsten_template/inline');
var Timer = require('./src/debug/timer');

// Using simplified lookup functions
Context.setAdapterFunctions({
  initialize: function(view, parentContext) {
    if (view == null) {
      view = {};
    }
    this.parent = parentContext;
  },
  lookupValue: function(view, name) {
    var value = null;
    if (view && view[name] != null) {
      value = view[name];
    }

    if (typeof value === 'function') {
      value = value.call(view);
    }
    return value;
  }
});

function getTemplate(templateStr, partials) {
  return compiler(templateStr || '', partials || {});
}

// Sample template with most Mustache features
// Section - Array
// Partial
// Static attribute
// Dynamic attribute
// Escaped text
// Unescaped text with HTML
var template = getTemplate('<select>\r\n{{#options}}  {{> option}}{{/options}}</select>', {
  option: '<option value="{{index}}" {{#even}}class="even"{{/even}} {{^even}}class="odd "{{/even}}>{{text}} {{nothing}} {{{raw_html}}} {{{raw_text}}}</option>\r\n'
});
var data = {
  raw_html: 'test &',
  raw_text: 'test',
  nothing: undefined,
  options: _.map(new Array(1000), function(v, i) {
    return {
      index: i,
      text: '"' + i + '"',
      even: i % 2 === 0
    };
  })
};

// Average render time over ten runs
// Using timer to grab any other timer data that is set
var t = new Timer('perf_run');
for (var i = 0; i < 10; i++) {
  template.toVdom(data);
  t.log('rendered');
}
<|endoftext|>


<commit_before>import './style/UserMiniCard.scss';

import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';

import userPlaceholder from '../assets/userPlaceholder.png';

export default class UserMiniCard extends Component {
  render() {
    const { user, hideUsername, hideName } = this.props;
    // Why are we using div tag instead of span?
    // Double clicking selects everything including near span tags.
    // display: inline-block doesn't.
    return (

        <Link to={`/${user.username}`}>

          { !hideName ? (

              {user.name}

          ) : false }
          { !hideUsername ? (

              {user.username}

          ) : false }
        </Link>

    );
  }
}

UserMiniCard.propTypes = {
  user: PropTypes.object.isRequired,
  hideUsername: PropTypes.bool,
  hideName: PropTypes.bool
};
<commit_msg>Change to display username if there is no name<commit_after>import './style/UserMiniCard.scss';

import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';

import userPlaceholder from '../assets/userPlaceholder.png';

export default class UserMiniCard extends Component {
  render() {
    const { user, hideUsername, hideName } = this.props;
    // Why are we using div tag instead of span?
    // Double clicking selects everything including near span tags.
    // display: inline-block doesn't.
    return (

        <Link to={`/${user.username}`}>

          { !hideName ? (

              {user.name || user.username}

          ) : false }
          { !hideUsername ? (

              {user.username}

          ) : false }
        </Link>

    );
  }
}

UserMiniCard.propTypes = {
  user: PropTypes.object.isRequired,
  hideUsername: PropTypes.bool,
  hideName: PropTypes.bool
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
var SyncApi     = require('sync_backend');
var mongoose = require('mongoose');
var winston  = require('winston');
var opts     = require('commander');
var express  = require('express');
var bodyParser = require('body-parser');
var app = express();

// ALWAYS use this logger instead of console.log
// so everything is logged out to file for debugging purposes
var logger   = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
        level:'debug',
        timestamp:true,
        colorize:true
    }),
    new (winston.transports.File)({
        name:"trace.log",
        filename:'../logs/trace.log',
        level:'debug',
        json:false,
        timestamp:true,
        prettyPrint:true,
        tailable:true
    }),
    new (winston.transports.File)({
        name:"error.log",
        filename:'../logs/error.log',
        level:'warn',
        json:false,
        timestamp:true,
        prettyPrint:true,
        tailable:true
    })
  ]
});
// set all command line options for help and parsing purposes
opts.version('0.1.0')
    .option('-p','--port', 'Rest endpoint port')
    .parse(process.argv);
if(!opts.socketioPort) opts.socketioPort = 9000

// magic happens from here on
app.use(express.static(__dirname + '/public_html'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

var sync = new SyncApi({
  logger: logger,
  express: app,
  ns: '/sync', // html namespace of the sync api,
  get: function(id) {
    // db get
  },
  create: function(model) { // doesn't have  $id field
    // db create
    // must return object with $id populated
    // if not populated assumed to have failed
    return model;
  },
  update: function(model) {
    // better have a $id field or you're having a bad day
    // db update
    // return falsy for failure
    return undefined;
  },
  del: function(id) {
    // db delete
    return false;
  }
});

app.listen(3000, function() {
    logger.info('express server started');
});
<commit_msg>updated to using callbacks on rest sync client<commit_after>#!/usr/bin/env node
var SyncApi     = require('sync_backend');
var mongoose = require('mongoose');
var winston  = require('winston');
var opts     = require('commander');
var express  = require('express');
var bodyParser = require('body-parser');
var app = express();

// ALWAYS use this logger instead of console.log
// so everything is logged out to file for debugging purposes
var logger   = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
        level:'debug',
        timestamp:true,
        colorize:true
    }),
    new (winston.transports.File)({
        name:"trace.log",
        filename:'../logs/trace.log',
        level:'debug',
        json:false,
        timestamp:true,
        prettyPrint:true,
        tailable:true
    }),
    new (winston.transports.File)({
        name:"error.log",
        filename:'../logs/error.log',
        level:'warn',
        json:false,
        timestamp:true,
        prettyPrint:true,
        tailable:true
    })
  ]
});
// set all command line options for help and parsing purposes
opts.version('0.1.0')
    .option('-p','--port', 'Rest endpoint port')
    .parse(process.argv);
if(!opts.socketioPort) opts.socketioPort = 9000

// magic happens from here on
app.use(express.static(__dirname + '/public_html'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

var sync = new SyncApi({
  logger: logger,
  express: app,
  ns: '/sync', // html namespace of the sync api,
  get: function(id, cb) {
    // db get
    return model;
  },
  create: function(model, cb) { // doesn't have  $id field
    // db create
    // must return object with $id populated
    // if not populated assumed to have failed
    return model;
  },
  update: function(model, cb) {
    // better have a $id field or you're having a bad day
    // db update
    // return falsy for failure
    return undefined;
  },
  del: function(id, cb) {
    // db delete
    return false;
  }
});

app.listen(3000, function() {
    logger.info('express server started');
});
<|endoftext|>


<commit_before>import {commitMutation, graphql} from 'react-relay';

const mutation = graphql`
  mutation addReactionMutation($input: AddReactionInput!) {
    addReaction(input: $input) {
      subject {
        reactionGroups {
          content
          users {
            totalCount
          }
        }
      }
    }
  }
`;

export default (environment, subjectId, content) => {
  const variables = {
    input: {
      content,
      subjectId,
    },
  };

  function optimisticUpdater(store) {
    const subject = store.get(subjectId);
    const reactionGroups = subject.getLinkedRecords('reactionGroups') || [];
    const reactionGroup = reactionGroups.find(group => group.getValue('content') === content);
    if (!reactionGroup) {
      return;
    }

    reactionGroup.setValue(true, 'viewerHasReacted');
    const conn = reactionGroup.getLinkedRecord('users');
    conn.setValue(conn.getValue('totalCount') + 1, 'totalCount');
  }

  return new Promise((resolve, reject) => {
    commitMutation(
      environment,
      {
        mutation,
        variables,
        optimisticUpdater,
        onCompleted: resolve,
        onError: reject,
      },
    );
  });
};
<commit_msg>Optimistic updater works when the reaction group is not already present<commit_after>import {commitMutation, graphql} from 'react-relay';

const mutation = graphql`
  mutation addReactionMutation($input: AddReactionInput!) {
    addReaction(input: $input) {
      subject {
        reactionGroups {
          content
          users {
            totalCount
          }
        }
      }
    }
  }
`;

let placeholderID = 0;

export default (environment, subjectId, content) => {
  const variables = {
    input: {
      content,
      subjectId,
    },
  };

  function optimisticUpdater(store) {
    const subject = store.get(subjectId);
    const reactionGroups = subject.getLinkedRecords('reactionGroups') || [];
    const reactionGroup = reactionGroups.find(group => group.getValue('content') === content);
    if (!reactionGroup) {
      const group = store.create(`add-reaction:reaction-group:${placeholderID++}`, 'ReactionGroup');
      group.setValue(true, 'viewerHasReacted');
      group.setValue(content, 'content');

      const conn = store.create(`add-reaction:reacting-user-conn:${placeholderID++}`, 'ReactingUserConnection');
      conn.setValue(1, 'totalCount');
      group.setLinkedRecord(conn, 'users');

      subject.setLinkedRecords([...reactionGroups, group], 'reactionGroups');

      return;
    }

    reactionGroup.setValue(true, 'viewerHasReacted');
    const conn = reactionGroup.getLinkedRecord('users');
    conn.setValue(conn.getValue('totalCount') + 1, 'totalCount');
  }

  return new Promise((resolve, reject) => {
    commitMutation(
      environment,
      {
        mutation,
        variables,
        optimisticUpdater,
        onCompleted: resolve,
        onError: reject,
      },
    );
  });
};
<|endoftext|>


<commit_before>import {isArray, isFunction, isObject} from 'lodash/lang';
import {capitalize} from 'lodash/string'
import {keys} from 'lodash/object';
import React, {Component} from 'react';

export default function connectToStores(storesConfiguration, getState) {
    // Validate the stores object
    if(!isArray(storesConfiguration)) {
        throw new Error('connectToStores: you need to provide an array of store config.');
    }

    // Validate .
    if(!isFunction(getState)) {
        throw new Error('connectToStores: you need to provide function to read state from store.');
    }
    // Return a wrapper function around the component
    return function connectComponent(DecoratedComponent) {

        // Save the display name for later
        const displayName = DecoratedComponent.displayName || 'Component';

        // The goal of this class is to connect a component to a list of stores with properties.
        class StoreConnector extends Component {

            constructor(props) {
                super(props);
                //Build the initial state from props.
                this.state = getState(props);
            }

            // When the component will mount, we listen to all stores changes.
            // When a change occurs the state is read again from the state.
            componentWillMount() {
                storesConfiguration.forEach(storeConf => {
                    const {properties, store} = storeConf;
                    properties.forEach((property) => {
                        if(!store || !store.definition || !store.definition[property]) {
                            console.warn(`
                                StoreConnector ${displayName}:
                                    You add a property : ${property} in your store configuration which is not in your definition : ${keys(store.definition)}
                            `);
                        }
                        const capitalizedProperty = capitalize(property);
                        storeConf.store[`add${capitalizedProperty}ChangeListener`](this.handleStoresChanged);
                        storeConf.store[`add${capitalizedProperty}ErrorListener`](this.handleStoresChanged);
                    });
                });
            }

            // When a component will receive a new props.
            componentWillReceiveProps(nextProps) {
                //if (!shallowEqual(nextProps, this.props)) {
                this.setState(getState(nextProps));
                //}
            }

            // Component unmount.
            componentWillUnmount() {
                storesConfiguration.forEach(storeConf => {
                    const {properties, store} = storeConf;
                    properties.forEach((property) => {
                        const capitalizedProperty = capitalize(property);
                        storeConf.store[`remove${capitalizedProperty}ChangeListener`](this.handleStoresChanged);
                        storeConf.store[`remove${capitalizedProperty}ErrorListener`](this.handleStoresChanged);
                    });
                });
            }

            //Handle the store changes
            handleStoresChanged = () => {
                this.setState(getState(this.props));
            }

            // Render the component with only props, some from the real props some from the state
            render() {
                const {props, state} = this;
                return (
                    <DecoratedComponent
                        {...props}
                        {...state}
                    />
                );
            }
        }
        StoreConnector.displayName = `${displayName}Connected`;
        return StoreConnector;
    };
}
<commit_msg>[connect] Add example.<commit_after>import {isArray, isFunction, isObject} from 'lodash/lang';
import {capitalize} from 'lodash/string'
import {keys} from 'lodash/object';
import React, {Component} from 'react';

// - Provide the component
// - Provide the store configuration `[{store: yourStore, properties: ['property1', 'property2']}]`
// - Provide a function to read state from your store
export default function connectToStores(storesConfiguration, getState) {
    // Validate the stores object
    if(!isArray(storesConfiguration)) {
        throw new Error('connectToStores: you need to provide an array of store config.');
    }

    // Validate .
    if(!isFunction(getState)) {
        throw new Error('connectToStores: you need to provide function to read state from store.');
    }
    // Return a wrapper function around the component
    return function connectComponent(DecoratedComponent) {

        // Save the display name for later
        const displayName = DecoratedComponent.displayName || 'Component';

        // The goal of this class is to connect a component to a list of stores with properties.
        class StoreConnector extends Component {

            constructor(props) {
                super(props);
                //Build the initial state from props.
                this.state = getState(props);
            }

            // When the component will mount, we listen to all stores changes.
            // When a change occurs the state is read again from the state.
            componentWillMount() {
                storesConfiguration.forEach(storeConf => {
                    const {properties, store} = storeConf;
                    properties.forEach((property) => {
                        if(!store || !store.definition || !store.definition[property]) {
                            console.warn(`
                                StoreConnector ${displayName}:
                                    You add a property : ${property} in your store configuration which is not in your definition : ${keys(store.definition)}
                            `);
                        }
                        const capitalizedProperty = capitalize(property);
                        storeConf.store[`add${capitalizedProperty}ChangeListener`](this.handleStoresChanged);
                        storeConf.store[`add${capitalizedProperty}ErrorListener`](this.handleStoresChanged);
                    });
                });
            }

            // When a component will receive a new props.
            componentWillReceiveProps(nextProps) {
                //if (!shallowEqual(nextProps, this.props)) {
                this.setState(getState(nextProps));
                //}
            }

            // Component unmount.
            componentWillUnmount() {
                storesConfiguration.forEach(storeConf => {
                    const {properties, store} = storeConf;
                    properties.forEach((property) => {
                        const capitalizedProperty = capitalize(property);
                        storeConf.store[`remove${capitalizedProperty}ChangeListener`](this.handleStoresChanged);
                        storeConf.store[`remove${capitalizedProperty}ErrorListener`](this.handleStoresChanged);
                    });
                });
            }

            //Handle the store changes
            handleStoresChanged = () => {
                this.setState(getState(this.props));
            }

            // Render the component with only props, some from the real props some from the state
            render() {
                const {props, state} = this;
                return (
                    <DecoratedComponent
                        {...props}
                        {...state}
                    />
                );
            }
        }
        StoreConnector.displayName = `${displayName}Connected`;
        return StoreConnector;
    };
}

// Add a function to connect a store to a component .
// All the store properties values will be provided to the component as props.
// This could be use as an ES7 annotation or as a function.

// ### ES6 version
// ```jsx
// store
// const newStore = new CoreStore({definition: {name: 'name', email: 'email'}});
//Component
// const Component = props => <div>{JSON.stringify(props)}</div>;
// create a connector function
// const connector = storeConnectBehaviour(
//     [{store: newStore, properties: ['name', 'email']}],
//     (props) => {return newStore.getValue()}
// );
// Component connected to the store
// const ConnectedComponent = connector(Component);
// ```

// ### ES7 version
// ```jsx
//    Class version
// @connect( [{store: newStore, properties: ['name', 'email']}],(props) => newStore.getValue())
// class YourComponent extends Component{
//     render(){
//          return  <div>{JSON.stringify(props)}</div>;
//     }
// }
// ```
<|endoftext|>


<commit_before>/**
 * modules/analytics data store: report tests.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import API from 'googlesitekit-api';
import { STORE_NAME } from './constants';
import {
	createTestRegistry,
	muteConsole,
	subscribeUntil,
	unsubscribeFromAll,
} from 'tests/js/utils';
import * as fixtures from './__fixtures__';

describe( 'modules/analytics report', () => {
	let registry;

	beforeAll( () => {
		API.setUsingCache( false );
	} );

	beforeEach( () => {
		registry = createTestRegistry();
	} );

	afterEach( () => {
		unsubscribeFromAll( registry );
	} );

	afterAll( () => {
		API.setUsingCache( true );
	} );

	describe( 'selectors', () => {
		describe( 'getReport', () => {
			const options = {
				dateRange: 'last-90-days',
				metrics: {
					expression: 'testExpression',
					alias: 'testAlias',
				},
			};

			it( 'uses a resolver to make a network request', async () => {
				fetchMock.getOnce(
					/^\/google-site-kit\/v1\/modules\/analytics\/data\/report/,
					{ body: fixtures.report, status: 200 }
				);

				const initialReport = registry.select( STORE_NAME ).getReport( options );

				expect( initialReport ).toEqual( undefined );
				await subscribeUntil( registry, () => (
					registry.select( STORE_NAME ).getReport( options ) !== undefined
				) );

				const report = registry.select( STORE_NAME ).getReport( options );

				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( report ).toEqual( fixtures.report );
			} );

			it( 'does not make a network request if report for given options is already present', async () => {
				// Load data into this store so there are matches for the data we're about to select,
				// even though the selector hasn't fulfilled yet.
				registry.dispatch( STORE_NAME ).receiveGetReport( fixtures.report, { options } );

				const report = registry.select( STORE_NAME ).getReport( options );

				await subscribeUntil( registry, () => registry
					.select( STORE_NAME )
					.hasFinishedResolution( 'getReport', [ options ] )
				);

				expect( fetchMock ).not.toHaveFetched();
				expect( report ).toEqual( fixtures.report );
			} );

			it( 'dispatches an error if the request fails', async () => {
				const response = {
					code: 'internal_server_error',
					message: 'Internal server error',
					data: { status: 500 },
				};

				fetchMock.getOnce(
					/^\/google-site-kit\/v1\/modules\/analytics\/data\/report/,
					{ body: response, status: 500 }
				);

				muteConsole( 'error' );
				registry.select( STORE_NAME ).getReport( options );
				await subscribeUntil(
					registry,
					() => registry.select( STORE_NAME ).isFetchingGetReport( options ) === false,
				);

				expect( fetchMock ).toHaveFetchedTimes( 1 );

				const report = registry.select( STORE_NAME ).getReport( options );
				expect( report ).toEqual( undefined );
			} );
		} );
	} );
} );
<commit_msg>Add test for new adsenseLinked behavior in getReport resolver.<commit_after>/**
 * modules/analytics data store: report tests.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import API from 'googlesitekit-api';
import { STORE_NAME } from './constants';
import {
	createTestRegistry,
	muteConsole,
	subscribeUntil,
	untilResolved,
	unsubscribeFromAll,
} from 'tests/js/utils';
import * as fixtures from './__fixtures__';

describe( 'modules/analytics report', () => {
	let registry;

	beforeAll( () => {
		API.setUsingCache( false );
	} );

	beforeEach( () => {
		registry = createTestRegistry();
	} );

	afterEach( () => {
		unsubscribeFromAll( registry );
	} );

	afterAll( () => {
		API.setUsingCache( true );
	} );

	describe( 'selectors', () => {
		describe( 'getReport', () => {
			const options = {
				dateRange: 'last-90-days',
				metrics: {
					expression: 'testExpression',
					alias: 'testAlias',
				},
			};

			it( 'uses a resolver to make a network request', async () => {
				fetchMock.getOnce(
					/^\/google-site-kit\/v1\/modules\/analytics\/data\/report/,
					{ body: fixtures.report, status: 200 }
				);

				const initialReport = registry.select( STORE_NAME ).getReport( options );

				expect( initialReport ).toEqual( undefined );
				await subscribeUntil( registry, () => (
					registry.select( STORE_NAME ).getReport( options ) !== undefined
				) );

				const report = registry.select( STORE_NAME ).getReport( options );

				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( report ).toEqual( fixtures.report );
			} );

			it( 'sets adsenseLinked to false if a 400 error is returned due to restricted metrics', async () => {
				const restrictedMetricsError = {
					code: 400,
					message: 'Restricted metric(s): ga:adsenseRevenue can only be queried under certain conditions.',
				};
				fetchMock.getOnce(
					/^\/google-site-kit\/v1\/modules\/analytics\/data\/report/,
					{ body: restrictedMetricsError, status: 400 }
				);

				registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
				registry.dispatch( STORE_NAME ).setAdsenseLinked( true );
				expect( registry.select( STORE_NAME ).getAdsenseLinked() ).toBe( true );

				muteConsole( 'error' ); // fetch will trigger 400 error.
				registry.select( STORE_NAME ).getReport( options );
				expect( fetchMock ).toHaveFetchedTimes( 1 );

				await untilResolved( registry, STORE_NAME ).getReport( options );

				expect( registry.select( STORE_NAME ).getAdsenseLinked() ).toBe( false );
			} );

			it( 'does not make a network request if report for given options is already present', async () => {
				// Load data into this store so there are matches for the data we're about to select,
				// even though the selector hasn't fulfilled yet.
				registry.dispatch( STORE_NAME ).receiveGetReport( fixtures.report, { options } );

				const report = registry.select( STORE_NAME ).getReport( options );

				await subscribeUntil( registry, () => registry
					.select( STORE_NAME )
					.hasFinishedResolution( 'getReport', [ options ] )
				);

				expect( fetchMock ).not.toHaveFetched();
				expect( report ).toEqual( fixtures.report );
			} );

			it( 'dispatches an error if the request fails', async () => {
				const response = {
					code: 'internal_server_error',
					message: 'Internal server error',
					data: { status: 500 },
				};

				fetchMock.getOnce(
					/^\/google-site-kit\/v1\/modules\/analytics\/data\/report/,
					{ body: response, status: 500 }
				);

				muteConsole( 'error' );
				registry.select( STORE_NAME ).getReport( options );
				await subscribeUntil(
					registry,
					() => registry.select( STORE_NAME ).isFetchingGetReport( options ) === false,
				);

				expect( fetchMock ).toHaveFetchedTimes( 1 );

				const report = registry.select( STORE_NAME ).getReport( options );
				expect( report ).toEqual( undefined );
			} );
		} );
	} );
} );
<|endoftext|>


<commit_before>'use strict';

var Page = require('bigpipe').Page
  , Contour = require('../../../')
  , contour = new Contour({
      brand: 'nodejitsu'
    });

Page.extend({
  path: '/',              // HTTP route we should respond to.
  view: './index.hbs',    // The base template we need to render.
  pagelets: {             // The pagelets that should be rendered.
    navigation: contour.navigation.extend({
      base: '',
      login: false,
      signup: true,       // Shows signup button, and relies on recursive pagelets
      navigation: [
        { name: 'Cloud', href: '/paas/' },
        { name: 'Company', href: '/company/' }
      ]
    }),
    footer: contour.footer
  }
}).on(module);
<commit_msg>[fix] extend data in example<commit_after>'use strict';

var Page = require('bigpipe').Page
  , Contour = require('../../../')
  , contour = new Contour({
      brand: 'nodejitsu'
    });

Page.extend({
  path: '/',              // HTTP route we should respond to.
  view: './index.hbs',    // The base template we need to render.
  pagelets: {             // The pagelets that should be rendered.
    navigation: contour.navigation.extend({
      data: {
        base: '',
        login: false,
        signup: true,       // Shows signup button, and relies on recursive pagelets
        navigation: [
          { name: 'Cloud', href: '/paas/' },
          { name: 'Company', href: '/company/' }
        ]
      }
    }),
    footer: contour.footer
  }
}).on(module);
<|endoftext|>


<commit_before>const { Form, Input, Icon, Switch, Select, Divider } = antd;

const ceaParameter = (param, getFieldDecorator) => {
  const { name, type, value, help } = param;

  const openDialog = () => {
    console.log('open dialog')
  };

  let input = [];

  if (["IntegerParameter", "RealParameter"].includes(type)) {
    const stringValue = value !== null ? value.toString() : "";
    const regex =
      type === "IntegerParameter"
        ? /^(?:[1-9][0-9]*|0)$/
        : /^(?:[1-9][0-9]*|0)(\.\d+)?$/;
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: stringValue,
          rules: [
            {
              type: "number",
              message: `Please enter an ${
                type === "IntegerParameter" ? "integer" : "float"
              }`,
              transform: num => {
                if (num === "") return 0;
                return regex.test(num) ? Number(num) : NaN;
              }
            }
          ]
        })(<Input />)}
      </React.Fragment>
    );
  } else if (["PathParameter", "FileParameter"].includes(type)) {
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(
          <Input
            addonAfter={
              <button
                className={type}
                type="button"
                style={{ height: "30px", width: "50px" }}
                onClick={openDialog}
              >
                <Icon type="ellipsis" />
              </button>
            }
          />
        )}
      </React.Fragment>
    );
  } else if (
    [
      "ChoiceParameter",
      "PlantNodeParameter",
      "ScenarioNameParameter",
      "SingleBuildingParameter"
    ].includes(type)
  ) {
    const { choices } = param;
    const { Option } = Select;
    const Options = choices.map(choice => (
      <Option key={choice} value={choice}>
        {choice}
      </Option>
    ));
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(<Select>{Options}</Select>)}
      </React.Fragment>
    );
  } else if (["MultiChoiceParameter", "BuildingsParameter"].includes(type)) {
    const { choices } = param;
    const { Option } = Select;
    const Options = choices.map(choice => (
      <Option key={choice} value={choice}>
        {choice}
      </Option>
    ));
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(
          <Select
            mode="multiple"
            style={{ width: "100%" }}
            placeholder="Nothing Selected"
            showArrow
          >
            {Options}
          </Select>
        )}
      </React.Fragment>
    );
  } else if (type === "WeatherPathParameter") {
    const { choices } = param;
    const { Option } = Select;
    const Options = Object.keys(choices).map(choice => (
      <Option key={choice} value={choices[choice]}>
        {choice}
      </Option>
    ));
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(
          <Select
            dropdownRender={menu => (

                {menu}
                <Divider style={{ margin: "4px 0" }} />

                  <Icon type="plus" /> Browse for weather file

            )}
          >
            {Options}
          </Select>
        )}
      </React.Fragment>
    );
  } else if (type === "BooleanParameter") {
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(<Switch defaultChecked={value} />)}
      </React.Fragment>
    );
  } else {
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(<Input />)}
      </React.Fragment>
    );
  }

  return (
    <Form.Item
      label={name}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 11, offset: 1 }}
      key={name}
    >
      {input}

      {help}
    </Form.Item>
  );
};
<commit_msg>Only show up to 10 selections in multi select in case of a huge list<commit_after>const { Form, Input, Icon, Switch, Select, Divider } = antd;

const ceaParameter = (param, getFieldDecorator) => {
  const { name, type, value, help } = param;

  const openDialog = () => {
    console.log('open dialog')
  };

  let input = [];

  if (["IntegerParameter", "RealParameter"].includes(type)) {
    const stringValue = value !== null ? value.toString() : "";
    const regex =
      type === "IntegerParameter"
        ? /^(?:[1-9][0-9]*|0)$/
        : /^(?:[1-9][0-9]*|0)(\.\d+)?$/;
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: stringValue,
          rules: [
            {
              type: "number",
              message: `Please enter an ${
                type === "IntegerParameter" ? "integer" : "float"
              }`,
              transform: num => {
                if (num === "") return 0;
                return regex.test(num) ? Number(num) : NaN;
              }
            }
          ]
        })(<Input />)}
      </React.Fragment>
    );
  } else if (["PathParameter", "FileParameter"].includes(type)) {
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(
          <Input
            addonAfter={
              <button
                className={type}
                type="button"
                style={{ height: "30px", width: "50px" }}
                onClick={openDialog}
              >
                <Icon type="ellipsis" />
              </button>
            }
          />
        )}
      </React.Fragment>
    );
  } else if (
    [
      "ChoiceParameter",
      "PlantNodeParameter",
      "ScenarioNameParameter",
      "SingleBuildingParameter"
    ].includes(type)
  ) {
    const { choices } = param;
    const { Option } = Select;
    const Options = choices.map(choice => (
      <Option key={choice} value={choice}>
        {choice}
      </Option>
    ));
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(<Select>{Options}</Select>)}
      </React.Fragment>
    );
  } else if (["MultiChoiceParameter", "BuildingsParameter"].includes(type)) {
    const { choices } = param;
    const { Option } = Select;
    const Options = choices.map(choice => (
      <Option key={choice} value={choice}>
        {choice}
      </Option>
    ));
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(
          <Select
            mode="multiple"
            style={{ width: "100%" }}
            placeholder="Nothing Selected"
            showArrow
            maxTagCount={10}
          >
            {Options}
          </Select>
        )}
      </React.Fragment>
    );
  } else if (type === "WeatherPathParameter") {
    const { choices } = param;
    const { Option } = Select;
    const Options = Object.keys(choices).map(choice => (
      <Option key={choice} value={choices[choice]}>
        {choice}
      </Option>
    ));
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(
          <Select
            dropdownRender={menu => (

                {menu}
                <Divider style={{ margin: "4px 0" }} />

                  <Icon type="plus" /> Browse for weather file

            )}
          >
            {Options}
          </Select>
        )}
      </React.Fragment>
    );
  } else if (type === "BooleanParameter") {
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(<Switch defaultChecked={value} />)}
      </React.Fragment>
    );
  } else {
    input = (
      <React.Fragment>
        {getFieldDecorator(name, {
          initialValue: value
        })(<Input />)}
      </React.Fragment>
    );
  }

  return (
    <Form.Item
      label={name}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 11, offset: 1 }}
      key={name}
    >
      {input}

      {help}
    </Form.Item>
  );
};
<|endoftext|>