<commit_before>/**
* trials search, selections to combine etc...
* @author Isaak Y Tecle <iyt2@cornell.edu>
*
*/

JSAN.use("Prototype");
JSAN.use('jquery.blockUI');

function getPopIds () {

    jQuery('#homepage_trials_list tr').filter(':has(:checkbox:checked)')
        .bind('click',  function() {

            var td =  jQuery(this).html();
            //alert(td);
            var selectedTrial = '
' + td + '
';

            jQuery("#selected_trials_table tr:last").after(selectedTrial);

            jQuery("#selected_trials_table tr").each( function() {
                jQuery(this).find("input[type=checkbox]")
                    .attr('onclick', 'removeSelectedTrial()')
                    .prop('checked', true);
            });
        });

    jQuery("#selected_trials").show();
    jQuery("#combine").show();
    jQuery("#search_again").show();

}

function doneSelecting() {
    jQuery("#homepage_trials_list").hide();
    jQuery("#done_selecting").hide();

}

function removeSelectedTrial() {

    jQuery("#selected_trials_table tr").on("change", function() {
        jQuery(this).remove();
    });

}

function searchAgain () {
    jQuery("#homepage_trials_list").show();
    jQuery("#done_selecting").show();

}

Array.prototype.unique =
    function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

<commit_msg>if all selected trials removed from list to be combined, return to trials search result<commit_after>/**
* trials search, selections to combine etc...
* @author Isaak Y Tecle <iyt2@cornell.edu>
*
*/

JSAN.use("Prototype");
JSAN.use('jquery.blockUI');

function getPopIds () {

    jQuery('#homepage_trials_list tr').filter(':has(:checkbox:checked)')
        .bind('click',  function() {

            var td =  jQuery(this).html();
            //alert(td);
            var selectedTrial = '
' + td + '
';

            jQuery("#selected_trials_table tr:last").after(selectedTrial);

            jQuery("#selected_trials_table tr").each( function() {
                jQuery(this).find("input[type=checkbox]")
                    .attr('onclick', 'removeSelectedTrial()')
                    .prop('checked', true);
            });
        });

    jQuery("#selected_trials").show();
    jQuery("#combine").show();
    jQuery("#search_again").show();

}

function doneSelecting() {
    jQuery("#homepage_trials_list").hide();
    jQuery("#done_selecting").hide();

}

function removeSelectedTrial() {

    jQuery("#selected_trials_table tr").on("change", function() {

        jQuery(this).remove();

        if( jQuery("#selected_trials_table td").doesExist() == false) {
            jQuery("#selected_trials").hide();
            jQuery("#combine").hide();
            jQuery("#search_again").hide();
            searchAgain();
        }
    });

}

function searchAgain () {
    searchTrials();
    jQuery("#done_selecting").show();
}

Array.prototype.unique =
    function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

<|endoftext|>


<commit_before>import $ from 'jquery';
import 'trumbowyg';
import app from '../../app';
import { getTrumboLangFileNameByCode } from '../../data/languages';

$.trumbowyg.svgPath = '../node_modules/trumbowyg/dist/ui/icons.svg';

export const defaultEditorOptions = {
  btns: [
    ['formatting'],
    ['bold', 'italic'],
    ['link'],
    ['insertImage'],
    'btnGrp-lists',
    ['horizontalRule'],
  ],

};

export function installRichEditor(attachPoint, options = {}) {
  const thing = app.localSettings.get('language');
  const lang = getTrumboLangFileNameByCode(thing);

  if (lang && !window.jQuery.trumbowyg.langs[lang]) {
    // eslint-disable-next-line global-require
    require(`../node_modules/trumbowyg/dist/langs/${lang}.min.js`);
  }

  options.editorOptions = {
    ...defaultEditorOptions,
    lang,
    ...options.editorOptions || {},
  };

  // accept a selector, element, or jQuery object
  const attach = $(attachPoint);

  // create editor
  attach.trumbowyg(options.editorOptions);

  if (options.topLevelClass) {
    attach.closest('.trumbowyg')
      .addClass(options.topLevelClass);
  }

  return attach;
}
<commit_msg>fix for directory path<commit_after>import $ from 'jquery';
import 'trumbowyg';
import app from '../../app';
import { getTrumboLangFileNameByCode } from '../../data/languages';

$.trumbowyg.svgPath = '../node_modules/trumbowyg/dist/ui/icons.svg';

export const defaultEditorOptions = {
  btns: [
    ['formatting'],
    ['bold', 'italic'],
    ['link'],
    ['insertImage'],
    'btnGrp-lists',
    ['horizontalRule'],
  ],

};

export function installRichEditor(attachPoint, options = {}) {
  const thing = app.localSettings.get('language');
  const lang = getTrumboLangFileNameByCode(thing);

  if (lang && !window.jQuery.trumbowyg.langs[lang]) {
    // eslint-disable-next-line global-require
    require(`../../../node_modules/trumbowyg/dist/langs/${lang}.min.js`);
  }

  options.editorOptions = {
    ...defaultEditorOptions,
    lang,
    ...options.editorOptions || {},
  };

  // accept a selector, element, or jQuery object
  const attach = $(attachPoint);

  // create editor
  attach.trumbowyg(options.editorOptions);

  if (options.topLevelClass) {
    attach.closest('.trumbowyg')
      .addClass(options.topLevelClass);
  }

  return attach;
}
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import PureComponent from '../PureComponent';
import Input from 'react-toolbox/lib/input';
import _ from '../underscore_ext';
import './GeneSuggest.css'; // XXX rename file
import XAutosuggest from './XAutosuggest';

var renderInputComponent = ({ref, onChange, ...props}) => (
	<Input
		spellCheck={false}
		innerRef={el => ref(el && el.inputNode)}
		onChange={(value, ev) => onChange(ev)}
		label='Search for a study'
		{...props} />);

class CohortSuggest extends PureComponent {
	state = {suggestions: [], value: this.props.cohort || ""};

	onSuggestionsFetchRequested = ({ value }) => {
		const wordValues = value.toLowerCase().trim().split(/\s+/);

		const filteredSuggestions = this.props.cohorts.filter(c =>
			_.every(wordValues, value => c.toLowerCase().indexOf(value) > -1)).sort();

		this.setState({ suggestions: filteredSuggestions });
	};

	onSuggestionsClearRequested = () => {
		this.setState({suggestions: []});
	};

	componentWillReceiveProps(props) {
		this.setState({value: this.state.value || props.cohort || ""});
	}

	onClear = () => {
		this.setState({value: ''});
		_.defer(() => this.props.onSelect(null));
	};

	onChange = (ev, {newValue}) => {
		this.setState({value: newValue});
	};

	onSelect = (ev, {suggestionValue}) => {
		// When props arrive we need to prefer user input, however that
		// prevents us setting state (setState here will be overwritten
		// by setState in componentWillReceiveProps, which will use the
		// old value of state). A horrible work-around is to defer
		// the call to onSelect. Similarly, with onClear, above.
		this.setState({value: ''});
		_.defer(() => this.props.onSelect(suggestionValue));
	};

	onBlur = () => {
		this.setState({value: this.props.cohort || this.state.value});
	};

	render() {
		var {onChange, onBlur} = this,
			{suggestions, value} = this.state;
		return (
			<XAutosuggest
				suggestions={suggestions}
				onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
				onSuggestionsClearRequested={this.onSuggestionsClearRequested}
				onSuggestionSelected={this.onSelect}
				getSuggestionValue={x => x}
				shouldRenderSuggestions={this.shouldRenderSuggestions}
				renderSuggestion={v => {v}}
				renderInputComponent={renderInputComponent}
				inputProps={{value, onChange, onBlur}}
				onClear={this.onClear}
				value={value} />
		);
	}
}

module.exports = CohortSuggest;
<commit_msg>Update cohort suggestions when props change.<commit_after>'use strict';

import React from 'react';
import PureComponent from '../PureComponent';
import Input from 'react-toolbox/lib/input';
import _ from '../underscore_ext';
import './GeneSuggest.css'; // XXX rename file
import XAutosuggest from './XAutosuggest';

var renderInputComponent = ({ref, onChange, ...props}) => (
	<Input
		spellCheck={false}
		innerRef={el => ref(el && el.inputNode)}
		onChange={(value, ev) => onChange(ev)}
		label='Search for a study'
		{...props} />);

var getSuggestions = (value, cohorts) => {
	const wordValues = value.toLowerCase().trim().split(/\s+/);
	return cohorts.filter(c => _.every(wordValues, value => c.toLowerCase().indexOf(value) > -1)).sort();
};

class CohortSuggest extends PureComponent {
	state = {suggestions: [], value: this.props.cohort || ""};

	onSuggestionsFetchRequested = ({value}) => {
		this.setState({ suggestions: getSuggestions(value, this.props.cohorts) });
	};

	onSuggestionsClearRequested = () => {
		this.setState({suggestions: []});
	};

	componentWillReceiveProps(props) {
		var value = this.state.value || props.cohort || "";
		this.setState({
			value,
			suggestions: value.trim().length > 0 ? getSuggestions(value, props.cohorts) : []
		});
	}

	onClear = () => {
		this.setState({value: ''});
		_.defer(() => this.props.onSelect(null));
	};

	onChange = (ev, {newValue}) => {
		this.setState({value: newValue});
	};

	onSelect = (ev, {suggestionValue}) => {
		// When props arrive we need to prefer user input, however that
		// prevents us setting state (setState here will be overwritten
		// by setState in componentWillReceiveProps, which will use the
		// old value of state). A horrible work-around is to defer
		// the call to onSelect. Similarly, with onClear, above.
		this.setState({value: ''});
		_.defer(() => this.props.onSelect(suggestionValue));
	};

	onBlur = () => {
		this.setState({value: this.props.cohort || this.state.value});
	};

	render() {
		var {onChange, onBlur} = this,
			{suggestions, value} = this.state;
		return (
			<XAutosuggest
				suggestions={suggestions}
				onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
				onSuggestionsClearRequested={this.onSuggestionsClearRequested}
				onSuggestionSelected={this.onSelect}
				getSuggestionValue={x => x}
				shouldRenderSuggestions={this.shouldRenderSuggestions}
				renderSuggestion={v => {v}}
				renderInputComponent={renderInputComponent}
				inputProps={{value, onChange, onBlur}}
				onClear={this.onClear}
				value={value} />
		);
	}
}

module.exports = CohortSuggest;
<|endoftext|>


<commit_before>/**
 * @requires OpenLayers/Control.js
 * @requires OpenLayers/Util/hideFromOldIE.js
 */

OpenLayers.Control.Info = OpenLayers.Class( OpenLayers.Control, {

    // remember that suffixes are added to this class: ItemActive or ItemInactive
    btnClass: 'olControlButtonInfo',
    elemsToHideSelector: '',
    title: null,
    widget: null,
    cnt: null,
    faqUrl: '',

    initialize: function(options) {
        var self = this;
        OpenLayers.Control.prototype.initialize.apply(self,[options]);
        self.type = OpenLayers.Control.TYPE_BUTTON;
        this.title = OpenLayers.Lang.translate('Keyboard shortcuts');
    }, // initialize

    draw: function () {
        var self = this,
            cName = 'nkButton btn',
            mapped,
            btn;

	      mapped = 'OpenLayers_Control_Info' + self.map.id;
        btn    = OpenLayers.Util.createButton( mapped, null, null, null, 'static');

        OpenLayers.Event.observe(btn, 'click', OpenLayers.Function.bind(self.toggleWidget, self));

        OpenLayers.Util.appendToggleToolClick({'self':self});

        btn.title = self.title;
        btn.className = btn.className === "" ? cName : btn.className + " " + cName;
        btn.innerHTML = OpenLayers.Util.hideFromOldIE('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 96.999999 97.000002" enable-background="new 0 0 841.9 595.3" xml:space="preserve"  width="24" height="24" > <g id="g3572" transform="translate(-372.3,-249.3)"> <g id="g3574"> <rect x="411.79999" y="287.29999" width="17" height="45" id="rect3576" style="fill:#ffffff" /> <circle cx="420.60001" cy="273.29999" r="8.8999996" id="circle3578" style="fill:#ffffff" /> </g> <g id="g3580"> <path d="m 420.8,346.3 c -26.7,0 -48.5,-21.8 -48.5,-48.5 0,-26.7 21.8,-48.5 48.5,-48.5 26.7,0 48.5,21.8 48.5,48.5 0,26.8 -21.7,48.5 -48.5,48.5 z m 0,-89 c -22.3,0 -40.5,18.2 -40.5,40.5 0,22.3 18.2,40.5 40.5,40.5 22.3,0 40.5,-18.2 40.5,-40.5 0,-22.3 -18.1,-40.5 -40.5,-40.5 z" id="path3582" style="fill:#ffffff" /> </g> </g> </svg>');

        if (self.div == null) {
            self.div = btn;
        } else {
            self.div.appendChild(btn);
        }

        self.cnt = document.createElement("div");
        OpenLayers.Element.addClass(self.cnt, "cnt");

        self.widget = OpenLayers.Util.createWidget( self.cnt, 1, true );
        self.div.appendChild( self.widget );

        return self.div;
    }, // draw

    hideControls: function () {
    	OpenLayers.Element.removeClass( this.div, 'active' );
    }, //hideControls

    insertFaq: function (response, status, request) {
      var faq = request.responseText.replace(/[\"\r\n]/g, '');
      $("#faqBox").html(faq);
      $(".faq-panel").accordion({
        collapsible: true,
        heightStyle: "content"
      });
      $(".infoBox-panel").accordion({
        collapsible: true,
        heightStyle: "content"
      });
      $(".info-menu").accordion({
        collapsible: true,
        heightStyle: "content",
        active: false
      });
    },

    showControls: function () {
      // user OS sniffing to display correct key name/symbol
      var mac = (navigator.platform && navigator.platform.indexOf('Mac') !== -1) || (navigator.userAgent && navigator.userAgent.indexOf('iPhone') !== -1);
      var ctrlKey = mac ? '⌘ ' : 'Ctrl + ';
      var html = '';
      html += '
';

      html += '
Ofte stilte sp\u00f8rsm\u00e5l om norgeskart.no
';
      html += '
';
      html += '
';

      html += '
' + OpenLayers.Lang.translate('Keyboard shortcuts') + '
';
      html += '
';
      html += '
';
      html += '
' + OpenLayers.Lang.translate('You can navigate using the following keyboard shortcuts') + ':
';
      html += '
' + OpenLayers.Lang.translate('Press TAB to change selected control. Press ENTER to activate the selected control.') + '
';
      html += '
';
      html += '

' + OpenLayers.Lang.translate('Keyboard shortcut') + '	' + OpenLayers.Lang.translate('Function') + '

';
      html += '

F11	Fullskjerm
';
      html += '
' + ctrlKey + 'P	Skriv ut
';
      html += '
+ og -	Zoom
';
      html += '
Piltaster	Panorere
';
      html += '
Home, End, PageUp, PageDown	Panorere raskt
';
      html += '

';
      html += '
';

      html += '
Om Norgeskart
';
      html += '
';
      html += '
Nyttig Info om Norgeskart kan du finne på kartverket.no
';
      html += '
';

      html += '
';
      this.cnt.innerHTML = html;

      OpenLayers.Util.renderToggleToolClick({'self':this});
      OpenLayers.Element.addClass( this.div, 'active' );

      $.ajax({
        url: this.faqUrl,
        success: this.insertFaq,
        type: 'GET'
      });
    }, // showControls

    enable: function () {
    }, // enable

    disable: function () {
    }, // disable

    toggleWidget: function () {
        OpenLayers.Element.hasClass( this.div, 'active' ) ? this.hideControls() : this.showControls();
    }, // toggleWidget

    toggleControls: function () {
    }, //togglecontrols

    CLASS_NAME: "OpenLayers.Control.Info"
}); // OpenLayers.Control.GetURL
<commit_msg>Typo: changed letter 'i' from uppercase to lowercase.<commit_after>/**
 * @requires OpenLayers/Control.js
 * @requires OpenLayers/Util/hideFromOldIE.js
 */

OpenLayers.Control.Info = OpenLayers.Class( OpenLayers.Control, {

    // remember that suffixes are added to this class: ItemActive or ItemInactive
    btnClass: 'olControlButtonInfo',
    elemsToHideSelector: '',
    title: null,
    widget: null,
    cnt: null,
    faqUrl: '',

    initialize: function(options) {
        var self = this;
        OpenLayers.Control.prototype.initialize.apply(self,[options]);
        self.type = OpenLayers.Control.TYPE_BUTTON;
        this.title = OpenLayers.Lang.translate('Keyboard shortcuts');
    }, // initialize

    draw: function () {
        var self = this,
            cName = 'nkButton btn',
            mapped,
            btn;

	      mapped = 'OpenLayers_Control_Info' + self.map.id;
        btn    = OpenLayers.Util.createButton( mapped, null, null, null, 'static');

        OpenLayers.Event.observe(btn, 'click', OpenLayers.Function.bind(self.toggleWidget, self));

        OpenLayers.Util.appendToggleToolClick({'self':self});

        btn.title = self.title;
        btn.className = btn.className === "" ? cName : btn.className + " " + cName;
        btn.innerHTML = OpenLayers.Util.hideFromOldIE('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 96.999999 97.000002" enable-background="new 0 0 841.9 595.3" xml:space="preserve"  width="24" height="24" > <g id="g3572" transform="translate(-372.3,-249.3)"> <g id="g3574"> <rect x="411.79999" y="287.29999" width="17" height="45" id="rect3576" style="fill:#ffffff" /> <circle cx="420.60001" cy="273.29999" r="8.8999996" id="circle3578" style="fill:#ffffff" /> </g> <g id="g3580"> <path d="m 420.8,346.3 c -26.7,0 -48.5,-21.8 -48.5,-48.5 0,-26.7 21.8,-48.5 48.5,-48.5 26.7,0 48.5,21.8 48.5,48.5 0,26.8 -21.7,48.5 -48.5,48.5 z m 0,-89 c -22.3,0 -40.5,18.2 -40.5,40.5 0,22.3 18.2,40.5 40.5,40.5 22.3,0 40.5,-18.2 40.5,-40.5 0,-22.3 -18.1,-40.5 -40.5,-40.5 z" id="path3582" style="fill:#ffffff" /> </g> </g> </svg>');

        if (self.div == null) {
            self.div = btn;
        } else {
            self.div.appendChild(btn);
        }

        self.cnt = document.createElement("div");
        OpenLayers.Element.addClass(self.cnt, "cnt");

        self.widget = OpenLayers.Util.createWidget( self.cnt, 1, true );
        self.div.appendChild( self.widget );

        return self.div;
    }, // draw

    hideControls: function () {
    	OpenLayers.Element.removeClass( this.div, 'active' );
    }, //hideControls

    insertFaq: function (response, status, request) {
      var faq = request.responseText.replace(/[\"\r\n]/g, '');
      $("#faqBox").html(faq);
      $(".faq-panel").accordion({
        collapsible: true,
        heightStyle: "content"
      });
      $(".infoBox-panel").accordion({
        collapsible: true,
        heightStyle: "content"
      });
      $(".info-menu").accordion({
        collapsible: true,
        heightStyle: "content",
        active: false
      });
    },

    showControls: function () {
      // user OS sniffing to display correct key name/symbol
      var mac = (navigator.platform && navigator.platform.indexOf('Mac') !== -1) || (navigator.userAgent && navigator.userAgent.indexOf('iPhone') !== -1);
      var ctrlKey = mac ? '⌘ ' : 'Ctrl + ';
      var html = '';
      html += '
';

      html += '
Ofte stilte sp\u00f8rsm\u00e5l om norgeskart.no
';
      html += '
';
      html += '
';

      html += '
' + OpenLayers.Lang.translate('Keyboard shortcuts') + '
';
      html += '
';
      html += '
';
      html += '
' + OpenLayers.Lang.translate('You can navigate using the following keyboard shortcuts') + ':
';
      html += '
' + OpenLayers.Lang.translate('Press TAB to change selected control. Press ENTER to activate the selected control.') + '
';
      html += '
';
      html += '

' + OpenLayers.Lang.translate('Keyboard shortcut') + '	' + OpenLayers.Lang.translate('Function') + '

';
      html += '

F11	Fullskjerm
';
      html += '
' + ctrlKey + 'P	Skriv ut
';
      html += '
+ og -	Zoom
';
      html += '
Piltaster	Panorere
';
      html += '
Home, End, PageUp, PageDown	Panorere raskt
';
      html += '

';
      html += '
';

      html += '
Om Norgeskart
';
      html += '
';
      html += '
Nyttig info om Norgeskart kan du finne på kartverket.no
';
      html += '
';

      html += '
';
      this.cnt.innerHTML = html;

      OpenLayers.Util.renderToggleToolClick({'self':this});
      OpenLayers.Element.addClass( this.div, 'active' );

      $.ajax({
        url: this.faqUrl,
        success: this.insertFaq,
        type: 'GET'
      });
    }, // showControls

    enable: function () {
    }, // enable

    disable: function () {
    }, // disable

    toggleWidget: function () {
        OpenLayers.Element.hasClass( this.div, 'active' ) ? this.hideControls() : this.showControls();
    }, // toggleWidget

    toggleControls: function () {
    }, //togglecontrols

    CLASS_NAME: "OpenLayers.Control.Info"
}); // OpenLayers.Control.GetURL
<|endoftext|>


<commit_before>/*global require: false, module: false */
'use strict';

var React = require('react');
var {ButtonGroup, Button, Input} = require('react-bootstrap/lib');
var _ = require('../underscore_ext');
var trim = require('underscore.string').trim;

function toGeneList(str) {
	// Have to wrap trim because it takes a 2nd param.
	return _.filter(_.map(str.split(/,| |\n|\t/), s => trim(s), _.identity));
}

function apply(features, state, hasGenes, dataset) {
	var {list, genes} = state,
		fields = toGeneList(list),
		fieldTxt = fields.join(', ');

	if (hasGenes && genes === undefined) {
		genes = true;
	}

	return {
		fields: fields,
		fetchType: 'xena',
		valueType: 'float',
		dsID: dataset.dsID,
		defaultNormalization: _.get(dataset, 'colnormalization'),
		fieldType: genes ? (fields.length > 1 ? 'genes' : 'geneProbes') : 'probes',
		fieldLabel: fieldTxt
	};
}

var valid = ({list}) => list && !!toGeneList(list).length;

// Select a list of genes, or list of identifiers. genes/identifier mode
// is selectable if the dataset supports gene views.
var GeneProbeEdit = React.createClass({
	// this.props
	//     hasGenes: boolean Whether the dataset has a gene mapping.
	//     genes: boolean User has selected 'genes' display.
	//     examples: list<string> Identifier examples from server.
	//     list: string List of genes/identifiers entered by user.
	//
	render: function () {

		var {genes = true, hasGenes, list, examples, makeLabel, setEditorState, chosenDs} = this.props,
			doGenes = hasGenes && genes,
			help = doGenes ? 'e.g. TP53 or TP53, PTEN' :
				`e.g. ${examples[0]} or ${examples[0]}, ${examples[1]}`,
			content,
			url, host, dataset,
			optionEl;

		if (hasGenes) {
			content =
				(<ButtonGroup justified>
					<Button href='#' active={!!genes}
						onClick={() => setEditorState({genes: true})}>
						Genes
					</Button>
					<Button href='#' active={!genes}
						onClick={() => setEditorState({genes: false})}>
						Identifiers
					</Button>
				</ButtonGroup>);
			optionEl = makeLabel(content, 'View mode');
		}

		host = JSON.parse(chosenDs[0]).host;
		dataset = JSON.parse(chosenDs[0]).name;
		url = '../datapages/?host=' + encodeURIComponent(host) +
			"&dataset=" + encodeURIComponent(dataset) +
			"&label=" + encodeURIComponent(dataset) +
			"&allIdentifiers=true";

		content =
			(

				<Input onChange={ev => setEditorState({list: ev.target.value})}
					type='textarea' value={list} />

					{help}

				{doGenes ? null :
					View all identifiers in the dataset
				}

);
		var inputEl = makeLabel(content, doGenes ? 'Genes' : 'Identifiers');

		return (

				{optionEl}
				{optionEl ?
 : null}
				{inputEl}

	   );
	}
});

module.exports = {
	Editor: GeneProbeEdit,
	valid,
	apply
};
<commit_msg>add ad hoc gene-probe gene example wording to tailor to our current miRNA dataset, all should be changed to proper miRNA gene name in the future<commit_after>/*global require: false, module: false */
'use strict';

var React = require('react');
var {ButtonGroup, Button, Input} = require('react-bootstrap/lib');
var _ = require('../underscore_ext');
var trim = require('underscore.string').trim;

function toGeneList(str) {
	// Have to wrap trim because it takes a 2nd param.
	return _.filter(_.map(str.split(/,| |\n|\t/), s => trim(s), _.identity));
}

function apply(features, state, hasGenes, dataset) {
	var {list, genes} = state,
		fields = toGeneList(list),
		fieldTxt = fields.join(', ');

	if (hasGenes && genes === undefined) {
		genes = true;
	}

	return {
		fields: fields,
		fetchType: 'xena',
		valueType: 'float',
		dsID: dataset.dsID,
		defaultNormalization: _.get(dataset, 'colnormalization'),
		fieldType: genes ? (fields.length > 1 ? 'genes' : 'geneProbes') : 'probes',
		fieldLabel: fieldTxt
	};
}

var valid = ({list}) => list && !!toGeneList(list).length;

// Select a list of genes, or list of identifiers. genes/identifier mode
// is selectable if the dataset supports gene views.
var GeneProbeEdit = React.createClass({
	// this.props
	//     hasGenes: boolean Whether the dataset has a gene mapping.
	//     genes: boolean User has selected 'genes' display.
	//     examples: list<string> Identifier examples from server.
	//     list: string List of genes/identifiers entered by user.
	//
	render: function () {

		var {genes = true, hasGenes, list, examples, makeLabel, setEditorState, chosenDs} = this.props,
			doGenes = hasGenes && genes,
			help = doGenes ? 'e.g. TP53 or TP53, PTEN, MIMAT0000062' : // MIMAT0000062 is just for xena's current miRNA data, it should be changed to the proper miRNA gene name
				`e.g. ${examples[0]} or ${examples[0]}, ${examples[1]}`,
			content,
			url, host, dataset,
			optionEl;

		if (hasGenes) {
			content =
				(<ButtonGroup justified>
					<Button href='#' active={!!genes}
						onClick={() => setEditorState({genes: true})}>
						Genes
					</Button>
					<Button href='#' active={!genes}
						onClick={() => setEditorState({genes: false})}>
						Identifiers
					</Button>
				</ButtonGroup>);
			optionEl = makeLabel(content, 'View mode');
		}

		host = JSON.parse(chosenDs[0]).host;
		dataset = JSON.parse(chosenDs[0]).name;
		url = '../datapages/?host=' + encodeURIComponent(host) +
			"&dataset=" + encodeURIComponent(dataset) +
			"&label=" + encodeURIComponent(dataset) +
			"&allIdentifiers=true";

		content =
			(

				<Input onChange={ev => setEditorState({list: ev.target.value})}
					type='textarea' value={list} />

					{help}

				{doGenes ? null :
					View all identifiers in the dataset
				}

);
		var inputEl = makeLabel(content, doGenes ? 'Genes' : 'Identifiers');

		return (

				{optionEl}
				{optionEl ?
 : null}
				{inputEl}

	   );
	}
});

module.exports = {
	Editor: GeneProbeEdit,
	valid,
	apply
};
<|endoftext|>


<commit_before>/*global THREE */
/*global assert */

var BEZIER = BEZIER || {};
BEZIER.widgets = BEZIER.widgets  || {};

///////////////////////
//3D Visualizer Class
//main interface to THREE.js
///////////////////////

BEZIER.widgets.visualizer_3d = function (curve_storage, width, height, stage_factory) {
	//FIXME: constructor is getting a little long.  Consider adding some setters and making some sensible defaults
	//it is also getting tougher to understand the constructor since a lot of the arguments are simple integers

	if(!curve_storage){
		throw BEZIER.errors.illegal_argument_error("curve_storage cannot be null");
	}

	var num_points = 100;
	stage_factory = stage_factory || BEZIER.widgets.stage_basic;
	var curve_factory = BEZIER.widgets.render_solid_tube;

	var curves = {};

	var stage = stage_factory(width || 500, height || 500);
	var scene = stage.make_scene();

	var render_trigger = false;
	function render() {
		stage.renderer.render(scene, stage.camera);
		render_trigger = true;
	}

	var that = {
		/////////POINTS//////////
		get_num_points: function () {
			return num_points;
		},

		set_num_points: function (num) {
			num_points = num;
		},

		////////RENDERING////////////

		set_curve_factory: function (_curve_factory) {
			curve_factory  = _curve_factory || curve_factory;
		},

		get_dom_element: function () {
			return stage.renderer.domElement;
		},

		update: function () {
			render_trigger = false;
			stage.camera_controls.update();

			if (!render_trigger) {
				render();
			}
		}

	};

	function process_curve(curve_name) {

			var radius = 0.25; //FIXME: hard coded for beta-1.
			var curve = curve_storage.get_curve(curve_name);
			var mesh = curve_factory(curve, radius, that.get_num_points());

			curves[curve_name] = mesh;
			scene.add(mesh.control_points);
			scene.add(mesh.control_polygon);
			scene.add(mesh.curve);

		}

	curve_storage.on(curve_storage.EVENT_UPDATED, process_curve);
	curve_storage.on(curve_storage.EVENT_ADDED, process_curve);

	curve_storage.on(curve_storage.EVENT_CLEARED, function (curve_name) {

		var mesh = curves[curve_name];
		if (mesh) {
			scene.remove(mesh.control_points);
			scene.remove(mesh.control_polygon);
			scene.remove(mesh.curve);
		}

		delete curves[curve_name];

	});

	stage.camera_controls.addEventListener('change', render);
	return that;

};

////////////////////
//Rendering Strategies
////////////////////

BEZIER.widgets.render_solid_tube = function (curve, radius, num_points) {
	assert(radius > 0, "radius must be greater than 0.");
	assert(num_points > 0, "num_points must be greater than 0.");

	var control_point_material =  new THREE.MeshLambertMaterial({ color: 0x0000ff, emissive: 0x000000, ambient: 0x000000, shading: THREE.SmoothShading });
	var control_polygon_material =  new THREE.MeshLambertMaterial({color: 0x00ff00, emissive: 0x000000, ambient: 0x000000, shading: THREE.SmoothShading});
	var curve_material =  new THREE.MeshLambertMaterial({ color: 0xff0000, emissive: 0x000000, ambient: 0x000000, shading: THREE.SmoothShading });

	//control points
	var control_points = new THREE.Object3D();
	var control_point_geom = new THREE.SphereGeometry(radius * 1.5, 16, 16);
	var cp, cp_mesh;
	for (var i = 0; i < curve.num_points(); i++) {
		cp = curve.get_point(i);
		cp_mesh = new THREE.Mesh(control_point_geom, control_point_material);
		cp_mesh.position.x = cp.x;
		cp_mesh.position.y = cp.y;
		cp_mesh.position.z = cp.z;
		control_points.add(cp_mesh);
	}

	//control polygon
	var curve_path = new THREE.CurvePath();
	var pt1, pt2, line, lineGeometry, lineMesh;
	for (i = 0; i < curve.num_points() - 1; i++) {
		pt1 = curve.get_point(i);
		pt2 = curve.get_point(i + 1);

		line = new THREE.LineCurve3(new THREE.Vector3(pt1.x, pt1.y, pt1.z), new THREE.Vector3(pt2.x, pt2.y, pt2.z));
		curve_path.add(line);
	}
	var control_polygon = new THREE.Mesh(new THREE.TubeGeometry(curve_path, 64, radius, 8, false),
										control_polygon_material);

	//curve
	var points = [];
	var pt;
	var tdelta = 1 / num_points;
	for (var t = 0; t <= 1; t += tdelta) {
		pt = curve.calculate(t);
		points.push(new THREE.Vector3(pt.x, pt.y, pt.z));
	}
	var spline = new THREE.SplineCurve3(points);
	var spline_geometry = new THREE.TubeGeometry(spline, 64, radius, 8, false);
	var curve_mesh = new THREE.Mesh(spline_geometry, curve_material);

	var meshes = {};
	meshes.control_points  = control_points;
	meshes.control_polygon = control_polygon;
	meshes.curve           = curve_mesh;
	return meshes;
};

/////////////////////////
//STAGE STRATEGIES
/////////////////////////

BEZIER.widgets.stage_basic = function (width, height) {
	var clear_color = 0xcccccc;

	//RENDERER
	var renderer = new THREE.WebGLRenderer({antialias: false});
	renderer.setClearColor(new THREE.Color(clear_color), 1);
	renderer.setSize(width, height);

	//CAMERA AND CONTROLS
	var camera = new THREE.PerspectiveCamera(60, width / height, 1, 1000);
	var camera_controls = new THREE.TrackballControls(camera, renderer.domElement);

	camera.position.z = 1;

	camera_controls.rotateSpeed = 3.0;
	camera_controls.zoomSpeed = 1.2;
	camera_controls.panSpeed = 0.8;

	camera_controls.noZoom = false;
	camera_controls.noPan = false;

	//SCENE
	function make_scene() {
		var scene = new THREE.Scene();
		scene.fog = new THREE.FogExp2(clear_color, 0.002);

		var light = new THREE.DirectionalLight(0xffffff);
		light.position.set(1, 1, 1);
		scene.add(light);

		light = new THREE.DirectionalLight(0xffffff);
		light.position.set(-1, -1, -1);
		scene.add(light);

		light = new THREE.AmbientLight(0xffffff);
		scene.add(light);

		return scene;

	}

	return {
		camera:          camera,
		camera_controls: camera_controls,
		make_scene:           make_scene,
		renderer:        renderer

	};

};

<commit_msg>added render call to the ADDED and EDITED events<commit_after>/*global THREE */
/*global assert */

var BEZIER = BEZIER || {};
BEZIER.widgets = BEZIER.widgets  || {};

///////////////////////
//3D Visualizer Class
//main interface to THREE.js
///////////////////////

BEZIER.widgets.visualizer_3d = function (curve_storage, width, height, stage_factory) {
	//FIXME: constructor is getting a little long.  Consider adding some setters and making some sensible defaults
	//it is also getting tougher to understand the constructor since a lot of the arguments are simple integers

	if(!curve_storage){
		throw BEZIER.errors.illegal_argument_error("curve_storage cannot be null");
	}

	var num_points = 100;
	stage_factory = stage_factory || BEZIER.widgets.stage_basic;
	var curve_factory = BEZIER.widgets.render_solid_tube;

	var curves = {};

	var stage = stage_factory(width || 500, height || 500);
	var scene = stage.make_scene();

	var render_trigger = false;
	function render() {
		stage.renderer.render(scene, stage.camera);
		render_trigger = true;
	}

	var that = {
		/////////POINTS//////////
		get_num_points: function () {
			return num_points;
		},

		set_num_points: function (num) {
			num_points = num;
		},

		////////RENDERING////////////

		set_curve_factory: function (_curve_factory) {
			curve_factory  = _curve_factory || curve_factory;
		},

		get_dom_element: function () {
			return stage.renderer.domElement;
		},

		update: function () {
			render_trigger = false;
			stage.camera_controls.update();

			if (!render_trigger) {
				render();
			}
		}

	};

	function process_curve(curve_name) {

			var radius = 0.25; //FIXME: hard coded for beta-1.
			var curve = curve_storage.get_curve(curve_name);
			var mesh = curve_factory(curve, radius, that.get_num_points());

			curves[curve_name] = mesh;
			scene.add(mesh.control_points);
			scene.add(mesh.control_polygon);
			scene.add(mesh.curve);

			that.update();
		}

	curve_storage.on(curve_storage.EVENT_UPDATED, process_curve);
	curve_storage.on(curve_storage.EVENT_ADDED, process_curve);

	curve_storage.on(curve_storage.EVENT_CLEARED, function (curve_name) {

		var mesh = curves[curve_name];
		if (mesh) {
			scene.remove(mesh.control_points);
			scene.remove(mesh.control_polygon);
			scene.remove(mesh.curve);
		}

		delete curves[curve_name];

	});

	stage.camera_controls.addEventListener('change', render);
	return that;

};

////////////////////
//Rendering Strategies
////////////////////

BEZIER.widgets.render_solid_tube = function (curve, radius, num_points) {
	assert(radius > 0, "radius must be greater than 0.");
	assert(num_points > 0, "num_points must be greater than 0.");

	var control_point_material =  new THREE.MeshLambertMaterial({ color: 0x0000ff, emissive: 0x000000, ambient: 0x000000, shading: THREE.SmoothShading });
	var control_polygon_material =  new THREE.MeshLambertMaterial({color: 0x00ff00, emissive: 0x000000, ambient: 0x000000, shading: THREE.SmoothShading});
	var curve_material =  new THREE.MeshLambertMaterial({ color: 0xff0000, emissive: 0x000000, ambient: 0x000000, shading: THREE.SmoothShading });

	//control points
	var control_points = new THREE.Object3D();
	var control_point_geom = new THREE.SphereGeometry(radius * 1.5, 16, 16);
	var cp, cp_mesh;
	for (var i = 0; i < curve.num_points(); i++) {
		cp = curve.get_point(i);
		cp_mesh = new THREE.Mesh(control_point_geom, control_point_material);
		cp_mesh.position.x = cp.x;
		cp_mesh.position.y = cp.y;
		cp_mesh.position.z = cp.z;
		control_points.add(cp_mesh);
	}

	//control polygon
	var curve_path = new THREE.CurvePath();
	var pt1, pt2, line, lineGeometry, lineMesh;
	for (i = 0; i < curve.num_points() - 1; i++) {
		pt1 = curve.get_point(i);
		pt2 = curve.get_point(i + 1);

		line = new THREE.LineCurve3(new THREE.Vector3(pt1.x, pt1.y, pt1.z), new THREE.Vector3(pt2.x, pt2.y, pt2.z));
		curve_path.add(line);
	}
	var control_polygon = new THREE.Mesh(new THREE.TubeGeometry(curve_path, 64, radius, 8, false),
										control_polygon_material);

	//curve
	var points = [];
	var pt;
	var tdelta = 1 / num_points;
	for (var t = 0; t <= 1; t += tdelta) {
		pt = curve.calculate(t);
		points.push(new THREE.Vector3(pt.x, pt.y, pt.z));
	}
	var spline = new THREE.SplineCurve3(points);
	var spline_geometry = new THREE.TubeGeometry(spline, 64, radius, 8, false);
	var curve_mesh = new THREE.Mesh(spline_geometry, curve_material);

	var meshes = {};
	meshes.control_points  = control_points;
	meshes.control_polygon = control_polygon;
	meshes.curve           = curve_mesh;
	return meshes;
};

/////////////////////////
//STAGE STRATEGIES
/////////////////////////

BEZIER.widgets.stage_basic = function (width, height) {
	var clear_color = 0xcccccc;

	//RENDERER
	var renderer = new THREE.WebGLRenderer({antialias: false});
	renderer.setClearColor(new THREE.Color(clear_color), 1);
	renderer.setSize(width, height);

	//CAMERA AND CONTROLS
	var camera = new THREE.PerspectiveCamera(60, width / height, 1, 1000);
	var camera_controls = new THREE.TrackballControls(camera, renderer.domElement);

	camera.position.z = 1;

	camera_controls.rotateSpeed = 3.0;
	camera_controls.zoomSpeed = 1.2;
	camera_controls.panSpeed = 0.8;

	camera_controls.noZoom = false;
	camera_controls.noPan = false;

	//SCENE
	function make_scene() {
		var scene = new THREE.Scene();
		scene.fog = new THREE.FogExp2(clear_color, 0.002);

		var light = new THREE.DirectionalLight(0xffffff);
		light.position.set(1, 1, 1);
		scene.add(light);

		light = new THREE.DirectionalLight(0xffffff);
		light.position.set(-1, -1, -1);
		scene.add(light);

		light = new THREE.AmbientLight(0xffffff);
		scene.add(light);

		return scene;

	}

	return {
		camera:          camera,
		camera_controls: camera_controls,
		make_scene:           make_scene,
		renderer:        renderer

	};

};

<|endoftext|>


<commit_before>'use scrict'

const jsonfile = require('jsonfile')

// saves graph to savedFile.json
module.exports = function save (cy, path) {
  const fileToSave = `${path}/graphs/savedFile.json`
  // parses graph and stores it as an object
  const fullgraph = cy.json()
  jsonfile.writeFile(fileToSave, fullgraph, (err) => {
    if (err) {
      throw err
    }
  })
  const htmlElement = document.getElementById('info-nodes-id')
  htmlElement.textContent = 'graph saved 👍'
}
<commit_msg>:hammer:<commit_after>'use scrict'

const jsonfile = require('jsonfile')
const printChat = require('./printChat.js')

// saves graph to savedFile.json
module.exports = function save (cy, path) {
  const fileToSave = `${path}/graphs/savedFile.json`
  // parses graph and stores it as an object
  const fullgraph = cy.json()
  jsonfile.writeFile(fileToSave, fullgraph, (err) => {
    if (err) {
      throw err
    }
  })
  printChat('graph saved 👍')
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
  View,
  Image,
  NativeModules,
  requireNativeComponent,
  ViewPropTypes,
  StyleSheet,
} from 'react-native'

const resolveAssetSource = require('react-native/Libraries/Image/resolveAssetSource')

const FastImageViewNativeModule = NativeModules.FastImageView

class FastImage extends Component {
  setNativeProps(nativeProps) {
    this._root.setNativeProps(nativeProps)
  }

  render() {
    const {
      source,
      onLoadStart,
      onProgress,
      onLoad,
      onError,
      onLoadEnd,
      style,
      children,
      borderRadius,
      ...props
    } = this.props

    // If there's no source or source uri just fallback to Image.
    if (!source || !source.uri) {
      return (
        <Image
          ref={e => (this._root = e)}
          {...props}
          source={source}
          onLoadStart={onLoadStart}
          onProgress={onProgress}
          onLoad={onLoad}
          onError={onError}
          onLoadEnd={onLoadEnd}
          style={style}
        />
      )
    }

    const resolvedSource = resolveAssetSource(source)

    if (children) {
      throw new Error(
        'The <FastImage> component cannot contain children. If you want to render content on top of the image consider using absolute positioning.',
      )
    }

    if (!borderRadius) {
      return (
        <FastImageView
          ref={e => (this._root = e)}
          {...props}
          style={style}
          source={resolvedSource}
          onFastImageLoadStart={onLoadStart}
          onFastImageProgress={onProgress}
          onFastImageLoad={onLoad}
          onFastImageError={onError}
          onFastImageLoadEnd={onLoadEnd}
        />
      )
    }

    return (
      <View style={[style, styles.imageContainer]} borderRadius={borderRadius}>
        <FastImageView
          ref={e => (this._root = e)}
          {...props}
          style={StyleSheet.absoluteFill}
          source={resolvedSource}
          onFastImageLoadStart={onLoadStart}
          onFastImageProgress={onProgress}
          onFastImageLoad={onLoad}
          onFastImageError={onError}
          onFastImageLoadEnd={onLoadEnd}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  imageContainer: {
    overflow: 'hidden',
  },
})

FastImage.resizeMode = {
  contain: 'contain',
  cover: 'cover',
  stretch: 'stretch',
  center: 'center',
}

FastImage.priority = {
  low: 'low',
  normal: 'normal',
  high: 'high',
}

FastImage.preload = sources => {
  FastImageViewNativeModule.preload(sources)
}

FastImage.defaultProps = {
  resizeMode: FastImage.resizeMode.cover,
}

const FastImageSourcePropType = PropTypes.shape({
  uri: PropTypes.string,
  headers: PropTypes.objectOf(PropTypes.string),
  priority: PropTypes.oneOf(Object.keys(FastImage.priority)),
})

FastImage.propTypes = {
  ...ViewPropTypes,
  source: PropTypes.oneOfType([FastImageSourcePropType, PropTypes.number]),
  onLoadStart: PropTypes.func,
  onProgress: PropTypes.func,
  onLoad: PropTypes.func,
  onError: PropTypes.func,
  onLoadEnd: PropTypes.func,
}

const FastImageView = requireNativeComponent('FastImageView', FastImage, {
  nativeOnly: {
    onFastImageLoadStart: true,
    onFastImageProgress: true,
    onFastImageLoad: true,
    onFastImageError: true,
    onFastImageLoadEnd: true,
  },
})

export default FastImage
<commit_msg>Fix prop order to be consistent.<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
  View,
  Image,
  NativeModules,
  requireNativeComponent,
  ViewPropTypes,
  StyleSheet,
} from 'react-native'

const resolveAssetSource = require('react-native/Libraries/Image/resolveAssetSource')

const FastImageViewNativeModule = NativeModules.FastImageView

class FastImage extends Component {
  setNativeProps(nativeProps) {
    this._root.setNativeProps(nativeProps)
  }

  render() {
    const {
      source,
      onLoadStart,
      onProgress,
      onLoad,
      onError,
      onLoadEnd,
      style,
      children,
      borderRadius,
      ...props
    } = this.props

    // If there's no source or source uri just fallback to Image.
    if (!source || !source.uri) {
      return (
        <Image
          ref={e => (this._root = e)}
          {...props}
          style={style}
          source={source}
          onLoadStart={onLoadStart}
          onProgress={onProgress}
          onLoad={onLoad}
          onError={onError}
          onLoadEnd={onLoadEnd}
        />
      )
    }

    const resolvedSource = resolveAssetSource(source)

    if (children) {
      throw new Error(
        'The <FastImage> component cannot contain children. If you want to render content on top of the image consider using absolute positioning.',
      )
    }

    if (!borderRadius) {
      return (
        <FastImageView
          ref={e => (this._root = e)}
          {...props}
          style={style}
          source={resolvedSource}
          onFastImageLoadStart={onLoadStart}
          onFastImageProgress={onProgress}
          onFastImageLoad={onLoad}
          onFastImageError={onError}
          onFastImageLoadEnd={onLoadEnd}
        />
      )
    }

    return (
      <View style={[style, styles.imageContainer]} borderRadius={borderRadius}>
        <FastImageView
          ref={e => (this._root = e)}
          {...props}
          style={StyleSheet.absoluteFill}
          source={resolvedSource}
          onFastImageLoadStart={onLoadStart}
          onFastImageProgress={onProgress}
          onFastImageLoad={onLoad}
          onFastImageError={onError}
          onFastImageLoadEnd={onLoadEnd}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  imageContainer: {
    overflow: 'hidden',
  },
})

FastImage.resizeMode = {
  contain: 'contain',
  cover: 'cover',
  stretch: 'stretch',
  center: 'center',
}

FastImage.priority = {
  low: 'low',
  normal: 'normal',
  high: 'high',
}

FastImage.preload = sources => {
  FastImageViewNativeModule.preload(sources)
}

FastImage.defaultProps = {
  resizeMode: FastImage.resizeMode.cover,
}

const FastImageSourcePropType = PropTypes.shape({
  uri: PropTypes.string,
  headers: PropTypes.objectOf(PropTypes.string),
  priority: PropTypes.oneOf(Object.keys(FastImage.priority)),
})

FastImage.propTypes = {
  ...ViewPropTypes,
  source: PropTypes.oneOfType([FastImageSourcePropType, PropTypes.number]),
  onLoadStart: PropTypes.func,
  onProgress: PropTypes.func,
  onLoad: PropTypes.func,
  onError: PropTypes.func,
  onLoadEnd: PropTypes.func,
}

const FastImageView = requireNativeComponent('FastImageView', FastImage, {
  nativeOnly: {
    onFastImageLoadStart: true,
    onFastImageProgress: true,
    onFastImageLoad: true,
    onFastImageError: true,
    onFastImageLoadEnd: true,
  },
})

export default FastImage
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var assert = require('assert');
var EventEmitter = require('./lib/event_emitter');
var inherits = require('util').inherits;

var errors = require('./errors');

function TChannelRequest(channel, options) {
    options = options || {};
    assert(!options.streamed, "streaming request federation not implemented");
    var self = this;
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.responseEvent = self.defineEvent('response');

    self.channel = channel;
    self.logger = self.channel.logger;
    self.random = self.channel.random;
    self.timers = self.channel.timers;

    self.options = options;

    if (!self.options.retryFlags) {
        self.options.retryFlags = {
            never: false,
            onConnectionError: true,
            onTimeout: false
        };
    }

    self.triedRemoteAddrs = {};
    self.outReqs = [];
    self.timeout = self.options.timeout || TChannelRequest.defaultTimeout;
    self.limit = self.options.retryLimit || TChannelRequest.defaultRetryLimit;
    self.start = 0;
    self.end = 0;
    self.elapsed = 0;
    self.resendSanity = 0;

    self.serviceName = options.serviceName || '';
    self.headers = self.options.headers || {}; // so that as-foo can punch req.headers.X
    self.options.headers = self.headers; // for passing to peer.request(opts) later

    self.arg1 = null;
    self.arg2 = null;
    self.arg3 = null;

    self.err = null;
    self.res = null;

    self.errorEvent.on(self.onError);
    self.responseEvent.on(self.onResponse);
}

inherits(TChannelRequest, EventEmitter);

TChannelRequest.defaultRetryLimit = 5;
TChannelRequest.defaultTimeout = 5000;

TChannelRequest.prototype.type = 'tchannel.request';

TChannelRequest.prototype.onError = function onError(err, self) {
    if (!self.end) self.end = self.timers.now();
    self.err = err;
};

TChannelRequest.prototype.onResponse = function onResponse(res, self) {
    if (!self.end) self.end = self.timers.now();
    self.res = res;
};

TChannelRequest.prototype.hookupStreamCallback = function hookupCallback(callback) {
    throw new Error('not implemented');
};

TChannelRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    if (callback.canStream) {
        return self.hookupStreamCallback(callback);
    }
    var called = false;

    self.errorEvent.on(onError);
    self.responseEvent.on(onResponse);

    function onError(err) {
        if (called) return;
        called = true;
        callback(err, null, null, null);
    }

    function onResponse(res) {
        if (called) return;
        called = true;
        res.withArg23(function gotArg23(err, arg2, arg3) {
            callback(err, res, arg2, arg3);
        });
    }

    return self;
};

TChannelRequest.prototype.choosePeer = function choosePeer() {
    var self = this;
    return self.channel.peers.choosePeer(self, self.options);
};

TChannelRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    self.arg1 = arg1;
    self.arg2 = arg2;
    self.arg3 = arg3;
    if (callback) {
        self.hookupCallback(callback);
    }
    self.start = self.timers.now();
    self.resendSanity = self.limit + 1;
    self.resend();
};

TChannelRequest.prototype.resend = function resend() {
    var self = this;

    if (self.checkTimeout()) return;

    var peer = self.choosePeer();
    if (!peer) {
        if (self.outReqs.length) {
            var lastReq = self.outReqs[self.outReqs.length - 1];
            if (lastReq.err) {
                self.errorEvent.emit(self, lastReq.err);
            } else {
                self.responseEvent.emit(self, lastReq.res);
            }
        } else {
            self.errorEvent.emit(self, errors.NoPeerAvailable());
        }
        return;
    }

    if (self.checkTimeout()) return;

    var opts = {};
    var keys = Object.keys(self.options);
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        opts[key] = self.options[key];
    }
    opts.timeout = self.timeout - self.elapsed;
    var outReq = peer.request(opts);
    self.outReqs.push(outReq);

    self.triedRemoteAddrs[outReq.remoteAddr] = (self.triedRemoteAddrs[outReq.remoteAddr] || 0) + 1;
    outReq.responseEvent.on(onResponse);
    outReq.errorEvent.on(onError);
    outReq.send(self.arg1, self.arg2, self.arg3);

    function onError(err) {
        self.onSubreqError(err);
    }

    function onResponse(res) {
        self.onSubreqResponse(res);
    }
};

TChannelRequest.prototype.onSubreqError = function onSubreqError(err) {
    var self = this;
    if (self.checkTimeout(err)) return;
    if (self.shouldRetryError(err)) {
        self.deferResend();
    } else {
        self.errorEvent.emit(self, err);
    }
};

TChannelRequest.prototype.onSubreqResponse = function onSubreqResponse(res) {
    var self = this;
    if (self.checkTimeout(null, res)) return;
    if (res.ok) {
        self.responseEvent.emit(self, res);
    } else {
        self.shouldRetry(null, res, function decided(err, should) {
            if (err) {
                self.errorEvent.emit(self, err);
            } else if (should) {
                self.deferResend();
            } else {
                self.responseEvent.emit(self, res);
            }
        });
    }
};

TChannelRequest.prototype.deferResend = function deferResend() {
    var self = this;
    if (--self.resendSanity <= 0) {
        self.errorEvent.emit(self, new Error('TChannelRequest out of resend sanity'));
    } else {
        process.nextTick(doResend);
    }
    function doResend() {
        self.resend();
    }
};

TChannelRequest.prototype.checkTimeout = function checkTimeout(err, res) {
    var self = this;
    var now = self.timers.now();
    self.elapsed = now - self.start;
    if (self.elapsed < self.timeout) return false;
    if (err) {
        if (!self.err) {
            self.errorEvent.emit(self, err);
        }
    } else if (res) {
        if (!self.err && !self.res) {
            self.responseEvent.emit(self, res);
        }
    } else if (!self.err) {
        self.errorEvent.emit(self, errors.TimeoutError({
            start: self.start,
            elapsed: self.elapsed,
            timeout: self.timeout
        }));
    }
    return true;
};

TChannelRequest.prototype.shouldRetryError = function shouldRetryError(err) {
    var self = this;

    if (self.outReqs.length >= self.limit) {
        return false;
    }

    if (self.options.retryFlags.never) {
        return false;
    }

    if (err) {
        switch (err.type) {
            case 'tchannel.bad-request':
            case 'tchannel.canceled':
                return false;

            case 'tchannel.busy':
            case 'tchannel.declined':
                return true;

            case 'tchannel.timeout':
                return !!self.options.retryFlags.onTimeout;

            case 'tchannel.socket':
            case 'tchannel.socket-closed':
            case 'tchannel.network':
            case 'tchannel.protocol':
            case 'tchannel.unexpected':
                return !!self.options.retryFlags.onConnectionError;

            default:
                self.logger.error('unknown error type in request retry', {
                    error: err
                });
                return true;
        }
    }

    return false;
};

TChannelRequest.prototype.shouldRetry = function shouldRetry(err, res, callback) {
    var self = this;

    if (self.shouldRetryError(err)) {
        callback(null, true);
        return;
    }

    res.withArg23(function onArg23(err, arg2, arg3) {
        if (self.checkTimeout(err, res)) return;
        if (err) {
            callback(err, null);
        } else if (self.options.shouldApplicationRetry) {
            callback(null, self.options.shouldApplicationRetry(self, res, arg2, arg3));
        } else {
            callback(null, false);
        }
    });
};

module.exports = TChannelRequest;
<commit_msg>TChannelRequest: refactor #shouldRetry => #maybeAppRetry<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var assert = require('assert');
var EventEmitter = require('./lib/event_emitter');
var inherits = require('util').inherits;

var errors = require('./errors');

function TChannelRequest(channel, options) {
    options = options || {};
    assert(!options.streamed, "streaming request federation not implemented");
    var self = this;
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.responseEvent = self.defineEvent('response');

    self.channel = channel;
    self.logger = self.channel.logger;
    self.random = self.channel.random;
    self.timers = self.channel.timers;

    self.options = options;

    if (!self.options.retryFlags) {
        self.options.retryFlags = {
            never: false,
            onConnectionError: true,
            onTimeout: false
        };
    }

    self.triedRemoteAddrs = {};
    self.outReqs = [];
    self.timeout = self.options.timeout || TChannelRequest.defaultTimeout;
    self.limit = self.options.retryLimit || TChannelRequest.defaultRetryLimit;
    self.start = 0;
    self.end = 0;
    self.elapsed = 0;
    self.resendSanity = 0;

    self.serviceName = options.serviceName || '';
    self.headers = self.options.headers || {}; // so that as-foo can punch req.headers.X
    self.options.headers = self.headers; // for passing to peer.request(opts) later

    self.arg1 = null;
    self.arg2 = null;
    self.arg3 = null;

    self.err = null;
    self.res = null;

    self.errorEvent.on(self.onError);
    self.responseEvent.on(self.onResponse);
}

inherits(TChannelRequest, EventEmitter);

TChannelRequest.defaultRetryLimit = 5;
TChannelRequest.defaultTimeout = 5000;

TChannelRequest.prototype.type = 'tchannel.request';

TChannelRequest.prototype.onError = function onError(err, self) {
    if (!self.end) self.end = self.timers.now();
    self.err = err;
};

TChannelRequest.prototype.onResponse = function onResponse(res, self) {
    if (!self.end) self.end = self.timers.now();
    self.res = res;
};

TChannelRequest.prototype.hookupStreamCallback = function hookupCallback(callback) {
    throw new Error('not implemented');
};

TChannelRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    if (callback.canStream) {
        return self.hookupStreamCallback(callback);
    }
    var called = false;

    self.errorEvent.on(onError);
    self.responseEvent.on(onResponse);

    function onError(err) {
        if (called) return;
        called = true;
        callback(err, null, null, null);
    }

    function onResponse(res) {
        if (called) return;
        called = true;
        res.withArg23(function gotArg23(err, arg2, arg3) {
            callback(err, res, arg2, arg3);
        });
    }

    return self;
};

TChannelRequest.prototype.choosePeer = function choosePeer() {
    var self = this;
    return self.channel.peers.choosePeer(self, self.options);
};

TChannelRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    self.arg1 = arg1;
    self.arg2 = arg2;
    self.arg3 = arg3;
    if (callback) {
        self.hookupCallback(callback);
    }
    self.start = self.timers.now();
    self.resendSanity = self.limit + 1;
    self.resend();
};

TChannelRequest.prototype.resend = function resend() {
    var self = this;

    if (self.checkTimeout()) return;

    var peer = self.choosePeer();
    if (!peer) {
        if (self.outReqs.length) {
            var lastReq = self.outReqs[self.outReqs.length - 1];
            if (lastReq.err) {
                self.errorEvent.emit(self, lastReq.err);
            } else {
                self.responseEvent.emit(self, lastReq.res);
            }
        } else {
            self.errorEvent.emit(self, errors.NoPeerAvailable());
        }
        return;
    }

    if (self.checkTimeout()) return;

    var opts = {};
    var keys = Object.keys(self.options);
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        opts[key] = self.options[key];
    }
    opts.timeout = self.timeout - self.elapsed;
    var outReq = peer.request(opts);
    self.outReqs.push(outReq);

    self.triedRemoteAddrs[outReq.remoteAddr] = (self.triedRemoteAddrs[outReq.remoteAddr] || 0) + 1;
    outReq.responseEvent.on(onResponse);
    outReq.errorEvent.on(onError);
    outReq.send(self.arg1, self.arg2, self.arg3);

    function onError(err) {
        self.onSubreqError(err);
    }

    function onResponse(res) {
        self.onSubreqResponse(res);
    }
};

TChannelRequest.prototype.onSubreqError = function onSubreqError(err) {
    var self = this;
    if (self.checkTimeout(err)) return;
    if (self.shouldRetryError(err)) {
        self.deferResend();
    } else {
        self.errorEvent.emit(self, err);
    }
};

TChannelRequest.prototype.onSubreqResponse = function onSubreqResponse(res) {
    var self = this;
    if (self.checkTimeout(null, res)) return;
    if (res.ok) {
        self.responseEvent.emit(self, res);
    } else {
        self.maybeAppRetry(res, function decided(err, should) {
            if (err) {
                self.errorEvent.emit(self, err);
            } else if (should) {
                self.deferResend();
            } else {
                self.responseEvent.emit(self, res);
            }
        });
    }
};

TChannelRequest.prototype.deferResend = function deferResend() {
    var self = this;
    if (--self.resendSanity <= 0) {
        self.errorEvent.emit(self, new Error('TChannelRequest out of resend sanity'));
    } else {
        process.nextTick(doResend);
    }
    function doResend() {
        self.resend();
    }
};

TChannelRequest.prototype.checkTimeout = function checkTimeout(err, res) {
    var self = this;
    var now = self.timers.now();
    self.elapsed = now - self.start;
    if (self.elapsed < self.timeout) return false;
    if (err) {
        if (!self.err) {
            self.errorEvent.emit(self, err);
        }
    } else if (res) {
        if (!self.err && !self.res) {
            self.responseEvent.emit(self, res);
        }
    } else if (!self.err) {
        self.errorEvent.emit(self, errors.TimeoutError({
            start: self.start,
            elapsed: self.elapsed,
            timeout: self.timeout
        }));
    }
    return true;
};

TChannelRequest.prototype.shouldRetryError = function shouldRetryError(err) {
    var self = this;

    if (self.outReqs.length >= self.limit) {
        return false;
    }

    if (self.options.retryFlags.never) {
        return false;
    }

    if (err) {
        switch (err.type) {
            case 'tchannel.bad-request':
            case 'tchannel.canceled':
                return false;

            case 'tchannel.busy':
            case 'tchannel.declined':
                return true;

            case 'tchannel.timeout':
                return !!self.options.retryFlags.onTimeout;

            case 'tchannel.socket':
            case 'tchannel.socket-closed':
            case 'tchannel.network':
            case 'tchannel.protocol':
            case 'tchannel.unexpected':
                return !!self.options.retryFlags.onConnectionError;

            default:
                self.logger.error('unknown error type in request retry', {
                    error: err
                });
                return true;
        }
    }

    return false;
};

TChannelRequest.prototype.maybeAppRetry = function maybeAppRetry(res, callback) {
    var self = this;

    res.withArg23(function onArg23(err, arg2, arg3) {
        if (self.checkTimeout(err, res)) return;
        if (err) {
            callback(err, null);
        } else if (self.options.shouldApplicationRetry) {
            callback(null, self.options.shouldApplicationRetry(self, res, arg2, arg3));
        } else {
            callback(null, false);
        }
    });
};

module.exports = TChannelRequest;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

/* GET cards listing. */
router.get('/', function (req, res, next) {
    var allowedOrigins = ['http://localhost', 'http://localhost:4200'];
    var origin = req.headers.origin;
    if (allowedOrigins.indexOf(origin) > -1) {
        res.set('Access-Control-Allow-Origin', origin);
    }
    var page = req.query.page ? req.query.page : 1;
    var pageSize = req.query.pageSize ? req.query.pageSize : 10;
    global.db.collection("cards").find().skip((page - 1) * pageSize).limit(pageSize).toArray(function (err, result) { // 返回集合中所有数据
        if (err) throw err;
        console.log("成功连接cards");
        console.log(result);
        res.json(result);
    });
});

/* GET users listing. */
router.get('/1', function (req, res, next) {
    // res.send('respond with a resource');
    res.json({user: 1});
});

module.exports = router;
<commit_msg>Allowed turning page<commit_after>var express = require('express');
var router = express.Router();

/* GET cards listing. */
router.get('/', function (req, res, next) {
    var allowedOrigins = ['http://localhost', 'http://localhost:4200'];
    var origin = req.headers.origin;
    if (allowedOrigins.indexOf(origin) > -1) {
        res.set('Access-Control-Allow-Origin', origin);
    }
    var page = req.query.page ? Number(req.query.page) : 1;
    var pageSize = req.query.pageSize ? Number(req.query.pageSize) : 10;
    global.db.collection("cards").find().skip((page - 1) * pageSize).limit(pageSize).toArray(function (err, result) { // 返回集合中所有数据
        if (err) throw err;
        console.log("成功连接cards");
        console.log(result);
        res.json(result);
    });
});

/* GET users listing. */
router.get('/1', function (req, res, next) {
    // res.send('respond with a resource');
    res.json({user: 1});
});

module.exports = router;
<|endoftext|>


<commit_before>var express     = require("express");
var router      = express.Router();
var blog        = require("../models/blog");

/**
 * Render Login Page
 * if auth redirect to blogs
 */
router.get("/login", function authenticatedOrNot(req, res, next) {
    if(req.isAuthenticated()) {
        res.redirect("/admin#/blogs");
    } else {
        next();
    }}, function(req, res) {
    res.render("admin/login", { message: req.flash('error') });
});

/**
 * Logout
 */
router.get("/logout", function(req, res) {
    req.logout();

    res.redirect("/login");
});

/**
 * Render Main Page
 */
router.get("/", function(req, res) {
    blog.find(function(err, blogs) {
        if(err) throw(err);

        res.render("client/index", {
            title: "Dimitri Mikadze",
            blogs: blogs,
            desc: "Dimitri Mikadze Personal Blog",
            url: "/"
        });
    });
});

/**
 * Render blog by url param id
 */
router.get("/blog/programming/:name/:id", function(req, res) {

    var name = req.params.name;
    var id = req.params.id;

    blog.findById(id, function(req, blog) {
       res.render("client/blog/blog", {
           title: name.replace("-", " "),
           blog: blog,
           desc: blog.short_desc,
           url: "/blog/" + name + "/" + id
       })
    });
});

// ===========================================
//                  Demos
// ===========================================

router.get("/demos/vanilla-slideshow", function(req, res) {
    res.render("demos/vanilla-slideshow.html");
});

/**
 * Download vanilla slideshow
 */
router.get("/download-vanilla-slideshow", function(req, res) {
    res.download("../client/views/demos/vanilla-slideshow.rar");
});

module.exports = router;<commit_msg>change routes<commit_after>var express     = require("express");
var router      = express.Router();
var blog        = require("../models/blog");

/**
 * Render Login Page
 * if auth redirect to blogs
 */
router.get("/login", function authenticatedOrNot(req, res, next) {
    if(req.isAuthenticated()) {
        res.redirect("/admin#/blogs");
    } else {
        next();
    }}, function(req, res) {
    res.render("admin/login", { message: req.flash('error') });
});

/**
 * Logout
 */
router.get("/logout", function(req, res) {
    req.logout();

    res.redirect("/login");
});

/**
 * Render Main Page
 */
router.get("/", function(req, res) {
    blog.find({}).sort({created_at: 'desc'}).exec(function(err, blogs) {
        if(err) throw(err);

        res.render("client/index", {
            title: "Dimitri Mikadze",
            blogs: blogs,
            desc: "Dimitri Mikadze Personal Blog",
            url: "/"
        });
    });
});

/**
 * Render blog by url param id
 */
router.get("/blog/programming/:name/:id", function(req, res) {

    var name = req.params.name;
    var id = req.params.id;

    blog.findById(id, function(req, blog) {
       res.render("client/blog/blog", {
           title: name.replace("-", " "),
           blog: blog,
           desc: blog.short_desc,
           url: "/blog/" + name + "/" + id
       })
    });
});

// ========================================================
//                          Demos
// ========================================================

router.get("/demos/vanilla-slideshow", function(req, res) {
    res.render("demos/vanilla-slideshow.html");
});

/**
 * Download vanilla slideshow
 */
router.get("/download-vanilla-slideshow", function(req, res) {
    res.download("../client/views/demos/vanilla-slideshow.rar");
});

module.exports = router;<|endoftext|>


<commit_before>import path from 'path';

import authentication from '../middleware/authentication';
import DocumentController from '../controllers/DocumentController';
import RoleController from '../controllers/RoleController';
import UserController from '../controllers/UserController';
import SearchController from '../controllers/SearchController';
import AuthController from '../controllers/AuthController';

const Routes = (app) => {
  app.post('/', (req, res) =>
    res.status(200).send({
      message: 'Welcome to E-DocCabinet - A document management API'
    })
  );
  app.get('/', (req, res) =>
    res.status(200).send({
      message: 'Welcome to E-DocCabinet - A document management API'
    })
  );
  // all user routes
  app.post('/api/v1/users/', UserController.signup);
  app.post('/api/v1/users/login', AuthController.login);
  app.use(authentication.verifyUser);
  app.get('/api/v1/users/', UserController.listUsers);
  app.get('/api/v1/users-docs/', UserController.listUsersAndDocuments);
  app.put('/api/v1/users/:userId', UserController.updateUsers);
  app.put('/api/v1/users-role/:userId', UserController.updateUsersRole);
  app.get('/api/v1/users/:userId', UserController.findUsers);
  app.delete('/api/v1/users/:userId', UserController.deleteUsers);
  app.get('/api/v1/search/users/', SearchController.searchUsers);
  app.get('/api/v1/users/:userId/documents/', UserController.findUserDocument);

  // all document routes
  app.post('/api/v1/documents/', DocumentController.newDocument);
  app.get('/api/v1/documents', DocumentController.showDocuments);
  app.put('/api/v1/documents/:documentId', DocumentController.updateDocument);
  app.get('/api/v1/documents/:documentId', DocumentController.findDocument);
  app.get('/api/v1/search/documents/', SearchController.searchDocument);
  app.delete(
    '/api/v1/documents/:documentId',
    DocumentController.deleteDocument
  );

  // all Role routes
  app.post('/api/v1/roles/', RoleController.newRole);
  app.get('/api/v1/roles', RoleController.listRoles);
  app.get('/api/v1/roles-users/', RoleController.listRolesAndUsers);

  app.use('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '../../public', 'index.html'));
  });
};
export default Routes;
<commit_msg>chore(fix): fix route naming convention<commit_after>import path from 'path';

import authentication from '../middleware/authentication';
import documentController from '../controllers/documentController';
import roleController from '../controllers/roleController';
import userController from '../controllers/userController';
import searchController from '../controllers/searchController';
import authController from '../controllers/authController';

const routes = (app) => {
  app.post('/', (req, res) =>
    res.status(200).send({
      message: 'Welcome to E-DocCabinet - A document management API'
    })
  );
  app.get('/', (req, res) =>
    res.status(200).send({
      message: 'Welcome to E-DocCabinet - A document management API'
    })
  );
  // all user routes
  app.post('/api/v1/users/', userController.signup);
  app.post('/api/v1/users/login', authController.login);
  app.use(authentication.verifyUser);
  app.get('/api/v1/users/', userController.listUsers);
  app.get('/api/v1/users-docs/', userController.listUsersAndDocuments);
  app.put('/api/v1/users/:userId', userController.updateUsers);
  app.put('/api/v1/users-role/:userId', userController.updateUsersRole);
  app.get('/api/v1/users/:userId', userController.findUsers);
  app.delete('/api/v1/users/:userId', userController.deleteUsers);
  app.get('/api/v1/search/users/', searchController.searchUsers);
  app.get('/api/v1/users/:userId/documents/', userController.findUserDocument);

  // all document routes
  app.post('/api/v1/documents/', documentController.newDocument);
  app.get('/api/v1/documents', documentController.showDocuments);
  app.put('/api/v1/documents/:documentId', documentController.updateDocument);
  app.get('/api/v1/documents/:documentId', documentController.findDocument);
  app.get('/api/v1/search/documents/', searchController.searchDocument);
  app.delete(
    '/api/v1/documents/:documentId',
    documentController.deleteDocument
  );

  // all Role routes
  app.post('/api/v1/roles/', roleController.newRole);
  app.get('/api/v1/roles', roleController.listRoles);
  app.get('/api/v1/roles-users/', roleController.listRolesAndUsers);

  app.use('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '../../public', 'index.html'));
  });
};
export default routes;
<|endoftext|>


<commit_before>'use strict';

var watch = require('express').Router();

var fs = require('fs');
var path = require('path');
var memoConfig = require('../config').memoConfig;

var enableWatch = process.env.WATCH && process.env.WATCH === 'true';
var watchType = process.env._system_name === 'OSX';

watch.start = function (server) {
  var io = require('socket.io').listen(server, {'log level': 0});
  io.sockets.on('connection', function (socket) {
    var watcher = null;

    socket.on('watch', function (file) {
      socket.set('file', file, function () {
        startWatching(watcher, socket, path.join(memoConfig.dir, file));
        sendMemo(socket);
      });
    });

    socket.on('save', function (data) {
      fs.writeFile(path.join(memoConfig.dir, data.file), data.memo.content, function (err) {
        if (err) {
          throw err;
        }
      });
    });

    socket.on('disconnect', function () {
      stopWatching(watcher);
    });
  });
};

function startWatching (watcher, socket, fileName) {
  if (!enableWatch) {
    return;
  }

  stopWatching(watcher);

  if (!fs.existsSync(fileName)) {
    return;
  }

  if (watchType) {
    try {
      watcher = fs.watch(fileName, {persistent: true}, function () {
        sendMemo(socket);
        startWatching(watcher, socket, fileName);
      });
    } catch (e) {
      console.log(e);
    }
  } else {
    fs.watchFile(fileName, {persistent: true, interval: 1000}, function () {
      sendMemo(socket);
    });
    watcher = fileName;
  }
}

function stopWatching (watcher) {
  if (watcher) {
    if (watchType) {
      watcher.close();
    } else {
      fs.unwatchFile(watcher);
    }

    watcher = null;
  }
}

function sendMemo (socket) {
  socket.get('file', function (err, file) {
    fs.readFile(path.join(memoConfig.dir, file), function (err, data) {
      if (data) {
        socket.emit('memo', {
          title: 'Title',
          content: data.toString()
        });
      }
    });
  });
}

watch.get(/^(.*)$/, function (req, res) {
  var file = req.params[0];
  console.log(file);

  res.send();
});

module.exports.watch = watch;
<commit_msg>Minor change<commit_after>'use strict';

var watch = require('express').Router();

var fs = require('fs');
var path = require('path');
var memoConfig = require('../config').memoConfig;

var enableWatch = process.env.WATCH && process.env.WATCH === 'true';
var watchType = process.env._system_name === 'OSX';

watch.start = function (server) {
  var io = require('socket.io').listen(server, {'log level': 0});
  io.sockets.on('connection', function (socket) {
    var watcher = null;

    socket.on('watch', function (file) {
      socket.set('file', file, function () {
        startWatching(watcher, socket, path.join(memoConfig.dir, file));
        sendMemo(socket);
      });
    });

    socket.on('save', function (data) {
      fs.writeFile(path.join(memoConfig.dir, data.file), data.memo.content, function (err) {
        if (err) {
          throw err;
        }
      });
    });

    socket.on('disconnect', function () {
      stopWatching(watcher);
    });
  });
};

function startWatching (watcher, socket, fileName) {
  if (!enableWatch) {
    return;
  }

  if (!fs.existsSync(fileName)) {
    return;
  }

  if (watchType) {
    try {
      watcher = fs.watch(fileName, {persistent: true}, function () {
        sendMemo(socket);

        stopWatching(watcher);
        startWatching(watcher, socket, fileName);
      });
    } catch (e) {
      console.log(e);
    }
  } else {
    fs.watchFile(fileName, {persistent: true, interval: 1000}, function () {
      sendMemo(socket);
    });
    watcher = fileName;
  }
}

function stopWatching (watcher) {
  if (watcher) {
    if (watchType) {
      watcher.close();
    } else {
      fs.unwatchFile(watcher);
    }

    watcher = null;
  }
}

function sendMemo (socket) {
  socket.get('file', function (err, file) {
    fs.readFile(path.join(memoConfig.dir, file), function (err, data) {
      if (data) {
        socket.emit('memo', {
          title: 'Title',
          content: data.toString()
        });
      }
    });
  });
}

watch.get(/^(.*)$/, function (req, res) {
  var file = req.params[0];
  console.log(file);

  res.send();
});

module.exports.watch = watch;
<|endoftext|>


<commit_before>const log = require('./lib/Log').getLogger(`server[${process.pid}]`)
const path = require('path')
const config = require('../project.config')
const getIPAddress = require('./lib/getIPAddress')
const http = require('http')
const fs = require('fs')
const { promisify } = require('util')
const parseCookie = require('./lib/parseCookie')
const jwtVerify = require('jsonwebtoken').verify
const Koa = require('koa')
const koaBody = require('koa-body')
const koaFavicon = require('koa-favicon')
const koaLogger = require('koa-logger')
const koaMount = require('koa-mount')
const koaRange = require('koa-range')
const koaStatic = require('koa-static')

const Prefs = require('./Prefs')
const libraryRouter = require('./Library/router')
const mediaRouter = require('./Media/router')
const prefsRouter = require('./Prefs/router')
const roomsRouter = require('./Rooms/router')
const userRouter = require('./User/router')
const SocketIO = require('socket.io')
const socketActions = require('./socket')
const IPC = require('./lib/IPCBridge')
const IPCLibraryActions = require('./Library/ipc')
const IPCMediaActions = require('./Media/ipc')
const {
  SERVER_WORKER_STATUS,
  SERVER_WORKER_ERROR,
} = require('../shared/actionTypes')

async function serverWorker ({ env, startScanner, stopScanner }) {
  const jwtKey = await Prefs.getJwtKey()
  const app = new Koa()

  // server error handler
  app.on('error', (err, ctx) => {
    if (err.code === 'EPIPE') {
      // these are common since browsers make multiple requests for media files
      log.verbose(err.message)
      return
    }

    // silence 4xx response "errors" (koa-logger should show these anyway)
    if (ctx.response && ctx.response.status.toString().startsWith('4')) {
      return
    }

    if (err.stack) log.error(err.stack)
    else log.error(err)
  })

  // middleware error handler
  app.use(async (ctx, next) => {
    try {
      await next()
    } catch (err) {
      ctx.status = err.status || 500
      ctx.body = err.message
      ctx.app.emit('error', err, ctx)
    }
  })

  // http request/response logging
  app.use(koaLogger((str, args) => (args.length === 6 && args[3] >= 500) ? log.error(str) : log.verbose(str)))

  app.use(koaFavicon(path.join(config.assetPath, 'favicon.ico')))
  app.use(koaRange)
  app.use(koaBody({ multipart: true }))

  // all http requests
  app.use(async (ctx, next) => {
    ctx.io = io
    ctx.jwtKey = jwtKey
    ctx.startScanner = startScanner
    ctx.stopScanner = stopScanner

    // verify jwt
    try {
      const { kfToken } = parseCookie(ctx.request.header.cookie)
      ctx.user = jwtVerify(kfToken, jwtKey)
    } catch (err) {
      ctx.user = {
        userId: null,
        username: null,
        name: null,
        isAdmin: false,
        roomId: null,
      }
    }

    await next()
  })

  // http api (koa-router) endpoints
  app.use(libraryRouter.routes())
  app.use(mediaRouter.routes())
  app.use(prefsRouter.routes())
  app.use(roomsRouter.routes())
  app.use(userRouter.routes())

  // @todo these could be read dynamically from src/routes
  // but should probably wait for react-router upgrade?
  const rewriteRoutes = ['account', 'library', 'queue', 'player']
  const indexFile = path.join(config.buildPath, 'index.html')

  if (env.NODE_ENV === 'development') {
    log.info('Enabling webpack dev and HMR middleware')
    const webpack = require('webpack')
    const webpackConfig = require('../webpack.config')
    const compiler = webpack(webpackConfig)
    const koaWebpack = require('koa-webpack')

    koaWebpack({ compiler })
      .then((middleware) => {
        // webpack-dev-middleware and webpack-hot-client
        app.use(middleware)

        // serve /assets since webpack-dev-server is unaware of this folder
        app.use(koaMount('/assets', koaStatic(config.assetPath)))

        // "rewrite" top level SPA routes to index.html
        app.use(async (ctx, next) => {
          const route = ctx.request.path.substring(1).split('/')[0]
          if (!rewriteRoutes.includes(route)) return next()

          ctx.body = await new Promise(function (resolve, reject) {
            compiler.outputFileSystem.readFile(indexFile, (err, result) => {
              if (err) { return reject(err) }
              return resolve(result)
            })
          })
          ctx.set('content-type', 'text/html')
          ctx.status = 200
        })
      })
  } else {
    // production mode
    // serve build folder as webroot
    app.use(koaStatic(config.buildPath))
    app.use(koaMount('/assets', koaStatic(config.assetPath)))

    // "rewrite" top level SPA routes to index.html
    const readFile = promisify(fs.readFile)

    app.use(async (ctx, next) => {
      const route = ctx.request.path.substring(1).split('/')[0]
      if (!rewriteRoutes.includes(route)) return next()

      ctx.body = await readFile(indexFile)
      ctx.set('content-type', 'text/html')
      ctx.status = 200
    })
  } // end if

  // create http server
  const server = http.createServer(app.callback())

  // http server error handler
  server.on('error', function (err) {
    log.error(err)

    process.emit('serverWorker', {
      type: SERVER_WORKER_ERROR,
      error: err.message,
    })

    // not much we can do without a working server
    process.exit(1)
  })

  // create socket.io server and attach handlers
  const io = new SocketIO(server)
  socketActions(io, jwtKey)

  // attach IPC action handlers
  IPC.use(IPCLibraryActions(io))
  IPC.use(IPCMediaActions(io))

  log.info(`Starting web server (host=${env.KF_SERVER_HOST}; port=${env.KF_SERVER_PORT})`)

  // success callback in 3rd arg
  server.listen(env.KF_SERVER_PORT, env.KF_SERVER_HOST, () => {
    const port = server.address().port
    const url = `http://${getIPAddress()}` + (port === 80 ? '' : ':' + port)
    log.info(`Web server running at ${url}`)

    process.emit('serverWorker', {
      type: SERVER_WORKER_STATUS,
      payload: { url },
    })
  })
}

module.exports = serverWorker
<commit_msg>Skip server listen() if we're only scanning<commit_after>const log = require('./lib/Log').getLogger(`server[${process.pid}]`)
const path = require('path')
const config = require('../project.config')
const getIPAddress = require('./lib/getIPAddress')
const http = require('http')
const fs = require('fs')
const { promisify } = require('util')
const parseCookie = require('./lib/parseCookie')
const jwtVerify = require('jsonwebtoken').verify
const Koa = require('koa')
const koaBody = require('koa-body')
const koaFavicon = require('koa-favicon')
const koaLogger = require('koa-logger')
const koaMount = require('koa-mount')
const koaRange = require('koa-range')
const koaStatic = require('koa-static')

const Prefs = require('./Prefs')
const libraryRouter = require('./Library/router')
const mediaRouter = require('./Media/router')
const prefsRouter = require('./Prefs/router')
const roomsRouter = require('./Rooms/router')
const userRouter = require('./User/router')
const SocketIO = require('socket.io')
const socketActions = require('./socket')
const IPC = require('./lib/IPCBridge')
const IPCLibraryActions = require('./Library/ipc')
const IPCMediaActions = require('./Media/ipc')
const {
  SERVER_WORKER_STATUS,
  SERVER_WORKER_ERROR,
} = require('../shared/actionTypes')

async function serverWorker ({ env, startScanner, stopScanner }) {
  const jwtKey = await Prefs.getJwtKey()
  const app = new Koa()

  // server error handler
  app.on('error', (err, ctx) => {
    if (err.code === 'EPIPE') {
      // these are common since browsers make multiple requests for media files
      log.verbose(err.message)
      return
    }

    // silence 4xx response "errors" (koa-logger should show these anyway)
    if (ctx.response && ctx.response.status.toString().startsWith('4')) {
      return
    }

    if (err.stack) log.error(err.stack)
    else log.error(err)
  })

  // middleware error handler
  app.use(async (ctx, next) => {
    try {
      await next()
    } catch (err) {
      ctx.status = err.status || 500
      ctx.body = err.message
      ctx.app.emit('error', err, ctx)
    }
  })

  // http request/response logging
  app.use(koaLogger((str, args) => (args.length === 6 && args[3] >= 500) ? log.error(str) : log.verbose(str)))

  app.use(koaFavicon(path.join(config.assetPath, 'favicon.ico')))
  app.use(koaRange)
  app.use(koaBody({ multipart: true }))

  // all http requests
  app.use(async (ctx, next) => {
    ctx.io = io
    ctx.jwtKey = jwtKey
    ctx.startScanner = startScanner
    ctx.stopScanner = stopScanner

    // verify jwt
    try {
      const { kfToken } = parseCookie(ctx.request.header.cookie)
      ctx.user = jwtVerify(kfToken, jwtKey)
    } catch (err) {
      ctx.user = {
        userId: null,
        username: null,
        name: null,
        isAdmin: false,
        roomId: null,
      }
    }

    await next()
  })

  // http api (koa-router) endpoints
  app.use(libraryRouter.routes())
  app.use(mediaRouter.routes())
  app.use(prefsRouter.routes())
  app.use(roomsRouter.routes())
  app.use(userRouter.routes())

  // @todo these could be read dynamically from src/routes
  // but should probably wait for react-router upgrade?
  const rewriteRoutes = ['account', 'library', 'queue', 'player']
  const indexFile = path.join(config.buildPath, 'index.html')

  if (env.NODE_ENV === 'development') {
    log.info('Enabling webpack dev and HMR middleware')
    const webpack = require('webpack')
    const webpackConfig = require('../webpack.config')
    const compiler = webpack(webpackConfig)
    const koaWebpack = require('koa-webpack')

    koaWebpack({ compiler })
      .then((middleware) => {
        // webpack-dev-middleware and webpack-hot-client
        app.use(middleware)

        // serve /assets since webpack-dev-server is unaware of this folder
        app.use(koaMount('/assets', koaStatic(config.assetPath)))

        // "rewrite" top level SPA routes to index.html
        app.use(async (ctx, next) => {
          const route = ctx.request.path.substring(1).split('/')[0]
          if (!rewriteRoutes.includes(route)) return next()

          ctx.body = await new Promise(function (resolve, reject) {
            compiler.outputFileSystem.readFile(indexFile, (err, result) => {
              if (err) { return reject(err) }
              return resolve(result)
            })
          })
          ctx.set('content-type', 'text/html')
          ctx.status = 200
        })
      })
  } else {
    // production mode
    // serve build folder as webroot
    app.use(koaStatic(config.buildPath))
    app.use(koaMount('/assets', koaStatic(config.assetPath)))

    // "rewrite" top level SPA routes to index.html
    const readFile = promisify(fs.readFile)

    app.use(async (ctx, next) => {
      const route = ctx.request.path.substring(1).split('/')[0]
      if (!rewriteRoutes.includes(route)) return next()

      ctx.body = await readFile(indexFile)
      ctx.set('content-type', 'text/html')
      ctx.status = 200
    })
  } // end if

  // create http server
  const server = http.createServer(app.callback())

  // http server error handler
  server.on('error', function (err) {
    log.error(err)

    process.emit('serverWorker', {
      type: SERVER_WORKER_ERROR,
      error: err.message,
    })

    // not much we can do without a working server
    process.exit(1)
  })

  // create socket.io server and attach handlers
  const io = new SocketIO(server)
  socketActions(io, jwtKey)

  // attach IPC action handlers
  IPC.use(IPCLibraryActions(io))
  IPC.use(IPCMediaActions(io))

  // nothing left to do if we're only scanning
  if (env.KF_SERVER_SCAN_ONLY) {
    return
  }

  log.info(`Starting web server (host=${env.KF_SERVER_HOST}; port=${env.KF_SERVER_PORT})`)

  // success callback in 3rd arg
  server.listen(env.KF_SERVER_PORT, env.KF_SERVER_HOST, () => {
    const port = server.address().port
    const url = `http://${getIPAddress()}` + (port === 80 ? '' : ':' + port)
    log.info(`Web server running at ${url}`)

    process.emit('serverWorker', {
      type: SERVER_WORKER_STATUS,
      payload: { url },
    })
  })
}

module.exports = serverWorker
<|endoftext|>