<commit_before>/*!
 * React Native Autolink
 *
 * Copyright 2016 Josh Swan
 * Released under the MIT license
 * https://github.com/joshswan/react-native-autolink/blob/master/LICENSE
 */
'use strict';

import React, {Component, PropTypes, createElement} from 'react';
import Autolinker from 'autolinker';
import {Linking, StyleSheet, Text} from 'react-native';

export default class Autolink extends Component {
  getURL(match) {
    let type = match.getType();

    switch (type) {
      case 'email':
        return 'mailto://' + encodeURIComponent(match.getEmail());
      case 'hashtag':
        let tag = encodeURIComponent(match.getHashtag());

        switch (this.props.hashtag) {
          case 'facebook':
            return 'facebook://hashtag/' + tag;
          case 'instagram':
            return 'instagram://tag?name=' + tag;
          case 'twitter':
            return 'twitter://search?query=%23' + tag;
          default:
            return match.getMatchedText();
        }
      case 'phone':
        return 'tel://' + match.getNumber();
      case 'twitter':
        return 'twitter://user?screen_name=' + encodeURIComponent(match.getTwitterHandle());
      case 'url':
        return match.getAnchorHref();
      default:
        return match.getMatchedText();
    }
  }

  _onPress(url, match) {
    if (this.props.onPress) {
      this.props.onPress(url, match);
    } else {
      Linking.openURL(url);
    }
  }

  renderLink(text, url, match) {
    let truncated = (this.props.truncate > 0) ? Autolinker.truncate.TruncateSmart(text, this.props.truncate, this.props.truncateChars) : text;

    return (
      <Text
        style={[styles.link, this.props.linkStyle]}
        onPress={this._onPress.bind(this, url, match)}>
          {truncated}
      </Text>
    );
  }

  render() {
    let text = this.props.text || '';

    // Creates a token with a random UID that should not be guessable or
    // conflict with other parts of the string.
    let uid = Math.floor(Math.random() * 0x10000000000).toString(16);
    let tokenRegexp = new RegExp(`(@__ELEMENT-${uid}-\\d+__@)`, 'g');

    let generateToken = (() => {
      let counter = 0;
      return () => `@__ELEMENT-${uid}-${counter += 1}__@`;
    })();

    let matches = {};

    try {
      text = Autolinker.link(text, {
        email: this.props.email,
        hashtag: this.props.hashtag,
        phone: this.props.phone,
        twitter: this.props.twitter,
        urls: this.props.url,
        stripPrefix: this.props.stripPrefix,
        replaceFn: (autolinker, match) => {
          let token = generateToken();

          matches[token] = match;

          return token;
        },
      });
    } catch (e) {
      console.warn(e);

      return null;
    }

    let nodes = text
      .split(tokenRegexp)
      .filter((part) => !!part)
      .map((part) => {
        let match = matches[part];

        if (!match) return part;

        switch (match.getType()) {
          case 'email':
          case 'hashtag':
          case 'phone':
          case 'twitter':
          case 'url':
            return (this.props.renderLink) ? this.props.renderLink(match.getAnchorText(), this.getURL(match), match) : this.renderLink(match.getAnchorText(), this.getURL(match), match);
          default:
            return part;
        }
      });

    return createElement(Text, {ref: (component) => { this._root = component; }, style: this.props.style}, ...nodes);
  }
}

const styles = StyleSheet.create({
  link: {
    color: '#0E7AFE',
  },
});

Autolink.defaultProps = {
  email: true,
  hashtag: false,
  phone: true,
  stripPrefix: true,
  truncate: 32,
  truncateChars: '..',
  twitter: false,
  url: true,
};

Autolink.propTypes = {
  email: PropTypes.bool,
  hashtag: PropTypes.oneOf([false, 'facebook', 'instagram', 'twitter']),
  linkStyle: Text.propTypes.style,
  onPress: PropTypes.func,
  phone: PropTypes.bool,
  renderLink: PropTypes.func,
  stripPrefix: PropTypes.bool,
  style: Text.propTypes.style,
  text: PropTypes.string.isRequired,
  truncate: PropTypes.number,
  truncateChars: PropTypes.string,
  twitter: PropTypes.bool,
  url: PropTypes.bool,
};
<commit_msg>Add a key= to let React native distinguish different elements. Fixes this warning:<commit_after>/*!
 * React Native Autolink
 *
 * Copyright 2016 Josh Swan
 * Released under the MIT license
 * https://github.com/joshswan/react-native-autolink/blob/master/LICENSE
 */
'use strict';

import React, {Component, PropTypes, createElement} from 'react';
import Autolinker from 'autolinker';
import {Linking, StyleSheet, Text} from 'react-native';

export default class Autolink extends Component {
  getURL(match) {
    let type = match.getType();

    switch (type) {
      case 'email':
        return 'mailto://' + encodeURIComponent(match.getEmail());
      case 'hashtag':
        let tag = encodeURIComponent(match.getHashtag());

        switch (this.props.hashtag) {
          case 'facebook':
            return 'facebook://hashtag/' + tag;
          case 'instagram':
            return 'instagram://tag?name=' + tag;
          case 'twitter':
            return 'twitter://search?query=%23' + tag;
          default:
            return match.getMatchedText();
        }
      case 'phone':
        return 'tel://' + match.getNumber();
      case 'twitter':
        return 'twitter://user?screen_name=' + encodeURIComponent(match.getTwitterHandle());
      case 'url':
        return match.getAnchorHref();
      default:
        return match.getMatchedText();
    }
  }

  _onPress(url, match) {
    if (this.props.onPress) {
      this.props.onPress(url, match);
    } else {
      Linking.openURL(url);
    }
  }

  renderLink(text, url, match) {
    let truncated = (this.props.truncate > 0) ? Autolinker.truncate.TruncateSmart(text, this.props.truncate, this.props.truncateChars) : text;

    return (
      <Text
        key={text}
        style={[styles.link, this.props.linkStyle]}
        onPress={this._onPress.bind(this, url, match)}>
          {truncated}
      </Text>
    );
  }

  render() {
    let text = this.props.text || '';

    // Creates a token with a random UID that should not be guessable or
    // conflict with other parts of the string.
    let uid = Math.floor(Math.random() * 0x10000000000).toString(16);
    let tokenRegexp = new RegExp(`(@__ELEMENT-${uid}-\\d+__@)`, 'g');

    let generateToken = (() => {
      let counter = 0;
      return () => `@__ELEMENT-${uid}-${counter += 1}__@`;
    })();

    let matches = {};

    try {
      text = Autolinker.link(text, {
        email: this.props.email,
        hashtag: this.props.hashtag,
        phone: this.props.phone,
        twitter: this.props.twitter,
        urls: this.props.url,
        stripPrefix: this.props.stripPrefix,
        replaceFn: (autolinker, match) => {
          let token = generateToken();

          matches[token] = match;

          return token;
        },
      });
    } catch (e) {
      console.warn(e);

      return null;
    }

    let nodes = text
      .split(tokenRegexp)
      .filter((part) => !!part)
      .map((part) => {
        let match = matches[part];

        if (!match) return part;

        switch (match.getType()) {
          case 'email':
          case 'hashtag':
          case 'phone':
          case 'twitter':
          case 'url':
            return (this.props.renderLink) ? this.props.renderLink(match.getAnchorText(), this.getURL(match), match) : this.renderLink(match.getAnchorText(), this.getURL(match), match);
          default:
            return part;
        }
      });

    return createElement(Text, {ref: (component) => { this._root = component; }, style: this.props.style}, ...nodes);
  }
}

const styles = StyleSheet.create({
  link: {
    color: '#0E7AFE',
  },
});

Autolink.defaultProps = {
  email: true,
  hashtag: false,
  phone: true,
  stripPrefix: true,
  truncate: 32,
  truncateChars: '..',
  twitter: false,
  url: true,
};

Autolink.propTypes = {
  email: PropTypes.bool,
  hashtag: PropTypes.oneOf([false, 'facebook', 'instagram', 'twitter']),
  linkStyle: Text.propTypes.style,
  onPress: PropTypes.func,
  phone: PropTypes.bool,
  renderLink: PropTypes.func,
  stripPrefix: PropTypes.bool,
  style: Text.propTypes.style,
  text: PropTypes.string.isRequired,
  truncate: PropTypes.number,
  truncateChars: PropTypes.string,
  twitter: PropTypes.bool,
  url: PropTypes.bool,
};
<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import BrowserRouter from 'react-router/BrowserRouter';
import { Provider } from 'react-redux';
import throttle from 'lodash/throttle';
import { loadState, saveState } from './utils/localStorage';
import rootReducer from './reducers';
import App from './views/App';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(rootReducer, loadState(), composeEnhancers(
  applyMiddleware(thunk)
));

store.subscribe(throttle(() => {
  const { token } = store.getState();
  saveState({
    token
  });
}), 1000);

render(
  <BrowserRouter>
    <Provider store={store}>
      <App />
    </Provider>
  </BrowserRouter>,
  document.getElementById('content')
);

/*
TODO :
- /// Build an unstyled "recipe" page directing to the right ID
- Put a different feel to the header in the Add Page ! (user request)
- Add page : add submit logic to firebase, add UI for invalid inputs :
  tooltip + red color on invalid inputs, disabled bottom button + recap of errors there*
- Add page : add notification for when recipe add succeeded / failed, modal ?
- Fix the ingredients form getting rendered twice on load
- Fix the "e" key reseting the numeric field ?
- Get the add page working fully
- use firebase rest api instead of sdk to shave client bytes
- Browse page : implement actual filters on recipes when selected
- Browse page : add first to last / last to first settings for triage
- FIX react router keeping the scrolling intact on route change!!!!
- Change avatar (also in menu items) to use image instead of background image maybe ?
- Add transition delay as inline style for user menu items
- Convert the NavBar to be dynamic based off route
- add "fake" loader as top bar (http://ricostacruz.com/nprogress/)
- add a generic loader component (the same one as my twitch project ?)
- Add a <form> html element to the Landing page header so that enter navigates to "browse"
- extract the logic from mapstatetoprops and put it in selectors (in reducer files)
- Get the "recipe" page working fully
- polish the ux, animations, transition between routes.. look at reactcsstransitiongroup & react motion
- Try to see if I can cache the recipes for offline and only update the modified records,
  check localforage, redux persist..
- localforage looks good
- find some improvements to start downloading other common routes
  from the landing page after it is interactive
*/
<commit_msg>Update TODOS<commit_after>import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import BrowserRouter from 'react-router/BrowserRouter';
import { Provider } from 'react-redux';
import throttle from 'lodash/throttle';
import { loadState, saveState } from './utils/localStorage';
import rootReducer from './reducers';
import App from './views/App';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(rootReducer, loadState(), composeEnhancers(
  applyMiddleware(thunk)
));

store.subscribe(throttle(() => {
  const { token } = store.getState();
  saveState({
    token
  });
}), 1000);

render(
  <BrowserRouter>
    <Provider store={store}>
      <App />
    </Provider>
  </BrowserRouter>,
  document.getElementById('content')
);

/*
TODO :
- Put a different feel to the header in the Add Page ! (user request)
- Add page : add submit logic to firebase, add UI for invalid inputs :
  tooltip + red color on invalid inputs, disabled bottom button + recap of errors there*
- Add page : add notification for when recipe add succeeded / failed, modal ?
- Fix the ingredients form getting rendered twice on load
- Fix the "e" key reseting the numeric field ?
- Get the add page working fully
- use firebase rest api instead of sdk to shave client bytes
- Browse page : implement actual filters on recipes when selected
- Browse page : add first to last / last to first settings for triage
- FIX react router keeping the scrolling intact on route change!!!!
- Change avatar (also in menu items) to use image instead of background image maybe ?
- Add transition delay as inline style for user menu items
- Convert the NavBar to be dynamic based off route
- add "fake" loader as top bar (http://ricostacruz.com/nprogress/)
- add a generic loader component (the same one as my twitch project ?)
- Add a <form> html element to the Landing page header so that enter navigates to "browse"
- extract the logic from mapstatetoprops and put it in selectors (in reducer files)
- Get the "recipe" page working fully
- polish the ux, animations, transition between routes.. look at reactcsstransitiongroup & react motion
- Try to see if I can cache the recipes for offline and only update the modified records,
  check localforage, redux persist..
- localforage looks good
- find some improvements to start downloading other common routes
  from the landing page after it is interactive
*/
<|endoftext|>


<commit_before>import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Router, Route, IndexRoute, IndexRedirect, Redirect } from "react-router";
import { routerActions } from "react-router-redux";
import { connectedReduxRedirect } from "redux-auth-wrapper/history3/redirect";

import { setConfig } from "./app/config/actions";
import App from "./app/App";
import Layout from "./app/global/Layout";
import LoginController from "./app/views/login/LoginController";
import CollectionsController from "./app/views/collections/CollectionsController";
import TeamsController from "./app/views/teams/TeamsController";
import SelectADataset from "./app/views/datasets-new/DatasetsController";
import DatasetEditionsController from "./app/views/datasets-new/editions/DatasetEditionsController";
import DatasetVersionsController from "./app/views/datasets-new/versions/DatasetVersionsController";
import DatasetMetadataController from "./app/views/datasets-new/edit-metadata/DatasetMetadataController";
import CreateVersionController from "./app/views/datasets-new/create/CreateVersionController";
import CreateEditionController from "./app/views/datasets-new/create/CreateEditionController";
import UsersController from "./app/views/users/UsersController";
import UserDetailsController from "./app/views/users/details/UserDetailsController";
import DatasetsController from "./app/views/datasets/DatasetsController";
import DatasetUploadsController from "./app/views/uploads/dataset/DatasetUploadsController";
import DatasetUploadDetails from "./app/views/uploads/dataset/upload-details/DatasetUploadDetails";
import DatasetUploadMetadata from "./app/views/uploads/dataset/upload-details/DatasetUploadMetadata";
import DatasetMetadata from "./app/views/datasets/metadata/DatasetMetadata";
import VersionMetadata from "./app/views/datasets/metadata/VersionMetadata";
import Logs from "./app/views/logs/Logs";

import auth from "./app/utilities/auth";

import "./scss/main.scss";

import { store, history } from "./app/config/store";

import SelectableTest from "./SelectableTest";
import VersionPreviewController from "./app/views/datasets/preview/VersionPreviewController";
import PreviewController from "./app/views/preview/PreviewController";
import DatasetPreviewController from "./app/views/datasets-new/preview/PreviewController";
import EditMetadataItem from "./app/views/datasets-new/edit-metadata/EditMetadataItem";
import ChangeUserPasswordController from "./app/views/users/change-password/ChangeUserPasswordController";
import ConfirmUserDeleteController from "./app/views/users/confirm-delete/ConfirmUserDeleteController";
import CollectionRoutesWrapper from "./app/global/collection-wrapper/CollectionRoutesWrapper";

const config = window.getEnv();
store.dispatch(setConfig(config));

const rootPath = store.getState().state.rootPath;

const userIsAuthenticated = connectedReduxRedirect({
    authenticatedSelector: state => {
        return auth.isAuthenticated(state.state.user);
    },
    redirectAction: routerActions.replace,
    wrapperDisplayName: "UserIsAuthenticated",
    redirectPath: `${rootPath}/login`
});

const userIsAdminOrEditor = connectedReduxRedirect({
    authenticatedSelector: state => {
        return auth.isAdminOrEditor(state.state.user);
    },
    redirectAction: routerActions.replace,
    wrapperDisplayName: "userIsAdminOrEditor",
    redirectPath: `${rootPath}/collections`,
    allowRedirectBack: false
});

class UnknownRoute extends Component {
    render() {
        return (

Sorry, this page couldnt be found

        );
    }
}

class Index extends Component {
    render() {
        return (
            <Provider store={store}>
                <Router history={history}>
                    <Route component={App}>
                        <Route component={Layout}>
                            <Redirect from={`${rootPath}`} to={`${rootPath}/collections`} />
                            <Route path={`${rootPath}/collections`} component={userIsAuthenticated(CollectionsController)}>
                                <Route path=":collectionID" component={userIsAuthenticated(CollectionsController)}>
                                    <Route path="edit" component={userIsAuthenticated(CollectionsController)} />
                                    <Route path="restore-content" component={userIsAuthenticated(CollectionsController)} />
                                </Route>
                            </Route>
                            <Route path={`${rootPath}/collections/:collectionID/preview`} component={userIsAuthenticated(PreviewController)} />

                            {config.enableDatasetImport === true && (
                                <Route component={CollectionRoutesWrapper}>
                                    <Route path={`${rootPath}/collections/:collectionID/datasets`}>
                                        <IndexRoute component={userIsAuthenticated(SelectADataset)} />
                                        <Route path=":datasetID">
                                            <IndexRoute component={userIsAuthenticated(DatasetEditionsController)} />
                                            <Route path={`editions`} component={userIsAuthenticated(CreateEditionController)} />
                                            <Route path="editions/:editionID">
                                                <Route path={`instances`} component={userIsAuthenticated(CreateVersionController)} />
                                                <IndexRoute component={userIsAuthenticated(DatasetVersionsController)} />
                                                <Route path={`versions/:versionID`} component={userIsAuthenticated(DatasetMetadataController)}>
                                                    <Route
                                                        path={`edit/:metadataField/:metadataItemID`}
                                                        component={userIsAuthenticated(EditMetadataItem)}
                                                    />
                                                </Route>
                                                <Route path="versions/:versionID/preview" component={userIsAuthenticated(DatasetPreviewController)} />
                                            </Route>
                                        </Route>
                                    </Route>
                                </Route>
                            )}

                            <Route path={`${rootPath}/teams`} component={userIsAuthenticated(userIsAdminOrEditor(TeamsController))}>
                                <Route path=":team" component={userIsAuthenticated(TeamsController)}>
                                    <Route path="edit" component={userIsAuthenticated(TeamsController)} />
                                    <Route path="delete" component={userIsAuthenticated(TeamsController)} />
                                </Route>
                            </Route>
                            <Route path={`${rootPath}/users`} component={userIsAuthenticated(userIsAdminOrEditor(UsersController))}>
                                <Route path=":userID" component={userIsAuthenticated(userIsAdminOrEditor(UserDetailsController))}>
                                    <Route
                                        path="change-password"
                                        component={userIsAuthenticated(userIsAdminOrEditor(ChangeUserPasswordController))}
                                    />
                                    <Route path="confirm-delete" component={userIsAuthenticated(userIsAdminOrEditor(ConfirmUserDeleteController))} />
                                </Route>
                            </Route>
                            {config.enableDatasetImport === true && (
                                <Route>
                                    <Route path={`${rootPath}/uploads`}>
                                        <IndexRedirect to="data" />
                                        <Route path="data">
                                            <IndexRoute component={userIsAuthenticated(userIsAdminOrEditor(DatasetUploadsController))} />
                                            <Route path=":jobID">
                                                <IndexRoute component={userIsAuthenticated(userIsAdminOrEditor(DatasetUploadDetails))} />
                                                <Route path="metadata" component={userIsAuthenticated(userIsAdminOrEditor(DatasetUploadMetadata))} />
                                            </Route>
                                        </Route>
                                    </Route>
                                    <Route path={`${rootPath}/datasets`}>
                                        <IndexRoute component={userIsAuthenticated(userIsAdminOrEditor(DatasetsController))} />
                                        <Route path=":datasetID">
                                            <IndexRedirect to={`${rootPath}/datasets`} />
                                            <Route path="preview" component={userIsAuthenticated(userIsAdminOrEditor(DatasetPreviewController))} />
                                            <Route path="metadata" component={userIsAuthenticated(userIsAdminOrEditor(DatasetMetadata))} />
                                            <Route path="editions/:edition/versions/:version">
                                                <IndexRedirect to="metadata" />
                                                <Route path="metadata" component={userIsAuthenticated(userIsAdminOrEditor(VersionMetadata))} />
                                                <Route
                                                    path="preview"
                                                    component={userIsAuthenticated(userIsAdminOrEditor(VersionPreviewController))}
                                                />
                                            </Route>
                                            <Route path="instances">
                                                <IndexRedirect to={`${rootPath}/datasets`} />
                                                <Route
                                                    path=":instanceID/metadata"
                                                    component={userIsAuthenticated(userIsAdminOrEditor(VersionMetadata))}
                                                />
                                            </Route>
                                        </Route>
                                    </Route>
                                </Route>
                            )}
                            <Route path={`${rootPath}/selectable-list`} component={SelectableTest} />
                            <Route path={`${rootPath}/logs`} component={Logs} />
                            <Route path={`${rootPath}/login`} component={LoginController} />
                            <Route path="*" component={UnknownRoute} />
                        </Route>
                    </Route>
                </Router>
            </Provider>
        );
    }
}

ReactDOM.render(<Index />, document.getElementById("app"));
<commit_msg>Add route for create dataset<commit_after>import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Router, Route, IndexRoute, IndexRedirect, Redirect } from "react-router";
import { routerActions } from "react-router-redux";
import { connectedReduxRedirect } from "redux-auth-wrapper/history3/redirect";

import { setConfig } from "./app/config/actions";
import App from "./app/App";
import Layout from "./app/global/Layout";
import LoginController from "./app/views/login/LoginController";
import CollectionsController from "./app/views/collections/CollectionsController";
import TeamsController from "./app/views/teams/TeamsController";
import SelectADataset from "./app/views/datasets-new/DatasetsController";
import DatasetEditionsController from "./app/views/datasets-new/editions/DatasetEditionsController";
import DatasetVersionsController from "./app/views/datasets-new/versions/DatasetVersionsController";
import DatasetMetadataController from "./app/views/datasets-new/edit-metadata/DatasetMetadataController";
import CreateDatasetController from "./app/views/datasets-new/create/CreateDatasetController";
import CreateVersionController from "./app/views/datasets-new/create/CreateVersionController";
import CreateEditionController from "./app/views/datasets-new/create/CreateEditionController";
import UsersController from "./app/views/users/UsersController";
import UserDetailsController from "./app/views/users/details/UserDetailsController";
import DatasetsController from "./app/views/datasets/DatasetsController";
import DatasetUploadsController from "./app/views/uploads/dataset/DatasetUploadsController";
import DatasetUploadDetails from "./app/views/uploads/dataset/upload-details/DatasetUploadDetails";
import DatasetUploadMetadata from "./app/views/uploads/dataset/upload-details/DatasetUploadMetadata";
import DatasetMetadata from "./app/views/datasets/metadata/DatasetMetadata";
import VersionMetadata from "./app/views/datasets/metadata/VersionMetadata";
import Logs from "./app/views/logs/Logs";

import auth from "./app/utilities/auth";

import "./scss/main.scss";

import { store, history } from "./app/config/store";

import SelectableTest from "./SelectableTest";
import VersionPreviewController from "./app/views/datasets/preview/VersionPreviewController";
import PreviewController from "./app/views/preview/PreviewController";
import DatasetPreviewController from "./app/views/datasets-new/preview/PreviewController";
import EditMetadataItem from "./app/views/datasets-new/edit-metadata/EditMetadataItem";
import ChangeUserPasswordController from "./app/views/users/change-password/ChangeUserPasswordController";
import ConfirmUserDeleteController from "./app/views/users/confirm-delete/ConfirmUserDeleteController";
import CollectionRoutesWrapper from "./app/global/collection-wrapper/CollectionRoutesWrapper";

const config = window.getEnv();
store.dispatch(setConfig(config));

const rootPath = store.getState().state.rootPath;

const userIsAuthenticated = connectedReduxRedirect({
    authenticatedSelector: state => {
        return auth.isAuthenticated(state.state.user);
    },
    redirectAction: routerActions.replace,
    wrapperDisplayName: "UserIsAuthenticated",
    redirectPath: `${rootPath}/login`
});

const userIsAdminOrEditor = connectedReduxRedirect({
    authenticatedSelector: state => {
        return auth.isAdminOrEditor(state.state.user);
    },
    redirectAction: routerActions.replace,
    wrapperDisplayName: "userIsAdminOrEditor",
    redirectPath: `${rootPath}/collections`,
    allowRedirectBack: false
});

class UnknownRoute extends Component {
    render() {
        return (

Sorry, this page couldnt be found

        );
    }
}

class Index extends Component {
    render() {
        return (
            <Provider store={store}>
                <Router history={history}>
                    <Route component={App}>
                        <Route component={Layout}>
                            <Redirect from={`${rootPath}`} to={`${rootPath}/collections`} />
                            <Route path={`${rootPath}/collections`} component={userIsAuthenticated(CollectionsController)}>
                                <Route path=":collectionID" component={userIsAuthenticated(CollectionsController)}>
                                    <Route path="edit" component={userIsAuthenticated(CollectionsController)} />
                                    <Route path="restore-content" component={userIsAuthenticated(CollectionsController)} />
                                </Route>
                            </Route>
                            <Route path={`${rootPath}/collections/:collectionID/preview`} component={userIsAuthenticated(PreviewController)} />

                            {config.enableDatasetImport === true && (
                                <Route component={CollectionRoutesWrapper}>
                                    <Route path={`${rootPath}/collections/:collectionID/datasets`}>
                                        <IndexRoute component={userIsAuthenticated(SelectADataset)} />
                                        <Route path="create">
                                            <IndexRoute component={userIsAuthenticated(CreateDatasetController)} />
                                        </Route>
                                        <Route path=":datasetID">
                                            <IndexRoute component={userIsAuthenticated(DatasetEditionsController)} />
                                            <Route path={`editions`} component={userIsAuthenticated(CreateEditionController)} />
                                            <Route path="editions/:editionID">
                                                <Route path={`instances`} component={userIsAuthenticated(CreateVersionController)} />
                                                <IndexRoute component={userIsAuthenticated(DatasetVersionsController)} />
                                                <Route path={`versions/:versionID`} component={userIsAuthenticated(DatasetMetadataController)}>
                                                    <Route
                                                        path={`edit/:metadataField/:metadataItemID`}
                                                        component={userIsAuthenticated(EditMetadataItem)}
                                                    />
                                                </Route>
                                                <Route path="versions/:versionID/preview" component={userIsAuthenticated(DatasetPreviewController)} />
                                            </Route>
                                        </Route>
                                        <Route path="datasets/create" component={userIsAuthenticated(CollectionsController)} />
                                    </Route>
                                </Route>
                            )}

                            <Route path={`${rootPath}/teams`} component={userIsAuthenticated(userIsAdminOrEditor(TeamsController))}>
                                <Route path=":team" component={userIsAuthenticated(TeamsController)}>
                                    <Route path="edit" component={userIsAuthenticated(TeamsController)} />
                                    <Route path="delete" component={userIsAuthenticated(TeamsController)} />
                                </Route>
                            </Route>
                            <Route path={`${rootPath}/users`} component={userIsAuthenticated(userIsAdminOrEditor(UsersController))}>
                                <Route path=":userID" component={userIsAuthenticated(userIsAdminOrEditor(UserDetailsController))}>
                                    <Route
                                        path="change-password"
                                        component={userIsAuthenticated(userIsAdminOrEditor(ChangeUserPasswordController))}
                                    />
                                    <Route path="confirm-delete" component={userIsAuthenticated(userIsAdminOrEditor(ConfirmUserDeleteController))} />
                                </Route>
                            </Route>
                            {config.enableDatasetImport === true && (
                                <Route>
                                    <Route path={`${rootPath}/uploads`}>
                                        <IndexRedirect to="data" />
                                        <Route path="data">
                                            <IndexRoute component={userIsAuthenticated(userIsAdminOrEditor(DatasetUploadsController))} />
                                            <Route path=":jobID">
                                                <IndexRoute component={userIsAuthenticated(userIsAdminOrEditor(DatasetUploadDetails))} />
                                                <Route path="metadata" component={userIsAuthenticated(userIsAdminOrEditor(DatasetUploadMetadata))} />
                                            </Route>
                                        </Route>
                                    </Route>
                                    <Route path={`${rootPath}/datasets`}>
                                        <IndexRoute component={userIsAuthenticated(userIsAdminOrEditor(DatasetsController))} />
                                        <Route path=":datasetID">
                                            <IndexRedirect to={`${rootPath}/datasets`} />
                                            <Route path="preview" component={userIsAuthenticated(userIsAdminOrEditor(DatasetPreviewController))} />
                                            <Route path="metadata" component={userIsAuthenticated(userIsAdminOrEditor(DatasetMetadata))} />
                                            <Route path="editions/:edition/versions/:version">
                                                <IndexRedirect to="metadata" />
                                                <Route path="metadata" component={userIsAuthenticated(userIsAdminOrEditor(VersionMetadata))} />
                                                <Route
                                                    path="preview"
                                                    component={userIsAuthenticated(userIsAdminOrEditor(VersionPreviewController))}
                                                />
                                            </Route>
                                            <Route path="instances">
                                                <IndexRedirect to={`${rootPath}/datasets`} />
                                                <Route
                                                    path=":instanceID/metadata"
                                                    component={userIsAuthenticated(userIsAdminOrEditor(VersionMetadata))}
                                                />
                                            </Route>
                                        </Route>
                                    </Route>
                                </Route>
                            )}
                            <Route path={`${rootPath}/selectable-list`} component={SelectableTest} />
                            <Route path={`${rootPath}/logs`} component={Logs} />
                            <Route path={`${rootPath}/login`} component={LoginController} />
                            <Route path="*" component={UnknownRoute} />
                        </Route>
                    </Route>
                </Router>
            </Provider>
        );
    }
}

ReactDOM.render(<Index />, document.getElementById("app"));
<|endoftext|>


<commit_before>/*globals exports, require */

'use strict';

var check, syntaxDefinitions;

check = require('check-types');
syntaxDefinitions = require('./syntax');

exports.walk = walk;

function walk (tree, settings, callbacks) {
    var syntaxes

    check.verifyObject(callbacks, 'Invalid callbacks');
    check.verifyFunction(callbacks.processNode, 'Invalid processNode callback');
    check.verifyFunction(callbacks.createScope, 'Invalid createScope callback');

    syntaxes = syntaxDefinitions.get(settings);

    visitNodes(tree);

    function visitNodes (nodes, assignedName) {
        check.verifyArray(tree, 'Invalid syntax tree');

        tree.forEach(function (node) {
            visitNode(node, assignedName);
        });
    }

    function visitNode (node, assignedName) {
        var syntax;

        if (check.isObject(node)) {
            syntax = syntaxes[node.type];

            if (check.isObject(syntax)) {
                callbacks.processNode(node, syntax);

                if (syntax.newScope) {
                    callbacks.createScope(node.id, assignedName, node.loc, node.params.length);
                }

                visitChildren(node);
            }
        }
    }

    function visitChildren (node) {
        var syntax = syntaxes[node.type];

        if (check.isArray(syntax.children)) {
            syntax.children.forEach(function (child) {
                visitChild(
                    node[child],
                    check.isFunction(syntax.assignableName) ? syntax.assignableName(node) : '',
                    currentReport
                );
            });
        }
    }

    function visitChild (child, assignedName) {
        var visitor = check.isArray(child) ? visitNodes : visitNode;
        visitor(child, assignedName);
    }
}

<commit_msg>Fixes for new interface.<commit_after>/*globals exports, require */

'use strict';

var check, syntaxDefinitions;

check = require('check-types');
syntaxDefinitions = require('./syntax');

exports.walk = walk;

function walk (tree, settings, callbacks) {
    var syntaxes

    check.verifyObject(tree, 'Invalid syntax tree');
    check.verifyArray(tree.body, 'Invalid syntax tree');
    check.verifyObject(settings, 'Invalid settings');
    check.verifyObject(callbacks, 'Invalid callbacks');
    check.verifyFunction(callbacks.processNode, 'Invalid processNode callback');
    check.verifyFunction(callbacks.createScope, 'Invalid createScope callback');

    syntaxes = syntaxDefinitions.get(settings);

    visitNodes(tree.body);

    function visitNodes (nodes, assignedName) {
        tree.forEach(function (node) {
            visitNode(node, assignedName);
        });
    }

    function visitNode (node, assignedName) {
        var syntax;

        if (check.isObject(node)) {
            syntax = syntaxes[node.type];

            if (check.isObject(syntax)) {
                callbacks.processNode(node, syntax);

                if (syntax.newScope) {
                    callbacks.createScope(node.id, assignedName, node.loc, node.params.length);
                }

                visitChildren(node);
            }
        }
    }

    function visitChildren (node) {
        var syntax = syntaxes[node.type];

        if (check.isArray(syntax.children)) {
            syntax.children.forEach(function (child) {
                visitChild(
                    node[child],
                    check.isFunction(syntax.assignableName) ? syntax.assignableName(node) : '',
                    currentReport
                );
            });
        }
    }

    function visitChild (child, assignedName) {
        var visitor = check.isArray(child) ? visitNodes : visitNode;
        visitor(child, assignedName);
    }
}

<|endoftext|>


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

export default function textdomain(translations, pluralForm) {
	const EOT = '\u0004'; // End of Transmission

	const getTranslations = function () {
		// if translations is function, call it to get translations object,
		// otherwise just use incoming translations object
		return typeof translations === 'function' ? translations() : translations;
	};

	const getPluralForm = (n) => {
		// return 0 if n is not integer
		if (isNaN(parseInt(n, 10))) {
			return 0;
		}

		// if pluralForm is function, use it to get plural form index
		if (typeof pluralForm === 'function') {
			return pluralForm(n);
		}

		// if pluralForm is string and contains only "n", "0-9", " ", "=?:%+-/*><&|"
		// characters, then we can eval it to calculate plural form
		if (typeof pluralForm === 'string' && !pluralForm.match(/[^n0-9 =?:%+-/*><&|]/i)) {
			/* eslint-disable no-eval */
			return eval(pluralForm.toLowerCase().split('n').join(n));
			/* eslint-enable no-eval */
		}

		return 0;
	};

	// return HOC function
	return (WrappedComponent) => {
		const WithGettext = class extends Component {
			getChildContext() {
				return {
					gettext: WithGettext.gettext,
					ngettext: WithGettext.ngettext,
					xgettext: WithGettext.xgettext,
				};
			}

			static gettext(message) {
				const messages = getTranslations();

				return messages[message] ? messages[message] : message;
			}

			static ngettext(singular, plural, n) {
				const messages = getTranslations();
				const pluralIndex = getPluralForm(n);

				return Array.isArray(messages[singular]) && messages[singular][pluralIndex]
					? messages[singular][pluralIndex]
					: singular;
			}

			static xgettext(message, context) {
				const messages = getTranslations();
				const key = context + EOT + message;

				return messages[key] ? messages[key] : message;
			}

			render() {
				return <WrappedComponent {...this.props} />;
			}
		};

		WithGettext.displayName = `WithGettext(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;

		WithGettext.childContextTypes = {
			gettext: PropTypes.func,
			ngettext: PropTypes.func,
			xgettext: PropTypes.func,
		};

		return WithGettext;
	};
}
<commit_msg>Converted plural form calculation result to integer<commit_after>import React, { Component, PropTypes } from 'react';

export default function textdomain(translations, pluralForm) {
	const EOT = '\u0004'; // End of Transmission

	const getTranslations = function () {
		// if translations is function, call it to get translations object,
		// otherwise just use incoming translations object
		return typeof translations === 'function' ? translations() : translations;
	};

	const getPluralForm = (n) => {
		// return 0 if n is not integer
		if (isNaN(parseInt(n, 10))) {
			return 0;
		}

		// if pluralForm is function, use it to get plural form index
		if (typeof pluralForm === 'function') {
			return pluralForm(n);
		}

		// if pluralForm is string and contains only "n", "0-9", " ", "=?:%+-/*><&|"
		// characters, then we can eval it to calculate plural form
		if (typeof pluralForm === 'string' && !pluralForm.match(/[^n0-9 =?:%+-/*><&|]/i)) {
			/* eslint-disable no-eval */
			return +eval(pluralForm.toLowerCase().split('n').join(n));
			/* eslint-enable no-eval */
		}

		return 0;
	};

	// return HOC function
	return (WrappedComponent) => {
		const WithGettext = class extends Component {
			getChildContext() {
				return {
					gettext: WithGettext.gettext,
					ngettext: WithGettext.ngettext,
					xgettext: WithGettext.xgettext,
				};
			}

			static gettext(message) {
				const messages = getTranslations();

				return messages[message] ? messages[message] : message;
			}

			static ngettext(singular, plural, n) {
				const messages = getTranslations();
				const pluralIndex = getPluralForm(n);

				return Array.isArray(messages[singular]) && messages[singular][pluralIndex]
					? messages[singular][pluralIndex]
					: singular;
			}

			static xgettext(message, context) {
				const messages = getTranslations();
				const key = context + EOT + message;

				return messages[key] ? messages[key] : message;
			}

			render() {
				return <WrappedComponent {...this.props} />;
			}
		};

		WithGettext.displayName = `WithGettext(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;

		WithGettext.childContextTypes = {
			gettext: PropTypes.func,
			ngettext: PropTypes.func,
			xgettext: PropTypes.func,
		};

		return WithGettext;
	};
}
<|endoftext|>


<commit_before>import path from 'path'
import { readFile as _readFile } from 'fs'
import promisify from 'es6-promisify'
import forEach from 'lodash.foreach'
import isObject from 'lodash.isobject'
import GitHubApi from 'github'
import Mustache from 'mustache'
import { asc as sortVersions } from 'semver-sort'

const readFile = promisify(_readFile)
const templateCache = {}

const DEFAULT_TEMPLATE = path.resolve(__dirname, 'defaultTemplate.md.hbs')
const NO_PREVIOUS_RELEASE = new Error('No previous release found')

const createGitHubRelease = async config => {
  if (!isObject(config)) {
    throw new Error('config must be an object')
  }
  ;['authenticateOptions', 'owner', 'repo', 'tag'].forEach(property => {
    if (!config[property]) {
      throw new Error(`${property} property is required`)
    }
  })
  forEach(
    {
      authenticateOptions: 'object',
      owner: 'string',
      repo: 'string',
      tag: 'string',
      render: 'function',
      template: 'string',
      templateProps: 'object',
      showDiff: 'function',
      apiOptions: 'object',
    },
    (type, property) => {
      const value = config[property]
      if (value !== undefined && (type === 'object' ? !isObject(value) : typeof value !== type)) {
        throw new Error(`${property} property must be of type ${type}`)
      }
    }
  )
  if (config.template && config.render) {
    throw new Error('template and render properties are exclusive')
  }

  const {
    authenticateOptions,
    owner,
    repo,
    tag,
    template: templatePath = DEFAULT_TEMPLATE,
    templateProps = {},
    showDiff = () => true,
    apiOptions = {},
  } = config

  let render
  if (config.render) {
    render = async view => await config.render(view)
  } else {
    let fetchingTemplate = templateCache[templatePath]
    if (!fetchingTemplate) {
      fetchingTemplate = readFile(templatePath, 'utf8')
      templateCache[templatePath] = fetchingTemplate
    }
    const template = await fetchingTemplate
    render = async view => Mustache.render(template, view)
  }

  const gitHub = new GitHubApi(apiOptions)
  gitHub.authenticate(authenticateOptions)

  const { newTag, previousTag } = await fetchTags(gitHub, { owner, repo, tag })
  const { compareUrl, commits, files } = await fetchDiff(gitHub, {
    owner,
    repo,
    newTag,
    previousTag,
  })
  const pullRequests = await fetchPullRequests(gitHub, { owner, repo, commits })
  const body = await renderBody({
    owner,
    repo,
    showDiff,
    newTag,
    render,
    templateProps,
    previousTag,
    compareUrl,
    commits,
    files,
    pullRequests,
  })

  return await createRelease(gitHub, { owner, repo, newTag, body })
}

createGitHubRelease.DEFAULT_TEMPLATE = DEFAULT_TEMPLATE
createGitHubRelease.NO_PREVIOUS_RELEASE = NO_PREVIOUS_RELEASE

export default createGitHubRelease

const fetchTags = async (gitHub, { owner, repo, tag }) => {
  const { data } = await gitHub.gitdata.getTags({ owner, repo })
  const tags = sortVersions(data.map(_tag => _tag.ref.split('/').pop()))

  const newTagIndex = tags.findIndex(_tag => _tag === tag)

  if (newTagIndex < 0) {
    throw new Error(`Could not find tag ${tag}`)
  } else if (newTagIndex === 0) {
    throw NO_PREVIOUS_RELEASE
  }

  return {
    newTag: tags[newTagIndex],
    previousTag: tags[newTagIndex - 1],
  }
}

const fetchDiff = async (gitHub, { owner, repo, newTag, previousTag }) => {
  const { data } = await gitHub.repos.compareCommits({
    owner,
    repo,
    base: previousTag,
    head: newTag,
  })
  return {
    compareUrl: data.html_url,
    commits: data.commits.map(commit => ({
      id: commit.sha.substr(0, 7),
      url: commit.html_url,
      author: {
        name: commit.author.login,
        url: commit.author.html_url,
        avatar: commit.author.avatar_url,
      },
      date: new Date(commit.commit.committer.date),
      message: commit.commit.message,
    })),
    files: data.files.map(file => ({
      filename: file.filename,
      url: file.blob_url,
      status: file.status,
      changes: file.changes,
      diff: file.patch || null,
    })),
  }
}

const fetchPullRequests = async (gitHub, { owner, repo, commits }) => {
  const numbers = commits
    .map(({ message }) => {
      const match = message.match(/\(#([0-9]+)\)/)
      if (match) {
        const [, number] = match
        return number
      } else {
        return null
      }
    })
    .filter(number => number)

  const pullRequests = await Promise.all(
    numbers.map(async number => {
      try {
        const [{ data: pullData }, { data: commentsData }] = await Promise.all([
          gitHub.pullRequests.get({
            owner,
            repo,
            number,
          }),
          gitHub.issues.getComments({
            owner,
            repo,
            number,
          }),
        ])
        return pullData.merged
          ? {
              url: pullData.html_url,
              number: pullData.number,
              title: pullData.title,
              body: pullData.body,
              comments: commentsData.map(comment => ({
                url: comment.html_url,
                body: comment.body,
                author: {
                  name: comment.user.login,
                  url: comment.user.html_url,
                  avatar: comment.user.avatar_url,
                },
                date: new Date(comment.created_at),
              })),
              author: {
                name: pullData.user.login,
                url: pullData.user.html_url,
                avatar: pullData.user.avatar_url,
              },
              date: new Date(pullData.merged_at),
            }
          : null
      } catch (err) {
        if (err.code === 404) {
          return null // ignore nonexistent PR's
        } else {
          throw err
        }
      }
    })
  )

  return pullRequests.filter(pullRequest => pullRequest)
}

const renderBody = async ({
  owner,
  repo,
  render,
  templateProps,
  showDiff,
  newTag,
  previousTag,
  compareUrl,
  commits,
  files,
  pullRequests,
}) =>
  await render({
    compareUrl,
    newTag: {
      name: newTag,
      url: `https://github.com/${owner}/${repo}/tree/${newTag}`,
    },
    previousTag: {
      name: previousTag,
      url: `https://github.com/${owner}/${repo}/tree/${previousTag}`,
    },
    commits: commits.map(commit => ({
      ...commit,
      message: commit.message.replace(/[\r\n]+/g, '
'),
    })),
    files: files.map(file => ({
      ...file,
      diff: file.diff && showDiff(file) && file.diff.replace(/`/g, '\\`'),
    })),
    pullRequests,
    icon() {
      return {
        added: ':heavy_plus_sign:',
        modified: '',
        removed: ':heavy_minus_sign:',
      }[this.status]
    },
    formattedDate() {
      return this.date.toLocaleDateString(undefined, { timeZone: 'UTC' })
    },
    avatarUrl() {
      const { avatar } = this.author
      return `${avatar}${avatar.includes('?') ? '&' : '?'}size=20`
    },
    ...templateProps,
  })

const createRelease = async (gitHub, { owner, repo, newTag, body }) => {
  const { data } = await gitHub.repos.createRelease({
    owner,
    repo,
    tag_name: newTag,
    name: newTag,
    body,
  })
  return data.html_url
}
<commit_msg>adding line count to data<commit_after>import path from 'path'
import { readFile as _readFile } from 'fs'
import promisify from 'es6-promisify'
import forEach from 'lodash.foreach'
import isObject from 'lodash.isobject'
import GitHubApi from 'github'
import Mustache from 'mustache'
import { asc as sortVersions } from 'semver-sort'

const readFile = promisify(_readFile)
const templateCache = {}

const DEFAULT_TEMPLATE = path.resolve(__dirname, 'defaultTemplate.md.hbs')
const NO_PREVIOUS_RELEASE = new Error('No previous release found')

const createGitHubRelease = async config => {
  if (!isObject(config)) {
    throw new Error('config must be an object')
  }
  ;['authenticateOptions', 'owner', 'repo', 'tag'].forEach(property => {
    if (!config[property]) {
      throw new Error(`${property} property is required`)
    }
  })
  forEach(
    {
      authenticateOptions: 'object',
      owner: 'string',
      repo: 'string',
      tag: 'string',
      render: 'function',
      template: 'string',
      templateProps: 'object',
      showDiff: 'function',
      apiOptions: 'object',
    },
    (type, property) => {
      const value = config[property]
      if (value !== undefined && (type === 'object' ? !isObject(value) : typeof value !== type)) {
        throw new Error(`${property} property must be of type ${type}`)
      }
    }
  )
  if (config.template && config.render) {
    throw new Error('template and render properties are exclusive')
  }

  const {
    authenticateOptions,
    owner,
    repo,
    tag,
    template: templatePath = DEFAULT_TEMPLATE,
    templateProps = {},
    showDiff = () => true,
    apiOptions = {},
  } = config

  let render
  if (config.render) {
    render = async view => await config.render(view)
  } else {
    let fetchingTemplate = templateCache[templatePath]
    if (!fetchingTemplate) {
      fetchingTemplate = readFile(templatePath, 'utf8')
      templateCache[templatePath] = fetchingTemplate
    }
    const template = await fetchingTemplate
    render = async view => Mustache.render(template, view)
  }

  const gitHub = new GitHubApi(apiOptions)
  gitHub.authenticate(authenticateOptions)

  const { newTag, previousTag } = await fetchTags(gitHub, { owner, repo, tag })
  const { compareUrl, commits, files } = await fetchDiff(gitHub, {
    owner,
    repo,
    newTag,
    previousTag,
  })
  const pullRequests = await fetchPullRequests(gitHub, { owner, repo, commits })
  const body = await renderBody({
    owner,
    repo,
    showDiff,
    newTag,
    render,
    templateProps,
    previousTag,
    compareUrl,
    commits,
    files,
    pullRequests,
  })

  return await createRelease(gitHub, { owner, repo, newTag, body })
}

createGitHubRelease.DEFAULT_TEMPLATE = DEFAULT_TEMPLATE
createGitHubRelease.NO_PREVIOUS_RELEASE = NO_PREVIOUS_RELEASE

export default createGitHubRelease

const fetchTags = async (gitHub, { owner, repo, tag }) => {
  const { data } = await gitHub.gitdata.getTags({ owner, repo })
  const tags = sortVersions(data.map(_tag => _tag.ref.split('/').pop()))

  const newTagIndex = tags.findIndex(_tag => _tag === tag)

  if (newTagIndex < 0) {
    throw new Error(`Could not find tag ${tag}`)
  } else if (newTagIndex === 0) {
    throw NO_PREVIOUS_RELEASE
  }

  return {
    newTag: tags[newTagIndex],
    previousTag: tags[newTagIndex - 1],
  }
}

const fetchDiff = async (gitHub, { owner, repo, newTag, previousTag }) => {
  const { data } = await gitHub.repos.compareCommits({
    owner,
    repo,
    base: previousTag,
    head: newTag,
  })
  return {
    compareUrl: data.html_url,
    commits: data.commits.map(commit => ({
      id: commit.sha.substr(0, 7),
      url: commit.html_url,
      author: {
        name: commit.author.login,
        url: commit.author.html_url,
        avatar: commit.author.avatar_url,
      },
      date: new Date(commit.commit.committer.date),
      message: commit.commit.message,
    })),
    files: data.files.map(file => ({
      filename: file.filename,
      url: file.blob_url,
      status: file.status,
      changes: file.changes,
      lines: file.patch ? file.patch.split('\n').length : null,
      diff: file.patch || null,
    })),
  }
}

const fetchPullRequests = async (gitHub, { owner, repo, commits }) => {
  const numbers = commits
    .map(({ message }) => {
      const match = message.match(/\(#([0-9]+)\)/)
      if (match) {
        const [, number] = match
        return number
      } else {
        return null
      }
    })
    .filter(number => number)

  const pullRequests = await Promise.all(
    numbers.map(async number => {
      try {
        const [{ data: pullData }, { data: commentsData }] = await Promise.all([
          gitHub.pullRequests.get({
            owner,
            repo,
            number,
          }),
          gitHub.issues.getComments({
            owner,
            repo,
            number,
          }),
        ])
        return pullData.merged
          ? {
              url: pullData.html_url,
              number: pullData.number,
              title: pullData.title,
              body: pullData.body,
              comments: commentsData.map(comment => ({
                url: comment.html_url,
                body: comment.body,
                author: {
                  name: comment.user.login,
                  url: comment.user.html_url,
                  avatar: comment.user.avatar_url,
                },
                date: new Date(comment.created_at),
              })),
              author: {
                name: pullData.user.login,
                url: pullData.user.html_url,
                avatar: pullData.user.avatar_url,
              },
              date: new Date(pullData.merged_at),
            }
          : null
      } catch (err) {
        if (err.code === 404) {
          return null // ignore nonexistent PR's
        } else {
          throw err
        }
      }
    })
  )

  return pullRequests.filter(pullRequest => pullRequest)
}

const renderBody = async ({
  owner,
  repo,
  render,
  templateProps,
  showDiff,
  newTag,
  previousTag,
  compareUrl,
  commits,
  files,
  pullRequests,
}) =>
  await render({
    compareUrl,
    newTag: {
      name: newTag,
      url: `https://github.com/${owner}/${repo}/tree/${newTag}`,
    },
    previousTag: {
      name: previousTag,
      url: `https://github.com/${owner}/${repo}/tree/${previousTag}`,
    },
    commits: commits.map(commit => ({
      ...commit,
      message: commit.message.replace(/[\r\n]+/g, '
'),
    })),
    files: files.map(file => ({
      ...file,
      diff: file.diff && showDiff(file) && file.diff.replace(/`/g, '\\`'),
    })),
    pullRequests,
    icon() {
      return {
        added: ':heavy_plus_sign:',
        modified: '',
        removed: ':heavy_minus_sign:',
      }[this.status]
    },
    formattedDate() {
      return this.date.toLocaleDateString(undefined, { timeZone: 'UTC' })
    },
    avatarUrl() {
      const { avatar } = this.author
      return `${avatar}${avatar.includes('?') ? '&' : '?'}size=20`
    },
    ...templateProps,
  })

const createRelease = async (gitHub, { owner, repo, newTag, body }) => {
  const { data } = await gitHub.repos.createRelease({
    owner,
    repo,
    tag_name: newTag,
    name: newTag,
    body,
  })
  return data.html_url
}
<|endoftext|>


<commit_before>'use strict';

const Alexa = require('alexa-sdk');
const dynasty = require('dynasty')({});
const languageStrings = require('./languageStrings');
const addItem = require('./intentDelegates/addItem');
const queryItem = require('./intentDelegates/queryItem');
const removeItem = require('./intentDelegates/removeItem');

const APP_ID = "amzn1.ask.skill.8371afd6-d231-4b54-bf1d-5987733228cd";
const stewardItems = dynasty.table('Steward_Items');

const handlers = {

    'AddItem': function() { addItem(this, stewardItems) },

    'RemoveItem': function() { removeItem(this, stewardItems) },

    'QueryItem': function() { queryItem(this, stewardItems) },

    'IncrementQuantity': function() { incrementQuantity(this, stewardItems) },

    'DecrementQuantity': function() { decrementQuantity(this, stewardItems) },

    'Affirmative': function() {
        const responses = this.t('AFFIRMATIVE_MESSAGE');
        const idx = Math.floor(Math.random() * responses.length);
        this.emit(':tell', responses[idx]);
    },

    'Error': function() {
        this.emit(':tell', this.t('ERROR_MESSAGE'))
    },

    'AMAZON.HelpIntent': function () {
        this.attributes.speechOutput = this.t('HELP_MESSAGE');
        this.attributes.repromptSpeech = this.t('HELP_REPROMT');
        this.emit(':ask', this.attributes.speechOutput, this.attributes.repromptSpeech);
    },
    'AMAZON.RepeatIntent': function () {
        this.emit(':ask', this.attributes.speechOutput, this.attributes.repromptSpeech);
    },
    'AMAZON.StopIntent': function () {
        this.emit('SessionEndedRequest');
    },
    'AMAZON.CancelIntent': function () {
        this.emit('SessionEndedRequest');
    },
};

exports.handler = (event, context) => {
    const alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    alexa.resources = languageStrings.strings;
    alexa.registerHandlers(handlers);
    alexa.execute();
};
<commit_msg>Importing delegates is hard...<commit_after>'use strict';

const Alexa = require('alexa-sdk');
const dynasty = require('dynasty')({});
const languageStrings = require('./languageStrings');
const addItem = require('./intentDelegates/addItem');
const queryItem = require('./intentDelegates/queryItem');
const removeItem = require('./intentDelegates/removeItem');
const incrementQuantity = require('./intentDelegates/incrementQuantity')
const decrementQuantity = require('./intentDelegates/decrementQuantity')

const APP_ID = "amzn1.ask.skill.8371afd6-d231-4b54-bf1d-5987733228cd";
const stewardItems = dynasty.table('Steward_Items');

const handlers = {

    'AddItem': function() { addItem(this, stewardItems) },

    'RemoveItem': function() { removeItem(this, stewardItems) },

    'QueryItem': function() { queryItem(this, stewardItems) },

    'IncrementQuantity': function() { incrementQuantity(this, stewardItems) },

    'DecrementQuantity': function() { decrementQuantity(this, stewardItems) },

    'Affirmative': function() {
        const responses = this.t('AFFIRMATIVE_MESSAGE');
        const idx = Math.floor(Math.random() * responses.length);
        this.emit(':tell', responses[idx]);
    },

    'Error': function() {
        this.emit(':tell', this.t('ERROR_MESSAGE'))
    },

    'AMAZON.HelpIntent': function () {
        this.attributes.speechOutput = this.t('HELP_MESSAGE');
        this.attributes.repromptSpeech = this.t('HELP_REPROMT');
        this.emit(':ask', this.attributes.speechOutput, this.attributes.repromptSpeech);
    },
    'AMAZON.RepeatIntent': function () {
        this.emit(':ask', this.attributes.speechOutput, this.attributes.repromptSpeech);
    },
    'AMAZON.StopIntent': function () {
        this.emit('SessionEndedRequest');
    },
    'AMAZON.CancelIntent': function () {
        this.emit('SessionEndedRequest');
    },
};

exports.handler = (event, context) => {
    const alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    alexa.resources = languageStrings.strings;
    alexa.registerHandlers(handlers);
    alexa.execute();
};
<|endoftext|>


<commit_before>import _Button from 'components/Button';
import _ButtonContainer from 'components/Button/Container';
import _Card from 'components/Card';
import _PageCard from 'components/PageCard';
import _StudentCard from 'components/StudentCard';
import _StudentPicture from 'components/StudentPicture';
import _AdultPicture from 'components/AdultPicture';
import _Grid from 'components/Grid';
import _Dialog from 'components/Dialog';
import _AlertDialog from 'components/AlertDialog';
import _ConfirmDialog from 'components/ConfirmDialog';
import _ErrorDialog from 'components/ErrorDialog';
import _Form from 'components/Form';
import _ProgressBar from 'components/ProgressBar';
import _createBuildRoute from 'domain/createBuildRoute';
import _connect from 'domain/connect';
import _Gender from 'domain/Gender';
import _Tooltip from 'components/Tooltip';
import _ProductionStatus from 'components/ProductionStatus';
import { mediaQuery as _mediaQuery } from 'domain/MediaQuery';
import { Api as _Api, buildUrl as _buildUrl, fetch as _fetch } from 'domain/Api';
import { ApiResponse as _ApiResponse } from 'domain/ApiResponse';
import { ApiResponseHelper as _ApiResponseHelper } from 'domain/ApiResponseHelper';
import _moment from 'domain/moment';
import _setupApp from './setupApp';
import _Store from 'domain/Store';
import _testClass from 'domain/testClass';
import _PrivilegeChecker from 'domain/PrivilegeChecker';
import _ApiCall from 'containers/ApiCalls';
import _Config from 'domain/Config';
import _DropdownBox from 'components/DropdownBox';
import _Permission from 'containers/Permission';
import _ColourLabel from 'components/ColourLabel';
import _Checkbox from 'components/Checkbox';
import _SolidRadio from 'components/SolidRadio';
import _Detailsboard from 'components/Detailsboard';
import _InputSelect from 'components/InputSelect';
import _NumberInput from 'components/NumberInput';
import _log from 'domain/log';
import _Sticky from 'components/Sticky';
import _InlineSvg from 'components/InlineSvg';
import _SelectionTable from 'components/SelectionTable';
import _Icon from 'components/Icon';
import _Person from 'components/Person';
import _HorizontalScroll from 'components/HorizontalScroll';
import _HorizontalSelect from 'components/HorizontalSelect';
import _CalendarPicker from 'components/CalendarPicker';
import _TextArea from 'components/TextArea';

export const Button = _Button;
export const ButtonContainer = _ButtonContainer;
export const Card = _Card;
export const PageCard = _PageCard;
export const StudentCard = _StudentCard;
export const StudentPicture = _StudentPicture;
export const AdultPicture = _AdultPicture;
export const Grid = _Grid;
export const Dialog = _Dialog;
export const AlertDialog = _AlertDialog;
export const Form = _Form;
export const ProgressBar = _ProgressBar;
export const createBuildRoute = _createBuildRoute;
export const connect = _connect;
export const Gender = _Gender;
export const Tooltip = _Tooltip;
export const ProductionStatus = _ProductionStatus;
export const mediaQuery = _mediaQuery;
export const Api = _Api;
export const buildUrl = _buildUrl;
export const fetch = _fetch;
export const ApiResponse = _ApiResponse;
export const ApiResponseHelper = _ApiResponseHelper;
export const moment = _moment;
export const setupApp = _setupApp;
export const Store = _Store;
export const testClass = _testClass;
export const PrivilegeChecker = _PrivilegeChecker;
export const ApiCall = _ApiCall;
export const Config = _Config;
export const DropdownBox = _DropdownBox;
export const Permission = _Permission;
export const ColourLabel = _ColourLabel;
export const ConfirmDialog = _ConfirmDialog;
export const ErrorDialog = _ErrorDialog;
export const Checkbox = _Checkbox;
export const SolidRadio = _SolidRadio;
export const Detailsboard = _Detailsboard;
export const InputSelect = _InputSelect;
export const NumberInput = _NumberInput;
export const log = _log;
export const Sticky = _Sticky;
export const InlineSvg = _InlineSvg;
export const SelectionTable = _SelectionTable;
export const Icon = _Icon;
export const Person = _Person;
export const HorizontalScroll = _HorizontalScroll;
export const HorizontalSelect = _HorizontalSelect;
export const CalendarPicker = _CalendarPicker;
export const TextArea = _TextArea;
<commit_msg>Exporting Breadcrumbs for omni-showcase<commit_after>import _Breadcrumbs from 'components/Breadcrumbs';
import _Button from 'components/Button';
import _ButtonContainer from 'components/Button/Container';
import _Card from 'components/Card';
import _PageCard from 'components/PageCard';
import _StudentCard from 'components/StudentCard';
import _StudentPicture from 'components/StudentPicture';
import _AdultPicture from 'components/AdultPicture';
import _Grid from 'components/Grid';
import _Dialog from 'components/Dialog';
import _AlertDialog from 'components/AlertDialog';
import _ConfirmDialog from 'components/ConfirmDialog';
import _ErrorDialog from 'components/ErrorDialog';
import _Form from 'components/Form';
import _ProgressBar from 'components/ProgressBar';
import _createBuildRoute from 'domain/createBuildRoute';
import _connect from 'domain/connect';
import _Gender from 'domain/Gender';
import _Tooltip from 'components/Tooltip';
import _ProductionStatus from 'components/ProductionStatus';
import { mediaQuery as _mediaQuery } from 'domain/MediaQuery';
import { Api as _Api, buildUrl as _buildUrl, fetch as _fetch } from 'domain/Api';
import { ApiResponse as _ApiResponse } from 'domain/ApiResponse';
import { ApiResponseHelper as _ApiResponseHelper } from 'domain/ApiResponseHelper';
import _moment from 'domain/moment';
import _setupApp from './setupApp';
import _Store from 'domain/Store';
import _testClass from 'domain/testClass';
import _PrivilegeChecker from 'domain/PrivilegeChecker';
import _ApiCall from 'containers/ApiCalls';
import _Config from 'domain/Config';
import _DropdownBox from 'components/DropdownBox';
import _Permission from 'containers/Permission';
import _ColourLabel from 'components/ColourLabel';
import _Checkbox from 'components/Checkbox';
import _SolidRadio from 'components/SolidRadio';
import _Detailsboard from 'components/Detailsboard';
import _InputSelect from 'components/InputSelect';
import _NumberInput from 'components/NumberInput';
import _log from 'domain/log';
import _Sticky from 'components/Sticky';
import _InlineSvg from 'components/InlineSvg';
import _SelectionTable from 'components/SelectionTable';
import _Icon from 'components/Icon';
import _Person from 'components/Person';
import _HorizontalScroll from 'components/HorizontalScroll';
import _HorizontalSelect from 'components/HorizontalSelect';
import _CalendarPicker from 'components/CalendarPicker';
import _TextArea from 'components/TextArea';

export const Breadcrumbs = _Breadcrumbs;
export const Button = _Button;
export const ButtonContainer = _ButtonContainer;
export const Card = _Card;
export const PageCard = _PageCard;
export const StudentCard = _StudentCard;
export const StudentPicture = _StudentPicture;
export const AdultPicture = _AdultPicture;
export const Grid = _Grid;
export const Dialog = _Dialog;
export const AlertDialog = _AlertDialog;
export const Form = _Form;
export const ProgressBar = _ProgressBar;
export const createBuildRoute = _createBuildRoute;
export const connect = _connect;
export const Gender = _Gender;
export const Tooltip = _Tooltip;
export const ProductionStatus = _ProductionStatus;
export const mediaQuery = _mediaQuery;
export const Api = _Api;
export const buildUrl = _buildUrl;
export const fetch = _fetch;
export const ApiResponse = _ApiResponse;
export const ApiResponseHelper = _ApiResponseHelper;
export const moment = _moment;
export const setupApp = _setupApp;
export const Store = _Store;
export const testClass = _testClass;
export const PrivilegeChecker = _PrivilegeChecker;
export const ApiCall = _ApiCall;
export const Config = _Config;
export const DropdownBox = _DropdownBox;
export const Permission = _Permission;
export const ColourLabel = _ColourLabel;
export const ConfirmDialog = _ConfirmDialog;
export const ErrorDialog = _ErrorDialog;
export const Checkbox = _Checkbox;
export const SolidRadio = _SolidRadio;
export const Detailsboard = _Detailsboard;
export const InputSelect = _InputSelect;
export const NumberInput = _NumberInput;
export const log = _log;
export const Sticky = _Sticky;
export const InlineSvg = _InlineSvg;
export const SelectionTable = _SelectionTable;
export const Icon = _Icon;
export const Person = _Person;
export const HorizontalScroll = _HorizontalScroll;
export const HorizontalSelect = _HorizontalSelect;
export const CalendarPicker = _CalendarPicker;
export const TextArea = _TextArea;
<|endoftext|>


<commit_before>import io from 'socket.io-client';

export const defaultOpts = {
  transports: ['websocket'],
};

export const defaultSocketEvents = [
  {
    action: 'NOOP',
    dispatch: (socket, store, action) => {
      console.debug('NOOP event called. Have you implemented your events?');
    },
  },
];

export const onSocketEvents = (event, data) => {
  console.error('Socket not listening for any events.');
};

export const socketIOMiddleware = (
  initialSocket = null,
  dispatchEvents = defaultSocketEvents,
  listenEvents = onSocketEvents,
  connectAction = 'CONNECT',
  options = defaultOpts) => {

  let socket = initialSocket;
  const onEvent = (socket, store, next, action) => listenEvents;

  return store => next => action => {

    if (action.type === connectAction) {
      const connStr = `${action.payload.host}:${action.payload.port}`;
      if (socket !== null) {
        socket.close();
      }

      socket = io.connect(connStr, opts);

      const onevent = socket.onevent;
      socket.onevent = (packet) => {
        const args = packet.data || [];
        packet.data = ['*'].concat(args);
        onevent.call(socket, packet);
      };

      socket.on('*', onEvent(socket, store, next, action));

      return next(action);
    }

    if (!socket.connected) {
      throw new Error('Socket must call a connect event before dispatching any actions.');
    }

    defaultEvents.map((event) => {
      if (action.type === event.action) {
        return event.dispatch(socket, store, action);
      }
    });

    return next(action);
  };
};

export default socketIOMiddleware;<commit_msg>Update parameter name<commit_after>import io from 'socket.io-client';

export const defaultOpts = {
  transports: ['websocket'],
};

export const defaultSocketEvents = [
  {
    action: 'NOOP',
    dispatch: (socket, store, action) => {
      console.debug('NOOP event called. Have you implemented your events?');
    },
  },
];

export const onSocketEvents = (event, data) => {
  console.error('Socket not listening for any events.');
};

export const socketIOMiddleware = (
  initialSocket = null,
  dispatchEvents = defaultSocketEvents,
  listenEvents = onSocketEvents,
  connectAction = 'CONNECT',
  options = defaultOpts) => {

  let socket = initialSocket;
  const onEvent = (socket, store, next, action) => listenEvents;

  return store => next => action => {

    if (action.type === connectAction) {
      const connStr = `${action.payload.host}:${action.payload.port}`;
      if (socket !== null) {
        socket.close();
      }

      socket = io.connect(connStr, options);

      const onevent = socket.onevent;
      socket.onevent = (packet) => {
        const args = packet.data || [];
        packet.data = ['*'].concat(args);
        onevent.call(socket, packet);
      };

      socket.on('*', onEvent(socket, store, next, action));

      return next(action);
    }

    if (!socket.connected) {
      throw new Error('Socket must call a connect event before dispatching any actions.');
    }

    defaultEvents.map((event) => {
      if (action.type === event.action) {
        return event.dispatch(socket, store, action);
      }
    });

    return next(action);
  };
};

export default socketIOMiddleware;<|endoftext|>


<commit_before>var chainMethods = 'select,from,where,orderBy,groupBy,having'.split(',');

buildFunctionalSQLPrototype();

var query = createQuery;

// return void(0);

function FunctionalSQL() {
	this.sources = [];
	this.selector = null;
	this.result = [];
}

function buildFunctionalSQLPrototype() {
	FunctionalSQL.prototype.select = select;
	FunctionalSQL.prototype.from = from;
	FunctionalSQL.prototype.where = where;
	FunctionalSQL.prototype.orderBy = orderBy;
	FunctionalSQL.prototype.groupBy = groupBy;
	FunctionalSQL.prototype.having = having;
	FunctionalSQL.prototype.execute = execute;

	chainMethods.forEach(function(methodName) {
		chinify(FunctionalSQL.prototype, methodName);
	});

	return void(0);

	function select(selector) {
		this.selector = selector;
	}

	function from() {
		this.result =
			this.sources = argumentsToArray(arguments);
	}

	function where() {}

	function orderBy() {}

	function groupBy() {}

	function having() {}

	function execute() {
		if(this.selector) {
			this.result = this.result.map(this.selector);
		}

		return this.result;
	}

}

function argumentsToArray(args) {
	return args.length === 1 ?
		args[0] :
		Array.prototype.slice.call(args);
}

function chinify(obj, methodName) {
	wrap.origin = obj[methodName];
	obj[methodName] = wrap;
	return void(0);

	function wrap() {
		wrap.origin.apply(this, arguments);
		return this;
	}
}

function createQuery() {
	return new FunctionalSQL();
}
<commit_msg>add where filters<commit_after>var chainMethods = 'select,from,where,orderBy,groupBy,having'.split(',');

buildFunctionalSQLPrototype();

var query = createQuery;

// return void(0);

function FunctionalSQL() {
	this.sources = [];
	this.selector = null;
	this.filters = [];
	this.result = [];
}

function buildFunctionalSQLPrototype() {
	FunctionalSQL.prototype.select = select;
	FunctionalSQL.prototype.from = from;
	FunctionalSQL.prototype.where = where;
	FunctionalSQL.prototype.orderBy = orderBy;
	FunctionalSQL.prototype.groupBy = groupBy;
	FunctionalSQL.prototype.having = having;
	FunctionalSQL.prototype.execute = execute;

	chainMethods.forEach(function(methodName) {
		chinify(FunctionalSQL.prototype, methodName);
	});

	return void(0);

	function select(selector) {
		this.selector = selector;
	}

	function from() {
		this.result =
			this.sources = argumentsToArray(arguments);
	}

	function where(filter) {
		if(filter) { // is function check
			this.filters.push(filter);
		}
	}

	function orderBy() {}

	function groupBy() {}

	function having() {}

	function execute() {
		this.filters.forEach(function(filter) {
			this.result = this.result.filter(filter);
		}, this);

		if(this.selector) {
			this.result = this.result.map(this.selector);
		}

		return this.result;
	}

}

function argumentsToArray(args) {
	return args.length === 1 ?
		args[0] :
		Array.prototype.slice.call(args);
}

function chinify(obj, methodName) {
	wrap.origin = obj[methodName];
	obj[methodName] = wrap;
	return void(0);

	function wrap() {
		wrap.origin.apply(this, arguments);
		return this;
	}
}

function createQuery() {
	return new FunctionalSQL();
}
<|endoftext|>


<commit_before>var through = require('through2');
var gutil = require('gulp-util');
var http = require('http');
var https = require('https');
var connect = require('connect');
var serveStatic = require('serve-static');
var connectLivereload = require('connect-livereload');
var proxy = require('proxy-middleware');
var tinyLr = require('tiny-lr');
var watch = require('node-watch');
var fs = require('fs');
var serveIndex = require('serve-index');
var path = require('path');
var open = require('open');
var url = require('url');
var enableMiddlewareShorthand = require('./enableMiddlewareShorthand');

module.exports = function(options) {

  var defaults = {

    /**
     *
     * BASIC DEFAULTS
     *
     **/

    host: 'localhost',
    port: 8000,
    fallback: false,
    https: false,
    open: false,

    /**
     *
     * MIDDLEWARE DEFAULTS
     *
     * NOTE:
     *  All middleware should defaults should have the 'enable'
     *  property if you want to support shorthand syntax like:
     *
     *    webserver({
     *      livereload: true
     *    });
     *
     */

    // Middleware: Livereload
    livereload: {
      enable: false,
      port: 35729
    },

    // Middleware: Directory listing
    // For possible options, see:
    //  https://github.com/expressjs/serve-index
    directoryListing: {
      enable: false,
      path: './',
      options: undefined
    },

    // Middleware: Proxy
    // For possible options, see:
    //  https://github.com/andrewrk/connect-proxy
    proxies: []

  };

  // Deep extend user provided options over the all of the defaults
  // Allow shorthand syntax, using the enable property as a flag
  var config = enableMiddlewareShorthand(defaults, options, [
    'directoryListing',
    'livereload'
  ]);

  if (typeof config.open === 'string' && config.open.length > 0) {
    // ensure leading slash
    config.open = (config.open.indexOf('/') !== 0 ? '/' : '') + config.open;
  }

  var app = connect();

  var openInBrowser = function() {
    if (config.open === false) return;
    open('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port + (typeof config.open === 'string' ? config.open : ''));
  };

  var lrServer;

  if (config.livereload.enable) {

    app.use(connectLivereload({
      port: config.livereload.port
    }));

    if (config.https) {
      lrServer = tinyLr({
        key: fs.readFileSync(config.https.key || __dirname + '/../ssl/dev-key.pem'),
        cert: fs.readFileSync(config.https.cert || __dirname + '/../ssl/dev-cert.pem')
      });
    } else {
      lrServer = tinyLr();
    }

    lrServer.listen(config.livereload.port);

  }

  if (config.directoryListing.enable) {
    app.use(serveIndex(path.resolve(config.directoryListing.path), config.directoryListing.options));
  }

  // Proxy requests
  for (var i = 0, len = config.proxies.length; i < len; i++) {
    app.use(config.proxies[i].source, proxy(url.parse(config.proxies[i].target)));
  }

  // Create server
  var stream = through.obj(function(file, enc, callback) {

    app.use(serveStatic(file.path));

    if (config.fallback) {

      var fallbackFile = file.path + '/' + config.fallback;

      if (fs.existsSync(fallbackFile)) {

        app.use(function(req, res) {
          fs.createReadStream(fallbackFile).pipe(res);
        });

      }
    }

    if (config.livereload.enable) {

      watch(file.path, function(filename) {

        lrServer.changed({
          body: {
            files: filename
          }
        });

      });

    }

    this.push(file);

    callback();

  });

  var webserver;

  if (config.https) {
    var opts = {
      key: fs.readFileSync(config.https.key || __dirname + '/../ssl/dev-key.pem'),
      cert: fs.readFileSync(config.https.cert || __dirname + '/../ssl/dev-cert.pem')
    };
    webserver = https.createServer(opts, app).listen(config.port, config.host, openInBrowser);
  } else {
    webserver = http.createServer(app).listen(config.port, config.host, openInBrowser);
  }

  gutil.log('Webserver started at', gutil.colors.cyan('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port));

  stream.on('kill', function() {

    webserver.close();

    if (config.livereload.enable) {
      lrServer.close();
    }

  });

  return stream;

};
<commit_msg>Adds support for pfx certs<commit_after>var through = require('through2');
var gutil = require('gulp-util');
var http = require('http');
var https = require('https');
var connect = require('connect');
var serveStatic = require('serve-static');
var connectLivereload = require('connect-livereload');
var proxy = require('proxy-middleware');
var tinyLr = require('tiny-lr');
var watch = require('node-watch');
var fs = require('fs');
var serveIndex = require('serve-index');
var path = require('path');
var open = require('open');
var url = require('url');
var enableMiddlewareShorthand = require('./enableMiddlewareShorthand');

module.exports = function(options) {

  var defaults = {

    /**
     *
     * BASIC DEFAULTS
     *
     **/

    host: 'localhost',
    port: 8000,
    fallback: false,
    https: false,
    open: false,

    /**
     *
     * MIDDLEWARE DEFAULTS
     *
     * NOTE:
     *  All middleware should defaults should have the 'enable'
     *  property if you want to support shorthand syntax like:
     *
     *    webserver({
     *      livereload: true
     *    });
     *
     */

    // Middleware: Livereload
    livereload: {
      enable: false,
      port: 35729
    },

    // Middleware: Directory listing
    // For possible options, see:
    //  https://github.com/expressjs/serve-index
    directoryListing: {
      enable: false,
      path: './',
      options: undefined
    },

    // Middleware: Proxy
    // For possible options, see:
    //  https://github.com/andrewrk/connect-proxy
    proxies: []

  };

  // Deep extend user provided options over the all of the defaults
  // Allow shorthand syntax, using the enable property as a flag
  var config = enableMiddlewareShorthand(defaults, options, [
    'directoryListing',
    'livereload'
  ]);

  if (typeof config.open === 'string' && config.open.length > 0) {
    // ensure leading slash
    config.open = (config.open.indexOf('/') !== 0 ? '/' : '') + config.open;
  }

  var app = connect();

  var openInBrowser = function() {
    if (config.open === false) return;
    open('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port + (typeof config.open === 'string' ? config.open : ''));
  };

  var lrServer;

  if (config.livereload.enable) {

    app.use(connectLivereload({
      port: config.livereload.port
    }));

    if (config.https) {
      if (config.https.pfx) {
        lrServer = tinyLr({
          pfx: fs.readFileSync(config.https.pfx),
          passphrase: config.https.passphrase
        });
      }
      else {
        lrServer = tinyLr({
          key: fs.readFileSync(config.https.key || __dirname + '/../ssl/dev-key.pem'),
          cert: fs.readFileSync(config.https.cert || __dirname + '/../ssl/dev-cert.pem')
        });
      }
    } else {
      lrServer = tinyLr();
    }

    lrServer.listen(config.livereload.port);

  }

  if (config.directoryListing.enable) {
    app.use(serveIndex(path.resolve(config.directoryListing.path), config.directoryListing.options));
  }

  // Proxy requests
  for (var i = 0, len = config.proxies.length; i < len; i++) {
    app.use(config.proxies[i].source, proxy(url.parse(config.proxies[i].target)));
  }

  // Create server
  var stream = through.obj(function(file, enc, callback) {

    app.use(serveStatic(file.path));

    if (config.fallback) {

      var fallbackFile = file.path + '/' + config.fallback;

      if (fs.existsSync(fallbackFile)) {

        app.use(function(req, res) {
          fs.createReadStream(fallbackFile).pipe(res);
        });

      }
    }

    if (config.livereload.enable) {

      watch(file.path, function(filename) {

        lrServer.changed({
          body: {
            files: filename
          }
        });

      });

    }

    this.push(file);

    callback();

  });

  var webserver;

  if (config.https) {
    var opts;

    if (config.https.pfx) {
      opts = {
        pfx: fs.readFileSync(config.https.pfx),
        passphrase: config.https.passphrase
      };
    } else {
      opts = {
        key: fs.readFileSync(config.https.key || __dirname + '/../ssl/dev-key.pem'),
        cert: fs.readFileSync(config.https.cert || __dirname + '/../ssl/dev-cert.pem')
      };
    }
    webserver = https.createServer(opts, app).listen(config.port, config.host, openInBrowser);
  } else {
    webserver = http.createServer(app).listen(config.port, config.host, openInBrowser);
  }

  gutil.log('Webserver started at', gutil.colors.cyan('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port));

  stream.on('kill', function() {

    webserver.close();

    if (config.livereload.enable) {
      lrServer.close();
    }

  });

  return stream;

};
<|endoftext|>


<commit_before>var loadConfiguration = require('./configuration'),
    environment = require('./utilities/environment'),
    logger = require('./logger'),
    utilities = require('./utilities'),
    path = require('path'),

    platforms = {
        express: require('./express'),
    },

    defaults = {
        platform: 'express',
        basePath: path.dirname(module.parent.filename),
        configFile: 'azureMobile',
        promiseConstructor: Promise,
        tableRootPath: '/tables',
        data: { },
        logging: {
            level: environment.debug ? 'info' : 'debug',
            transports: {
                Console: {
                    colorize: true,
                    timestamp: true,
                    showLevel: true
                }
            }
        }
    };

module.exports = function (configuration) {
    configuration = configuration || {};
    var configFile = path.resolve(configuration.basePath || defaults.basePath, configuration.configFile || defaults.configFile);
    configuration = utilities.assign(loadConfiguration.fromFile(configFile), defaults, configuration);
    loadConfiguration.fromEnvironment(configuration);
    logger.initialise(configuration);

    return platforms[configuration.platform](configuration);
};
<commit_msg>Fixing incorrect logging configuration object<commit_after>var loadConfiguration = require('./configuration'),
    environment = require('./utilities/environment'),
    logger = require('./logger'),
    utilities = require('./utilities'),
    path = require('path'),

    platforms = {
        express: require('./express'),
    },

    defaults = {
        platform: 'express',
        basePath: path.dirname(module.parent.filename),
        configFile: 'azureMobile',
        promiseConstructor: Promise,
        tableRootPath: '/tables',
        data: { },
        logging: {
            level: environment.debug ? 'info' : 'debug',
            transports: {
                Console: {
                    colorize: true,
                    timestamp: true,
                    showLevel: true
                }
            }
        }
    };

module.exports = function (configuration) {
    configuration = configuration || {};
    var configFile = path.resolve(configuration.basePath || defaults.basePath, configuration.configFile || defaults.configFile);
    configuration = utilities.assign(loadConfiguration.fromFile(configFile), defaults, configuration);
    loadConfiguration.fromEnvironment(configuration);
    logger.initialise(configuration.logging);

    return platforms[configuration.platform](configuration);
};
<|endoftext|>


<commit_before>export { default as reduxDraft } from './components/reduxDraft';
export { default as reduxDraftEntity } from './components/reduxDraftEntity';
export { default as reducer } from './reducers/index';
<commit_msg>Export action creators<commit_after>export { default as reduxDraft } from './components/reduxDraft';
export { default as reduxDraftEntity } from './components/reduxDraftEntity';
export * as actionCreators from './actions/index';
export { default as reducer } from './reducers/index';
<|endoftext|>


<commit_before>import h from 'snabbdom/h'

import init from 'snabbdom'

import hh from 'hyperscript-helpers'
const {
  a, abbr, address, area, article, aside, audio, b, base,
  bdi, bdo, blockquote, body, br, button, canvas, caption,
  cite, code, col, colgroup, dd, del, dfn, dir, div, dl,
  dt, em, embed, fieldset, figcaption, figure, footer, form,
  h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html,
  i, iframe, img, input, ins, kbd, keygen, label, legend,
  li, link, main, map, mark, menu, meta, nav, noscript,
  object, ol, optgroup, option, p, param, pre, q, rp, rt,
  ruby, s, samp, script, section, select, small, source, span,
  strong, style, sub, sup, table, tbody, td, textarea, tfoot,
  th, thead, title, tr, u, ul, video
} = hh(h)

export {
  a, abbr, address, area, article, aside, audio, b, base,
  bdi, bdo, blockquote, body, br, button, canvas, caption,
  cite, code, col, colgroup, dd, del, dfn, dir, div, dl,
  dt, em, embed, fieldset, figcaption, figure, footer, form,
  h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html,
  i, iframe, img, input, ins, kbd, keygen, label, legend,
  li, link, main, map, mark, menu, meta, nav, noscript,
  object, ol, optgroup, option, p, param, pre, q, rp, rt,
  ruby, s, samp, script, section, select, small, source, span,
  strong, style, sub, sup, table, tbody, td, textarea, tfoot,
  th, thead, title, tr, u, ul, video,
  h, init
}
<commit_msg>First try at a render function<commit_after>import h from 'snabbdom/h'
import init from 'snabbdom'

import ClassModule from 'snabbdom/modules/class'
import PropsModule from 'snabbdom/modules/props'
import AttrsModule from 'snabbdom/modules/attributes'
import EventsModule from 'snabbdom/modules/eventlisteners'
import StyleModule from 'snabbdom/modules/style'

const patch = init([ClassModule, PropsModule, StyleModule, EventsModule, AttrsModule])

import hh from 'hyperscript-helpers'
const {
  a, abbr, address, area, article, aside, audio, b, base,
  bdi, bdo, blockquote, body, br, button, canvas, caption,
  cite, code, col, colgroup, dd, del, dfn, dir, div, dl,
  dt, em, embed, fieldset, figcaption, figure, footer, form,
  h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html,
  i, iframe, img, input, ins, kbd, keygen, label, legend,
  li, link, main, map, mark, menu, meta, nav, noscript,
  object, ol, optgroup, option, p, param, pre, q, rp, rt,
  ruby, s, samp, script, section, select, small, source, span,
  strong, style, sub, sup, table, tbody, td, textarea, tfoot,
  th, thead, title, tr, u, ul, video
} = hh(h)

export {
  a, abbr, address, area, article, aside, audio, b, base,
  bdi, bdo, blockquote, body, br, button, canvas, caption,
  cite, code, col, colgroup, dd, del, dfn, dir, div, dl,
  dt, em, embed, fieldset, figcaption, figure, footer, form,
  h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html,
  i, iframe, img, input, ins, kbd, keygen, label, legend,
  li, link, main, map, mark, menu, meta, nav, noscript,
  object, ol, optgroup, option, p, param, pre, q, rp, rt,
  ruby, s, samp, script, section, select, small, source, span,
  strong, style, sub, sup, table, tbody, td, textarea, tfoot,
  th, thead, title, tr, u, ul, video,
  h
}

export function render(derivable, domElement) {
  let latestRender = domElement
  derivable.react((ddom) => {
    patch(latestRender, ddom)
    latestRender = ddom
  })
}
<|endoftext|>


<commit_before>import { h, Component } from 'preact';
import { exec, pathRankSort } from './util';

const routers = [];

const EMPTY = {};

export function route(url, replace=false) {
	if (typeof url!=='string' && url.url) {
		replace = url.replace;
		url = url.url;
	}
	if (history) {
		if (replace===true) {
			history.replaceState(null, null, url);
		}
		else {
			history.pushState(null, null, url);
		}
	}
	routeTo(url);
}

function routeTo(url) {
	routers.forEach( router => router.routeTo(url) );
}

function getCurrentUrl() {
	let url = typeof location!=='undefined' ? location : EMPTY;
	return `${url.pathname || ''}${url.search || ''}`;
}

if (typeof addEventListener==='function') {
	addEventListener('popstate', () => routeTo(getCurrentUrl()));
}

function handleLinkClick(e) {
	route(this.getAttribute('href'));
	if (e.stopImmediatePropagation) e.stopImmediatePropagation();
	e.stopPropagation();
	e.preventDefault();
	return false;
}

export const Link = ({ children, ...props }) => (
	{ children }
);

export class Router extends Component {
	getInitialState() {
		return { url: getCurrentUrl() };
	}

	routeTo(url) {
		this.setState({ url });
	}

	componentWillMount() {
		routers.push(this);
	}

	componentWillUnmount() {
		routers.splice(routers.indexOf(this), 1);
	}

	render({ children, onChange }, { url }) {
		let active = children.slice().sort(pathRankSort).filter( ({ attributes }) => {
			let path = attributes.path,
				matches = exec(url, path, attributes);
			if (matches) {
				attributes.url = url;
				attributes.matches = matches;
				// copy matches onto props
				for (let i in matches) {
					if (matches.hasOwnProperty(i)) {
						attributes[i] = matches[i];
					}
				}
				return true;
			}
		});
		let previous = this.previousUrl;
		if (url!==previous) {
			this.previousUrl = url;
			if (typeof onChange==='function') {
				onChange({
					router: this,
					url,
					previous,
					active,
					current: active[0]
				});
			}
		}
		return active[0] || null;
	}
}

export const Route = ({ component:RoutedComponent, url, matches }) => (
	<RoutedComponent {...{url, matches}} />
);

Router.route = route;
Router.Route = Route;
Router.Link = Link;
export default Router;
<commit_msg>Switch to loose exports to fix default import bug in 1.2.2<commit_after>import { h, Component } from 'preact';
import { exec, pathRankSort } from './util';

const routers = [];

const EMPTY = {};

function route(url, replace=false) {
	if (typeof url!=='string' && url.url) {
		replace = url.replace;
		url = url.url;
	}
	if (history) {
		if (replace===true) {
			history.replaceState(null, null, url);
		}
		else {
			history.pushState(null, null, url);
		}
	}
	routeTo(url);
}

function routeTo(url) {
	routers.forEach( router => router.routeTo(url) );
}

function getCurrentUrl() {
	let url = typeof location!=='undefined' ? location : EMPTY;
	return `${url.pathname || ''}${url.search || ''}`;
}

if (typeof addEventListener==='function') {
	addEventListener('popstate', () => routeTo(getCurrentUrl()));
}

function handleLinkClick(e) {
	route(this.getAttribute('href'));
	if (e.stopImmediatePropagation) e.stopImmediatePropagation();
	e.stopPropagation();
	e.preventDefault();
	return false;
}

const Link = ({ children, ...props }) => (
	{ children }
);

class Router extends Component {
	getInitialState() {
		return { url: getCurrentUrl() };
	}

	routeTo(url) {
		this.setState({ url });
	}

	componentWillMount() {
		routers.push(this);
	}

	componentWillUnmount() {
		routers.splice(routers.indexOf(this), 1);
	}

	render({ children, onChange }, { url }) {
		let active = children.slice().sort(pathRankSort).filter( ({ attributes }) => {
			let path = attributes.path,
				matches = exec(url, path, attributes);
			if (matches) {
				attributes.url = url;
				attributes.matches = matches;
				// copy matches onto props
				for (let i in matches) {
					if (matches.hasOwnProperty(i)) {
						attributes[i] = matches[i];
					}
				}
				return true;
			}
		});
		let previous = this.previousUrl;
		if (url!==previous) {
			this.previousUrl = url;
			if (typeof onChange==='function') {
				onChange({
					router: this,
					url,
					previous,
					active,
					current: active[0]
				});
			}
		}
		return active[0] || null;
	}
}

const Route = ({ component:RoutedComponent, url, matches }) => (
	<RoutedComponent {...{url, matches}} />
);

Router.route = route;
Router.Router = Router;
Router.Route = Route;
Router.Link = Link;

export default Router;
<|endoftext|>


<commit_before>import home from './routes/home';
import general from './routes/general';
import '../style/index.scss';
// var $ = require('jquery');

// alert('Test');
const routes = {
    'http://plays.tv/home': home,
};

zzz
function router() {
    if (window.location.href in routes) {
        routes[window.location.href]();
    }
    general();
}

(function () {
    router();
}());

<commit_msg>Cant break javascript....<commit_after>import home from './routes/home';
import general from './routes/general';
import '../style/index.scss';
// var $ = require('jquery');

// alert('Test');
const routes = {
    'http://plays.tv/home': home,
};

z { ]
function router() {
    if (window.location.href in routes) {
        routes[window.location.href]();
    }
    general();
}

(function () {
    router();
}());

<|endoftext|>