<commit_before>//style
import 'vis/dist/vis.css';
//import 'materialize-css/dist/css/materialize.min.css';
import './App.css';

//react
import React, { Component } from 'react';

//demo data
import demo from './demo.json';

//react components
import { Chip, Tabs, Tab, Footer, Collection, CollectionItem, Row, Col, Preloader, Navbar, NavItem, Icon } from 'react-materialize';
import { Timeline } from './Timeline.js';
import { DataSetItem } from './DataSet.js';
import { FilterView } from './Filter.js';
import { SettingsView } from './Settings.js';

//utility for Caipy (parse JSON data)
import * as ApiUtils from './caipy-api.js';
import * as Storage from './Storage.js';

// jquery & materialize
import $ from 'jquery';
//import $ from 'jquery';
window.$ = window.jQuery = require('jquery');
//window.$ = window.jQuery = $;

require('materialize-css/dist/js/materialize.min.js');
//require('materialize-css/materialize.min.js')

/**
 * Default start date for query in live mode
 * @type {String}
 */
const defaultStartDate = "08/02/2017";

/**
 * Default end date for query in live mode
 * @type {String}
 */
const defaultEndDate = "08/02/2017";

/**
 * Footer component
 */
class FooterView extends Component {
    render() {
        return <Footer className='white-text footer blue darken-1'
                       moreLinks={

                            Copyright (c) 2017 Bertrand Martel

                         }>

    }
}

/**
 * View showing a Loader in the middle of the screen
 */
class ProgressView extends Component {
    render() {
        return <Row className={this.props.value ? "center-div hidden" : "center-div"}>
                    <Col s={12}>
                        <Preloader size="big" color="blue"/>
                    </Col>

{this.props.message}

                </Row>
    }
}

/**
 * The navigation bar
 */
class TopNavbar extends Component {

    /**
     * fit the items in the timeline
     */
    fit() {
        if (typeof this.props.onFit === 'function') {
            this.props.onFit();
        }
    }

    /**
     * update the type of item in the timeline ("point"/"range")
     */
    updateType() {
        if (typeof this.props.onUpdateType === 'function') {
            this.props.onUpdateType();
        }
    }

    /**
     * refresh data (in dataset & in timeline)
     * @param  {String} type refresh type ("create" or "update")
     */
    refresh(type) {
        if (typeof this.props.onRefresh === 'function') {
            this.props.onRefresh(type);
        }
    }

    /**
     * open URL settings view
     */
    urlSettings() {
        if (typeof this.props.onUrlSettings === 'function') {
            this.props.onUrlSettings();
        }
    }

    render() {
        return <Navbar href={process.env.PUBLIC_URL} brand='Caipy Dashboard' className="blue darken-1" right>
                    <NavItem onClick={() => this.fit()}><Icon medium>center_focus_strong</Icon></NavItem>
                    <NavItem onClick={() => this.updateType()}><Icon medium>timeline</Icon></NavItem>
                    <NavItem onClick={() => this.refresh("update")}><Icon>refresh</Icon></NavItem>
                    <NavItem onClick={() => this.urlSettings()}><Chip close={false}>{this.props.mode} mode</Chip></NavItem>
                    <NavItem href="https://github.com/bertrandmartel/caipy-dashboard" target="_blank" ><Icon>code</Icon></NavItem>
                </Navbar>
    }
}

/**
 * Tab view showing the dataset & the timeline
 */
class TabCollection extends Component {

    render() {
        return

                    <Tabs>
                            <Tab title="timeline" active>

                                    <Collection>
                                        {
                                            this.props.items.map(function(value, index){
                                                return (
                                                        <CollectionItem className="coll-item" key={value.channelName + "-coll"}>
                                                            <Timeline key={value.channelName}
                                                                      data={value}
                                                                      actionType={this.props.actionType}
                                                                      itemType={this.props.itemType}/>
                                                        </CollectionItem>
                                               );
                                            },this)
                                        }
                                    </Collection>

                            </Tab>
                            <Tab title="dataset" active>

                                    <Collection>
                                        {
                                            this.props.data.map(function(value, index){
                                                return (
                                                    <DataSetItem key={value.name}
                                                                 name={value.name}
                                                                 rows={value.rows}
                                                                 length={value.rows.length}
                                                                 perPage={15}/>
                                               );
                                            },this)
                                        }
                                    </Collection>

                            </Tab>
                    </Tabs>

    }
}

/**
 * Main app component
 */
class App extends Component {

    /**
     * date filter used to init filter & to be used in query in live mode.
     * @type {Object}
     */
    date = {
        startDate: defaultStartDate,
        endDate: defaultEndDate
    }

    state = {
        ready: false,
        items: [],
        data: [],
        mode: "demo",
        url: Storage.getApiUrl(),
        message: "",
        startDate: this.date.startDate,
        endDate: this.date.endDate
    };

    /**
     * mode can be "demo" or "live"
     * @type {String}
     */
    mode = "demo";

    /**
     * default timeline item type (false for "range" / true for "point")
     * @type {Boolean}
     */
    itemType = false;

    constructor() {
        super();
        this.items = [];
        this.data = [];
        this.checkItemType();
        this.checkDate();
        this.fit = this.fit.bind(this);
        this.refresh = this.refresh.bind(this);
        this.updateType = this.updateType.bind(this);
        this.setUrlSettings = this.setUrlSettings.bind(this);
        this.setMode = this.setMode.bind(this);
        this.setFilterSettings = this.setFilterSettings.bind(this);
    }

    /**
     * initialize dates used in filter & query
     */
    checkDate() {
        var startDate = Storage.getStartDate();
        var endDate = Storage.getEndDate();
        if (startDate !== null && startDate !== "undefined" &&
            endDate !== null && endDate !== "undefined") {
            this.date.startDate = startDate;
            this.date.endDate = endDate;
        }
    }

    /**
     * initiliaze timeline item type
     */
    checkItemType() {
        var type = Storage.getItemType();
        if (type === null) {
            Storage.setItemType(false);
            this.itemType = false;
        } else {
            this.itemType = (type === 'true');
        }
    }

    /**
     * On mount check the mode ("live" or "demo") and refresh the data according to this
     */
    componentDidMount() {
        if (Storage.checkMode() !== null &&
            Storage.checkMode() === "live" &&
            Storage.checkApiUrl()) {
            this.mode = "live";
        } else {
            Storage.setMode("demo");
        }
        this.refresh("create");
    }

    /**
     * Parse the JSON data to build timeline DataSet
     * @param  {Object} data       JSON data object (from query response or from local JSON file)
     * @param  {String} actionType type of action to perform ("create","update","idle")
     */
    parseItems(data, actionType) {
        this.items = ApiUtils.buildItems(data);
        this.data = data;
        this.setState({
            actionType: actionType,
            ready: true,
            data: this.data,
            items: this.items,
            mode: this.mode,
            url: Storage.getApiUrl(),
            message: "",
            startDate: this.date.startDate,
            endDate: this.date.endDate
        });
    }

    /**
     * Refresh the data according to mode
     * @param  {String} actionType type of action to perform ("create","update","idle")
     * @return {[type]}            [description]
     */
    refresh(actionType) {

        var that = this;

        that.setState({
            actionType: "idle",
            ready: false,
            data: that.data,
            items: that.items,
            mode: this.mode,
            url: Storage.getApiUrl(),
            message: "",
            startDate: this.date.startDate,
            endDate: this.date.endDate
        });

        if (this.mode === "live") {
            fetch(Storage.getApiUrl() + "?type=channels&startdate=" + this.date.startDate + "&starttime=00:00:00&" +
                    "enddate=" + this.date.endDate + "&endtime=23:59:59")
                .then(function(response) {
                    if (response.status >= 400) {
                        throw new Error("Bad response from server");
                    }
                    return response.json();
                })
                .then(function(data) {
                    that.parseItems(data, actionType);
                })
                .catch(function(e) {
                    console.log(e);
                    //show error message and set mode to "idle"
                    that.setState({
                        actionType: "idle",
                        ready: false,
                        data: that.data,
                        items: that.items,
                        mode: that.mode,
                        url: Storage.getApiUrl(),
                        message: "error occured",
                        startDate: that.date.startDate,
                        endDate: that.date.endDate
                    });
                });
        } else {
            //in demo mode just parse the raw item
            that.parseItems(demo, actionType);
        }
    }

    /**
     * set settings URL value
     * @param {String} url URL value
     */
    setUrlSettings(url) {
        Storage.setApiUrl(url);
        Storage.setMode("live");
        this.mode = "live";
        this.refresh("update");
    }

    /**
     * Set filter value
     * @param {Date} startDate start date filter
     * @param {Date} endDate   end date filter
     */
    setFilterSettings(startDate, endDate) {
        Storage.setDate(startDate, endDate);
        this.date.startDate = startDate;
        this.date.endDate = endDate;
        this.refresh("update");
    }

    /**
     * Set the mode ("demo" or "live")
     * @param {String} mode the mode
     */
    setMode(mode) {
        Storage.setMode(mode);
        this.mode = mode;
        this.refresh("update");
    }

    /**
     * Open URL settings modal
     */
    urlSettings() {
        $('#url-settings').modal('open');
    }

    /**
     * fit the items in the timeline according to time window or selected items
     */
    fit() {
        this.setState({
            actionType: "fit",
            ready: true,
            data: this.data,
            items: this.items,
            mode: this.mode,
            url: Storage.getApiUrl(),
            message: "",
            startDate: this.date.startDate,
            endDate: this.date.endDate
        })
    }

    /**
     * toggle timeline item type ("range" or "type")
     */
    updateType() {
        this.itemType = !this.itemType;
        Storage.setItemType(this.itemType);
        this.setState({
            actionType: "update-type",
            ready: true,
            data: this.data,
            items: this.items,
            mode: this.mode,
            url: Storage.getApiUrl(),
            message: "",
            startDate: this.date.startDate,
            endDate: this.date.endDate
        });
    }

    render() {
        return (

                    <TopNavbar mode={this.state.mode}
                               onFit={this.fit}
                               onUpdateType={this.updateType}
                               onRefresh={this.refresh}
                               onUrlSettings={this.urlSettings} />
                    <FilterView onSetFilterSettings={this.setFilterSettings}
                                mode={this.state.mode}
                                startDate={this.state.startDate}
                                endDate={this.state.endDate}/>
                    <TabCollection ready={this.state.ready}
                                   items={this.state.items}
                                   data={this.state.data}
                                   actionType={this.state.actionType}
                                   itemType={this.itemType}/>
                    <ProgressView value={this.state.ready}
                                  message={this.state.message}/>
                    <SettingsView mode={this.state.mode}
                                  url={this.state.url}
                                  onSetUrlSettings={this.setUrlSettings}
                                  onSetMode={this.setMode}/>

                <FooterView/>

        );
    }
}

export default App;<commit_msg>fix link base url<commit_after>//style
import 'vis/dist/vis.css';
//import 'materialize-css/dist/css/materialize.min.css';
import './App.css';

//react
import React, { Component } from 'react';

//demo data
import demo from './demo.json';

//react components
import { Chip, Tabs, Tab, Footer, Collection, CollectionItem, Row, Col, Preloader, Navbar, NavItem, Icon } from 'react-materialize';
import { Timeline } from './Timeline.js';
import { DataSetItem } from './DataSet.js';
import { FilterView } from './Filter.js';
import { SettingsView } from './Settings.js';

//utility for Caipy (parse JSON data)
import * as ApiUtils from './caipy-api.js';
import * as Storage from './Storage.js';

// jquery & materialize
import $ from 'jquery';
//import $ from 'jquery';
window.$ = window.jQuery = require('jquery');
//window.$ = window.jQuery = $;

require('materialize-css/dist/js/materialize.min.js');
//require('materialize-css/materialize.min.js')

/**
 * Default start date for query in live mode
 * @type {String}
 */
const defaultStartDate = "08/02/2017";

/**
 * Default end date for query in live mode
 * @type {String}
 */
const defaultEndDate = "08/02/2017";

/**
 * Footer component
 */
class FooterView extends Component {
    render() {
        return <Footer className='white-text footer blue darken-1'
                       moreLinks={

                            Copyright (c) 2017 Bertrand Martel

                         }>

    }
}

/**
 * View showing a Loader in the middle of the screen
 */
class ProgressView extends Component {
    render() {
        return <Row className={this.props.value ? "center-div hidden" : "center-div"}>
                    <Col s={12}>
                        <Preloader size="big" color="blue"/>
                    </Col>

{this.props.message}

                </Row>
    }
}

/**
 * The navigation bar
 */
class TopNavbar extends Component {

    /**
     * fit the items in the timeline
     */
    fit() {
        if (typeof this.props.onFit === 'function') {
            this.props.onFit();
        }
    }

    /**
     * update the type of item in the timeline ("point"/"range")
     */
    updateType() {
        if (typeof this.props.onUpdateType === 'function') {
            this.props.onUpdateType();
        }
    }

    /**
     * refresh data (in dataset & in timeline)
     * @param  {String} type refresh type ("create" or "update")
     */
    refresh(type) {
        if (typeof this.props.onRefresh === 'function') {
            this.props.onRefresh(type);
        }
    }

    /**
     * open URL settings view
     */
    urlSettings() {
        if (typeof this.props.onUrlSettings === 'function') {
            this.props.onUrlSettings();
        }
    }

    render() {
        return <Navbar href={process.env.PUBLIC_URL +"/caipy-dashboard"} brand='Caipy Dashboard' className="blue darken-1" right>
                    <NavItem onClick={() => this.fit()}><Icon medium>center_focus_strong</Icon></NavItem>
                    <NavItem onClick={() => this.updateType()}><Icon medium>timeline</Icon></NavItem>
                    <NavItem onClick={() => this.refresh("update")}><Icon>refresh</Icon></NavItem>
                    <NavItem onClick={() => this.urlSettings()}><Chip close={false}>{this.props.mode} mode</Chip></NavItem>
                    <NavItem href="https://github.com/bertrandmartel/caipy-dashboard" target="_blank" ><Icon>code</Icon></NavItem>
                </Navbar>
    }
}

/**
 * Tab view showing the dataset & the timeline
 */
class TabCollection extends Component {

    render() {
        return

                    <Tabs>
                            <Tab title="timeline" active>

                                    <Collection>
                                        {
                                            this.props.items.map(function(value, index){
                                                return (
                                                        <CollectionItem className="coll-item" key={value.channelName + "-coll"}>
                                                            <Timeline key={value.channelName}
                                                                      data={value}
                                                                      actionType={this.props.actionType}
                                                                      itemType={this.props.itemType}/>
                                                        </CollectionItem>
                                               );
                                            },this)
                                        }
                                    </Collection>

                            </Tab>
                            <Tab title="dataset" active>

                                    <Collection>
                                        {
                                            this.props.data.map(function(value, index){
                                                return (
                                                    <DataSetItem key={value.name}
                                                                 name={value.name}
                                                                 rows={value.rows}
                                                                 length={value.rows.length}
                                                                 perPage={15}/>
                                               );
                                            },this)
                                        }
                                    </Collection>

                            </Tab>
                    </Tabs>

    }
}

/**
 * Main app component
 */
class App extends Component {

    /**
     * date filter used to init filter & to be used in query in live mode.
     * @type {Object}
     */
    date = {
        startDate: defaultStartDate,
        endDate: defaultEndDate
    }

    state = {
        ready: false,
        items: [],
        data: [],
        mode: "demo",
        url: Storage.getApiUrl(),
        message: "",
        startDate: this.date.startDate,
        endDate: this.date.endDate
    };

    /**
     * mode can be "demo" or "live"
     * @type {String}
     */
    mode = "demo";

    /**
     * default timeline item type (false for "range" / true for "point")
     * @type {Boolean}
     */
    itemType = false;

    constructor() {
        super();
        this.items = [];
        this.data = [];
        this.checkItemType();
        this.checkDate();
        this.fit = this.fit.bind(this);
        this.refresh = this.refresh.bind(this);
        this.updateType = this.updateType.bind(this);
        this.setUrlSettings = this.setUrlSettings.bind(this);
        this.setMode = this.setMode.bind(this);
        this.setFilterSettings = this.setFilterSettings.bind(this);
    }

    /**
     * initialize dates used in filter & query
     */
    checkDate() {
        var startDate = Storage.getStartDate();
        var endDate = Storage.getEndDate();
        if (startDate !== null && startDate !== "undefined" &&
            endDate !== null && endDate !== "undefined") {
            this.date.startDate = startDate;
            this.date.endDate = endDate;
        }
    }

    /**
     * initiliaze timeline item type
     */
    checkItemType() {
        var type = Storage.getItemType();
        if (type === null) {
            Storage.setItemType(false);
            this.itemType = false;
        } else {
            this.itemType = (type === 'true');
        }
    }

    /**
     * On mount check the mode ("live" or "demo") and refresh the data according to this
     */
    componentDidMount() {
        if (Storage.checkMode() !== null &&
            Storage.checkMode() === "live" &&
            Storage.checkApiUrl()) {
            this.mode = "live";
        } else {
            Storage.setMode("demo");
        }
        this.refresh("create");
    }

    /**
     * Parse the JSON data to build timeline DataSet
     * @param  {Object} data       JSON data object (from query response or from local JSON file)
     * @param  {String} actionType type of action to perform ("create","update","idle")
     */
    parseItems(data, actionType) {
        this.items = ApiUtils.buildItems(data);
        this.data = data;
        this.setState({
            actionType: actionType,
            ready: true,
            data: this.data,
            items: this.items,
            mode: this.mode,
            url: Storage.getApiUrl(),
            message: "",
            startDate: this.date.startDate,
            endDate: this.date.endDate
        });
    }

    /**
     * Refresh the data according to mode
     * @param  {String} actionType type of action to perform ("create","update","idle")
     * @return {[type]}            [description]
     */
    refresh(actionType) {

        var that = this;

        that.setState({
            actionType: "idle",
            ready: false,
            data: that.data,
            items: that.items,
            mode: this.mode,
            url: Storage.getApiUrl(),
            message: "",
            startDate: this.date.startDate,
            endDate: this.date.endDate
        });

        if (this.mode === "live") {
            fetch(Storage.getApiUrl() + "?type=channels&startdate=" + this.date.startDate + "&starttime=00:00:00&" +
                    "enddate=" + this.date.endDate + "&endtime=23:59:59")
                .then(function(response) {
                    if (response.status >= 400) {
                        throw new Error("Bad response from server");
                    }
                    return response.json();
                })
                .then(function(data) {
                    that.parseItems(data, actionType);
                })
                .catch(function(e) {
                    console.log(e);
                    //show error message and set mode to "idle"
                    that.setState({
                        actionType: "idle",
                        ready: false,
                        data: that.data,
                        items: that.items,
                        mode: that.mode,
                        url: Storage.getApiUrl(),
                        message: "error occured",
                        startDate: that.date.startDate,
                        endDate: that.date.endDate
                    });
                });
        } else {
            //in demo mode just parse the raw item
            that.parseItems(demo, actionType);
        }
    }

    /**
     * set settings URL value
     * @param {String} url URL value
     */
    setUrlSettings(url) {
        Storage.setApiUrl(url);
        Storage.setMode("live");
        this.mode = "live";
        this.refresh("update");
    }

    /**
     * Set filter value
     * @param {Date} startDate start date filter
     * @param {Date} endDate   end date filter
     */
    setFilterSettings(startDate, endDate) {
        Storage.setDate(startDate, endDate);
        this.date.startDate = startDate;
        this.date.endDate = endDate;
        this.refresh("update");
    }

    /**
     * Set the mode ("demo" or "live")
     * @param {String} mode the mode
     */
    setMode(mode) {
        Storage.setMode(mode);
        this.mode = mode;
        this.refresh("update");
    }

    /**
     * Open URL settings modal
     */
    urlSettings() {
        $('#url-settings').modal('open');
    }

    /**
     * fit the items in the timeline according to time window or selected items
     */
    fit() {
        this.setState({
            actionType: "fit",
            ready: true,
            data: this.data,
            items: this.items,
            mode: this.mode,
            url: Storage.getApiUrl(),
            message: "",
            startDate: this.date.startDate,
            endDate: this.date.endDate
        })
    }

    /**
     * toggle timeline item type ("range" or "type")
     */
    updateType() {
        this.itemType = !this.itemType;
        Storage.setItemType(this.itemType);
        this.setState({
            actionType: "update-type",
            ready: true,
            data: this.data,
            items: this.items,
            mode: this.mode,
            url: Storage.getApiUrl(),
            message: "",
            startDate: this.date.startDate,
            endDate: this.date.endDate
        });
    }

    render() {
        return (

                    <TopNavbar mode={this.state.mode}
                               onFit={this.fit}
                               onUpdateType={this.updateType}
                               onRefresh={this.refresh}
                               onUrlSettings={this.urlSettings} />
                    <FilterView onSetFilterSettings={this.setFilterSettings}
                                mode={this.state.mode}
                                startDate={this.state.startDate}
                                endDate={this.state.endDate}/>
                    <TabCollection ready={this.state.ready}
                                   items={this.state.items}
                                   data={this.state.data}
                                   actionType={this.state.actionType}
                                   itemType={this.itemType}/>
                    <ProgressView value={this.state.ready}
                                  message={this.state.message}/>
                    <SettingsView mode={this.state.mode}
                                  url={this.state.url}
                                  onSetUrlSettings={this.setUrlSettings}
                                  onSetMode={this.setMode}/>

                <FooterView/>

        );
    }
}

export default App;<|endoftext|>


<commit_before>import path from 'path';

import React, {Fragment} from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';

import RefHolder from '../models/ref-holder';
import ChangedFileItem from '../items/changed-file-item';
import CommitPreviewItem from '../items/commit-preview-item';
import CommitDetailItem from '../items/commit-detail-item';

export default class FilePatchHeaderView extends React.Component {
  static propTypes = {
    relPath: PropTypes.string.isRequired,
    stagingStatus: PropTypes.oneOf(['staged', 'unstaged']),
    isPartiallyStaged: PropTypes.bool,
    hasHunks: PropTypes.bool.isRequired,
    hasUndoHistory: PropTypes.bool,
    hasMultipleFileSelections: PropTypes.bool.isRequired,

    tooltips: PropTypes.object.isRequired,

    undoLastDiscard: PropTypes.func.isRequired,
    diveIntoMirrorPatch: PropTypes.func.isRequired,
    openFile: PropTypes.func.isRequired,
    toggleFile: PropTypes.func.isRequired,

    itemType: PropTypes.oneOf([ChangedFileItem, CommitPreviewItem, CommitDetailItem]).isRequired,
    disableStageUnstage: PropTypes.bool,
  };

  constructor(props) {
    super(props);

    this.refMirrorButton = new RefHolder();
    this.refOpenFileButton = new RefHolder();
  }

  render() {
    return (

          {this.renderTitle()}

        {this.renderButtonGroup()}

    );
  }

  renderTitle() {
    if (this.props.itemType === ChangedFileItem) {
      const status = this.props.stagingStatus;
      return (
        {status[0].toUpperCase()}{status.slice(1)} Changes for {this.renderPath()}
      );
    } else {
      return this.renderPath();
    }
  }

  renderPath() {
    const dirname = path.dirname(this.props.relPath);
    const basename = path.basename(this.props.relPath);

    if (dirname === '.') {
      return {basename};
    } else {
      return (

          {dirname}{path.sep}{basename}

      );
    }
  }

  renderButtonGroup() {
    return (

        {!this.props.disableStageUnstage && this.renderUndoDiscardButton()}
        {!this.props.disableStageUnstage && this.renderMirrorPatchButton()}
        {this.renderOpenFileButton()}
        {!this.props.disableStageUnstage && this.renderToggleFileButton()}

    );
  }

  renderUndoDiscardButton() {
    const unstagedChangedFileItem = this.props.itemType === ChangedFileItem && this.props.stagingStatus === 'unstaged';
    if (unstagedChangedFileItem && this.props.hasUndoHistory) {
      return (
        <button className="btn icon icon-history" onClick={this.props.undoLastDiscard}>
        Undo Discard
        </button>
      );
    } else {
      return null;
    }
  }

  renderMirrorPatchButton() {
    if (!this.props.isPartiallyStaged && this.props.hasHunks) {
      return null;
    }

    const attrs = this.props.stagingStatus === 'unstaged'
      ? {
        iconClass: 'icon-tasklist',
        buttonText: 'View Staged',
      }
      : {
        iconClass: 'icon-list-unordered',
        buttonText: 'View Unstaged',
      };

    return (
      <Fragment>
        <button
          ref={this.refMirrorButton.setter}
          className={cx('btn', 'icon', attrs.iconClass)}
          onClick={this.props.diveIntoMirrorPatch}>
          {attrs.buttonText}
        </button>
      </Fragment>
    );
  }

  renderOpenFileButton() {
    let buttonText = 'Jump To File';
    if (this.props.hasMultipleFileSelections) {
      buttonText += 's';
    }

    return (
      <Fragment>
        <button
          ref={this.refOpenFileButton.setter}
          className="btn icon icon-code github-FilePatchHeaderView-jumpToFileButton"
          onClick={this.props.openFile}>
          {buttonText}
        </button>
      </Fragment>
    );
  }

  renderToggleFileButton() {
    const attrs = this.props.stagingStatus === 'unstaged'
      ? {
        buttonClass: 'icon-move-down',
        buttonText: 'Stage File',
      }
      : {
        buttonClass: 'icon-move-up',
        buttonText: 'Unstage File',
      };

    return (
      <button className={cx('btn', 'icon', attrs.buttonClass)} onClick={this.props.toggleFile}>
        {attrs.buttonText}
      </button>
    );
  }
}
<commit_msg>remove jump to file<commit_after>import path from 'path';

import React, {Fragment} from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';

import RefHolder from '../models/ref-holder';
import ChangedFileItem from '../items/changed-file-item';
import CommitPreviewItem from '../items/commit-preview-item';
import CommitDetailItem from '../items/commit-detail-item';

export default class FilePatchHeaderView extends React.Component {
  static propTypes = {
    relPath: PropTypes.string.isRequired,
    stagingStatus: PropTypes.oneOf(['staged', 'unstaged']),
    isPartiallyStaged: PropTypes.bool,
    hasHunks: PropTypes.bool.isRequired,
    hasUndoHistory: PropTypes.bool,
    hasMultipleFileSelections: PropTypes.bool.isRequired,

    tooltips: PropTypes.object.isRequired,

    undoLastDiscard: PropTypes.func.isRequired,
    diveIntoMirrorPatch: PropTypes.func.isRequired,
    openFile: PropTypes.func.isRequired,
    toggleFile: PropTypes.func.isRequired,

    itemType: PropTypes.oneOf([ChangedFileItem, CommitPreviewItem, CommitDetailItem]).isRequired,
    disableStageUnstage: PropTypes.bool,
  };

  constructor(props) {
    super(props);

    this.refMirrorButton = new RefHolder();
    this.refOpenFileButton = new RefHolder();
  }

  render() {
    return (

          {this.renderTitle()}

        {this.renderButtonGroup()}

    );
  }

  renderTitle() {
    if (this.props.itemType === ChangedFileItem) {
      const status = this.props.stagingStatus;
      return (
        {status[0].toUpperCase()}{status.slice(1)} Changes for {this.renderPath()}
      );
    } else {
      return this.renderPath();
    }
  }

  renderPath() {
    const dirname = path.dirname(this.props.relPath);
    const basename = path.basename(this.props.relPath);

    if (dirname === '.') {
      return {basename};
    } else {
      return (

          {dirname}{path.sep}{basename}

      );
    }
  }

  renderButtonGroup() {
    if (this.props.disableStageUnstage) {
      return null;
    } else {
      return (

          {this.renderUndoDiscardButton()}
          {this.renderMirrorPatchButton()}
          {this.renderOpenFileButton()}
          {this.renderToggleFileButton()}

      );
    }
  }

  renderUndoDiscardButton() {
    const unstagedChangedFileItem = this.props.itemType === ChangedFileItem && this.props.stagingStatus === 'unstaged';
    if (unstagedChangedFileItem && this.props.hasUndoHistory) {
      return (
        <button className="btn icon icon-history" onClick={this.props.undoLastDiscard}>
        Undo Discard
        </button>
      );
    } else {
      return null;
    }
  }

  renderMirrorPatchButton() {
    if (!this.props.isPartiallyStaged && this.props.hasHunks) {
      return null;
    }

    const attrs = this.props.stagingStatus === 'unstaged'
      ? {
        iconClass: 'icon-tasklist',
        buttonText: 'View Staged',
      }
      : {
        iconClass: 'icon-list-unordered',
        buttonText: 'View Unstaged',
      };

    return (
      <Fragment>
        <button
          ref={this.refMirrorButton.setter}
          className={cx('btn', 'icon', attrs.iconClass)}
          onClick={this.props.diveIntoMirrorPatch}>
          {attrs.buttonText}
        </button>
      </Fragment>
    );
  }

  renderOpenFileButton() {
    let buttonText = 'Jump To File';
    if (this.props.hasMultipleFileSelections) {
      buttonText += 's';
    }

    return (
      <Fragment>
        <button
          ref={this.refOpenFileButton.setter}
          className="btn icon icon-code github-FilePatchHeaderView-jumpToFileButton"
          onClick={this.props.openFile}>
          {buttonText}
        </button>
      </Fragment>
    );
  }

  renderToggleFileButton() {
    const attrs = this.props.stagingStatus === 'unstaged'
      ? {
        buttonClass: 'icon-move-down',
        buttonText: 'Stage File',
      }
      : {
        buttonClass: 'icon-move-up',
        buttonText: 'Unstage File',
      };

    return (
      <button className={cx('btn', 'icon', attrs.buttonClass)} onClick={this.props.toggleFile}>
        {attrs.buttonText}
      </button>
    );
  }
}
<|endoftext|>


<commit_before>//Chris Samuel
//Github: Alayode
//2015-3-12

// Code School: Changing Declarations to Expressions

// Developers for the Forest of Function Expressions
// Theme Park have created a function declaration named forestFright,
// but they’ve decided not to keep the function in memory.
// Convert the function from a named function
// declaration to an anonymous function
// expression and assign it to a variable called runAway.
<commit_msg>added comments and function to explain how to use a function in a variable<commit_after>//Chris Samuel
//Github: Alayode
//2015-3-12

// Code School: Changing Declarations to Expressions

// Developers for the Forest of Function Expressions
// Theme Park have created a function declaration named forestFright,
// but they’ve decided not to keep the function in memory.
// Convert the function from a named function
// declaration to an anonymous function
// expression and assign it to a variable called runAway.

function forestFright() {
  var toAlert = "";
  for (var i = 0; i < 5; i++) {
    toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";
  }
  alert(toAlert);
}

// First lets create a variable called runAway
var runAway;

//Next lets try remeber that when a function expression is added to a
//variable we can remove the name of the function from the "()"
// this will make it become an anonymous function.

function() {
  var toAlert = "";
  for (var i = 0; i < 5; i++) {
    toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";
  }
  alert(toAlert);
}
<|endoftext|>


<commit_before>/*
 * 2010-2016 Sellermania / Froggy Commerce / 23Prod SARL
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to team@froggy-commerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade your module to newer
 * versions in the future.
 *
 *  @author         Froggy Commerce <team@froggy-commerce.com>
 *  @copyright      2010-2016 Sellermania / Froggy Commerce / 23Prod SARL
 *  @version        1.0
 *  @license        http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

$(document).ready(function() {

    // Fill product details
    var nb_buttons = 0;
    for (i = 1; sellermania_block_products_list[i]; i++)
    {
        var sm_block_product = sellermania_block_products_list[i];

        var sku_short = sm_block_product.html().split('
');
		sku_short[1] = sku_short[1].replace('Numéro de référence', 'Ref');
		var remove = sku_short[1].split(' ');
        if (remove[1] == ':')
            sku_short = sku_short[1].replace(remove[0] + ' ' + remove[1], '').trim();
        else
            sku_short = sku_short[1].replace(remove[0], '').trim();

        if (sku_short != '' && typeof sellermania_products[sku_short] != 'undefined')
        {
            var html_order_line = '';
            if (sellermania_products[sku_short].insurance_price > 0)
                html_order_line += '
' + insurance_price_label + ' ' + sellermania_products[sku_short].insurance_price + ' ' + sellermania_products[sku_short].currency + '
';
            if (sellermania_products[sku_short].order_item_id != '') html_order_line += '
' + order_item_id_label + ' ' + sellermania_products[sku_short].order_item_id + '
';
            if (sellermania_products[sku_short].external_order_id != '') html_order_line += '
' + external_order_id_label + ' ' + sellermania_products[sku_short].external_order_id + '
';
            html_order_line += '' + sku_label + ' ' + sellermania_products[sku_short].sku + '
';
            if (sellermania_products[sku_short].ean != '') html_order_line += '' + ean_label + ' ' + sellermania_products[sku_short].ean + '
';
            if (sellermania_products[sku_short].product_id != '') html_order_line += '' + asin_label + ' ' + sellermania_products[sku_short].product_id + '
';
            if (sellermania_products[sku_short].item_condition != '')
                html_order_line += '' + condition_label + ' ' + sellermania_products[sku_short].item_condition + '
';
            else
                html_order_line += '' + condition_label + ' ' + unknown_label + '
';
            html_order_line += '' + status_label + ' ' + sellermania_products[sku_short].status + '
';
            if (sellermania_products[sku_short].status_id == 6)
            {
                html_order_line += '<input type="radio" id="status_confirm_' + i + '" name="status_' + i + '" value="9" class="status_order_line" data-toggle="' + sellermania_products[sku_short].sku + '" /> ' + confirm_label + ' ';
                html_order_line += '<input type="radio" id="status_cancel_' + i + '" name="status_' + i + '" value="4" class="status_order_line" data-toggle="' + sellermania_products[sku_short].sku + '" /> ' + cancel_label + ' ';
                nb_buttons++;
            }
            sm_block_product.append(html_order_line);
        }
    }

    // Add button check all
    if (nb_buttons > 0)
    {
        var sellermania_html_buttons_all = '<input type="button" value="Confirm all products" id="sellermania_confirm_all_products" class="button btn btn-default" />';
        sellermania_html_buttons_all += '<input type="button" value="Cancel all products" id="sellermania_cancel_all_products" class="button btn btn-default" />';
        sellermania_block_product_general_legend.html(sellermania_html_buttons_all);
        sellermania_block_product_general_legend.show();

        $('#sellermania_confirm_all_products').click(function() {
            for (i = 1; sellermania_block_products_list[i]; i++)
                $('#status_confirm_' + i).attr('checked', 'checked');
            sellermania_update_line_status();
        });
        $('#sellermania_cancel_all_products').click(function() {
            for (i = 1; sellermania_block_products_list[i]; i++)
                $('#status_cancel_' + i).attr('checked', 'checked');
            sellermania_update_line_status();
        });
    }

    // If status has changed
    if (sellermania_status_update_result !== 'undefined')
        sellermania_block_product_general_legend.after(sellermania_status_update_result);
    if (sellermania_error_result !== 'undefined')
        sellermania_block_product_general_legend.after(sellermania_error_result);

    // Check status
    $('.status_order_line').click(function() {
        sellermania_update_line_status();
    });

    function sellermania_update_line_status()
    {
        // Fill product details
        var line_max = 0;
        var sellermania_status_defined = 0;
        for (i = 1; sellermania_block_products_list[i]; i++)
        {
            // Status
            var order_line_status = 'Not defined';
            if ($('#status_confirm_' + i).attr('checked'))
                order_line_status = 'Confirmed';
            if ($('#status_cancel_' + i).attr('checked'))
                order_line_status = 'Cancelled';

            // Count not defined Status
            if (order_line_status != 'Not defined')
                sellermania_status_defined++;

            // Save the line max
            line_max = i;
        }

        // Check how many not defined status there is
        if (sellermania_status_defined > 0)
        {
            // Display submit
            sellermania_block_product_general_legend.html('<input type="button" id="sellermania_register_status" value="Register status" class="button btn btn-default" />');

            // Generate form and submit it
            $('#sellermania_register_status').click(function() {

                // Generate form
                var html_form = '<input type="hidden" name="sellermania_line_max" value="' + line_max + '" />';
                $('.status_order_line').each(function() {
                    if ($(this).attr('checked'))
                    {
                        html_form += '<input type="hidden" name="' + $(this).attr('name') + '" value="' + $(this).attr('value') + '" />';
                        html_form += '<input type="hidden" name="sku_' + $(this).attr('name') + '" value="' + $(this).attr('data-toggle') + '" />';
                    }
                });

                // Display form and submit
                $('#sellermania_status_form').html(html_form);
                document.forms["sellermania_status_form"].submit();

                return false;
            });
        }
    }
});
<commit_msg>Quick fix<commit_after>/*
 * 2010-2016 Sellermania / Froggy Commerce / 23Prod SARL
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to team@froggy-commerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade your module to newer
 * versions in the future.
 *
 *  @author         Froggy Commerce <team@froggy-commerce.com>
 *  @copyright      2010-2016 Sellermania / Froggy Commerce / 23Prod SARL
 *  @version        1.0
 *  @license        http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

$(document).ready(function() {

    // Fill product details
    var nb_buttons = 0;
    for (i = 1; sellermania_block_products_list[i]; i++)
    {
        var sm_block_product = sellermania_block_products_list[i];

        var sku_short = sm_block_product.html().split('
');
		sku_short[1] = sku_short[1].replace('Numéro de référence', 'Ref').replace('Reference number', 'Ref');
		var remove = sku_short[1].split(' ');
        if (remove[1] == ':')
            sku_short = sku_short[1].replace(remove[0] + ' ' + remove[1], '').trim();
        else
            sku_short = sku_short[1].replace(remove[0], '').trim();

        if (sku_short != '' && typeof sellermania_products[sku_short] != 'undefined')
        {
            var html_order_line = '';
            if (sellermania_products[sku_short].insurance_price > 0)
                html_order_line += '
' + insurance_price_label + ' ' + sellermania_products[sku_short].insurance_price + ' ' + sellermania_products[sku_short].currency + '
';
            if (sellermania_products[sku_short].order_item_id != '') html_order_line += '
' + order_item_id_label + ' ' + sellermania_products[sku_short].order_item_id + '
';
            if (sellermania_products[sku_short].external_order_id != '') html_order_line += '
' + external_order_id_label + ' ' + sellermania_products[sku_short].external_order_id + '
';
            html_order_line += '' + sku_label + ' ' + sellermania_products[sku_short].sku + '
';
            if (sellermania_products[sku_short].ean != '') html_order_line += '' + ean_label + ' ' + sellermania_products[sku_short].ean + '
';
            if (sellermania_products[sku_short].product_id != '') html_order_line += '' + asin_label + ' ' + sellermania_products[sku_short].product_id + '
';
            if (sellermania_products[sku_short].item_condition != '')
                html_order_line += '' + condition_label + ' ' + sellermania_products[sku_short].item_condition + '
';
            else
                html_order_line += '' + condition_label + ' ' + unknown_label + '
';
            html_order_line += '' + status_label + ' ' + sellermania_products[sku_short].status + '
';
            if (sellermania_products[sku_short].status_id == 6)
            {
                html_order_line += '<input type="radio" id="status_confirm_' + i + '" name="status_' + i + '" value="9" class="status_order_line" data-toggle="' + sellermania_products[sku_short].sku + '" /> ' + confirm_label + ' ';
                html_order_line += '<input type="radio" id="status_cancel_' + i + '" name="status_' + i + '" value="4" class="status_order_line" data-toggle="' + sellermania_products[sku_short].sku + '" /> ' + cancel_label + ' ';
                nb_buttons++;
            }
            sm_block_product.append(html_order_line);
        }
    }

    // Add button check all
    if (nb_buttons > 0)
    {
        var sellermania_html_buttons_all = '<input type="button" value="Confirm all products" id="sellermania_confirm_all_products" class="button btn btn-default" />';
        sellermania_html_buttons_all += '<input type="button" value="Cancel all products" id="sellermania_cancel_all_products" class="button btn btn-default" />';
        sellermania_block_product_general_legend.html(sellermania_html_buttons_all);
        sellermania_block_product_general_legend.show();

        $('#sellermania_confirm_all_products').click(function() {
            for (i = 1; sellermania_block_products_list[i]; i++)
                $('#status_confirm_' + i).attr('checked', 'checked');
            sellermania_update_line_status();
        });
        $('#sellermania_cancel_all_products').click(function() {
            for (i = 1; sellermania_block_products_list[i]; i++)
                $('#status_cancel_' + i).attr('checked', 'checked');
            sellermania_update_line_status();
        });
    }

    // If status has changed
    if (sellermania_status_update_result !== 'undefined')
        sellermania_block_product_general_legend.after(sellermania_status_update_result);
    if (sellermania_error_result !== 'undefined')
        sellermania_block_product_general_legend.after(sellermania_error_result);

    // Check status
    $('.status_order_line').click(function() {
        sellermania_update_line_status();
    });

    function sellermania_update_line_status()
    {
        // Fill product details
        var line_max = 0;
        var sellermania_status_defined = 0;
        for (i = 1; sellermania_block_products_list[i]; i++)
        {
            // Status
            var order_line_status = 'Not defined';
            if ($('#status_confirm_' + i).attr('checked'))
                order_line_status = 'Confirmed';
            if ($('#status_cancel_' + i).attr('checked'))
                order_line_status = 'Cancelled';

            // Count not defined Status
            if (order_line_status != 'Not defined')
                sellermania_status_defined++;

            // Save the line max
            line_max = i;
        }

        // Check how many not defined status there is
        if (sellermania_status_defined > 0)
        {
            // Display submit
            sellermania_block_product_general_legend.html('<input type="button" id="sellermania_register_status" value="Register status" class="button btn btn-default" />');

            // Generate form and submit it
            $('#sellermania_register_status').click(function() {

                // Generate form
                var html_form = '<input type="hidden" name="sellermania_line_max" value="' + line_max + '" />';
                $('.status_order_line').each(function() {
                    if ($(this).attr('checked'))
                    {
                        html_form += '<input type="hidden" name="' + $(this).attr('name') + '" value="' + $(this).attr('value') + '" />';
                        html_form += '<input type="hidden" name="sku_' + $(this).attr('name') + '" value="' + $(this).attr('data-toggle') + '" />';
                    }
                });

                // Display form and submit
                $('#sellermania_status_form').html(html_form);
                document.forms["sellermania_status_form"].submit();

                return false;
            });
        }
    }
});
<|endoftext|>


<commit_before>require("./core");
var types = require("../lib/types");
var def = types.Type.def;
var or = types.Type.or;
var builtin = types.builtInTypes;
var isString = builtin.string;
var isBoolean = builtin.boolean;
var defaults = require("../lib/shared").defaults;

def("JSXAttribute")
    .bases("Node")
    .build("name", "value")
    .field("name", or(def("JSXIdentifier"), def("JSXNamespacedName")))
    .field("value", or(
        def("Literal"), // attr="value"
        def("JSXExpressionContainer"), // attr={value}
        null // attr= or just attr
    ), defaults["null"]);

def("JSXIdentifier")
    .bases("Identifier")
    .build("name")
    .field("name", isString);

def("JSXNamespacedName")
    .bases("Node")
    .build("namespace", "name")
    .field("namespace", def("JSXIdentifier"))
    .field("name", def("JSXIdentifier"));

def("JSXMemberExpression")
    .bases("MemberExpression")
    .build("object", "property")
    .field("object", or(def("JSXIdentifier"), def("JSXMemberExpression")))
    .field("property", def("JSXIdentifier"))
    .field("computed", isBoolean, defaults.false);

var JSXElementName = or(
    def("JSXIdentifier"),
    def("JSXNamespacedName"),
    def("JSXMemberExpression")
);

def("JSXSpreadAttribute")
    .bases("Node")
    .build("argument")
    .field("argument", def("Expression"));

var JSXAttributes = [or(
    def("JSXAttribute"),
    def("JSXSpreadAttribute")
)];

def("JSXExpressionContainer")
    .bases("Expression")
    .build("expression")
    .field("expression", def("Expression"));

def("JSXElement")
    .bases("Expression")
    .build("openingElement", "closingElement", "children")
    .field("openingElement", def("JSXOpeningElement"))
    .field("closingElement", or(def("JSXClosingElement"), null), defaults["null"])
    .field("children", [or(
        def("JSXElement"),
        def("JSXExpressionContainer"),
        def("JSXText"),
        def("Literal") // TODO Esprima should return JSXText instead.
    )], defaults.emptyArray)
    .field("name", JSXElementName, function() {
        // Little-known fact: the `this` object inside a default function
        // is none other than the partially-built object itself, and any
        // fields initialized directly from builder function arguments
        // (like openingElement, closingElement, and children) are
        // guaranteed to be available.
        return this.openingElement.name;
    })
    .field("selfClosing", isBoolean, function() {
        return this.openingElement.selfClosing;
    })
    .field("attributes", JSXAttributes, function() {
        return this.openingElement.attributes;
    });

def("JSXOpeningElement")
    .bases("Node") // TODO Does this make sense? Can't really be an JSXElement.
    .build("name", "attributes", "selfClosing")
    .field("name", JSXElementName)
    .field("attributes", JSXAttributes, defaults.emptyArray)
    .field("selfClosing", isBoolean, defaults["false"]);

def("JSXClosingElement")
    .bases("Node") // TODO Same concern.
    .build("name")
    .field("name", JSXElementName);

def("JSXText")
    .bases("Literal")
    .build("value")
    .field("value", isString);

def("JSXEmptyExpression").bases("Expression").build();

// Type Annotations
def("Type")
  .bases("Node");

def("AnyTypeAnnotation")
  .bases("Type");

def("VoidTypeAnnotation")
  .bases("Type");

def("NumberTypeAnnotation")
  .bases("Type");

def("StringTypeAnnotation")
  .bases("Type");

def("StringLiteralTypeAnnotation")
  .bases("Type")
  .build("value", "raw")
  .field("value", isString)
  .field("raw", isString);

def("BooleanTypeAnnotation")
  .bases("Type");

def("TypeAnnotation")
  .bases("Node")
  .build("typeAnnotation")
  .field("typeAnnotation", def("Type"));

def("NullableTypeAnnotation")
  .bases("Type")
  .build("typeAnnotation")
  .field("typeAnnotation", def("Type"));

def("FunctionTypeAnnotation")
  .bases("Type")
  .build("params", "returnType", "rest", "typeParameters")
  .field("params", [def("FunctionTypeParam")])
  .field("returnType", def("Type"))
  .field("rest", or(def("FunctionTypeParam"), null))
  .field("typeParameters", or(def("TypeParameterDeclaration"), null));

def("FunctionTypeParam")
  .bases("Node")
  .build("name", "typeAnnotation", "optional")
  .field("name", def("Identifier"))
  .field("typeAnnotation", def("Type"))
  .field("optional", isBoolean);

def("ArrayTypeAnnotation")
  .bases("Type")
  .build("elementType")
  .field("elementType", def("Type"));

def("ObjectTypeAnnotation")
  .bases("Type")
  .build("properties")
  .field("properties", [def("ObjectTypeProperty")])
  .field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray)
  .field("callProperties", [def("ObjectTypeCallProperty")], defaults.emptyArray);

def("ObjectTypeProperty")
  .bases("Node")
  .build("key", "value", "optional")
  .field("key", or(def("Literal"), def("Identifier")))
  .field("value", def("Type"))
  .field("optional", isBoolean);

def("ObjectTypeIndexer")
  .bases("Node")
  .build("id", "key", "value")
  .field("id", def("Identifier"))
  .field("key", def("Type"))
  .field("value", def("Type"));

def("ObjectTypeCallProperty")
  .bases("Node")
  .build("value")
  .field("value", def("FunctionTypeAnnotation"))
  .field("static", isBoolean, false);

def("QualifiedTypeIdentifier")
  .bases("Node")
  .build("qualification", "id")
  .field("qualification", or(def("Identifier"), def("QualifiedTypeIdentifier")))
  .field("id", def("Identifier"));

def("GenericTypeAnnotation")
  .bases("Type")
  .build("id", "typeParameters")
  .field("id", or(def("Identifier"), def("QualifiedTypeIdentifier")))
  .field("typeParameters", or(def("TypeParameterInstantiation"), null));

def("MemberTypeAnnotation")
  .bases("Type")
  .build("object", "property")
  .field("object", def("Identifier"))
  .field("property", or(def("MemberTypeAnnotation"), def("GenericTypeAnnotation")));

def("UnionTypeAnnotation")
  .bases("Type")
  .build("types")
  .field("types", [def("Type")]);

def("IntersectionTypeAnnotation")
  .bases("Type")
  .build("types")
  .field("types", [def("Type")]);

def("TypeofTypeAnnotation")
  .bases("Type")
  .build("argument")
  .field("argument", def("Type"));

def("Identifier")
  .field("typeAnnotation", or(def("TypeAnnotation"), null), defaults["null"]);

def("TypeParameterDeclaration")
  .bases("Node")
  .build("params")
  .field("params", [def("Identifier")]);

def("TypeParameterInstantiation")
  .bases("Node")
  .build("params")
  .field("params", [def("Type")]);

def("Function")
  .field("returnType", or(def("TypeAnnotation"), null), defaults["null"])
  .field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"]);

def("ClassProperty")
  .build("key", "typeAnnotation")
  .field("typeAnnotation", def("TypeAnnotation"))
  .field("static", isBoolean, false);

def("ClassImplements")
  .field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]);

def("InterfaceDeclaration")
  .bases("Statement")
  .build("id", "body", "extends")
  .field("id", def("Identifier"))
  .field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"])
  .field("body", def("ObjectTypeAnnotation"))
  .field("extends", [def("InterfaceExtends")]);

def("InterfaceExtends")
  .bases("Node")
  .build("id")
  .field("id", def("Identifier"))
  .field("typeParameters", or(def("TypeParameterInstantiation"), null));

def("TypeAlias")
  .bases("Statement")
  .build("id", "typeParameters", "right")
  .field("id", def("Identifier"))
  .field("typeParameters", or(def("TypeParameterDeclaration"), null))
  .field("right", def("Type"));

def("TypeCastExpression")
  .bases("Expression")
  .build("expression", "typeAnnotation")
  .field("expression", def("Expression"))
  .field("typeAnnotation", def("TypeAnnotation"));

def("TupleTypeAnnotation")
  .bases("Type")
  .build("types")
  .field("types", [def("Type")]);

def("DeclareVariable")
  .bases("Statement")
  .build("id")
  .field("id", def("Identifier"));

def("DeclareFunction")
  .bases("Statement")
  .build("id")
  .field("id", def("Identifier"));

def("DeclareClass")
  .bases("InterfaceDeclaration")
  .build("id");

def("DeclareModule")
  .bases("Statement")
  .build("id", "body")
  .field("id", or(def("Identifier"), def("Literal")))
  .field("body", def("BlockStatement"));
<commit_msg>Add NumberLiteralTypeAnnotation to fb-harmony<commit_after>require("./core");
var types = require("../lib/types");
var def = types.Type.def;
var or = types.Type.or;
var builtin = types.builtInTypes;
var isString = builtin.string;
var isNumber = builtin.number;
var isBoolean = builtin.boolean;
var defaults = require("../lib/shared").defaults;

def("JSXAttribute")
    .bases("Node")
    .build("name", "value")
    .field("name", or(def("JSXIdentifier"), def("JSXNamespacedName")))
    .field("value", or(
        def("Literal"), // attr="value"
        def("JSXExpressionContainer"), // attr={value}
        null // attr= or just attr
    ), defaults["null"]);

def("JSXIdentifier")
    .bases("Identifier")
    .build("name")
    .field("name", isString);

def("JSXNamespacedName")
    .bases("Node")
    .build("namespace", "name")
    .field("namespace", def("JSXIdentifier"))
    .field("name", def("JSXIdentifier"));

def("JSXMemberExpression")
    .bases("MemberExpression")
    .build("object", "property")
    .field("object", or(def("JSXIdentifier"), def("JSXMemberExpression")))
    .field("property", def("JSXIdentifier"))
    .field("computed", isBoolean, defaults.false);

var JSXElementName = or(
    def("JSXIdentifier"),
    def("JSXNamespacedName"),
    def("JSXMemberExpression")
);

def("JSXSpreadAttribute")
    .bases("Node")
    .build("argument")
    .field("argument", def("Expression"));

var JSXAttributes = [or(
    def("JSXAttribute"),
    def("JSXSpreadAttribute")
)];

def("JSXExpressionContainer")
    .bases("Expression")
    .build("expression")
    .field("expression", def("Expression"));

def("JSXElement")
    .bases("Expression")
    .build("openingElement", "closingElement", "children")
    .field("openingElement", def("JSXOpeningElement"))
    .field("closingElement", or(def("JSXClosingElement"), null), defaults["null"])
    .field("children", [or(
        def("JSXElement"),
        def("JSXExpressionContainer"),
        def("JSXText"),
        def("Literal") // TODO Esprima should return JSXText instead.
    )], defaults.emptyArray)
    .field("name", JSXElementName, function() {
        // Little-known fact: the `this` object inside a default function
        // is none other than the partially-built object itself, and any
        // fields initialized directly from builder function arguments
        // (like openingElement, closingElement, and children) are
        // guaranteed to be available.
        return this.openingElement.name;
    })
    .field("selfClosing", isBoolean, function() {
        return this.openingElement.selfClosing;
    })
    .field("attributes", JSXAttributes, function() {
        return this.openingElement.attributes;
    });

def("JSXOpeningElement")
    .bases("Node") // TODO Does this make sense? Can't really be an JSXElement.
    .build("name", "attributes", "selfClosing")
    .field("name", JSXElementName)
    .field("attributes", JSXAttributes, defaults.emptyArray)
    .field("selfClosing", isBoolean, defaults["false"]);

def("JSXClosingElement")
    .bases("Node") // TODO Same concern.
    .build("name")
    .field("name", JSXElementName);

def("JSXText")
    .bases("Literal")
    .build("value")
    .field("value", isString);

def("JSXEmptyExpression").bases("Expression").build();

// Type Annotations
def("Type")
  .bases("Node");

def("AnyTypeAnnotation")
  .bases("Type");

def("VoidTypeAnnotation")
  .bases("Type");

def("NumberTypeAnnotation")
  .bases("Type");

def("NumberLiteralTypeAnnotation")
  .bases("Type")
  .build("value", "raw")
  .field("value", isNumber)
  .field("raw", isString);

def("StringTypeAnnotation")
  .bases("Type");

def("StringLiteralTypeAnnotation")
  .bases("Type")
  .build("value", "raw")
  .field("value", isString)
  .field("raw", isString);

def("BooleanTypeAnnotation")
  .bases("Type");

def("TypeAnnotation")
  .bases("Node")
  .build("typeAnnotation")
  .field("typeAnnotation", def("Type"));

def("NullableTypeAnnotation")
  .bases("Type")
  .build("typeAnnotation")
  .field("typeAnnotation", def("Type"));

def("FunctionTypeAnnotation")
  .bases("Type")
  .build("params", "returnType", "rest", "typeParameters")
  .field("params", [def("FunctionTypeParam")])
  .field("returnType", def("Type"))
  .field("rest", or(def("FunctionTypeParam"), null))
  .field("typeParameters", or(def("TypeParameterDeclaration"), null));

def("FunctionTypeParam")
  .bases("Node")
  .build("name", "typeAnnotation", "optional")
  .field("name", def("Identifier"))
  .field("typeAnnotation", def("Type"))
  .field("optional", isBoolean);

def("ArrayTypeAnnotation")
  .bases("Type")
  .build("elementType")
  .field("elementType", def("Type"));

def("ObjectTypeAnnotation")
  .bases("Type")
  .build("properties")
  .field("properties", [def("ObjectTypeProperty")])
  .field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray)
  .field("callProperties", [def("ObjectTypeCallProperty")], defaults.emptyArray);

def("ObjectTypeProperty")
  .bases("Node")
  .build("key", "value", "optional")
  .field("key", or(def("Literal"), def("Identifier")))
  .field("value", def("Type"))
  .field("optional", isBoolean);

def("ObjectTypeIndexer")
  .bases("Node")
  .build("id", "key", "value")
  .field("id", def("Identifier"))
  .field("key", def("Type"))
  .field("value", def("Type"));

def("ObjectTypeCallProperty")
  .bases("Node")
  .build("value")
  .field("value", def("FunctionTypeAnnotation"))
  .field("static", isBoolean, false);

def("QualifiedTypeIdentifier")
  .bases("Node")
  .build("qualification", "id")
  .field("qualification", or(def("Identifier"), def("QualifiedTypeIdentifier")))
  .field("id", def("Identifier"));

def("GenericTypeAnnotation")
  .bases("Type")
  .build("id", "typeParameters")
  .field("id", or(def("Identifier"), def("QualifiedTypeIdentifier")))
  .field("typeParameters", or(def("TypeParameterInstantiation"), null));

def("MemberTypeAnnotation")
  .bases("Type")
  .build("object", "property")
  .field("object", def("Identifier"))
  .field("property", or(def("MemberTypeAnnotation"), def("GenericTypeAnnotation")));

def("UnionTypeAnnotation")
  .bases("Type")
  .build("types")
  .field("types", [def("Type")]);

def("IntersectionTypeAnnotation")
  .bases("Type")
  .build("types")
  .field("types", [def("Type")]);

def("TypeofTypeAnnotation")
  .bases("Type")
  .build("argument")
  .field("argument", def("Type"));

def("Identifier")
  .field("typeAnnotation", or(def("TypeAnnotation"), null), defaults["null"]);

def("TypeParameterDeclaration")
  .bases("Node")
  .build("params")
  .field("params", [def("Identifier")]);

def("TypeParameterInstantiation")
  .bases("Node")
  .build("params")
  .field("params", [def("Type")]);

def("Function")
  .field("returnType", or(def("TypeAnnotation"), null), defaults["null"])
  .field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"]);

def("ClassProperty")
  .build("key", "typeAnnotation")
  .field("typeAnnotation", def("TypeAnnotation"))
  .field("static", isBoolean, false);

def("ClassImplements")
  .field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]);

def("InterfaceDeclaration")
  .bases("Statement")
  .build("id", "body", "extends")
  .field("id", def("Identifier"))
  .field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"])
  .field("body", def("ObjectTypeAnnotation"))
  .field("extends", [def("InterfaceExtends")]);

def("InterfaceExtends")
  .bases("Node")
  .build("id")
  .field("id", def("Identifier"))
  .field("typeParameters", or(def("TypeParameterInstantiation"), null));

def("TypeAlias")
  .bases("Statement")
  .build("id", "typeParameters", "right")
  .field("id", def("Identifier"))
  .field("typeParameters", or(def("TypeParameterDeclaration"), null))
  .field("right", def("Type"));

def("TypeCastExpression")
  .bases("Expression")
  .build("expression", "typeAnnotation")
  .field("expression", def("Expression"))
  .field("typeAnnotation", def("TypeAnnotation"));

def("TupleTypeAnnotation")
  .bases("Type")
  .build("types")
  .field("types", [def("Type")]);

def("DeclareVariable")
  .bases("Statement")
  .build("id")
  .field("id", def("Identifier"));

def("DeclareFunction")
  .bases("Statement")
  .build("id")
  .field("id", def("Identifier"));

def("DeclareClass")
  .bases("InterfaceDeclaration")
  .build("id");

def("DeclareModule")
  .bases("Statement")
  .build("id", "body")
  .field("id", or(def("Identifier"), def("Literal")))
  .field("body", def("BlockStatement"));
<|endoftext|>


<commit_before>import React from 'react';

module.exports = React.createClass({

    // RENDER
    render: function() {

        return (

                		Lorem Ipsum Sit Amet Dolor Bla

                		Mussum Ipsum, cacilds vidis litro abertis. Detraxit consequat et quo num tendi nada. Quem num gosti di mum que vai caçá sua turmis! Diuretics paradis num copo é motivis de denguis. Interagi no mé, cursus quis, vehicula ac nisi.

						in elementis mé pra quem é amistosis quis leo. A ordem dos tratores não altera o pão duris Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Per aumento de cachacis, eu reclamis.

						Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis. Em pé sem cair, deitado sem dormir, sentado sem cochilar e fazendo pose. Cevadis im ampola pa arma uma pindureta. Leite de capivaris, leite de mula manquis.

            			13/02/2017 - 01:01PM

        );
    }
});<commit_msg>Basic layout for the new BLOG app. It will be used as basis for the redux boilerplate implementation<commit_after>import React from 'react';

module.exports = React.createClass({

    // RENDER
    render: function() {

        return (

                        Lorem Ipsum Sit Amet Dolor Bla

                        Mussum Ipsum, cacilds vidis litro abertis. Detraxit consequat et quo num tendi nada. Quem num gosti di mum que vai caçá sua turmis! Diuretics paradis num copo é motivis de denguis. Interagi no mé, cursus quis, vehicula ac nisi.

                        in elementis mé pra quem é amistosis quis leo. A ordem dos tratores não altera o pão duris Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Per aumento de cachacis, eu reclamis.

                        Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis. Em pé sem cair, deitado sem dormir, sentado sem cochilar e fazendo pose. Cevadis im ampola pa arma uma pindureta. Leite de capivaris, leite de mula manquis.

                        13/02/2017 - 01:01PM

                        Lorem Ipsum Sit Amet Dolor Bla

                        Mussum Ipsum, cacilds vidis litro abertis. Detraxit consequat et quo num tendi nada. Quem num gosti di mum que vai caçá sua turmis! Diuretics paradis num copo é motivis de denguis. Interagi no mé, cursus quis, vehicula ac nisi.

                        in elementis mé pra quem é amistosis quis leo. A ordem dos tratores não altera o pão duris Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Per aumento de cachacis, eu reclamis.

                        Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis. Em pé sem cair, deitado sem dormir, sentado sem cochilar e fazendo pose. Cevadis im ampola pa arma uma pindureta. Leite de capivaris, leite de mula manquis.

                        13/02/2017 - 01:01PM

                        Lorem Ipsum Sit Amet Dolor Bla

                        Mussum Ipsum, cacilds vidis litro abertis. Detraxit consequat et quo num tendi nada. Quem num gosti di mum que vai caçá sua turmis! Diuretics paradis num copo é motivis de denguis. Interagi no mé, cursus quis, vehicula ac nisi.

                        in elementis mé pra quem é amistosis quis leo. A ordem dos tratores não altera o pão duris Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Per aumento de cachacis, eu reclamis.

                        Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis. Em pé sem cair, deitado sem dormir, sentado sem cochilar e fazendo pose. Cevadis im ampola pa arma uma pindureta. Leite de capivaris, leite de mula manquis.

                        13/02/2017 - 01:01PM

        );
    }
});<|endoftext|>


<commit_before>/*
  ==============================================================================

   Copyright (C) 2013 Jacob Sologub

   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.

  ==============================================================================
*/

var libcrypto = require ('crypto');
var libcommander = require ('commander');
var libmongo = require ('mongodb');
var BSON = libmongo.BSONPure;

var BaaSKitDb = require ('./db').BaaSKitDb;

//==============================================================================
var BaaSKitAdmin = (function () {

	//==========================================================================
	/** Creates a BaaSKitAdmin object. */
    function BaaSKitAdmin (asksForUserConfirmation_)
    {
    	this.asksForUserConfirmation = asksForUserConfirmation_;
    }

    //==========================================================================
    /** Creates an application with a specified name if an application with the
    	specified name does not exists.

		@see deleteApplication
	*/
    BaaSKitAdmin.prototype.createApplication = function (applicationName, callback) {

    	var colleciton = BaaSKitDb.getInstance().getMainDb().collection ('applications');

		colleciton.findOne ({ 'name' : applicationName }, function (error, item) {

			if (item == null)
			{
				var app = {

					'name' : applicationName,
					'id' : libcrypto.randomBytes (12).toString ('hex'),
					'clientKey' : libcrypto.randomBytes (12).toString ('hex')
				};

				colleciton.insert (app, function (error, object) {

					if (!error)
					{
						callback (null, object[0]);
					}
					else
					{
						callback ({ 'message' : 'An unknown error occurred.' } , null);
					}
				});
			}
			else
			{
				callback ({ 'message' : 'An application with that name already exists.' } , null);
			}
		});
    };

    /** Deletes an application with a specified Id.
		@see createApplication
	*/
    BaaSKitAdmin.prototype.deleteApplication = function (applicationId, callback) {

    	var colleciton = BaaSKitDb.getInstance().getMainDb().collection ('applications');
    	var asksForUserConfirmation = this.asksForUserConfirmation;

		colleciton.findOne ({ 'id' : applicationId }, function (error, item) {

			if (item != null)
			{
				var confirmation = function (ok) {

					if (ok)
					{
						colleciton.remove (item, function (error, num) {

							if (!error)
							{
								callback (null);
							}
							else
							{
								callback ({ 'message' : 'An unknown error occurred.' });
							}
						});
					}
					else
					{
						callback ({ 'message' : 'goodbye' } , null);
					}
				};

				if (asksForUserConfirmation)
				{
					libcommander.confirm ('Are you sure you want to delete this application? ', function (ok) {

						confirmation (ok);
					});
				}
				else
				{
					confirmation (true);
				}
			}
			else
			{
				callback ({ 'message' : 'An application with that id does not exist.' });
			}
		});
    };

    /** Returns a list of all applications.
		@see getApplication
	*/
    BaaSKitAdmin.prototype.listAllApplications = function (callback) {

    	var colleciton = BaaSKitDb.getInstance().getMainDb().collection ('applications');

		colleciton.find ({}, {}, function (error, items) {

			items.toArray (function (error, items) {

				if (!error)
				{
					callback (null, items);
				}
				else
				{
					callback ({ 'message' : 'An unknown error occurred.' }, null);
				}
			});
		});
    };

    /** Returns an application with a specified Id.
		@see listAllApplications
	*/
    BaaSKitAdmin.prototype.getApplication = function (applicationId, callback) {

    	var colleciton = BaaSKitDb.getInstance().getMainDb().collection ('applications');

		colleciton.findOne ({ 'id' : applicationId }, function (error, object) {

			if (object != null)
			{
				callback (null, object);
			}
			else
			{
				callback ({ 'message' : 'An application with that id does not exist.' });
			}
		});
    };

	/** Generates a new clientKey for an application with a specified Id.
		@see createApplicaiton
	*/
    BaaSKitAdmin.prototype.generateApplicationClientKey = function (applicationId, callback) {

		var colleciton = BaaSKitDb.getInstance().getMainDb().collection ('applications');
		var asksForUserConfirmation = this.asksForUserConfirmation;

		colleciton.findOne ({ 'id' : applicationId }, function (error, item) {

			if (item != null)
			{
				var confirmation = function (ok) {

					if (ok)
					{
						var newClientKey = libcrypto.randomBytes (12).toString ('hex');
						var operator = { $set : { 'clientKey' : newClientKey } };

						colleciton.update (item, operator, function (error, result) {

							if (!error)
							{
								callback (null);
							}
							else
							{
								callback ({ 'message' : 'An unknown error occurred.' });
							}
						});
					}
					else
					{
						callback ({ 'message' : 'goodbye' });
					}
				};

				if (asksForUserConfirmation)
				{
					libcommander.confirm ('Are you sure you want to generate a new client key for this application? ', function (ok) {

						confirmation (ok);
					});
				}
				else
				{
					confirmation (true);
				}
			}
			else
			{
				callback ({ 'message' : 'An application with that id does not exist.' });
			}
		});
    };

    return BaaSKitAdmin;
})();

exports.BaaSKitAdmin = BaaSKitAdmin;<commit_msg>Fixed typo/spelling mistake in admin.js.<commit_after>/*
  ==============================================================================

   Copyright (C) 2013 Jacob Sologub

   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.

  ==============================================================================
*/

var libcrypto = require ('crypto');
var libcommander = require ('commander');
var libmongo = require ('mongodb');
var BSON = libmongo.BSONPure;

var BaaSKitDb = require ('./db').BaaSKitDb;

//==============================================================================
var BaaSKitAdmin = (function () {

	//==========================================================================
	/** Creates a BaaSKitAdmin object. */
    function BaaSKitAdmin (asksForUserConfirmation_)
    {
    	this.asksForUserConfirmation = asksForUserConfirmation_;
    }

    //==========================================================================
    /** Creates an application with a specified name if an application with the
    	specified name does not exists.

		@see deleteApplication
	*/
    BaaSKitAdmin.prototype.createApplication = function (applicationName, callback) {

    	var collection = BaaSKitDb.getInstance().getMainDb().collection ('applications');

		collection.findOne ({ 'name' : applicationName }, function (error, item) {

			if (item == null)
			{
				var app = {

					'name' : applicationName,
					'id' : libcrypto.randomBytes (12).toString ('hex'),
					'clientKey' : libcrypto.randomBytes (12).toString ('hex')
				};

				collection.insert (app, function (error, object) {

					if (!error)
					{
						callback (null, object[0]);
					}
					else
					{
						callback ({ 'message' : 'An unknown error occurred.' } , null);
					}
				});
			}
			else
			{
				callback ({ 'message' : 'An application with that name already exists.' } , null);
			}
		});
    };

    /** Deletes an application with a specified Id.
		@see createApplication
	*/
    BaaSKitAdmin.prototype.deleteApplication = function (applicationId, callback) {

    	var collection = BaaSKitDb.getInstance().getMainDb().collection ('applications');
    	var asksForUserConfirmation = this.asksForUserConfirmation;

		collection.findOne ({ 'id' : applicationId }, function (error, item) {

			if (item != null)
			{
				var confirmation = function (ok) {

					if (ok)
					{
						collection.remove (item, function (error, num) {

							if (!error)
							{
								callback (null);
							}
							else
							{
								callback ({ 'message' : 'An unknown error occurred.' });
							}
						});
					}
					else
					{
						callback ({ 'message' : 'goodbye' } , null);
					}
				};

				if (asksForUserConfirmation)
				{
					libcommander.confirm ('Are you sure you want to delete this application? ', function (ok) {

						confirmation (ok);
					});
				}
				else
				{
					confirmation (true);
				}
			}
			else
			{
				callback ({ 'message' : 'An application with that id does not exist.' });
			}
		});
    };

    /** Returns a list of all applications.
		@see getApplication
	*/
    BaaSKitAdmin.prototype.listAllApplications = function (callback) {

    	var collection = BaaSKitDb.getInstance().getMainDb().collection ('applications');

		collection.find ({}, {}, function (error, items) {

			items.toArray (function (error, items) {

				if (!error)
				{
					callback (null, items);
				}
				else
				{
					callback ({ 'message' : 'An unknown error occurred.' }, null);
				}
			});
		});
    };

    /** Returns an application with a specified Id.
		@see listAllApplications
	*/
    BaaSKitAdmin.prototype.getApplication = function (applicationId, callback) {

    	var collection = BaaSKitDb.getInstance().getMainDb().collection ('applications');

		collection.findOne ({ 'id' : applicationId }, function (error, object) {

			if (object != null)
			{
				callback (null, object);
			}
			else
			{
				callback ({ 'message' : 'An application with that id does not exist.' });
			}
		});
    };

	/** Generates a new clientKey for an application with a specified Id.
		@see createApplicaiton
	*/
    BaaSKitAdmin.prototype.generateApplicationClientKey = function (applicationId, callback) {

		var collection = BaaSKitDb.getInstance().getMainDb().collection ('applications');
		var asksForUserConfirmation = this.asksForUserConfirmation;

		collection.findOne ({ 'id' : applicationId }, function (error, item) {

			if (item != null)
			{
				var confirmation = function (ok) {

					if (ok)
					{
						var newClientKey = libcrypto.randomBytes (12).toString ('hex');
						var operator = { $set : { 'clientKey' : newClientKey } };

						collection.update (item, operator, function (error, result) {

							if (!error)
							{
								callback (null);
							}
							else
							{
								callback ({ 'message' : 'An unknown error occurred.' });
							}
						});
					}
					else
					{
						callback ({ 'message' : 'goodbye' });
					}
				};

				if (asksForUserConfirmation)
				{
					libcommander.confirm ('Are you sure you want to generate a new client key for this application? ', function (ok) {

						confirmation (ok);
					});
				}
				else
				{
					confirmation (true);
				}
			}
			else
			{
				callback ({ 'message' : 'An application with that id does not exist.' });
			}
		});
    };

    return BaaSKitAdmin;
})();

exports.BaaSKitAdmin = BaaSKitAdmin;<|endoftext|>


<commit_before>/**
 * Created by Christian on 24.02.2015.
 */
define(['./listeners'], function (listeners) {

  var scale = d3.scale.category10();
  var numTypes = -1;

  return {
    setTypeInfos: {},
    setInfos: {},

    addToType: function (setType, setId) {
      var t = this.setTypeInfos[setType];
      if (typeof t === "undefined") {
        numTypes++;
        t = {type: setType, sets: [setId], color: scale(numTypes)};
        this.setTypeInfos[setType] = t;
      } else {
        if (t.sets.indexOf(setId) === -1)
          t.sets.push(setId);
      }
    },

    getSetTypeInfo: function (type) {
      return this.setTypeInfos[type];
    },

    get: function (setId) {
      return this.setInfos[setId];
    },

    fetch: function (setIds) {
      var that = this;
      $.ajax({
        type: 'POST',
        url: '/api/pathway/setinfo',
        accepts: 'application/json',
        contentType: 'application/json',
        data: JSON.stringify(setIds),
        success: function (response) {
          var setInfos = JSON.parse(response);
          for (var key in setInfos) {

            var tempPWKey = key.substr(5, key.length);
            var localInfo = that.setInfos[tempPWKey];
            var fetchedInfo = setInfos[key];
            if (typeof localInfo !== "undefined") {
              for (var k in fetchedInfo) {
                localInfo[k] = fetchedInfo[k];
              }
            } else {
              that.setInfos[tempPWKey] = fetchedInfo;
            }
          }

          listeners.notify(listeners.updateType.SET_INFO_UPDATE, that);
        }
      });
    }
  }
})
<commit_msg>optimize setinfo to use a local cache<commit_after>/**
 * Created by Christian on 24.02.2015.
 */
define(['./listeners'], function (listeners) {

  var scale = d3.scale.category10();
  var numTypes = -1;

  return {
    setTypeInfos: {},
    setInfos: {},
    currentlyLoading : {},

    addToType: function (setType, setId) {
      var t = this.setTypeInfos[setType];
      if (typeof t === "undefined") {
        numTypes++;
        t = {type: setType, sets: [setId], color: scale(numTypes)};
        this.setTypeInfos[setType] = t;
      } else {
        if (t.sets.indexOf(setId) === -1)
          t.sets.push(setId);
      }
    },

    getSetTypeInfo: function (type) {
      return this.setTypeInfos[type];
    },

    get: function (setId) {
      return this.setInfos[setId];
    },

    fetch: function (setIds) {
      var that = this;
      //reduce to still unknown setsIds

      var lookup = setIds.filter(function(id) { return !(id in that.setInfos); });

      if (lookup.length === 0) { //all already loaded
        listeners.notify(listeners.updateType.SET_INFO_UPDATE, that);
        return;
      }

      //not currently loading
      lookup = setIds.filter(function(id) { return !(id in that.currentlyLoading); });

      if (lookup.length === 0) {
        return; // another callback will fire
      }

      //mark all as being catched
      lookup.forEach(function(d) { that.currentlyLoading[d] = true});
      $.getJSON('/api/pathway/setinfo', {
        sets : lookup
      }).then(function (data) {
        //integrate the map
        Object.keys(data).map(function(id) {
          var key = id.substr(5);
          that.setInfos[key] = data[id];
          delete that.currentlyLoading[key];
        });
        listeners.notify(listeners.updateType.SET_INFO_UPDATE, that);
      });
    }
  }
});
<|endoftext|>