<commit_before>import React, { Component, PropTypes } from 'react';
import firebase from 'firebase';
import ReactFireMixin from 'reactfire';

import styles from './styles.scss';

const SaveAndSubmitCard = React.createClass({
  mixins: [ReactFireMixin],
  getInitialState: function(){
    return {
      data: [],
      isSubmitted: false,
    };
  },

  componentWillMount: function() {
    this.bindAsArray(firebase.database().ref('userResults'), 'budgetData');
  },

  handleSubmit: function(e) {
    e.preventDefault();
    const name = this.refs.name.value.trim();
    const email = this.refs.email.value.trim();
    const budgetArray = this.summarizeUserBudget(this.props.data);
    this.onSubmit({ name, email, budgetArray });
    this.refs.name.value = '';
    this.refs.email.value = '';
    this.setState({ isSubmitted: true });
  },

  summarizeUserBudget: function(data) {
    let budgetArray = [];
    const totalBudget = { item: 'Total Budget', amount: this.props.data.servicesSum };

    data.departments.map(function(dept){
      const deptObj = { item: dept.name, amount: dept.amount };
      budgetArray.push(deptObj);
    });

    budgetArray.push(totalBudget);

    return budgetArray;
  },

  onSubmit: function(result) {
    this.firebaseRefs['budgetData'].push(result);
  },

  componentWillUnmount: function() {
    // I was getting a console error when I was unbinding this. So now I'm not.
    // this.unbind('budgetData');
  },

  render: function() {
    let isSubmitted = this.state.isSubmitted;
    return (

          {
            isSubmitted &&

Thanks!

          }
          {
            !isSubmitted &&

Save & Submit

Your Budget

          }

        <div className={`${styles.cardBody} ${isSubmitted ? 'hidden' : ''}`}>

Submit your budget

          Name
          <input
            ref="name"
            type="text"
            placeholder="Name"
            name="name"
            className={styles.formInput}
          />

          Email
          <input type="text" placeholder="Email" name="email" ref="email" className={styles.formInput} />
          <div
            className={`${styles.buttonWhiteOutline} btn btn-lg btn-success`}
            onClick={this.handleSubmit}
          >
            Submit

    );
  },
});

export default SaveAndSubmitCard;
<commit_msg>extract totalBudget from budgetArray for easier access<commit_after>import React, { Component, PropTypes } from 'react';
import firebase from 'firebase';
import ReactFireMixin from 'reactfire';

import styles from './styles.scss';

const SaveAndSubmitCard = React.createClass({
  mixins: [ReactFireMixin],
  getInitialState: function(){
    return {
      data: [],
      isSubmitted: false,
    };
  },

  componentWillMount: function() {
    this.bindAsArray(firebase.database().ref('userResults'), 'budgetData');
  },

  handleSubmit: function(e) {
    e.preventDefault();
    const name = this.refs.name.value.trim();
    const email = this.refs.email.value.trim();
    const budgetArray = this.summarizeUserBudget(this.props.data);
    const totalBudget = this.props.data.servicesSum;
    this.onSubmit({ name, email, budgetArray, totalBudget });
    this.refs.name.value = '';
    this.refs.email.value = '';
    this.setState({ isSubmitted: true });
  },

  summarizeUserBudget: function(data) {
    let budgetArray = [];

    data.departments.map(function(dept){
      const deptObj = { item: dept.name, amount: dept.amount };
      budgetArray.push(deptObj);
    });

    return budgetArray;
  },

  onSubmit: function(result) {
    this.firebaseRefs['budgetData'].push(result);
  },

  componentWillUnmount: function() {
    // I was getting a console error when I was unbinding this. So now I'm not.
    // this.unbind('budgetData');
  },

  render: function() {
    let isSubmitted = this.state.isSubmitted;
    return (

          {
            isSubmitted &&

Thanks!

          }
          {
            !isSubmitted &&

Save & Submit

Your Budget

          }

        <div className={`${styles.cardBody} ${isSubmitted ? 'hidden' : ''}`}>

Submit your budget

          Name
          <input
            ref="name"
            type="text"
            placeholder="Name"
            name="name"
            className={styles.formInput}
          />

          Email
          <input type="text" placeholder="Email" name="email" ref="email" className={styles.formInput} />
          <div
            className={`${styles.buttonWhiteOutline} btn btn-lg btn-success`}
            onClick={this.handleSubmit}
          >
            Submit

    );
  },
});

export default SaveAndSubmitCard;
<|endoftext|>


<commit_before>'use strict';
var React = require('react');
var url = require('url');
var globals = require('./globals');
var parseAndLogError = require('./mixins').parseAndLogError;
var StickyHeader = require('./StickyHeader');

var lookup_column = function (result, column) {
    var value = result;
    var names = column.split('.');
    for (var i = 0, len = names.length; i < len && value !== undefined; i++) {
        value = value[names[i]];
    }
    return value;
};

    var Collection = module.exports.Collection = React.createClass({
        render: function () {
            var context = this.props.context;
            return (

{context.title}

{context.description}

            );
        }
    });

    globals.content_views.register(Collection, 'Collection');

    class Cell {
        constructor(value, sortable) {
            this.value = value;
            this.sortable = sortable;
        }
    }

    class Row {
        constructor(item, cells, text) {
            this.item = item;
            this.cells = cells;
            this.text = text;
        }
    }

    class Data {
        constructor(rows) {
            this.rows = rows;
            this.sortedOn = null;
            this.reversed = false;
        }
        sort(sortColumn, reverse) {
            reverse = !!reverse;
            if (this.sortedOn === sortColumn && this.reversed === reverse) return;
            this.sortedOn = sortColumn;
            this.reversed = reverse;
            this.rows.sort(function (rowA, rowB) {
                var a = '' + rowA.cells[sortColumn].sortable;
                var b = '' + rowB.cells[sortColumn].sortable;
                if (a  b) {
                    return reverse ? -1 : 1;
                }
                return 0;
            });
        }
    }

    var RowView = function (props) {
        var row = props.row;
        var id = row.item['@id'];
        var tds = row.cells.map( function (cell, index) {
            if (index === 0) {
                return (
                    {cell.value}
                );
            }
            return (
                {cell.value}
            );
        });
        return (

{tds}

        );
    };

    var Table = module.exports.Table = React.createClass({
        contextTypes: {
            fetch: React.PropTypes.func,
            location_href: React.PropTypes.string
        },

        getDefaultProps: function () {
            return {
                defaultSortOn: 0,
                showControls: true,
            };
        },

        getInitialState: function () {
            var state = this.extractParams(this.props, this.context);
            state.columns = this.guessColumns(this.props);
            state.data = new Data([]);  // Tables may be long so render empty first
            state.communicating = true;
            return state;
        },

        componentWillReceiveProps: function (nextProps, nextContext) {
            var updateData = false;
            if (nextProps.context !== this.props.context) {
                updateData = true;
                this.setState({
                    communicating: this.fetchAll(nextProps)
                });
            }
            if (nextProps.columns !== this.props.columns) {
                updateData = true;
            }
            if (updateData) {
                var columns = this.guessColumns(nextProps);
                this.extractData(nextProps, columns);
            }
            if (nextContext.location_href !== this.context.location_href) {
                this.extractParams(nextProps, nextContext);
            }

        },

        extractParams: function(props, context) {
            var params = url.parse(context.location_href, true).query;
            var sorton = parseInt(params.sorton, 10);
            if (isNaN(sorton)) {
                sorton = props.defaultSortOn;
            }
            var state = {
                sortOn: sorton,
                reversed: params.reversed || false,
                searchTerm: params.q || ''
            };
            this.setState(state);
            return state;
        },

        guessColumns: function (props) {
            var column_list = props.columns || props.context.columns;
            var columns = [];
            if (!column_list || Object.keys(column_list).length === 0) {
                for (var key in props.context['@graph'][0]) {
                    if (key.slice(0, 1) != '@' && key.search(/(uuid|_no|accession)/) == -1) {
                        columns.push(key);
                    }
                }
                columns.sort();
                columns.unshift('@id');
            } else {
                for(var column in column_list) {
                    columns.push(column);
                }
            }
            this.setState({columns: columns});
            return columns;
        },

        extractData: function (props, columns) {
            var context = props.context;
            columns = columns || this.state.columns;
            var rows = context['@graph'].map(function (item) {
                var cells = columns.map(function (column) {
                    var factory;
                    // cell factories
                    //if (factory) {
                    //    return factory({context: item, column: column});
                    //}
                    var value = lookup_column(item, column);
                    if (column == '@id') {
                        factory = globals.listing_titles.lookup(item);
                        value = factory({context: item});
                    } else if (value == null) {
                        value = '';
                    } else if (value instanceof Array) {
                        value = value;
                    } else if (value['@type']) {
                        factory = globals.listing_titles.lookup(value);
                        value = factory({context: value});
                    }
                    var sortable = ('' + value).toLowerCase();
                    return new Cell(value, sortable);
                });
                var text = cells.map(function (cell) {
                    return cell.value;
                }).join(' ').toLowerCase();
                return new Row(item, cells, text);
            });
            var data = new Data(rows);
            this.setState({data: data});
            return data;
        },

        fetchAll: function (props) {
            var context = props.context;
            var communicating;
            var request = this.state.allRequest;
            if (request) request.abort();
            var self = this;
            if (context.all) {
                communicating = true;
                request = this.context.fetch(context.all, {
                    headers: {'Accept': 'application/json'}
                });
                request.then(response => {
                    if (!response.ok) throw response;
                    return response.json();
                })
                .then(data => {
                    self.extractData({context: data});
                    self.setState({communicating: false});
                }, parseAndLogError.bind(undefined, 'allRequest'));
                this.setState({
                    allRequest: request,
                    communicating: true
                });
            }
            return communicating;
        },

        render: function () {
            var columns = this.state.columns;
            var context = this.props.context;
            var defaultSortOn = this.props.defaultSortOn;
            var sortOn = this.state.sortOn;
            var reversed = this.state.reversed;
            var searchTerm = this.state.searchTerm;
            this.state.searchTerm = searchTerm;
            var titles = context.columns || {};
            var data = this.state.data;
            var params = url.parse(this.context.location_href, true).query;
            var total = context.count || data.rows.length;
            data.sort(sortOn, reversed);
            var self = this;
            var headers = columns.map(function (column, index) {
                var className = "icon";
                if (index === sortOn) {
                    className += reversed ? " icon-chevron-down" : " icon-chevron-up";
                }
                return (

                        {titles[column] && titles[column]['title'] || column}

                );
            });
            var actions = (context.actions || []).map(action =>

                        <button className={'btn ' + action.className || ''}>{action.title}</button>

            );
            var searchTermLower = this.state.searchTerm.trim().toLowerCase();
            var matching = [];
            var not_matching = [];
            // Reorder rows so that the nth-child works
            if (searchTerm) {
                data.rows.forEach(function (row) {
                    if (row.text.indexOf(searchTermLower) == -1) {
                        not_matching.push(row);
                    } else {
                        matching.push(row);
                    }
                });
            } else {
                matching = data.rows;
            }
            var rows = matching.map(function (row) {
                return RowView({row: row});
            });
            rows.push.apply(rows, not_matching.map(function (row) {
                return RowView({row: row, hidden: true});
            }));
            var table_class = "sticky-area collection-table";
            var loading_or_total;
            if (this.state.communicating) {
                table_class += ' communicating';
                loading_or_total = (
                    Loading...
                );
            } else {
                loading_or_total = (

                        {matching.length}
                        of {total} records

                );
            }
            return (

                      <StickyHeader>

                            {this.props.showControls ?

                                    {loading_or_total}
                                    {actions}
                                    <form ref="form" className="table-filter" onKeyUp={this.handleKeyUp}
                                        data-skiprequest="true" data-removeempty="true">
                                        <input ref="q" disabled={this.state.communicating || undefined}
                                            name="q" type="search" defaultValue={searchTerm}
                                            placeholder="Filter table by..." className="filter form-control"
                                            id="table-filter" />

                                        <input ref="sorton" type="hidden" name="sorton" defaultValue={sortOn !== defaultSortOn ? sortOn : ''} />
                                        <input ref="reversed" type="hidden" name="reversed" defaultValue={!!reversed || ''} />
                                    </form>

 : ''}

                                {headers}

                      </StickyHeader>

                            {rows}

            );
        },

        componentDidMount: function () {
            this.setState({
                data: this.extractData(this.props),
                communicating: this.fetchAll(this.props),
                mounted: true,
            });
        },

        handleClickHeader: function (event) {
            var target = event.target;
            while (target.tagName != 'TH') {
                target = target.parentElement;
            }
            var cellIndex = target.cellIndex;
            var reversed = '';
            var sorton = this.refs.sorton.getDOMNode();
            if (this.props.defaultSortOn !== cellIndex) {
                sorton.value = cellIndex;
            } else {
                sorton.value = '';
            }
            if (this.state.sortOn == cellIndex) {
                reversed = !this.state.reversed || '';
            }
            this.refs.reversed.getDOMNode().value = reversed;
            event.preventDefault();
            event.stopPropagation();
            this.submit();
        },

        handleKeyUp: function (event) {
            if (typeof this.submitTimer != 'undefined') {
                clearTimeout(this.submitTimer);
            }
            // Skip when enter key is pressed
            if (event.nativeEvent.keyCode == 13) return;
            // IE8 should only submit on enter as page reload is triggered
            if (!this.hasEvent) return;
            this.submitTimer = setTimeout(this.submit, 200);
        },

        hasEvent: typeof Event !== 'undefined',

        submit: function () {
            // form.submit() does not fire onsubmit handlers...
            var target = this.refs.form.getDOMNode();

            // IE8 does not support the Event constructor
            if (!this.hasEvent) {
                target.submit();
                return;
            }

            var event = new Event('submit', {bubbles: true, cancelable: true});
            target.dispatchEvent(event);
        },

        clearFilter: function (event) {
            this.refs.q.getDOMNode().value = '';
            this.submitTimer = setTimeout(this.submit);
        },

        componentWillUnmount: function () {
            if (typeof this.submitTimer != 'undefined') {
                clearTimeout(this.submitTimer);
            }
            var request = this.state.allRequest;
            if (request) request.abort();
        }

    });
<commit_msg>Fix indenting<commit_after>'use strict';
var React = require('react');
var url = require('url');
var globals = require('./globals');
var parseAndLogError = require('./mixins').parseAndLogError;
var StickyHeader = require('./StickyHeader');

var lookup_column = function (result, column) {
    var value = result;
    var names = column.split('.');
    for (var i = 0, len = names.length; i < len && value !== undefined; i++) {
        value = value[names[i]];
    }
    return value;
};

var Collection = module.exports.Collection = React.createClass({
    render: function () {
        var context = this.props.context;
        return (

{context.title}

{context.description}

        );
    }
});

globals.content_views.register(Collection, 'Collection');

class Cell {
    constructor(value, sortable) {
        this.value = value;
        this.sortable = sortable;
    }
}

class Row {
    constructor(item, cells, text) {
        this.item = item;
        this.cells = cells;
        this.text = text;
    }
}

class Data {
    constructor(rows) {
        this.rows = rows;
        this.sortedOn = null;
        this.reversed = false;
    }
    sort(sortColumn, reverse) {
        reverse = !!reverse;
        if (this.sortedOn === sortColumn && this.reversed === reverse) return;
        this.sortedOn = sortColumn;
        this.reversed = reverse;
        this.rows.sort(function (rowA, rowB) {
            var a = '' + rowA.cells[sortColumn].sortable;
            var b = '' + rowB.cells[sortColumn].sortable;
            if (a  b) {
                return reverse ? -1 : 1;
            }
            return 0;
        });
    }
}

var RowView = function (props) {
    var row = props.row;
    var id = row.item['@id'];
    var tds = row.cells.map( function (cell, index) {
        if (index === 0) {
            return (
                {cell.value}
            );
        }
        return (
            {cell.value}
        );
    });
    return (

{tds}

    );
};

var Table = module.exports.Table = React.createClass({
    contextTypes: {
        fetch: React.PropTypes.func,
        location_href: React.PropTypes.string
    },

    getDefaultProps: function () {
        return {
            defaultSortOn: 0,
            showControls: true,
        };
    },

    getInitialState: function () {
        var state = this.extractParams(this.props, this.context);
        state.columns = this.guessColumns(this.props);
        state.data = new Data([]);  // Tables may be long so render empty first
        state.communicating = true;
        return state;
    },

    componentWillReceiveProps: function (nextProps, nextContext) {
        var updateData = false;
        if (nextProps.context !== this.props.context) {
            updateData = true;
            this.setState({
                communicating: this.fetchAll(nextProps)
            });
        }
        if (nextProps.columns !== this.props.columns) {
            updateData = true;
        }
        if (updateData) {
            var columns = this.guessColumns(nextProps);
            this.extractData(nextProps, columns);
        }
        if (nextContext.location_href !== this.context.location_href) {
            this.extractParams(nextProps, nextContext);
        }

    },

    extractParams: function(props, context) {
        var params = url.parse(context.location_href, true).query;
        var sorton = parseInt(params.sorton, 10);
        if (isNaN(sorton)) {
            sorton = props.defaultSortOn;
        }
        var state = {
            sortOn: sorton,
            reversed: params.reversed || false,
            searchTerm: params.q || ''
        };
        this.setState(state);
        return state;
    },

    guessColumns: function (props) {
        var column_list = props.columns || props.context.columns;
        var columns = [];
        if (!column_list || Object.keys(column_list).length === 0) {
            for (var key in props.context['@graph'][0]) {
                if (key.slice(0, 1) != '@' && key.search(/(uuid|_no|accession)/) == -1) {
                    columns.push(key);
                }
            }
            columns.sort();
            columns.unshift('@id');
        } else {
            for(var column in column_list) {
                columns.push(column);
            }
        }
        this.setState({columns: columns});
        return columns;
    },

    extractData: function (props, columns) {
        var context = props.context;
        columns = columns || this.state.columns;
        var rows = context['@graph'].map(function (item) {
            var cells = columns.map(function (column) {
                var factory;
                // cell factories
                //if (factory) {
                //    return factory({context: item, column: column});
                //}
                var value = lookup_column(item, column);
                if (column == '@id') {
                    factory = globals.listing_titles.lookup(item);
                    value = factory({context: item});
                } else if (value == null) {
                    value = '';
                } else if (value instanceof Array) {
                    value = value;
                } else if (value['@type']) {
                    factory = globals.listing_titles.lookup(value);
                    value = factory({context: value});
                }
                var sortable = ('' + value).toLowerCase();
                return new Cell(value, sortable);
            });
            var text = cells.map(function (cell) {
                return cell.value;
            }).join(' ').toLowerCase();
            return new Row(item, cells, text);
        });
        var data = new Data(rows);
        this.setState({data: data});
        return data;
    },

    fetchAll: function (props) {
        var context = props.context;
        var communicating;
        var request = this.state.allRequest;
        if (request) request.abort();
        var self = this;
        if (context.all) {
            communicating = true;
            request = this.context.fetch(context.all, {
                headers: {'Accept': 'application/json'}
            });
            request.then(response => {
                if (!response.ok) throw response;
                return response.json();
            })
            .then(data => {
                self.extractData({context: data});
                self.setState({communicating: false});
            }, parseAndLogError.bind(undefined, 'allRequest'));
            this.setState({
                allRequest: request,
                communicating: true
            });
        }
        return communicating;
    },

    render: function () {
        var columns = this.state.columns;
        var context = this.props.context;
        var defaultSortOn = this.props.defaultSortOn;
        var sortOn = this.state.sortOn;
        var reversed = this.state.reversed;
        var searchTerm = this.state.searchTerm;
        this.state.searchTerm = searchTerm;
        var titles = context.columns || {};
        var data = this.state.data;
        var params = url.parse(this.context.location_href, true).query;
        var total = context.count || data.rows.length;
        data.sort(sortOn, reversed);
        var self = this;
        var headers = columns.map(function (column, index) {
            var className = "icon";
            if (index === sortOn) {
                className += reversed ? " icon-chevron-down" : " icon-chevron-up";
            }
            return (

                    {titles[column] && titles[column]['title'] || column}

            );
        });
        var actions = (context.actions || []).map(action =>

                    <button className={'btn ' + action.className || ''}>{action.title}</button>

        );
        var searchTermLower = this.state.searchTerm.trim().toLowerCase();
        var matching = [];
        var not_matching = [];
        // Reorder rows so that the nth-child works
        if (searchTerm) {
            data.rows.forEach(function (row) {
                if (row.text.indexOf(searchTermLower) == -1) {
                    not_matching.push(row);
                } else {
                    matching.push(row);
                }
            });
        } else {
            matching = data.rows;
        }
        var rows = matching.map(function (row) {
            return RowView({row: row});
        });
        rows.push.apply(rows, not_matching.map(function (row) {
            return RowView({row: row, hidden: true});
        }));
        var table_class = "sticky-area collection-table";
        var loading_or_total;
        if (this.state.communicating) {
            table_class += ' communicating';
            loading_or_total = (
                Loading...
            );
        } else {
            loading_or_total = (

                    {matching.length}
                    of {total} records

            );
        }
        return (

                    <StickyHeader>

                        {this.props.showControls ?

                                {loading_or_total}
                                {actions}
                                <form ref="form" className="table-filter" onKeyUp={this.handleKeyUp}
                                    data-skiprequest="true" data-removeempty="true">
                                    <input ref="q" disabled={this.state.communicating || undefined}
                                        name="q" type="search" defaultValue={searchTerm}
                                        placeholder="Filter table by..." className="filter form-control"
                                        id="table-filter" />

                                    <input ref="sorton" type="hidden" name="sorton" defaultValue={sortOn !== defaultSortOn ? sortOn : ''} />
                                    <input ref="reversed" type="hidden" name="reversed" defaultValue={!!reversed || ''} />
                                </form>

 : ''}

                            {headers}

                    </StickyHeader>

                        {rows}

        );
    },

    componentDidMount: function () {
        this.setState({
            data: this.extractData(this.props),
            communicating: this.fetchAll(this.props),
            mounted: true,
        });
    },

    handleClickHeader: function (event) {
        var target = event.target;
        while (target.tagName != 'TH') {
            target = target.parentElement;
        }
        var cellIndex = target.cellIndex;
        var reversed = '';
        var sorton = this.refs.sorton.getDOMNode();
        if (this.props.defaultSortOn !== cellIndex) {
            sorton.value = cellIndex;
        } else {
            sorton.value = '';
        }
        if (this.state.sortOn == cellIndex) {
            reversed = !this.state.reversed || '';
        }
        this.refs.reversed.getDOMNode().value = reversed;
        event.preventDefault();
        event.stopPropagation();
        this.submit();
    },

    handleKeyUp: function (event) {
        if (typeof this.submitTimer != 'undefined') {
            clearTimeout(this.submitTimer);
        }
        // Skip when enter key is pressed
        if (event.nativeEvent.keyCode == 13) return;
        // IE8 should only submit on enter as page reload is triggered
        if (!this.hasEvent) return;
        this.submitTimer = setTimeout(this.submit, 200);
    },

    hasEvent: typeof Event !== 'undefined',

    submit: function () {
        // form.submit() does not fire onsubmit handlers...
        var target = this.refs.form.getDOMNode();

        // IE8 does not support the Event constructor
        if (!this.hasEvent) {
            target.submit();
            return;
        }

        var event = new Event('submit', {bubbles: true, cancelable: true});
        target.dispatchEvent(event);
    },

    clearFilter: function (event) {
        this.refs.q.getDOMNode().value = '';
        this.submitTimer = setTimeout(this.submit);
    },

    componentWillUnmount: function () {
        if (typeof this.submitTimer != 'undefined') {
            clearTimeout(this.submitTimer);
        }
        var request = this.state.allRequest;
        if (request) request.abort();
    }

});
<|endoftext|>


<commit_before>'use strict'

var fs = require('fs') // fs instance
var parseString = require('xml2js').parseString // xml2js method parseString instance
var prefixMatch = new RegExp(/(?!xmlns)^.*:/);
var promise = require('promise');
var dataXML; // variable for data processing
var resultJSON; //variable for json processing

/*
 ---Bunch of functions to create a new valid json structure (relations part)
 */
function analyzeRelations(request) {
    function analyzeRefs(request) {

        var result = {};

        if (request.hasOwnProperty('comment') || request.hasOwnProperty('namespace')) {
            result.comment = request.comment;
            result.namespace = request.namespace;
        }

        result.id = request.id;

        if (request.hasOwnProperty('indexes')) {
            result.indexes = [];
            if (Array.isArray(request.indexes.index)) {
                for (var i = 0; i < request.indexes.index.length; i++) {
                    result.indexes[i] = request.indexes.index[i]
                }
            } else result.indexes[0] = request.indexes.index
        }
        return result;
    }

    var result = {};
    result.id = request.id;
    if (request.hasOwnProperty('comment')) {
        result.comment = request.comment;
    }
    result.refs = [];
    if (Array.isArray(request.refs.entryRef)) {
        for (var i = 0; i < request.refs.entryRef.length; i++) {
            result.refs[i] = analyzeRefs(request.refs.entryRef[i])
        }
    } else result.refs[0] = analyzeRefs(request.refs.entryRef)

    return result;
}

/*
 ---Bunch of functions to create a new valid json structure (main part)
 */
function analyze(request) {
    function analyzeNamespaces(request) {
        function analyzeEntities(request) {
            function analyzeAttr(request) {

                var result = {};
                result.id = request.id;
                if (request.hasOwnProperty('comment')) {
                    result.comment = request.comment;
                }
                result.type = request.type;

                return result;

            }

            var result = {};
            result.id = request.id;
            if (request.hasOwnProperty('comment')) {
                result.comment = request.comment;
            }
            result.attributes = [];
            if (Array.isArray(request.attributes.attribute)) {
                for (var i = 0; i < request.attributes.attribute.length; i++) {
                    result.attributes[i] = analyzeAttr(request.attributes.attribute[i])
                }
            } else result.attributes[0] = analyzeAttr(request.attributes.attribute)

            return result;

        }

        var result = {};

        result.id = request.id;
        if (request.hasOwnProperty('comment')) {
            result.comment = request.comment;
        }
        result.entities = [];
        if (Array.isArray(request.entities.entity)) {
            for (var i = 0; i < request.entities.entity.length; i++) {
                result.entities[i] = analyzeEntities(request.entities.entity[i])
            }
        } else result.entities[0] = analyzeEntities(request.entities.entity)

        if (request.hasOwnProperty('relations')) {
            result.relations = [];
            if (Array.isArray(request.relations.relation)) {
                for (var i = 0; i < request.relations.relation.length; i++) {
                    result.relations[i] = analyzeRelations(request.relations.relation[i])
                }
            } else result.relations[0] = analyzeRelations(request.relations.relation)
        }

        return result;
    }

    var result = {"dBEAR": {}};

    if (request.dBEAR.hasOwnProperty('comment')) {
        result.dBEAR.comment = request.dBEAR.comment;
    }
    result.dBEAR.namespaces = [];
    if (Array.isArray(request.dBEAR.namespaces.namespace)) {
        for (var i = 0; i < request.dBEAR.namespaces.namespace.length; i++) {
            result.dBEAR.namespaces[i] = analyzeNamespaces(request.dBEAR.namespaces.namespace[i])
        }
    } else result.dBEAR.namespaces[0] = analyzeNamespaces(request.dBEAR.namespaces.namespace)

    return result
}

/*
 ---Main part of convertor
 */
function Converter() {
    this.run = function (param) {
        var fileIn = param.demFileIn
        var fileOut = param.demFileOut

        fs.readFile(fileIn, 'ascii', function (err, data) {
            dataXML = data

            parseString(dataXML, {
                    tagNameProcessors: [tagStripPrefix], // strip tag prefix
                    explicitArray: false, // remove arrays in child nodes
                    mergeAttrs: true, // attributes become child nodes
                    emptyTag: {}
                }, // default value of empty tag

                function (err, result) {
                    var result = analyze(result) // get a new json structure
                    resultJSON = result

                    return result // return JSON model
                })

            /* ded.json is writing to the same directory. Maybe we should create special folder? */
            fs.writeFile(fileOut, JSON.stringify(resultJSON,
                function (key, value) // callable function to strip some useless nodes
                {
                    var result = value
                    if (key == 'xmlns:tns' || key == 'xmlns:xsi' || key == 'xsi:schemaLocation') result = undefined;
                    return result;
                }, 2))

        })

    }
}

/*
 ---Function to strip tag prefix
 */
function tagStripPrefix(name) {
    /* Is this function obliged? It is used once. */
    var result = name.replace(prefixMatch, '')
    return result //function to strip tag prefix
}

module['exports'] = Converter

/* TODO create test for converter
 * #Created on 21-Jul-15
 * */

/* To launch convert.js create test.js in this directory (it's already in gitignore) with this code: */

//var converter = require('./convert.js')
//var params = require('./generate/params.js')
//var cnv = new converter
//params.demFileIn = '../../sample/01_person/sample_01.dem.xml'
//params.demFileOut = 'dem.json'
//cnv.run(params)

/* Launch it with 'node test.js' */
<commit_msg>Revert "code review"<commit_after>'use strict'

var fs = require('fs') // fs instance
var parseString = require('xml2js').parseString // xml2js method parseString instance
var prefixMatch = new RegExp(/(?!xmlns)^.*:/);
var promise = require('promise');
var dataXML; // variable for data processing
var resultJSON; //variable for json processing

/*
 ---Bunch of functions to create a new valid json structure (relations part)
 */
function analyzeRelations(request) {
    function analyzeRefs(request) {

        var result = {};

        if (request.hasOwnProperty('comment') || request.hasOwnProperty('namespace')) {
            result.comment = request.comment;
            result.namespace = request.namespace;
        }

        result.id = request.id;

        if (request.hasOwnProperty('indexes')) {
            result.indexes = [];
            if (Array.isArray(request.indexes.index)) {
                for (var i = 0; i < request.indexes.index.length; i++) {
                    result.indexes[i] = request.indexes.index[i]
                }
            } else result.indexes[0] = request.indexes.index
        }
        return result;
    }

    var result = {};
    result.id = request.id;
    if (request.hasOwnProperty('comment')) {
        result.comment = request.comment;
    }
    result.refs = [];
    if (Array.isArray(request.refs.entryRef)) {
        for (var i = 0; i < request.refs.entryRef.length; i++) {
            result.refs[i] = analyzeRefs(request.refs.entryRef[i])
        }
    } else result.refs[0] = analyzeRefs(request.refs.entryRef)

    return result;
}

/*
 ---Bunch of functions to create a new valid json structure (main part)
 */
function analyze(request) {
    function analyzeNamespaces(request) {
        function analyzeEntities(request) {
            function analyzeAttr(request) {

                var result = {};
                result.id = request.id;
                if (request.hasOwnProperty('comment')) {
                    result.comment = request.comment;
                }
                result.type = request.type;

                return result;

            }

            var result = {};
            result.id = request.id;
            if (request.hasOwnProperty('comment')) {
                result.comment = request.comment;
            }
            result.attributes = [];
            if (Array.isArray(request.attributes.attribute)) {
                for (var i = 0; i < request.attributes.attribute.length; i++) {
                    result.attributes[i] = analyzeAttr(request.attributes.attribute[i])
                }
            } else result.attributes[0] = analyzeAttr(request.attributes.attribute)

            return result;

        }

        var result = {};

        result.id = request.id;
        if (request.hasOwnProperty('comment')) {
            result.comment = request.comment;
        }
        result.entities = [];
        if (Array.isArray(request.entities.entity)) {
            for (var i = 0; i < request.entities.entity.length; i++) {
                result.entities[i] = analyzeEntities(request.entities.entity[i])
            }
        } else result.entities[0] = analyzeEntities(request.entities.entity)

        if (request.hasOwnProperty('relations')) {
            result.relations = [];
            if (Array.isArray(request.relations.relation)) {
                for (var i = 0; i < request.relations.relation.length; i++) {
                    result.relations[i] = analyzeRelations(request.relations.relation[i])
                }
            } else result.relations[0] = analyzeRelations(request.relations.relation)
        }

        return result;
    }

    var result = {"dBEAR":{}};

    if (request.dBEAR.hasOwnProperty('comment')) {
        result.dBEAR.comment = request.dBEAR.comment;
    }
    result.dBEAR.namespaces = [];
    if (Array.isArray(request.dBEAR.namespaces.namespace)) {
        for (var i = 0; i < request.dBEAR.namespaces.namespace.length; i++) {
            result.dBEAR.namespaces[i] = analyzeNamespaces(request.dBEAR.namespaces.namespace[i])
        }
    } else result.dBEAR.namespaces[0] = analyzeNamespaces(request.dBEAR.namespaces.namespace)

    return result
}

/*
 ---Main part of convertor
 */
function Converter() {
    this.run = function (param) {
        var fileIn = param.demFileIn
        var fileOut = param.demFileOut

        var promise = new Promise(function (resolve, reject) {
            fs.readFile(fileIn, 'ascii', function (err, data) {
                if (err) {reject (err)} else resolve("The data was successfully read!")
                dataXML = data
            }).then(function() {
                parseString(dataXML, {
                        tagNameProcessors: [tagStripPrefix], // strip tag prefix
                        explicitArray: false, // remove arrays in child nodes
                        mergeAttrs: true, // attributes become child nodes
                        emptyTag: {}}, // default value of empty tag

                    function (err, result) {
                        if (err) {reject (err)} else resolve("Strings are successfully parsed!")
                        var result = analyze(result) // get a new json structure
                        resultJSON = result

                        return result // return JSON model
                    })
            }).then(function () {
                /* ded.json is writing to the same directory. Maybe we should create special folder? */
                fs.writeFile(fileOut, JSON.stringify(resultJSON,
                    function (key, value) // callable function to strip some useless nodes
                    {
                        var result = value
                        if (key == 'xmlns:tns' || key == 'xmlns:xsi' || key == 'xsi:schemaLocation') result = undefined;
                        return result;
                    }, 2))
                if (isElement(fileOut)) {
                    resolve("File was successfully written!")
                } else reject("Error!")
            })
        })
    }
}

/*
---Function to strip tag prefix
*/
function tagStripPrefix(name) {
    /* Is this function obliged? It is used once. */
    var result = name.replace(prefixMatch, '')
    return result //function to strip tag prefix
}

module['exports'] = Converter

/* TODO create test for converter
 * #Created on 21-Jul-15
 * */

/* To launch convert.js create test.js in this directory (it's already in gitignore) with this code: */

//var converter = require('./convert.js')
//var params = require('./generate/params.js')
//var cnv = new converter
//params.demFileIn = '../../sample/01_person/sample_01.dem.xml'
//params.demFileOut = 'dem.json'
//cnv.run(params)

/* Launch it with 'node test.js' */
<|endoftext|>


<commit_before>var express = require('express')
var app = express()
var nodemailer = require('nodemailer')
var smtpTransport = require('nodemailer-smtp-transport')
var CONFIG = require('config')
var bodyParser = require('body-parser')
var Joi = require('joi')
var bunyan = require('bunyan')
var pkg = require('./package.json')
var log = bunyan.createLogger({ name: pkg.name })

var contactSchema = Joi.object().keys({
  name: Joi.string().alphanum().min(3).max(30).required(),
  email: Joi.string().email(),
  subject: Joi.string().alphanum().max(70),
  message: Joi.string().alphanum().max(2000).required()
})

// Parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

var smtpTrans = nodemailer.createTransport(smtpTransport(CONFIG.smtp))

app.post('/', function (req, res) {

  log.info('Got POST:')
  log.info(req.body)

  Joi.validate(req.body, contactSchema, function (err, value) {

    if (err) {
      log.error(err)
      res.status(500).send('Invalid form data.')
    }

    // Mailer options
    var mailOpts = {
      from: req.body.name + ' <' + req.body.email + '>',
      to: CONFIG.to,
      subject: CONFIG.prefix + req.body.subject,
      text: req.body.message
    }

    log.info('Sending email:')
    log.info(mailOpts)

    smtpTrans.sendMail(mailOpts, function (error, response) {
      if (error) {
        log.error(error)
        res.status(500).send('Failed to send the message.')
      } else {
        log.info(response)
        res.status(200).send('Message successfully sent!')
      }
    })
  })
})

var server = app.listen(CONFIG.port, function () {
  var host = server.address().address
  var port = server.address().port

  log.info('Mailer listening at http://%s:%s', host, port)
})
<commit_msg>Logger fix.<commit_after>var express = require('express')
var app = express()
var nodemailer = require('nodemailer')
var smtpTransport = require('nodemailer-smtp-transport')
var CONFIG = require('config')
var bodyParser = require('body-parser')
var Joi = require('joi')
var bunyan = require('bunyan')
var pkg = require('./package.json')
var log = bunyan.createLogger({ name: pkg.name })

var contactSchema = Joi.object().keys({
  name: Joi.string().alphanum().min(3).max(30).required(),
  email: Joi.string().email(),
  subject: Joi.string().alphanum().max(70),
  message: Joi.string().alphanum().max(2000).required()
})

// Parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

var smtpTrans = nodemailer.createTransport(smtpTransport(CONFIG.smtp))

app.post('/', function (req, res) {

  log.info('Got POST:')
  log.info({body: req.body})

  Joi.validate(req.body, contactSchema, function (err, value) {

    if (err) {
      log.error(err)
      res.status(500).send('Invalid form data.')
    }

    // Mailer options
    var mailOpts = {
      from: req.body.name + ' <' + req.body.email + '>',
      to: CONFIG.to,
      subject: CONFIG.prefix + req.body.subject,
      text: req.body.message
    }

    log.info('Sending email:')
    log.info({options: mailOpts})

    smtpTrans.sendMail(mailOpts, function (error, response) {
      if (error) {
        log.error(error)
        res.status(500).send('Failed to send the message.')
      } else {
        log.info(response)
        res.status(200).send('Message successfully sent!')
      }
    })
  })
})

var server = app.listen(CONFIG.port, function () {
  var host = server.address().address
  var port = server.address().port

  log.info('Mailer listening at http://%s:%s', host, port)
})
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while <|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!<commit_msg>Correcting style<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?<|endoftext|>


<commit_before>module.exports = {
  ensureMasterIssue,
};

// istanbul ignore next
function getListItem(branch, type) {
  let item = ' - [ ] ';
  item += `<!-- ${type}-branch=${branch.branchName} -->`;
  if (branch.prNo) {
    item += `[${branch.prTitle}](../pull/${branch.prNo})`;
  } else {
    item += branch.prTitle;
  }
  const uniquePackages = [
    ...new Set(branch.upgrades.map(upgrade => '`' + upgrade.depName + '`')),
  ];
  if (uniquePackages.length < 2) {
    return item + '\n';
  }
  return item + ' (' + uniquePackages.join(', ') + ')\n';
}

// istanbul ignore next
async function ensureMasterIssue(config, branches) {
  if (!(config.masterIssue || config.masterIssueApproval)) {
    return;
  }
  if (
    !branches.length ||
    branches.every(branch => branch.res === 'automerged')
  ) {
    if (config.masterIssueAutoclose) {
      await platform.ensureIssueClosing(config.masterIssueTitle);
      return;
    }
    await platform.ensureIssue(
      config.masterIssueTitle,
      'This repository is up-to-date and has no outstanding updates open or pending.'
    );
    return;
  }
  let issueBody =
    'This issue contains a list of Renovate updates and their statuses.\n\n';
  const pendingApprovals = branches.filter(
    branch => branch.res === 'needs-approval'
  );
  if (pendingApprovals.length) {
    issueBody += '## Pending Approval\n\n';
    issueBody +=
      'These PRs will be created by Renovate only once you click their checkbox below.\n\n';
    for (const branch of pendingApprovals) {
      issueBody += getListItem(branch, 'approve');
    }
    issueBody += '\n';
  }
  const awaitingSchedule = branches.filter(
    branch => branch.res === 'not-scheduled'
  );
  if (awaitingSchedule.length) {
    issueBody += '## Awaiting Schedule\n\n';
    issueBody +=
      'These updates are awaiting their schedule. Click on a checkbox to ignore the schedule.\n';
    for (const branch of awaitingSchedule) {
      issueBody += getListItem(branch, 'unschedule');
    }
    issueBody += '\n';
  }
  const rateLimited = branches.filter(
    branch => branch.res && branch.res.endsWith('pr-hourly-limit-reached')
  );
  if (rateLimited.length) {
    issueBody += '## Rate Limited\n\n';
    issueBody +=
      'These updates are currently rate limited. Click on a checkbox below to override.\n\n';
    for (const branch of rateLimited) {
      issueBody += getListItem(branch, 'unlimit');
    }
    issueBody += '\n';
  }
  const errorList = branches.filter(
    branch => branch.res && branch.res.endsWith('error')
  );
  if (errorList.length) {
    issueBody += '## Errored\n\n';
    issueBody +=
      'These updates encountered an error and will be retried. Click a checkbox below to force a retry now.\n\n';
    for (const branch of errorList) {
      issueBody += getListItem(branch, 'retry');
    }
    issueBody += '\n';
  }
  const prEdited = branches.filter(branch => branch.res === 'pr-edited');
  if (prEdited.length) {
    issueBody += '## Edited/Blocked\n\n';
    issueBody +=
      'These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, check the box below.\n\n';
    for (const branch of prEdited) {
      issueBody += getListItem(branch, 'reset');
    }
    issueBody += '\n';
  }
  const otherRes = [
    'needs-approval',
    'not-scheduled',
    'pr-hourly-limit-reached',
    'already-existed',
    'error',
    'automerged',
    'pr-edited',
  ];
  const inProgress = branches.filter(branch => !otherRes.includes(branch.res));
  if (inProgress.length) {
    issueBody += '## Open\n\n';
    issueBody +=
      'These updates have all been created already. Click a checkbox below to force a retry/rebase of any.\n\n';
    for (const branch of inProgress) {
      const pr = await platform.getBranchPr(branch.branchName);
      if (pr) {
        branch.prNo = pr.number;
      }
      issueBody += getListItem(branch, 'rebase');
    }
    issueBody += '\n';
  }
  const alreadyExisted = branches.filter(
    branch => branch.res && branch.res.endsWith('already-existed')
  );
  if (alreadyExisted.length) {
    issueBody += '## Closed/Ignored\n\n';
    issueBody +=
      'These updates were closed unmerged and will not be recreated unless you click a checkbox below.\n\n';
    for (const branch of alreadyExisted) {
      issueBody += getListItem(branch, 'recreate');
    }
    issueBody += '\n';
  }
  await platform.ensureIssue(config.masterIssueTitle, issueBody);
}
<commit_msg>feat: Add master issue link to closed PRs (#2730)<commit_after>module.exports = {
  ensureMasterIssue,
};

// istanbul ignore next
function getListItem(branch, type, pr) {
  let item = ' - [ ] ';
  item += `<!-- ${type}-branch=${branch.branchName} -->`;
  if (pr) {
    item += `[${branch.prTitle}](../pull/${pr.number})`;
  } else {
    item += branch.prTitle;
  }
  const uniquePackages = [
    ...new Set(branch.upgrades.map(upgrade => '`' + upgrade.depName + '`')),
  ];
  if (uniquePackages.length < 2) {
    return item + '\n';
  }
  return item + ' (' + uniquePackages.join(', ') + ')\n';
}

// istanbul ignore next
async function ensureMasterIssue(config, branches) {
  if (!(config.masterIssue || config.masterIssueApproval)) {
    return;
  }
  if (
    !branches.length ||
    branches.every(branch => branch.res === 'automerged')
  ) {
    if (config.masterIssueAutoclose) {
      await platform.ensureIssueClosing(config.masterIssueTitle);
      return;
    }
    await platform.ensureIssue(
      config.masterIssueTitle,
      'This repository is up-to-date and has no outstanding updates open or pending.'
    );
    return;
  }
  let issueBody =
    'This issue contains a list of Renovate updates and their statuses.\n\n';
  const pendingApprovals = branches.filter(
    branch => branch.res === 'needs-approval'
  );
  if (pendingApprovals.length) {
    issueBody += '## Pending Approval\n\n';
    issueBody +=
      'These PRs will be created by Renovate only once you click their checkbox below.\n\n';
    for (const branch of pendingApprovals) {
      issueBody += getListItem(branch, 'approve');
    }
    issueBody += '\n';
  }
  const awaitingSchedule = branches.filter(
    branch => branch.res === 'not-scheduled'
  );
  if (awaitingSchedule.length) {
    issueBody += '## Awaiting Schedule\n\n';
    issueBody +=
      'These updates are awaiting their schedule. Click on a checkbox to ignore the schedule.\n';
    for (const branch of awaitingSchedule) {
      issueBody += getListItem(branch, 'unschedule');
    }
    issueBody += '\n';
  }
  const rateLimited = branches.filter(
    branch => branch.res && branch.res.endsWith('pr-hourly-limit-reached')
  );
  if (rateLimited.length) {
    issueBody += '## Rate Limited\n\n';
    issueBody +=
      'These updates are currently rate limited. Click on a checkbox below to override.\n\n';
    for (const branch of rateLimited) {
      issueBody += getListItem(branch, 'unlimit');
    }
    issueBody += '\n';
  }
  const errorList = branches.filter(
    branch => branch.res && branch.res.endsWith('error')
  );
  if (errorList.length) {
    issueBody += '## Errored\n\n';
    issueBody +=
      'These updates encountered an error and will be retried. Click a checkbox below to force a retry now.\n\n';
    for (const branch of errorList) {
      issueBody += getListItem(branch, 'retry');
    }
    issueBody += '\n';
  }
  const prEdited = branches.filter(branch => branch.res === 'pr-edited');
  if (prEdited.length) {
    issueBody += '## Edited/Blocked\n\n';
    issueBody +=
      'These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, check the box below.\n\n';
    for (const branch of prEdited) {
      issueBody += getListItem(branch, 'reset');
    }
    issueBody += '\n';
  }
  const otherRes = [
    'needs-approval',
    'not-scheduled',
    'pr-hourly-limit-reached',
    'already-existed',
    'error',
    'automerged',
    'pr-edited',
  ];
  const inProgress = branches.filter(branch => !otherRes.includes(branch.res));
  if (inProgress.length) {
    issueBody += '## Open\n\n';
    issueBody +=
      'These updates have all been created already. Click a checkbox below to force a retry/rebase of any.\n\n';
    for (const branch of inProgress) {
      const pr = await platform.getBranchPr(branch.branchName);
      issueBody += getListItem(branch, 'rebase', pr);
    }
    issueBody += '\n';
  }
  const alreadyExisted = branches.filter(
    branch => branch.res && branch.res.endsWith('already-existed')
  );
  if (alreadyExisted.length) {
    issueBody += '## Closed/Ignored\n\n';
    issueBody +=
      'These updates were closed unmerged and will not be recreated unless you click a checkbox below.\n\n';
    for (const branch of alreadyExisted) {
      const pr = await platform.findPr(
        branch.branchName,
        branch.prTitle,
        '!open'
      );
      issueBody += getListItem(branch, 'recreate', pr);
    }
    issueBody += '\n';
  }
  await platform.ensureIssue(config.masterIssueTitle, issueBody);
}
<|endoftext|>


<commit_before>'use strict';

function EntityFieldCreator(base_wall, entity_creator_or_editor) {
    this.__init__(base_wall, entity_creator_or_editor);
}

EntityFieldCreator.prototype = {

    __init__: function(base_wall, entity_creator_or_editor) {
        this.base_wall = base_wall;
        this.entity_creator_or_editor = entity_creator_or_editor;
    },

    set_display_button: function(button) {
        this.add_new_field_button = button;
        this.add_new_field_button.set_engage_function(this._add_entity_field_button_pressed.bind(this));
    },

    _add_entity_field_button_pressed: function() {
        this.create();
        this.wall_add_new_field.display_self_and_all_child_attachments_recursively();
        this.base_wall.refresh_position_and_look_at();
    },

    create: function() {
        if (is_defined(this.wall_add_new_field)) {
            this.wall_add_new_field.fully_remove_self_and_all_sub_attachments();
        }

        this.wall_add_new_field = new FloatingWall(200, 300, null, null, this.base_wall.world, false, COLOR_BLUE);
        this.wall_add_new_field.manual_visibility = true;
        this.wall_add_new_field.set_attachment_depth_offset(10);
        this.wall_add_new_field.attach_to(this.add_new_field_button);
        this.wall_add_new_field.add_close_button();
        this.wall_add_new_field.add_full_row_3D(-1, 'Add New Field', TYPE_TITLE);

        // All the field options.
        this.wall_add_new_field.add_full_row_2D(0, 'Default Fields', TYPE_CONSTANT);

        // Adding an emtpy row for spacing.
        this.wall_add_new_field.add_row();

        this._add_selectable_entity_field(ENTITY_PROPERTY_DUE_DATE);
        this._add_selectable_entity_field(ENTITY_PROPERTY_DUE_TIME);
        this._add_selectable_entity_field(ENTITY_PROPERTY_TAGS);
        this._add_selectable_entity_field(ENTITY_PROPERTY_NOTE);

        // Adding an emtpy row for spacing.
        this.wall_add_new_field.add_row();

        this.wall_add_new_field.add_full_row_2D(null, 'Or create a custom field', TYPE_CONSTANT);
        this.custom_field_name = this.wall_add_new_field.add_full_row_2D(null, 'Field Name', TYPE_INPUT);
        this.wall_add_new_field.add_row(null).add_2D_button([0, 1], 'Add custom field', null, this._add_selectable_custom_entity_field.bind(this));

        this.wall_add_new_field.hide_self_and_all_child_attachments_recursively();
    },

    _add_selectable_custom_entity_field: function() {
        this.wall_add_new_field.hide_self_and_all_child_attachments_recursively();
        var custom_field_name = this.custom_field_name.get_text();
        if (!custom_field_name.startsWith('ep_')) {
            custom_field_name = 'ep_' + custom_field_name;
        }
        this.add_entity_field(custom_field_name);
        // TODO : Add all the error checking needed!!!
    },

    _add_entity_field: function(field_name) {
        this.wall_add_new_field.hide_self_and_all_child_attachments_recursively();
        this.entity_creator_or_editor.add_entity_field(field_name);
    },

    _add_selectable_entity_field: function(field_name) {
        if (!this.wall_create_new_entity.has_row_with_name(field_name)) {
            this.wall_add_new_field.add_row(null, field_name).add_2D_button([0, 1], field_name, null, this._add_entity_field.bind(this, field_name));
        }
    }

};<commit_msg>schedule features 25<commit_after>'use strict';

function EntityFieldCreator(base_wall, entity_creator_or_editor) {
    this.__init__(base_wall, entity_creator_or_editor);
}

EntityFieldCreator.prototype = {

    __init__: function(base_wall, entity_creator_or_editor) {
        this.base_wall = base_wall;
        this.entity_creator_or_editor = entity_creator_or_editor;
    },

    set_display_button: function(button) {
        this.add_new_field_button = button;
        this.add_new_field_button.set_engage_function(this._add_entity_field_button_pressed.bind(this));
    },

    _add_entity_field_button_pressed: function() {
        this.create();
        this.wall_add_new_field.display_self_and_all_child_attachments_recursively();
        this.base_wall.refresh_position_and_look_at();
    },

    create: function() {
        if (is_defined(this.wall_add_new_field)) {
            this.wall_add_new_field.fully_remove_self_and_all_sub_attachments();
        }

        this.wall_add_new_field = new FloatingWall(200, 300, null, null, this.base_wall.world, false, COLOR_BLUE);
        this.wall_add_new_field.manual_visibility = true;
        this.wall_add_new_field.set_attachment_depth_offset(10);
        this.wall_add_new_field.attach_to(this.add_new_field_button);
        this.wall_add_new_field.add_close_button();
        this.wall_add_new_field.add_full_row_3D(-1, 'Add New Field', TYPE_TITLE);

        // All the field options.
        this.wall_add_new_field.add_full_row_2D(0, 'Default Fields', TYPE_CONSTANT);

        // Adding an emtpy row for spacing.
        this.wall_add_new_field.add_row();

        this._add_selectable_entity_field(ENTITY_PROPERTY_DUE_DATE);
        this._add_selectable_entity_field(ENTITY_PROPERTY_DUE_TIME);
        this._add_selectable_entity_field(ENTITY_PROPERTY_TAGS);
        this._add_selectable_entity_field(ENTITY_PROPERTY_NOTE);

        // Adding an emtpy row for spacing.
        this.wall_add_new_field.add_row();

        this.wall_add_new_field.add_full_row_2D(null, 'Or create a custom field', TYPE_CONSTANT);
        this.custom_field_name = this.wall_add_new_field.add_full_row_2D(null, 'Field Name', TYPE_INPUT);
        this.wall_add_new_field.add_row(null).add_2D_button([0, 1], 'Add custom field', null, this._add_selectable_custom_entity_field.bind(this));

        this.wall_add_new_field.hide_self_and_all_child_attachments_recursively();
    },

    _add_selectable_custom_entity_field: function() {
        this.wall_add_new_field.hide_self_and_all_child_attachments_recursively();
        var custom_field_name = this.custom_field_name.get_text();
        if (!custom_field_name.startsWith('ep_')) {
            custom_field_name = 'ep_' + custom_field_name;
        }
        this.add_entity_field(custom_field_name);
        // TODO : Add all the error checking needed!!!
    },

    _add_entity_field: function(field_name) {
        this.wall_add_new_field.hide_self_and_all_child_attachments_recursively();
        this.entity_creator_or_editor.add_entity_field(field_name);
    },

    _add_selectable_entity_field: function(field_name) {
        if (!this.entity_creator_or_editor.has_row_with_name(field_name)) {
            this.wall_add_new_field.add_row(null, field_name).add_2D_button([0, 1], field_name, null, this._add_entity_field.bind(this, field_name));
        }
    }

};<|endoftext|>


<commit_before>/** @jsx React.DOM */
'use strict';
var React = require('react');
var _ = require('underscore');
var globals = require('./globals');
var dbxref = require('./dbxref');
var dataset = require('./dataset');
var antibody = require('./antibody');

var DbxrefList = dbxref.DbxrefList;
var FileTable = dataset.FileTable;
var StatusLabel = antibody.StatusLabel;

var Panel = function (props) {
    // XXX not all panels have the same markup
    var context;
    if (props['@id']) {
        context = props;
        props = {context: context};
    }
    return globals.panel_views.lookup(props.context)(props);
};

var Experiment = module.exports.Experiment = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'view-item');
        var replicates = _.sortBy(context.replicates, function(item) {
            return item.biological_replicate_number;
        });
        var aliasList = context.aliases.join(", ");

        var documents = {};
        replicates.forEach(function (replicate) {
            if (!replicate.library) return;
            replicate.library.documents.forEach(function (doc) {
                documents[doc['@id']] = Panel({context: doc});
            });
        });

        // Process biosamples for summary display
        var biosamples = [], lifeAge = [], organismName = [];
        replicates.forEach(function (replicate) {
            var biosample = replicate.library && replicate.library.biosample;
            if (biosample) {
                biosamples.push(biosample);

                // Add to array of scientific names for rare experiments with cross-species biosamples
                organismName.push(biosample.organism.scientific_name);

                // Build a string with non-'unknown' life_stage, age, and age_units concatenated
                var lifeAgeString = (biosample.life_stage && biosample.life_stage != 'unknown') ? biosample.life_stage : '';
                if (biosample.age && biosample.age != 'unknown') {
                    lifeAgeString += (lifeAgeString ? ' ' : '') + biosample.age;
                    lifeAgeString += (biosample.age_units && biosample.age_units != 'unknown') ? ' ' + biosample.age_units : '';
                }
                if (lifeAgeString) {
                    lifeAge.push(lifeAgeString);
                }
            }
        });

        // Eliminate duplicates in lifeAge and organismName arrays so each displayed only once
        if (lifeAge.length) {
            lifeAge = _.uniq(lifeAge);
        }
        if (organismName.length) {
            organismName = _.uniq(organismName);
        }

        // Build the text of the Treatment string
        var treatmentText = [];
        if (biosamples.length && biosamples[0].treatments && biosamples[0].treatments.length > 0) {
            treatmentText = biosamples[0].treatments.map(function(treatment) {
                var singleTreatment = '';
                if (treatment.concentration) {
                    singleTreatment += treatment.concentration + ' ' + treatment.concentration_units + ' ';
                }
                singleTreatment += treatment.treatment_term_name + ' (' + treatment.treatment_term_id + ') ';
                if (treatment.duration) {
                    singleTreatment += 'for ' + treatment.duration + ' ' + treatment.duration_units;
                }
                return singleTreatment;
            });
        }

        // Adding experiment specific documents
        context.documents.forEach(function (document) {
            documents[document['@id']] = Panel({context: document});
        });
        var antibodies = {};
        replicates.forEach(function (replicate) {
            if (replicate.antibody) {
                antibodies[replicate.antibody['@id']] = replicate.antibody;
            }
        });
        var antibody_accessions = [];
        for (var key in antibodies) {
            antibody_accessions.push(antibodies[key].accession);
        }

        // Determine this experiment's ENCODE version
        var encodevers = "";
        if (context.award.rfa) {
            encodevers = globals.encodeVersionMap[context.award.rfa.substring(0,7)];
            if (typeof encodevers === "undefined") {
                encodevers = "";
            }
        }

        // Make list of statuses
        var statuses = [{status: context.status, title: "Status"}];
        if (encodevers === "3" && context.status === "released") {
            statuses.push({status: "pending", title: "Validation"});
        }

        // XXX This makes no sense.
        //var control = context.possible_controls[0];
        return (

Experiment

{context.assay_term_name}

                            Experiment summary for {context.accession}

                            <StatusLabel status={statuses} />

Assay

{context.assay_term_name}

Accession

{context.accession}

                        {biosamples.length ?
Biosample summary
 : null}
                        {biosamples.length ?

                                {context.biosample_term_name ? {context.biosample_term_name + ' '} : null}
                                {organismName.length || lifeAge.length ? '(' : null}
                                {organismName.length ?

                                        {organismName.map(function(name, i) {
                                            if (i === 0) {
                                                return ({name});
                                            } else {
                                                return ({' and '}{name});
                                            }
                                        })}

                                : null}
                                {lifeAge.length ? ', ' + lifeAge.join(' and ') : ''}
                                {organismName.length || lifeAge.length ? ')' : null}

                        : null}

                        {context.biosample_type ?
Type
 : null}
                        {context.biosample_type ?
{context.biosample_type}
 : null}

                        {treatmentText.length ?
Treatment
 : null}
                        {treatmentText.length ?

                                    {treatmentText.map(function (treatment) {
                                        return (
{treatment}
);
                                    })}

                        : null}

                        {context.target ?
Target
 : null}
                        {context.target ?
{context.target.label}
 : null}

                        {antibody_accessions.length ?
Antibody
 : null}
                        {antibody_accessions.length ?
{antibody_accessions.join(', ')}
 : null}

                        {context.possible_controls.length ?
Controls
 : null}
                        {context.possible_controls.length ?

                                    {context.possible_controls.map(function (control) {
                                        return (

                                                    {control.accession}

                                        );
                                    })}

                        : null}

                        {context.description ?
Description
 : null}
                        {context.description ?
{context.description}
 : null}

Lab

{context.lab.title}

Project

{context.award.project}

                        {context.dbxrefs.length ?
External resources
 : null}
                        {context.dbxrefs.length ?
<DbxrefList values={context.dbxrefs} />
 : null}

                        {context.aliases.length ?
Aliases
 : null}
                        {context.aliases.length ?
{aliasList}
 : null}

                <AssayDetails replicates={replicates} />

                {Object.keys(documents).length ?

Protocols

                        {documents}

                : null}

                {replicates.map(function (replicate, index) {
                    return (
                        <Replicate replicate={replicate} key={index} />
                    );
                })}

                {context.files.length ?

Files linked to {context.accession}

                        <FileTable items={context.files} encodevers={encodevers} />

                : null }

        );
    }
});

globals.content_views.register(Experiment, 'experiment');

var AssayDetails = module.exports.AssayDetails = function (props) {
    var replicates = props.replicates.sort(function(a, b) {
        if (b.biological_replicate_number === a.biological_replicate_number) {
            return a.technical_replicate_number - b.technical_replicate_number;
        }
        return a.biological_replicate_number - b.biological_replicate_number;
    });

    if (!replicates.length) return (

);

    var replicate = replicates[0];
    var library = replicate.library;
    var platform = replicate.platform;
    var depletedIn;
    var treatments;

    if (library && library.depleted_in_term_name && library.depleted_in_term_name.length) {
        depletedIn = library.depleted_in_term_name.join(", ");
    }

    if (library && library.treatments && library.treatments.length) {
        var i = library.treatments.length;
        var t;
        var treatmentList = [];
        while (i--) {
            t = library.treatments[i];
            treatmentList.push(t.treatment_term_name);
        }
        treatments = treatmentList.join(", ");
    }

    return (

Assay details

                {library && library.nucleic_acid_term_name ?
Nucleic acid type
 : null}
				{library && library.nucleic_acid_term_name ?
{library.nucleic_acid_term_name}
 : null}

                {library && library.nucleic_acid_starting_quantity ?
NA starting quantity
 : null}
				{library && library.nucleic_acid_starting_quantity ?
{library.nucleic_acid_starting_quantity}
 : null}

                {depletedIn ?
Depleted in
 : null}
				{depletedIn ?
{depletedIn}
 : null}

                {library && library.lysis_method ?
Lysis method
 : null}
				{library && library.lysis_method ?
{library.lysis_method}
 : null}

                {library && library.extraction_method ?
Extraction method
 : null}
				{library && library.extraction_method ?
{library.extraction_method}
 : null}

                {library && library.fragmentation_method ?
Fragmentation method
 : null}
				{library && library.fragmentation_method ?
{library.fragmentation_method}
 : null}

                {library && library.size_range ?
Size range
 : null}
				{library && library.size_range ?
{library.size_range}
 : null}

                {library && library.library_size_selection_method ?
Size selection method
 : null}
				{library && library.library_size_selection_method ?
{library.library_size_selection_method}
 : null}

                {treatments ?
Treatments
 : null}
				{treatments ?
{treatments}
 : null}

                {platform ?
Platform
 : null}
				{platform ?
{platform.title}
 : null}

    );
};

var Replicate = module.exports.Replicate = function (props) {
    var replicate = props.replicate;
    var concentration = replicate.rbns_protein_concentration;
    var library = replicate.library;
    var biosample = library && library.biosample;
    var paired_end = replicate.paired_ended;
    return (

Biological replicate - {replicate.biological_replicate_number}

Technical replicate

{replicate.technical_replicate_number}

                {concentration ?
Protein concentration
 : null}
                {concentration ?
{concentration}{replicate.rbns_protein_concentration_units}
 : null}

                {library ?
Library
 : null}
                {library ?
{library.accession}
 : null}

                {biosample ?
Biosample
 : null}
                {biosample ?

                        {biosample.accession}
                    {' '}-{' '}{biosample.biosample_term_name}

 : null}

                {replicate.read_length ?
Run type
 : null}
                {replicate.read_length ?
{paired_end ? 'paired-end' : 'single-end'}
 : null}

                {replicate.read_length ?
Read length
 : null}
                {replicate.read_length ?
{replicate.read_length}{replicate.read_length_units}
 : null}

    );
};

// Can't be a proper panel as the control must be passed in.
//globals.panel_views.register(Replicate, 'replicate');
<commit_msg>Handle multiple treatment types across biosamples.<commit_after>/** @jsx React.DOM */
/** @jsx React.DOM */
'use strict';
var React = require('react');
var _ = require('underscore');
var globals = require('./globals');
var dbxref = require('./dbxref');
var dataset = require('./dataset');
var antibody = require('./antibody');

var DbxrefList = dbxref.DbxrefList;
var FileTable = dataset.FileTable;
var StatusLabel = antibody.StatusLabel;

var Panel = function (props) {
    // XXX not all panels have the same markup
    var context;
    if (props['@id']) {
        context = props;
        props = {context: context};
    }
    return globals.panel_views.lookup(props.context)(props);
};

var Experiment = module.exports.Experiment = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'view-item');
        var replicates = _.sortBy(context.replicates, function(item) {
            return item.biological_replicate_number;
        });
        var aliasList = context.aliases.join(", ");

        var documents = {};
        replicates.forEach(function (replicate) {
            if (!replicate.library) return;
            replicate.library.documents.forEach(function (doc) {
                documents[doc['@id']] = Panel({context: doc});
            });
        });

        // Process biosamples for summary display
        var biosamples = [], lifeAge = [], organismName = [];
        replicates.forEach(function (replicate) {
            var biosample = replicate.library && replicate.library.biosample;
            if (biosample) {
                biosamples.push(biosample);

                // Add to array of scientific names for rare experiments with cross-species biosamples
                organismName.push(biosample.organism.scientific_name);

                // Build a string with non-'unknown' life_stage, age, and age_units concatenated
                var lifeAgeString = (biosample.life_stage && biosample.life_stage != 'unknown') ? biosample.life_stage : '';
                if (biosample.age && biosample.age != 'unknown') {
                    lifeAgeString += (lifeAgeString ? ' ' : '') + biosample.age;
                    lifeAgeString += (biosample.age_units && biosample.age_units != 'unknown') ? ' ' + biosample.age_units : '';
                }
                if (lifeAgeString) {
                    lifeAge.push(lifeAgeString);
                }
            }
        });

        // Eliminate duplicates in lifeAge and organismName arrays so each displayed only once
        if (lifeAge.length) {
            lifeAge = _.uniq(lifeAge);
        }
        if (organismName.length) {
            organismName = _.uniq(organismName);
        }

        // Build the text of the Treatment string
        var treatmentText = [];
        biosamples.map(function(biosample) {
            treatmentText = treatmentText.concat(biosample.treatments.map(function(treatment) {
                var singleTreatment = '';
                if (treatment.concentration) {
                    singleTreatment += treatment.concentration + (treatment.concentration_units ? ' ' + treatment.concentration_units : '') + ' ';
                }
                singleTreatment += treatment.treatment_term_name + (treatment.treatment_term_id ? ' (' + treatment.treatment_term_id + ')' : '') + ' ';
                if (treatment.duration) {
                    singleTreatment += 'for ' + treatment.duration + ' ' + (treatment.duration_units ? treatment.duration_units : '');
                }
                return singleTreatment;
            }));
        });
        if (treatmentText) {
            treatmentText = _.uniq(treatmentText);
        }

        // Adding experiment specific documents
        context.documents.forEach(function (document) {
            documents[document['@id']] = Panel({context: document});
        });
        var antibodies = {};
        replicates.forEach(function (replicate) {
            if (replicate.antibody) {
                antibodies[replicate.antibody['@id']] = replicate.antibody;
            }
        });
        var antibody_accessions = [];
        for (var key in antibodies) {
            antibody_accessions.push(antibodies[key].accession);
        }

        // Determine this experiment's ENCODE version
        var encodevers = "";
        if (context.award.rfa) {
            encodevers = globals.encodeVersionMap[context.award.rfa.substring(0,7)];
            if (typeof encodevers === "undefined") {
                encodevers = "";
            }
        }

        // Make list of statuses
        var statuses = [{status: context.status, title: "Status"}];
        if (encodevers === "3" && context.status === "released") {
            statuses.push({status: "pending", title: "Validation"});
        }

        // XXX This makes no sense.
        //var control = context.possible_controls[0];
        return (

Experiment

{context.assay_term_name}

                            Experiment summary for {context.accession}

                            <StatusLabel status={statuses} />

Assay

{context.assay_term_name}

Accession

{context.accession}

                        {biosamples.length ?
Biosample summary
 : null}
                        {biosamples.length ?

                                {context.biosample_term_name ? {context.biosample_term_name + ' '} : null}
                                {organismName.length || lifeAge.length ? '(' : null}
                                {organismName.length ?

                                        {organismName.map(function(name, i) {
                                            if (i === 0) {
                                                return ({name});
                                            } else {
                                                return ({' and '}{name});
                                            }
                                        })}

                                : null}
                                {lifeAge.length ? ', ' + lifeAge.join(' and ') : ''}
                                {organismName.length || lifeAge.length ? ')' : null}

                        : null}

                        {context.biosample_type ?
Type
 : null}
                        {context.biosample_type ?
{context.biosample_type}
 : null}

                        {treatmentText.length ?
Treatment
 : null}
                        {treatmentText.length ?

                                    {treatmentText.map(function (treatment) {
                                        return (
{treatment}
);
                                    })}

                        : null}

                        {context.target ?
Target
 : null}
                        {context.target ?
{context.target.label}
 : null}

                        {antibody_accessions.length ?
Antibody
 : null}
                        {antibody_accessions.length ?
{antibody_accessions.join(', ')}
 : null}

                        {context.possible_controls.length ?
Controls
 : null}
                        {context.possible_controls.length ?

                                    {context.possible_controls.map(function (control) {
                                        return (

                                                    {control.accession}

                                        );
                                    })}

                        : null}

                        {context.description ?
Description
 : null}
                        {context.description ?
{context.description}
 : null}

Lab

{context.lab.title}

Project

{context.award.project}

                        {context.dbxrefs.length ?
External resources
 : null}
                        {context.dbxrefs.length ?
<DbxrefList values={context.dbxrefs} />
 : null}

                        {context.aliases.length ?
Aliases
 : null}
                        {context.aliases.length ?
{aliasList}
 : null}

                <AssayDetails replicates={replicates} />

                {Object.keys(documents).length ?

Protocols

                        {documents}

                : null}

                {replicates.map(function (replicate, index) {
                    return (
                        <Replicate replicate={replicate} key={index} />
                    );
                })}

                {context.files.length ?

Files linked to {context.accession}

                        <FileTable items={context.files} encodevers={encodevers} />

                : null }

        );
    }
});

globals.content_views.register(Experiment, 'experiment');

var AssayDetails = module.exports.AssayDetails = function (props) {
    var replicates = props.replicates.sort(function(a, b) {
        if (b.biological_replicate_number === a.biological_replicate_number) {
            return a.technical_replicate_number - b.technical_replicate_number;
        }
        return a.biological_replicate_number - b.biological_replicate_number;
    });

    if (!replicates.length) return (

);

    var replicate = replicates[0];
    var library = replicate.library;
    var platform = replicate.platform;
    var depletedIn;
    var treatments;

    if (library && library.depleted_in_term_name && library.depleted_in_term_name.length) {
        depletedIn = library.depleted_in_term_name.join(", ");
    }

    if (library && library.treatments && library.treatments.length) {
        var i = library.treatments.length;
        var t;
        var treatmentList = [];
        while (i--) {
            t = library.treatments[i];
            treatmentList.push(t.treatment_term_name);
        }
        treatments = treatmentList.join(", ");
    }

    return (

Assay details

                {library && library.nucleic_acid_term_name ?
Nucleic acid type
 : null}
				{library && library.nucleic_acid_term_name ?
{library.nucleic_acid_term_name}
 : null}

                {library && library.nucleic_acid_starting_quantity ?
NA starting quantity
 : null}
				{library && library.nucleic_acid_starting_quantity ?
{library.nucleic_acid_starting_quantity}
 : null}

                {depletedIn ?
Depleted in
 : null}
				{depletedIn ?
{depletedIn}
 : null}

                {library && library.lysis_method ?
Lysis method
 : null}
				{library && library.lysis_method ?
{library.lysis_method}
 : null}

                {library && library.extraction_method ?
Extraction method
 : null}
				{library && library.extraction_method ?
{library.extraction_method}
 : null}

                {library && library.fragmentation_method ?
Fragmentation method
 : null}
				{library && library.fragmentation_method ?
{library.fragmentation_method}
 : null}

                {library && library.size_range ?
Size range
 : null}
				{library && library.size_range ?
{library.size_range}
 : null}

                {library && library.library_size_selection_method ?
Size selection method
 : null}
				{library && library.library_size_selection_method ?
{library.library_size_selection_method}
 : null}

                {treatments ?
Treatments
 : null}
				{treatments ?
{treatments}
 : null}

                {platform ?
Platform
 : null}
				{platform ?
{platform.title}
 : null}

    );
};

var Replicate = module.exports.Replicate = function (props) {
    var replicate = props.replicate;
    var concentration = replicate.rbns_protein_concentration;
    var library = replicate.library;
    var biosample = library && library.biosample;
    var paired_end = replicate.paired_ended;
    return (

Biological replicate - {replicate.biological_replicate_number}

Technical replicate

{replicate.technical_replicate_number}

                {concentration ?
Protein concentration
 : null}
                {concentration ?
{concentration}{replicate.rbns_protein_concentration_units}
 : null}

                {library ?
Library
 : null}
                {library ?
{library.accession}
 : null}

                {biosample ?
Biosample
 : null}
                {biosample ?

                        {biosample.accession}
                    {' '}-{' '}{biosample.biosample_term_name}

 : null}

                {replicate.read_length ?
Run type
 : null}
                {replicate.read_length ?
{paired_end ? 'paired-end' : 'single-end'}
 : null}

                {replicate.read_length ?
Read length
 : null}
                {replicate.read_length ?
{replicate.read_length}{replicate.read_length_units}
 : null}

    );
};

// Can't be a proper panel as the control must be passed in.
//globals.panel_views.register(Replicate, 'replicate');
<|endoftext|>


<commit_before>// Our Twitter library
var Twit = require('twit');

// We need to include our configuration file
var T = new Twit(require('./config.js'));
var request = require('request');
var fs = require("fs");
var gm = require("gm").subClass({
    imageMagick: true
});

function watchTag() {

    var stream = T.stream('statuses/filter', {
        // track: ['art']
        track: ['@DitheredBot']
    })

    stream.on('tweet', function(tweet) {
        try {
            var imgurl = tweet.entities.media[0].media_url
            var id = imgurl.split("/")[4]
            var outputFileName = 'output/' + id
            var nameID = tweet.id_str;
            var name = tweet.user.screen_name;

            var stream = request(imgurl)
            gm(stream, outputFileName).normalize().monochrome().write(outputFileName, function(err) {

                if (!err) {
                    console.log('wrote: ' + id);
                    // console.log(name)
                    tweetImage(outputFileName, name, nameID)
                }

            });

        } catch (e) {
            // console.log(e)
        }
    })

}

function tweetImage(path, name, nameID) {

    fs.readFile(path, {
            encoding: 'base64'
        },

        function(err, buf) {
            var b64content = buf

            T.post('media/upload', {
                media_data: b64content
            }, function(err, data, response) {
                // now we can reference the media and post a tweet (media will attach to the tweet)
                var mediaIdStr = data.media_id_string
                var params = {
                    // status: '#dithered',
                    media_ids: [mediaIdStr],
                    in_reply_to_status_id: nameID,
                    status: 'dithered!' + ' @' + name
                }

                T.post('statuses/update', params, function(err, data, response) {
                    // console.log(data)
                    console.log('tweeted: ' + params.status)
                })
                fs.unlink(path, function() {})
            })
        });
}

watchTag();
<commit_msg> asdasd<commit_after>var Twit = require('twit');
var T = new Twit(require('./config.js'));
var request = require('request');
var fs = require("fs");
var gm = require("gm").subClass({
    imageMagick: true
});

var stream = T.stream('statuses/filter', {
    track: ['@DitheredBot']
})

stream.on('tweet', function(tweet) {
    if (tweet.entities.media == undefined)
        return

    var imgurl = tweet.entities.media[0].media_url
    var id = imgurl.split("/")[4]

    var name = tweet.user.screen_name;
    var nameID = tweet.id_str;

    var outputFileName = 'output/' + id

    var stream = request(imgurl)

    gm(stream, outputFileName).normalize().monochrome().write(outputFileName, function(err) {
        if (!err) {
            console.log('wrote: ' + id);
            tweetImage(outputFileName, name, nameID)
        }

    });

})

function tweetImage(path, name, nameID) {

    fs.readFile(path, {
            encoding: 'base64'
        },

        function(err, buf) {
            var b64content = buf

            T.post('media/upload', {
                media_data: b64content
            }, function(err, data, response) {

                var mediaIdStr = data.media_id_string
                var params = {
                    status: 'dithered!' + ' @' + name,
                    media_ids: [mediaIdStr],
                    in_reply_to_status_id: nameID
                }

                T.post('statuses/update', params, function(err, data, response) {
                    console.log('tweeted: ' + params.status)
                })

                fs.unlink(path, function() {})
            })
        });
}
<|endoftext|>