<commit_before>/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */

// Needed for redux-saga es6 generator support
import 'babel-polyfill';

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import FontFaceObserver from 'fontfaceobserver';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';
import 'flexboxgrid/css/flexboxgrid.css';
import 'font-awesome/css/font-awesome.css';

// Import root app
import App from 'containers/App';

// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';

// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';

// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-webpack-loader-syntax */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions
/* eslint-enable import/no-webpack-loader-syntax */

import configureStore from './store';

// Import i18n messages
import { translationMessages } from './i18n';

// Import CSS reset and Global Styles
import './global-styles';

// Import routes
import createRoutes from './routes';

// Observe loading of Montserrat (to remove Montserrat, remove the <link> tag in
// the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Montserrat', {});

// When Montserrat is loaded, add a font-family using Montserrat to the body
openSansObserver.load().then(() => {
  document.body.classList.add('fontLoaded');
}, () => {
  document.body.classList.remove('fontLoaded');
});

// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);

// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: makeSelectLocationState(),
});

// Set up the router, wrapping all Routes in the App component
const rootRoute = {
  component: App,
  childRoutes: createRoutes(store),
};

const render = (messages) => {
  history.listen(function (location) {
    window.ga('send', 'pageview', location.pathname);
  });
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={messages}>
        <Router
          history={history}
          routes={rootRoute}
          render={
            // Scroll to top when going to a new page, imitating default browser
            // behaviour
            applyRouterMiddleware(useScroll())
          }
        />
      </LanguageProvider>
    </Provider>,
    document.getElementById('app')
  );
};

// Hot reloadable translation json files
if (module.hot) {
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept('./i18n', () => {
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(import('intl'));
  }))
    .then(() => Promise.all([
      import('intl/locale-data/jsonp/en.js'),
      import('intl/locale-data/jsonp/de.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
  require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
<commit_msg>fix : pathname<commit_after>/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */

// Needed for redux-saga es6 generator support
import 'babel-polyfill';

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import FontFaceObserver from 'fontfaceobserver';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';
import 'flexboxgrid/css/flexboxgrid.css';
import 'font-awesome/css/font-awesome.css';

// Import root app
import App from 'containers/App';

// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';

// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';

// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-webpack-loader-syntax */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions
/* eslint-enable import/no-webpack-loader-syntax */

import configureStore from './store';

// Import i18n messages
import { translationMessages } from './i18n';

// Import CSS reset and Global Styles
import './global-styles';

// Import routes
import createRoutes from './routes';

// Observe loading of Montserrat (to remove Montserrat, remove the <link> tag in
// the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Montserrat', {});

// When Montserrat is loaded, add a font-family using Montserrat to the body
openSansObserver.load().then(() => {
  document.body.classList.add('fontLoaded');
}, () => {
  document.body.classList.remove('fontLoaded');
});

// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);

// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: makeSelectLocationState(),
});

// Set up the router, wrapping all Routes in the App component
const rootRoute = {
  component: App,
  childRoutes: createRoutes(store),
};

const render = (messages) => {
  history.listen(function (location) {
    window.ga('send', 'pageview', window.location.pathname);
  });
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={messages}>
        <Router
          history={history}
          routes={rootRoute}
          render={
            // Scroll to top when going to a new page, imitating default browser
            // behaviour
            applyRouterMiddleware(useScroll())
          }
        />
      </LanguageProvider>
    </Provider>,
    document.getElementById('app')
  );
};

// Hot reloadable translation json files
if (module.hot) {
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept('./i18n', () => {
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(import('intl'));
  }))
    .then(() => Promise.all([
      import('intl/locale-data/jsonp/en.js'),
      import('intl/locale-data/jsonp/de.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
  require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
<|endoftext|>


<commit_before>/*
 * Format for Selenium Remote Control Java client.
 */

load('remoteControl.js');

this.name = "java-rc";

function useSeparateEqualsForArray() {
	return true;
}

function testMethodName(testName) {
	return "test" + capitalize(testName);
}

function assertTrue(expression) {
	return "assertTrue(" + expression.toString() + ");";
}

function verifyTrue(expression) {
	return "verifyTrue(" + expression.toString() + ");";
}

function assertFalse(expression) {
	return "assertFalse(" + expression.toString() + ");";
}

function verifyFalse(expression) {
	return "verifyFalse(" + expression.toString() + ");";
}

function assignToVariable(type, variable, expression) {
	return type + " " + variable + " = " + expression.toString();
}

function waitFor(expression) {
	return "for (int second = 0;; second++) {\n" +
		"\tif (second >= 60) fail(\"timeout\");\n" +
		"\ttry { " + (expression.setup ? expression.setup() + " " : "") +
		"if (" + expression.toString() + ") break; } catch (Exception e) {}\n" +
		"\tThread.sleep(1000);\n" +
		"}\n";
	//return "while (" + not(expression).toString() + ") { Thread.sleep(1000); }";
}

function assertOrVerifyFailure(line, isAssert) {
	var message = '"expected failure"';
	var failStatement = isAssert ? "fail(" + message  + ");" :
		"verificationErrors.append(" + message + ");";
	return "try { " + line + " " + failStatement + " } catch (Throwable e) {}";
}

Equals.prototype.toString = function() {
	return this.e1.toString() + ".equals(" + this.e2.toString() + ")";
}

Equals.prototype.assert = function() {
	return "assertEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
}

Equals.prototype.verify = function() {
	return "verifyEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
}

NotEquals.prototype.toString = function() {
	return "!" + this.e1.toString() + ".equals(" + this.e2.toString() + ")";
}

NotEquals.prototype.assert = function() {
	return "assertNotEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
}

NotEquals.prototype.verify = function() {
	return "verifyNotEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
}

RegexpMatch.prototype.toString = function() {
	if (this.pattern.match(/^\^/) && this.pattern.match(/\$$/)) {
		return this.expression + ".matches(" + string(this.pattern) + ")";
	} else {
		return "Pattern.compile(" + string(this.pattern) + ").matcher(" + this.expression + ").find()";
	}
}

EqualsArray.prototype.length = function() {
	return this.variableName + ".length";
}

EqualsArray.prototype.item = function(index) {
	return this.variableName + "[" + index + "]";
}

function pause(milliseconds) {
	return "Thread.sleep(" + parseInt(milliseconds) + ");";
}

function echo(message) {
	return "System.out.println(" + xlateArgument(message) + ");";
}

function statement(expression) {
	return expression.toString() + ';';
}

function array(value) {
	var str = 'new String[] {';
	for (var i = 0; i < value.length; i++) {
		str += string(value[i]);
		if (i < value.length - 1) str += ", ";
	}
	str += '}';
	return str;
}

CallSelenium.prototype.toString = function() {
	var result = '';
	if (this.negative) {
		result += '!';
	}
	if (options.receiver) {
		result += options.receiver + '.';
	}
	result += this.message;
	result += '(';
	for (var i = 0; i < this.args.length; i++) {
		result += this.args[i];
		if (i < this.args.length - 1) {
			result += ', ';
		}
	}
	result += ')';
	return result;
}

function formatComment(comment) {
	return comment.comment.replace(/.+/mg, function(str) {
			return "// " + str;
		});
}

this.options = {
	receiver: "selenium",
	packageName: "com.example.tests",
	superClass: "SeleneseTestCase",
    indent:	'tab',
    initialIndents:	'2'
};

options.header =
	"package ${packageName};\n" +
	"\n" +
	"import com.thoughtworks.selenium.*;\n" +
	"import java.util.regex.Pattern;\n" +
	"\n" +
    "public class ${className} extends ${superClass} {\n" +
    "\tpublic void ${methodName}() throws Exception {\n";

options.footer =
	"\t\tcheckForVerificationErrors();\n" +
	"\t}\n" +
	"}\n";

this.configForm =
	'<description>Variable for Selenium instance</description>' +
	'<textbox id="options_receiver" />';

<commit_msg>removed verifycationErrors.append because verificationErrors is now private<commit_after>/*
 * Format for Selenium Remote Control Java client.
 */

load('remoteControl.js');

this.name = "java-rc";

function useSeparateEqualsForArray() {
	return true;
}

function testMethodName(testName) {
	return "test" + capitalize(testName);
}

function assertTrue(expression) {
	return "assertTrue(" + expression.toString() + ");";
}

function verifyTrue(expression) {
	return "verifyTrue(" + expression.toString() + ");";
}

function assertFalse(expression) {
	return "assertFalse(" + expression.toString() + ");";
}

function verifyFalse(expression) {
	return "verifyFalse(" + expression.toString() + ");";
}

function assignToVariable(type, variable, expression) {
	return type + " " + variable + " = " + expression.toString();
}

function waitFor(expression) {
	return "for (int second = 0;; second++) {\n" +
		"\tif (second >= 60) fail(\"timeout\");\n" +
		"\ttry { " + (expression.setup ? expression.setup() + " " : "") +
		"if (" + expression.toString() + ") break; } catch (Exception e) {}\n" +
		"\tThread.sleep(1000);\n" +
		"}\n";
	//return "while (" + not(expression).toString() + ") { Thread.sleep(1000); }";
}

function assertOrVerifyFailure(line, isAssert) {
	var message = '"expected failure"';
    var failStatement = "fail(" + message + ");";
	return "try { " + line + " " + failStatement + " } catch (Throwable e) {}";
}

Equals.prototype.toString = function() {
	return this.e1.toString() + ".equals(" + this.e2.toString() + ")";
}

Equals.prototype.assert = function() {
	return "assertEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
}

Equals.prototype.verify = function() {
	return "verifyEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
}

NotEquals.prototype.toString = function() {
	return "!" + this.e1.toString() + ".equals(" + this.e2.toString() + ")";
}

NotEquals.prototype.assert = function() {
	return "assertNotEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
}

NotEquals.prototype.verify = function() {
	return "verifyNotEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
}

RegexpMatch.prototype.toString = function() {
	if (this.pattern.match(/^\^/) && this.pattern.match(/\$$/)) {
		return this.expression + ".matches(" + string(this.pattern) + ")";
	} else {
		return "Pattern.compile(" + string(this.pattern) + ").matcher(" + this.expression + ").find()";
	}
}

EqualsArray.prototype.length = function() {
	return this.variableName + ".length";
}

EqualsArray.prototype.item = function(index) {
	return this.variableName + "[" + index + "]";
}

function pause(milliseconds) {
	return "Thread.sleep(" + parseInt(milliseconds) + ");";
}

function echo(message) {
	return "System.out.println(" + xlateArgument(message) + ");";
}

function statement(expression) {
	return expression.toString() + ';';
}

function array(value) {
	var str = 'new String[] {';
	for (var i = 0; i < value.length; i++) {
		str += string(value[i]);
		if (i < value.length - 1) str += ", ";
	}
	str += '}';
	return str;
}

CallSelenium.prototype.toString = function() {
	var result = '';
	if (this.negative) {
		result += '!';
	}
	if (options.receiver) {
		result += options.receiver + '.';
	}
	result += this.message;
	result += '(';
	for (var i = 0; i < this.args.length; i++) {
		result += this.args[i];
		if (i < this.args.length - 1) {
			result += ', ';
		}
	}
	result += ')';
	return result;
}

function formatComment(comment) {
	return comment.comment.replace(/.+/mg, function(str) {
			return "// " + str;
		});
}

this.options = {
	receiver: "selenium",
	packageName: "com.example.tests",
	superClass: "SeleneseTestCase",
    indent:	'tab',
    initialIndents:	'2'
};

options.header =
	"package ${packageName};\n" +
	"\n" +
	"import com.thoughtworks.selenium.*;\n" +
	"import java.util.regex.Pattern;\n" +
	"\n" +
    "public class ${className} extends ${superClass} {\n" +
    "\tpublic void ${methodName}() throws Exception {\n";

options.footer =
	"\t\tcheckForVerificationErrors();\n" +
	"\t}\n" +
	"}\n";

this.configForm =
	'<description>Variable for Selenium instance</description>' +
	'<textbox id="options_receiver" />';

<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import { Slider } from 'antd-mobile'
import { Icon } from 'components'
import { renderBgImage, parseTime } from 'utils/tools'
import styles from './FullScreenPlayer.less'

class FullScreenPlayer extends Component {
  static propTypes = {
    title: PropTypes.string.isRequired,
    author: PropTypes.string.isRequired,
    thumb: PropTypes.string.isRequired,
    source: PropTypes.string.isRequired,
    loop: PropTypes.bool.isRequired,
    playing: PropTypes.bool.isRequired,
    isFullScreen: PropTypes.bool.isRequired,
    hideFullScreen: PropTypes.func.isRequired,
    handleLoop: PropTypes.func.isRequired,
    handlePlayPause: PropTypes.func.isRequired,
    handlePrev: PropTypes.func.isRequired,
    handleNext: PropTypes.func.isRequired,
    setAudioElement: PropTypes.func.isRequired,
  }

  state = {
    isSliding: false,
    currentTime: 0,
    totalTime: 0,
    percent: 0,
  }

  componentDidMount () {
    const { $audio } = this

    $audio.addEventListener('canplay', (e) => {
      this.setState({ totalTime: e.target.duration })
    })

    $audio.addEventListener('ended', () => {

    })

    $audio.addEventListener('timeupdate', (e) => {
      const { currentTime, duration } = e.target
      if(!this.state.isSliding && !isNaN(duration)) {
        this.setState({ currentTime, percent: (currentTime / duration) * 100 })
      }
    })
  }

  render () {
    const {
      title, thumb, author, source, playing, loop, isFullScreen,
      setAudioElement, hideFullScreen, handleLoop, handlePlayPause, handlePrev, handleNext } = this.props

    const { currentTime, totalTime, percent } = this.state

    const slideProps = {
      step: 0.1,
      value: percent,
      onChange: (per) => {
        this.setState({ percent: per, isSliding: true, currentTime: (percent * totalTime) / 100 })
      },
      onAfterChange: (per) => {
        this.setState({ isSliding: false })
        this.$audio.currentTime = this.$audio.duration * (per / 100)
      },
      trackStyle: {
        backgroundColor: '#666',
        height: '3px',
      },
      railStyle: {
        backgroundColor: '#cfcbd0',
        height: '3px',
      },
      handleStyle: {
        borderColor: '#999',
        height: '16px',
        width: '16px',
        marginLeft: '-7px',
        marginTop: '-7px',
        backgroundColor: '#999',
        boxShadow: '0 0 1px 1px #e3e3e3',
      },
    }

    const audioProps = {
      autoPlay: playing,
      src: source,
      ref: (c) => {
        this.$audio = c
        setAudioElement(c)
      },
    }

    return (

          <Icon type={require('svg/arrow-down.svg')} />

          {title}

          {author}

          {parseTime(currentTime)}
          <Slider {...slideProps} />
          {parseTime(totalTime)}

          {loop ?
            <Icon onClick={handleLoop} type={require('svg/loop.svg')} /> :
            <Icon onClick={handleLoop} type={require('svg/loop-no.svg')} />
          }
          <Icon type={require('svg/prev.svg')} onClick={handlePrev} />
          {playing ?
            <Icon className={styles.pause_o} onClick={handlePlayPause} type={require('svg/pause-o.svg')} /> :
            <Icon className={styles.play_o} onClick={handlePlayPause} type={require('svg/play-o.svg')} />
          }
          <Icon type={require('svg/next.svg')} onClick={handleNext} />
          <Icon type={require('svg/share.svg')} />

        <audio {...audioProps}>audio not supported :(</audio>

    )
  }
}

export default FullScreenPlayer
<commit_msg>fix AudioPlayer<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import { Slider } from 'antd-mobile'
import { Icon } from 'components'
import { renderBgImage, parseTime } from 'utils/tools'
import styles from './FullScreenPlayer.less'

class FullScreenPlayer extends Component {
  static propTypes = {
    title: PropTypes.string.isRequired,
    author: PropTypes.string.isRequired,
    thumb: PropTypes.string.isRequired,
    source: PropTypes.string.isRequired,
    loop: PropTypes.bool.isRequired,
    playing: PropTypes.bool.isRequired,
    isFullScreen: PropTypes.bool.isRequired,
    hideFullScreen: PropTypes.func.isRequired,
    handleLoop: PropTypes.func.isRequired,
    handlePlayPause: PropTypes.func.isRequired,
    handlePrev: PropTypes.func.isRequired,
    handleNext: PropTypes.func.isRequired,
    setAudioElement: PropTypes.func.isRequired,
  }

  state = {
    isSliding: false,
    currentTime: 0,
    totalTime: 0,
    percent: 0,
  }

  componentDidMount () {
    const { $audio } = this

    $audio.addEventListener('canplay', (e) => {
      this.setState({ totalTime: e.target.duration })
    })

    $audio.addEventListener('ended', () => {

    })

    $audio.addEventListener('timeupdate', (e) => {
      const { currentTime, duration } = e.target
      if (!this.state.isSliding && !isNaN(duration)) {
        this.setState({ currentTime, percent: (currentTime / duration) * 100 })
      }
    })
  }

  render () {
    const {
      title, thumb, author, source, playing, loop, isFullScreen,
      setAudioElement, hideFullScreen, handleLoop, handlePlayPause, handlePrev, handleNext } = this.props

    const { currentTime, totalTime, percent } = this.state

    const slideProps = {
      step: 0.1,
      value: percent,
      onChange: (per) => {
        this.setState({ percent: per, isSliding: true, currentTime: (percent * totalTime) / 100 })
      },
      onAfterChange: (per) => {
        this.setState({ isSliding: false })
        this.$audio.currentTime = this.$audio.duration * (per / 100)
      },
      trackStyle: {
        backgroundColor: '#666',
        height: '3px',
      },
      railStyle: {
        backgroundColor: '#cfcbd0',
        height: '3px',
      },
      handleStyle: {
        borderColor: '#999',
        height: '16px',
        width: '16px',
        marginLeft: '-7px',
        marginTop: '-7px',
        backgroundColor: '#999',
        boxShadow: '0 0 1px 1px #e3e3e3',
      },
    }

    const audioProps = {
      autoPlay: playing,
      src: source,
      ref: (c) => {
        this.$audio = c
        setAudioElement(c)
      },
    }

    return (

          <Icon type={require('svg/arrow-down.svg')} />

          {title}

          {author}

          {parseTime(currentTime)}
          <Slider {...slideProps} />
          {parseTime(totalTime)}

          {loop ?
            <Icon onClick={handleLoop} type={require('svg/loop.svg')} /> :
            <Icon onClick={handleLoop} type={require('svg/loop-no.svg')} />
          }
          <Icon type={require('svg/prev.svg')} onClick={handlePrev} />
          {playing ?
            <Icon className={styles.pause_o} onClick={handlePlayPause} type={require('svg/pause-o.svg')} /> :
            <Icon className={styles.play_o} onClick={handlePlayPause} type={require('svg/play-o.svg')} />
          }
          <Icon type={require('svg/next.svg')} onClick={handleNext} />
          <Icon type={require('svg/share.svg')} />

        <audio {...audioProps}>audio not supported :(</audio>

    )
  }
}

export default FullScreenPlayer
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2019 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable consistent-return */
const BaseBlueprintGenerator = require('../generator-base-blueprint');
const writeFiles = require('./files').writeFiles;
const prettierConfigFiles = require('./files').prettierConfigFiles;
const constants = require('../generator-constants');

let useBlueprint;

module.exports = class extends BaseBlueprintGenerator {
    constructor(args, opts) {
        super(args, opts);

        this.configOptions = this.options.configOptions || {};
        // This adds support for a `--from-cli` flag
        this.option('from-cli', {
            desc: 'Indicates the command is run from JHipster CLI',
            type: Boolean,
            defaults: false
        });

        this.setupServerOptions(this);
        this.setupClientOptions(this);
        const blueprint = this.options.blueprint || this.configOptions.blueprint || this.config.get('blueprint');
        if (!opts.fromBlueprint) {
            // use global variable since getters dont have access to instance property
            useBlueprint = this.composeBlueprint(blueprint, 'common', {
                ...this.options,
                'client-hook': !this.skipClient,
                configOptions: this.configOptions
            });
        } else {
            useBlueprint = false;
        }
    }

    // Public API method used by the getter and also by Blueprints
    _initializing() {
        return {
            validateFromCli() {
                this.checkInvocationFromCLI();
            },

            setupConsts() {
                // Make constants available in templates
                this.TEST_DIR = constants.TEST_DIR;
                this.SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;
                this.CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;
                this.CLIENT_TEST_SRC_DIR = constants.CLIENT_TEST_SRC_DIR;
                this.BUILD_DIR = this.getBuildDirectoryForBuildTool(this.buildTool);
                this.CLIENT_DIST_DIR = this.getResourceBuildDirectoryForBuildTool(this.configOptions.buildTool) + constants.CLIENT_DIST_DIR;

                // Make documentation URL available in templates
                this.DOCUMENTATION_URL = constants.JHIPSTER_DOCUMENTATION_URL;
                this.DOCUMENTATION_ARCHIVE_PATH = constants.JHIPSTER_DOCUMENTATION_ARCHIVE_PATH;
            }
        };
    }

    get initializing() {
        if (useBlueprint) return;
        return this._initializing();
    }

    // Public API method used by the getter and also by Blueprints
    _default() {
        return {
            getSharedConfigOptions() {
                this.jhipsterVersion = this.config.get('jhipsterVersion');
                this.applicationType = this.config.get('applicationType') || this.configOptions.applicationType;
                this.enableSwaggerCodegen = this.configOptions.enableSwaggerCodegen;
                this.serverPort = this.configOptions.serverPort;
                this.clientFramework = this.configOptions.clientFramework;
                this.protractorTests = this.testFrameworks.includes('protractor');
                this.gatlingTests = this.testFrameworks.includes('gatling');
            },
            writePrettierConfig() {
                // Prettier configuration needs to be the first written files - all subgenerators considered - for prettier transform to work
                this.writeFilesToDisk(prettierConfigFiles, this, false, this.fetchFromInstalledJHipster('common/templates'));
            }
        };
    }

    get default() {
        if (useBlueprint) return;
        return this._default();
    }

    // Public API method used by the getter and also by Blueprints
    _writing() {
        return writeFiles();
    }

    get writing() {
        if (useBlueprint) return;
        return this._writing();
    }
};
<commit_msg>Init MAIN_DIR folder in common generator<commit_after>/**
 * Copyright 2013-2019 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable consistent-return */
const BaseBlueprintGenerator = require('../generator-base-blueprint');
const writeFiles = require('./files').writeFiles;
const prettierConfigFiles = require('./files').prettierConfigFiles;
const constants = require('../generator-constants');

let useBlueprint;

module.exports = class extends BaseBlueprintGenerator {
    constructor(args, opts) {
        super(args, opts);

        this.configOptions = this.options.configOptions || {};
        // This adds support for a `--from-cli` flag
        this.option('from-cli', {
            desc: 'Indicates the command is run from JHipster CLI',
            type: Boolean,
            defaults: false
        });

        this.setupServerOptions(this);
        this.setupClientOptions(this);
        const blueprint = this.options.blueprint || this.configOptions.blueprint || this.config.get('blueprint');
        if (!opts.fromBlueprint) {
            // use global variable since getters dont have access to instance property
            useBlueprint = this.composeBlueprint(blueprint, 'common', {
                ...this.options,
                'client-hook': !this.skipClient,
                configOptions: this.configOptions
            });
        } else {
            useBlueprint = false;
        }
    }

    // Public API method used by the getter and also by Blueprints
    _initializing() {
        return {
            validateFromCli() {
                this.checkInvocationFromCLI();
            },

            setupConsts() {
                // Make constants available in templates
                this.MAIN_DIR = constants.MAIN_DIR;
                this.TEST_DIR = constants.TEST_DIR;
                this.SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;
                this.CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;
                this.CLIENT_TEST_SRC_DIR = constants.CLIENT_TEST_SRC_DIR;
                this.BUILD_DIR = this.getBuildDirectoryForBuildTool(this.buildTool);
                this.CLIENT_DIST_DIR = this.getResourceBuildDirectoryForBuildTool(this.configOptions.buildTool) + constants.CLIENT_DIST_DIR;

                // Make documentation URL available in templates
                this.DOCUMENTATION_URL = constants.JHIPSTER_DOCUMENTATION_URL;
                this.DOCUMENTATION_ARCHIVE_PATH = constants.JHIPSTER_DOCUMENTATION_ARCHIVE_PATH;
            }
        };
    }

    get initializing() {
        if (useBlueprint) return;
        return this._initializing();
    }

    // Public API method used by the getter and also by Blueprints
    _default() {
        return {
            getSharedConfigOptions() {
                this.jhipsterVersion = this.config.get('jhipsterVersion');
                this.applicationType = this.config.get('applicationType') || this.configOptions.applicationType;
                this.enableSwaggerCodegen = this.configOptions.enableSwaggerCodegen;
                this.serverPort = this.configOptions.serverPort;
                this.clientFramework = this.configOptions.clientFramework;
                this.protractorTests = this.testFrameworks.includes('protractor');
                this.gatlingTests = this.testFrameworks.includes('gatling');
            },
            writePrettierConfig() {
                // Prettier configuration needs to be the first written files - all subgenerators considered - for prettier transform to work
                this.writeFilesToDisk(prettierConfigFiles, this, false, this.fetchFromInstalledJHipster('common/templates'));
            }
        };
    }

    get default() {
        if (useBlueprint) return;
        return this._default();
    }

    // Public API method used by the getter and also by Blueprints
    _writing() {
        return writeFiles();
    }

    get writing() {
        if (useBlueprint) return;
        return this._writing();
    }
};
<|endoftext|>


<commit_before>/**
 * Observable Subscription
 * An implementation of the TC39 Subscription object
 * https://tc39.github.io/proposal-observable/#subscription-objects
 *
 * @id ObservableSubscription
 * @name ObservableSubscription
 * @param {stream} source - Highland stream to subscribe to
 * arguments to the callback. Only valid if `source` is a String.
 * @api private
 */
function ObservableSubscription (source) {
    this.source = source;
    this.closed = false;
}

// Static Methods

ObservableSubscription.create = function create (source) {
    return new ObservableSubscription(source);
};

ObservableSubscription.cleanup = function cleanup (subscription) {
    if (subscription.closed) {
        return;
    }
    subscription.source.destroy();
    subscription.source = null;
    subscription.closed = true;
};

// Instance Methods

ObservableSubscription.prototype.unsubscribe = function unsubscribe () {
    ObservableSubscription.cleanup(this);
};

module.exports = ObservableSubscription;
<commit_msg>Added more documentation to observableSubscription<commit_after>/**
 * Observable Subscription
 * An implementation of the TC39 Subscription object
 * https://tc39.github.io/proposal-observable/#subscription-objects
 *
 * This class is intended for internal use only.
 *
 * @id ObservableSubscription
 * @name ObservableSubscription
 * @param {stream} source - Highland stream to subscribe to
 * arguments to the callback. Only valid if `source` is a String.
 * @api private
 */
function ObservableSubscription (source) {
    this.source = source;
    this.closed = false;
}

// Static Methods

/**
 * Create
 * Return an instance of an ObservableSubscription class
 *
 * @id ObservableSubscription.create(source)
 * @name ObservableSubscription.create
 * @param {stream} [source] - Optional highland stream source
 * @returns {ObservableSubscription} A subscription that can be unsubscribed
 * @api private
 */

ObservableSubscription.create = function create (source) {
    return new ObservableSubscription(source);
};

/**
 * Cleanup
 * Perform cleanup routine on a subscription. This can only be called once per
 * subscription. Once its closed the subscription cannot be cleaned up again.
 *
 * Note: This relies heavily upon side-effects and mutates the subscription.
 *
 * @id ObservableSubscription.cleanup(subscription)
 * @name ObservableSubscription.cleanup
 * @param {ObservableSubscription} subscription - Subscription to cleanup
 * @returns {undefined} Side-effectful function cleans up subscription
 * @api private
 */

ObservableSubscription.cleanup = function cleanup (subscription) {
    if (subscription.closed) {
        return;
    }
    subscription.source = null;
    subscription.closed = true;
};

// Instance Methods

/**
 * Unsubscribe
 * Destroy the stream resources and cleanup the subscription.
 * @id ObservableSubscription.prototype.unsubscribe()
 * @name ObservableSubscription.prototype.unsubscribe()
 * @returns {undefined} Side-effectful. Destroys stream and cleans up subscription.
 * @api private
 */

ObservableSubscription.prototype.unsubscribe = function unsubscribe () {
    this.source.destroy();
    ObservableSubscription.cleanup(this);
};

module.exports = ObservableSubscription;
<|endoftext|>


<commit_before>// This looks for file defaults.js in resource folder, expects:
//	objName - (string) main object name for the add-on, to be added to window element
//	objPathString - (string) add-on path name to use in URIs
//	prefList: (object) { prefName: defaultValue } - add-on preferences
//	startConditions(aData, aReason) - (method) should return false if any requirements the add-on needs aren't met, otherwise return true or call continueStartup(aData, aReason)
//	onStartup(aData, aReason) and onShutdown(aData, aReason) - (methods) to be called on startup() and shutdown() to initialize and terminate the add-on respectively
//	resource folder in installpath, with modules folder containing moduleAid, sandboxUtils and utils modules
//	chrome.manifest file with content, locale and skin declarations properly set
// prepareObject(window, aName) - initializes a window-dependent add-on object with utils loaded into it, returns the newly created object
//	window - (xul object) the window object to be initialized
//	(optional) aName - (string) the object name, defaults to objName
// removeObject(window, aName) - closes and removes the object initialized by prepareObject()
//	see prepareObject()
// preparePreferences(window, aName) - loads the preferencesUtils module into that window's object initialized by prepareObject() (if it hasn't yet, it will be initialized)
//	see prepareObject()
// listenOnce(aSubject, type, handler, capture) - adds handler to window listening to event type that will be removed after one execution.
//	aSubject - (xul object) to add the handler to
//	type - (string) event type to listen to
//	handler - (function(event, aSubject)) - method to be called when event is triggered
//	(optional) capture - (bool) capture mode
// callOnLoad(aSubject, aCallback) - calls aCallback when load event is fired on that window
//	aSubject - (xul object) to execute aCallback on
//	aCallback - (function(aSubject)) to be called on aSubject
// disable() - disables the add-on
// Note: Firefox 8 is the minimum version supported as the bootstrap requires the chrome.manifest file to be loaded, which was implemented in Firefox 8.

let bootstrapVersion = '1.2.1';
let UNLOADED = false;
let STARTED = false;
let addonData = null;
let observerLOADED = false;
let onceListeners = [];

const {classes: Cc, interfaces: Ci, utils: Cu, manager: Cm} = Components;
Cu.import("resource://gre/modules/AddonManager.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/PlacesUIUtils.jsm");
XPCOMUtils.defineLazyServiceGetter(Services, "fuel", "@mozilla.org/fuel/application;1", "fuelIApplication");
XPCOMUtils.defineLazyServiceGetter(Services, "navigator", "@mozilla.org/network/protocol;1?name=http", "nsIHttpProtocolHandler");
XPCOMUtils.defineLazyServiceGetter(Services, "privateBrowsing", "@mozilla.org/privatebrowsing;1", "nsIPrivateBrowsingService");
XPCOMUtils.defineLazyServiceGetter(Services, "stylesheet", "@mozilla.org/content/style-sheet-service;1", "nsIStyleSheetService");

function prepareObject(window, aName) {
	// I can override the object name if I want
	let objectName = aName || objName;
	if(window[objectName]) { return; }

	window[objectName] = {
		objName: objectName,
		objPathString: objPathString,

		// every supposedly global variable is inaccessible because bootstraped means sandboxed, so I have to reference all these;
		// it's easier to reference more specific objects from within the modules for better control, only setting these two here because they're more generalized
		window: window,
		get document () { return window.document; },
		$: function(id) { return window.document.getElementById(id); },
		$$: function(sel) { return window.document.querySelectorAll(sel); }
	};

	Services.scriptloader.loadSubScript("resource://"+objPathString+"/modules/utils/moduleAid.jsm", window[objectName]);
	window[objectName].moduleAid.load("utils/windowUtils");
}

function removeObject(window, aName) {
	let objectName = aName || objName;

	if(window[objectName]) {
		window[objectName].moduleAid.unload("utils/windowUtils");
		delete window[objectName];
	}
}

function preparePreferences(window, aName) {
	let objectName = aName || objName;

	if(!window[objectName]) {
		prepareObject(window, objectName);
	}
	window[objectName].moduleAid.load("utils/preferencesUtils");
}

function removeOnceListener(oncer) {
	for(var i=0; i<onceListeners.length; i++) {
		if(!oncer) {
			if(onceListeners[i].obj) {
				onceListeners[i].obj.removeEventListener(onceListeners[i].type, onceListeners[i].handler, onceListeners[i].capture);
			}
			continue;
		}

		if(onceListeners[i].handler == oncer) {
			if(onceListeners[i].obj) {
				onceListeners[i].obj.removeEventListener(onceListeners[i].type, onceListeners[i].handler, onceListeners[i].capture);
			}
			onceListeners.splice(i, 1);
			return;
		}
	}
}

function listenOnce(aSubject, type, handler, capture) {
	if(UNLOADED || !aSubject || !aSubject.addEventListener) { return; }

	var runOnce = function(event) {
		removeOnceListener(runOnce);
		if(!UNLOADED) {
			try { handler(event, aSubject); }
			catch(ex) { Cu.reportError(ex); }
		}
	};

	aSubject.addEventListener(type, runOnce, capture);
	onceListeners.push({ obj: aSubject, type: type, handler: runOnce, capture: capture});
}

function callOnLoad(aSubject, aCallback, arg1) {
	listenOnce(aSubject, "load", function(event, aSubject) {
		if(UNLOADED) { return; }

		try { aCallback(aSubject, arg1); }
		catch(ex) { Cu.reportError(ex); }
	}, false);
}

function setResourceHandler() {
	// chrome.manifest files are loaded automatically in Firefox 10+.
	// I haven't tested this, got it directly from https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIComponentManager#addBootstrappedManifestLocation()
	if(Services.vc.compare(Services.appinfo.platformVersion, "10.0") < 0) {
		Cm.addBootstrappedManifestLocation(addonData.installPath);
	}

	let alias = Services.io.newFileURI(addonData.installPath);
	let resourceURI = (addonData.installPath.isDirectory()) ? alias.spec : 'jar:' + alias.spec + '!/';
	resourceURI += 'resource/';

	// Set the default strings for the add-on
	Services.scriptloader.loadSubScript(resourceURI + 'defaults.js', this);

	alias = Services.io.newURI(resourceURI, null, null);
	let resource = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
	resource.setSubstitution(objPathString, alias);

	// Get the utils.jsm module into our sandbox
	Services.scriptloader.loadSubScript("resource://"+objPathString+"/modules/utils/moduleAid.jsm", this);
	moduleAid.load("utils/sandboxUtils");
}

function removeResourceHandler() {
	moduleAid.unload("utils/sandboxUtils");

	let resource = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
	resource.setSubstitution(objPathString, null);

	// chrome.manifest files are loaded automatically in Firefox 10+.
	// I haven't tested this, got it directly from https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIComponentManager#addBootstrappedManifestLocation()
	if(Services.vc.compare(Services.appinfo.platformVersion, "10.0") < 0) {
		Cm.removeBootstrappedManifestLocation(addonData.installPath);
	}
}

function disable() {
	AddonManager.getAddonByID(addonData.id, function(addon) {
		addon.userDisabled = true;
	});
}

function continueStartup(aReason) {
	STARTED = aReason;

	// set add-on preferences defaults
	prefAid.setDefaults(prefList);

	onStartup(aReason);
}

function startup(aData, aReason) {
	UNLOADED = false;
	addonData = aData;

	// add resource:// protocol handler so I can access my modules
	setResourceHandler();

	// In the case of OmnibarPlus, I need the Omnibar add-on enabled for everything to work
	if(startConditions(aReason)) {
		continueStartup(aReason);
	}
}

function shutdown(aData, aReason) {
	UNLOADED = aReason;

	if(aReason == APP_SHUTDOWN) {
		if(observerLOADED) { observerAid.callQuits(); }
		removeOnceListener();
		return;
	}

	if(STARTED) {
		onShutdown(aReason);
	}

	// remove resource://
	removeResourceHandler();
	removeOnceListener();
}

function install() {}
function uninstall() {}
<commit_msg>simplified listenOnce()<commit_after>// This looks for file defaults.js in resource folder, expects:
//	objName - (string) main object name for the add-on, to be added to window element
//	objPathString - (string) add-on path name to use in URIs
//	prefList: (object) { prefName: defaultValue } - add-on preferences
//	startConditions(aData, aReason) - (method) should return false if any requirements the add-on needs aren't met, otherwise return true or call continueStartup(aData, aReason)
//	onStartup(aData, aReason) and onShutdown(aData, aReason) - (methods) to be called on startup() and shutdown() to initialize and terminate the add-on respectively
//	resource folder in installpath, with modules folder containing moduleAid, sandboxUtils and utils modules
//	chrome.manifest file with content, locale and skin declarations properly set
// prepareObject(window, aName) - initializes a window-dependent add-on object with utils loaded into it, returns the newly created object
//	window - (xul object) the window object to be initialized
//	(optional) aName - (string) the object name, defaults to objName
// removeObject(window, aName) - closes and removes the object initialized by prepareObject()
//	see prepareObject()
// preparePreferences(window, aName) - loads the preferencesUtils module into that window's object initialized by prepareObject() (if it hasn't yet, it will be initialized)
//	see prepareObject()
// listenOnce(aSubject, type, handler, capture) - adds handler to window listening to event type that will be removed after one execution.
//	aSubject - (xul object) to add the handler to
//	type - (string) event type to listen to
//	handler - (function(event, aSubject)) - method to be called when event is triggered
//	(optional) capture - (bool) capture mode
// callOnLoad(aSubject, aCallback) - calls aCallback when load event is fired on that window
//	aSubject - (xul object) to execute aCallback on
//	aCallback - (function(aSubject)) to be called on aSubject
// disable() - disables the add-on
// Note: Firefox 8 is the minimum version supported as the bootstrap requires the chrome.manifest file to be loaded, which was implemented in Firefox 8.

let bootstrapVersion = '1.2.2';
let UNLOADED = false;
let STARTED = false;
let addonData = null;
let observerLOADED = false;
let onceListeners = [];

const {classes: Cc, interfaces: Ci, utils: Cu, manager: Cm} = Components;
Cu.import("resource://gre/modules/AddonManager.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/PlacesUIUtils.jsm");
XPCOMUtils.defineLazyServiceGetter(Services, "fuel", "@mozilla.org/fuel/application;1", "fuelIApplication");
XPCOMUtils.defineLazyServiceGetter(Services, "navigator", "@mozilla.org/network/protocol;1?name=http", "nsIHttpProtocolHandler");
XPCOMUtils.defineLazyServiceGetter(Services, "privateBrowsing", "@mozilla.org/privatebrowsing;1", "nsIPrivateBrowsingService");
XPCOMUtils.defineLazyServiceGetter(Services, "stylesheet", "@mozilla.org/content/style-sheet-service;1", "nsIStyleSheetService");

function prepareObject(window, aName) {
	// I can override the object name if I want
	let objectName = aName || objName;
	if(window[objectName]) { return; }

	window[objectName] = {
		objName: objectName,
		objPathString: objPathString,

		// every supposedly global variable is inaccessible because bootstraped means sandboxed, so I have to reference all these;
		// it's easier to reference more specific objects from within the modules for better control, only setting these two here because they're more generalized
		window: window,
		get document () { return window.document; },
		$: function(id) { return window.document.getElementById(id); },
		$$: function(sel) { return window.document.querySelectorAll(sel); }
	};

	Services.scriptloader.loadSubScript("resource://"+objPathString+"/modules/utils/moduleAid.jsm", window[objectName]);
	window[objectName].moduleAid.load("utils/windowUtils");
}

function removeObject(window, aName) {
	let objectName = aName || objName;

	if(window[objectName]) {
		window[objectName].moduleAid.unload("utils/windowUtils");
		delete window[objectName];
	}
}

function preparePreferences(window, aName) {
	let objectName = aName || objName;

	if(!window[objectName]) {
		prepareObject(window, objectName);
	}
	window[objectName].moduleAid.load("utils/preferencesUtils");
}

function removeOnceListener(oncer) {
	for(var i=0; i<onceListeners.length; i++) {
		if(!oncer) {
			onceListeners[i]();
			continue;
		}

		if(onceListeners[i] == oncer) {
			onceListeners.splice(i, 1);
			return;
		}
	}

	if(!oncer) {
		onceListeners = [];
	}
}

function listenOnce(aSubject, type, handler, capture) {
	if(UNLOADED || !aSubject || !aSubject.addEventListener) { return; }

	var runOnce = function(event) {
		aSubject.removeEventListener(type, runOnce, capture);
		if(!UNLOADED && event !== undefined) {
			removeOnceListener(runOnce);
			try { handler(event, aSubject); }
			catch(ex) { Cu.reportError(ex); }
		}
	};

	aSubject.addEventListener(type, runOnce, capture);
	onceListeners.push(runOnce);
}

function callOnLoad(aSubject, aCallback, arg1) {
	listenOnce(aSubject, "load", function(event, aSubject) {
		if(UNLOADED) { return; }

		try { aCallback(aSubject, arg1); }
		catch(ex) { Cu.reportError(ex); }
	}, false);
}

function setResourceHandler() {
	// chrome.manifest files are loaded automatically in Firefox 10+.
	// I haven't tested this, got it directly from https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIComponentManager#addBootstrappedManifestLocation()
	if(Services.vc.compare(Services.appinfo.platformVersion, "10.0") < 0) {
		Cm.addBootstrappedManifestLocation(addonData.installPath);
	}

	let alias = Services.io.newFileURI(addonData.installPath);
	let resourceURI = (addonData.installPath.isDirectory()) ? alias.spec : 'jar:' + alias.spec + '!/';
	resourceURI += 'resource/';

	// Set the default strings for the add-on
	Services.scriptloader.loadSubScript(resourceURI + 'defaults.js', this);

	alias = Services.io.newURI(resourceURI, null, null);
	let resource = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
	resource.setSubstitution(objPathString, alias);

	// Get the utils.jsm module into our sandbox
	Services.scriptloader.loadSubScript("resource://"+objPathString+"/modules/utils/moduleAid.jsm", this);
	moduleAid.load("utils/sandboxUtils");
}

function removeResourceHandler() {
	moduleAid.unload("utils/sandboxUtils");

	let resource = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
	resource.setSubstitution(objPathString, null);

	// chrome.manifest files are loaded automatically in Firefox 10+.
	// I haven't tested this, got it directly from https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIComponentManager#addBootstrappedManifestLocation()
	if(Services.vc.compare(Services.appinfo.platformVersion, "10.0") < 0) {
		Cm.removeBootstrappedManifestLocation(addonData.installPath);
	}
}

function disable() {
	AddonManager.getAddonByID(addonData.id, function(addon) {
		addon.userDisabled = true;
	});
}

function continueStartup(aReason) {
	STARTED = aReason;

	// set add-on preferences defaults
	prefAid.setDefaults(prefList);

	onStartup(aReason);
}

function startup(aData, aReason) {
	UNLOADED = false;
	addonData = aData;

	// add resource:// protocol handler so I can access my modules
	setResourceHandler();

	// In the case of OmnibarPlus, I need the Omnibar add-on enabled for everything to work
	if(startConditions(aReason)) {
		continueStartup(aReason);
	}
}

function shutdown(aData, aReason) {
	UNLOADED = aReason;

	if(aReason == APP_SHUTDOWN) {
		if(observerLOADED) { observerAid.callQuits(); }
		removeOnceListener();
		return;
	}

	if(STARTED) {
		onShutdown(aReason);
	}

	// remove resource://
	removeResourceHandler();
	removeOnceListener();
}

function install() {}
function uninstall() {}
<|endoftext|>


<commit_before>var stringify     = require("querystring").stringify,
	hmac          = require("crypto").createHmac,
	request       = require("request"),
	publicMethods = ['getmarkets', 'getcurrencies', 'getticker', 'getmarketsummary', 'getmarketsummaries', 'getorderbook', 'getmarkethistory'];

function BleuTradeClient(key, secret, requeue) {
	var self    = this;

	self.key     = key;
	self.secret  = secret;
	self.jar     = request.jar();
	self.requeue = requeue || 0;

	function api_query(method, callback, args) {
		var args_tmp = {};

		for(var i in args) {
			if(args[i]) {
				args_tmp[i] = args[i];
			}
		}

		args = args_tmp;

		var options = {
			uri     : 'https://bleutrade.com/api/v2/' + method,
			agent   : false,
			method  : 'GET',
			jar     : self.jar,
			headers : {
				"User-Agent": "Mozilla/4.0 (compatible; Bleutrade API node client)",
				"Content-type": "application/x-www-form-urlencoded"
			}
		};

		if(publicMethods.indexOf(method) > -1) {
			options.method = 'GET';
			options.uri    = 'https://bleutrade.com/api/v2/public/' + method + '?' + stringify(args);;
		}	else	{
			if (!self.key || !self.secret) {
				throw new Error("Must provide key and secret to make this API request.");
			}	else{
				args.apikey = self.key;
				args.nonce = new Date().getTime();
			 	options.uri += ('?' + stringify(args));
				options.headers.apisign = new hmac("sha512", self.secret).update(options.uri).digest('hex');
			}
		}

		request(options, function(err, res, body) {
			if(!body || !res || res.statusCode != 200) {
				var requeue = +self.requeue;

				if(requeue) {
					setTimeout(function() {
						api_query(method, callback, args);
					}, requeue);
				}
				else if(typeof callback === 'function') {
					console.error(err);
					console.error(body);
					callback.call(this, "Error in server response", null);
				}
			} else {
				var error  = null;
				var result = null;

				try {
					var response = JSON.parse(body);

					if(response.error) {
						error = response.error;
					} else {
						result = response.return || response;
					}
				} catch(e) {
					error = "Error parsing server response: " + e.message;
				}

				if(typeof callback === 'function') {
					callback.call(this, error, result);
				}
			}
		});
	}

	// public
	self.getcurrencies = function(callback) {
		api_query('getcurrencies', callback);
	};

	self.getmarkets = function(callback) {
		api_query('getmarkets', callback);
	};

	self.getticker = function(market, callback) {
		api_query('getticker', callback, {market: market});
	};

	self.getmarketsummaries = function(callback) {
		api_query('getmarketsummaries', callback);
	};

	self.getmarketsummary = function(market, callback) {
		api_query('getmarketsummaries', callback, {market: market});
	};

	self.getorderbook = function(market, type, depth, callback) {
		api_query('getorderbook', callback, {market: market, type: type, depth: depth});
	};

	self.getmarkethistory = function(market, count, callback) {
		api_query('getmarkethistory', callback, {market: market, count: count});
	};

	self.getcandles = function(market, period, count, lasthours, callback) {
		api_query('getorderbook', callback, {market: market, period: period, count: count, lasthours: lasthours});
	};

	////////////////////////////////////////////////////////////////////////
	// Private
	////////////////////////////////////////////////////////////////////////

	// Market
	self.market_buylimit = function(market, rate, quantity, comments, callback) {
		api_query('market/buylimit', callback, {market: market, rate: rate, quantity: quantity, comments: comments});
	};

	self.market_selllimit = function(market, rate, quantity, comments, callback) {
		api_query('market/selllimit', callback, {market: market, rate: rate, quantity: quantity, comments: comments});
	};

	self.market_cancel = function(orderid, callback) {
		api_query('market/cancel', callback, {orderid: orderid});
	};

	self.market_getopenorders = function(callback) {
		api_query('market/getopenorders', callback);
	};

	// Account
	self.getbalances = function(currencies, callback) {
		api_query('account/getbalances', callback, { currencies: currencies });
	};

	self.getbalance = function(currency, callback) {
		api_query('account/getbalance', callback, { currency: currency });
	};

	self.getdepositaddress = function(currency, callback) {
		api_query('account/getdepositaddress', callback, { currency: currency });
	};

	self.withdraw = function(currency, quantity, address, callback) {
		api_query('account/withdraw', callback, { currency: currency, quantity: quantity, address: address });
	};

	self.transfer = function(currency, quantity, touser, callback) {
		api_query('account/transfer', callback, { currency: currency, quantity: quantity, touser: touser });
	};

	self.getorder = function(orderid, callback) {
		api_query('account/getorder', callback, { orderid: orderid });
	};

	self.getorders = function(market, orderstatus, callback) {
		api_query('account/getorders', callback, { market: market, orderstatus: orderstatus });
	};

	self.getorderhistory = function(orderid, callback) {
		api_query('account/getorderhistory', callback, { orderid: orderid });
	};
}

module.exports = BleuTradeClient;
<commit_msg>Deposit/Withdarw history & Chat<commit_after>var stringify     = require("querystring").stringify,
	hmac          = require("crypto").createHmac,
	request       = require("request"),
	publicMethods = ['getmarkets', 'getcurrencies', 'getticker', 'getmarketsummary', 'getmarketsummaries', 'getorderbook', 'getmarkethistory'];

function BleuTradeClient(key, secret, requeue) {
	var self    = this;

	self.key     = key;
	self.secret  = secret;
	self.jar     = request.jar();
	self.requeue = requeue || 0;

	function api_query(method, callback, args) {
		var args_tmp = {};

		for(var i in args) {
			if(args[i]) {
				args_tmp[i] = args[i];
			}
		}

		args = args_tmp;

		var options = {
			uri     : 'https://bleutrade.com/api/v2/' + method,
			agent   : false,
			method  : 'GET',
			jar     : self.jar,
			headers : {
				"User-Agent": "Mozilla/4.0 (compatible; Bleutrade API node client)",
				"Content-type": "application/x-www-form-urlencoded"
			}
		};

		if(publicMethods.indexOf(method) > -1) {
			options.method = 'GET';
			options.uri    = 'https://bleutrade.com/api/v2/public/' + method + '?' + stringify(args);;
		}	else	{
			if (!self.key || !self.secret) {
				throw new Error("Must provide key and secret to make this API request.");
			}	else{
				args.apikey = self.key;
				args.nonce = new Date().getTime();
			 	options.uri += ('?' + stringify(args));
				options.headers.apisign = new hmac("sha512", self.secret).update(options.uri).digest('hex');
			}
		}

		request(options, function(err, res, body) {
			if(!body || !res || res.statusCode != 200) {
				var requeue = +self.requeue;

				if(requeue) {
					setTimeout(function() {
						api_query(method, callback, args);
					}, requeue);
				}
				else if(typeof callback === 'function') {
					console.error(err);
					console.error(body);
					callback.call(this, "Error in server response", null);
				}
			} else {
				var error  = null;
				var result = null;

				try {
					var response = JSON.parse(body);

					if(response.error) {
						error = response.error;
					} else {
						result = response.return || response;
					}
				} catch(e) {
					error = "Error parsing server response: " + e.message;
				}

				if(typeof callback === 'function') {
					callback.call(this, error, result);
				}
			}
		});
	}

	// public
	self.getcurrencies = function(callback) {
		api_query('getcurrencies', callback);
	};

	self.getmarkets = function(callback) {
		api_query('getmarkets', callback);
	};

	self.getticker = function(market, callback) {
		api_query('getticker', callback, {market: market});
	};

	self.getmarketsummaries = function(callback) {
		api_query('getmarketsummaries', callback);
	};

	self.getmarketsummary = function(market, callback) {
		api_query('getmarketsummaries', callback, {market: market});
	};

	self.getorderbook = function(market, type, depth, callback) {
		api_query('getorderbook', callback, {market: market, type: type, depth: depth});
	};

	self.getmarkethistory = function(market, count, callback) {
		api_query('getmarkethistory', callback, {market: market, count: count});
	};

	self.getcandles = function(market, period, count, lasthours, callback) {
		api_query('getorderbook', callback, {market: market, period: period, count: count, lasthours: lasthours});
	};

	////////////////////////////////////////////////////////////////////////
	// Private
	////////////////////////////////////////////////////////////////////////

	// Market
	self.market_buylimit = function(market, rate, quantity, comments, callback) {
		api_query('market/buylimit', callback, {market: market, rate: rate, quantity: quantity, comments: comments});
	};

	self.market_selllimit = function(market, rate, quantity, comments, callback) {
		api_query('market/selllimit', callback, {market: market, rate: rate, quantity: quantity, comments: comments});
	};

	self.market_cancel = function(orderid, callback) {
		api_query('market/cancel', callback, {orderid: orderid});
	};

	self.market_getopenorders = function(callback) {
		api_query('market/getopenorders', callback);
	};

	// Account
	self.getbalances = function(currencies, callback) {
		api_query('account/getbalances', callback, { currencies: currencies });
	};

	self.getbalance = function(currency, callback) {
		api_query('account/getbalance', callback, { currency: currency });
	};

	self.getdepositaddress = function(currency, callback) {
		api_query('account/getdepositaddress', callback, { currency: currency });
	};

	self.withdraw = function(currency, quantity, address, callback) {
		api_query('account/withdraw', callback, { currency: currency, quantity: quantity, address: address });
	};

	self.transfer = function(currency, quantity, touser, callback) {
		api_query('account/transfer', callback, { currency: currency, quantity: quantity, touser: touser });
	};

	self.getorder = function(orderid, callback) {
		api_query('account/getorder', callback, { orderid: orderid });
	};

	self.getorders = function(market, orderstatus, callback) {
		api_query('account/getorders', callback, { market: market, orderstatus: orderstatus });
	};

	self.getorderhistory = function(orderid, callback) {
		api_query('account/getorderhistory', callback, { orderid: orderid });
	};

	self.getdeposithistory = function(callback) {
		api_query('account/getdeposithistory', callback);
	};

	self.getwithdrawhistory = function(callback) {
		api_query('account/getwithdrawhistory', callback);
	};

	self.chatsend = function(channel, text, callback) {
		api_query('account/chatsend', callback, {channel: channel, text: text});
	};
}

module.exports = BleuTradeClient;
<|endoftext|>


<commit_before>
import React from "react";
import format from "date-fns/format";

export default class PostPreview extends React.Component {
  render() {
    const {entry, widgetFor} = this.props;

    return

{ entry.getIn(["data", "title"])}

{ format(entry.getIn(["data", "date"]), "ddd, MMM D, YYYY") }

Read in x minutes

        { widgetFor("body") }

;
  }
}
<commit_msg>image in template again<commit_after>
import React from "react";
import format from "date-fns/format";

export default class PostPreview extends React.Component {
  render() {
    const {entry, widgetFor} = this.props;

    return

{ entry.getIn(["data", "title"])}

{ format(entry.getIn(["data", "date"]), "ddd, MMM D, YYYY") }

Read in x minutes

        { widgetFor("body") }

;
  }
}
<|endoftext|>


<commit_before>ngapp.directive('unfocusModal', function($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            let el = element[0],
                mouseDown = false,
                callback = $parse(attrs.unfocusModal),
                handleMouseUp = () => mouseDown = false;

            el.addEventListener('mousedown', function(e) {
                mouseDown = e.target === el;
            });
            el.addEventListener('mouseup', function(e) {
                if (!mouseDown || e.target !== el) return;
                if (callback) {
                    scope.$apply(() => callback(scope, {$event: e}))
                } else {
                    scope.$emit('closeModal');
                }
            });

            document.addEventListener('mouseup', handleMouseUp);
            scope.$on('destroy', function() {
                document.removeEventListener('mouseUp', handleMouseUp);
            });
        }
    }
});
<commit_msg>fixed bug with unfocusing modals not working when a custom callback isn't provided<commit_after>ngapp.directive('unfocusModal', function($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            let el = element[0],
                mouseDown = false,
                callback = attrs.unfocusModal && $parse(attrs.unfocusModal),
                handleMouseUp = () => mouseDown = false;

            el.addEventListener('mousedown', function(e) {
                mouseDown = e.target === el;
            });
            el.addEventListener('mouseup', function(e) {
                if (!mouseDown || e.target !== el) return;
                if (callback) {
                    scope.$apply(() => callback(scope, {$event: e}))
                } else {
                    scope.$emit('closeModal');
                }
            });

            document.addEventListener('mouseup', handleMouseUp);
            scope.$on('destroy', function() {
                document.removeEventListener('mouseUp', handleMouseUp);
            });
        }
    }
});
<|endoftext|>


<commit_before>import React from 'react'

import styles from './button.less'

class Button extends React.Component {
	render() {
		return (
			<button className={styles['button']}>
				{this.props.children}
			</button>
		)
	}
}
export default Button<commit_msg>Told the button.js file to look in our-styles.less for its styles.<commit_after>import React from 'react'
import styles from './our-styles.less'

class Button extends React.Component {
	render() {
		return (
			<button className={styles['button']}>
				{this.props.children}
			</button>
		)
	}
}
export default Button<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

module.exports = function (config) {
  var testWebpackConfig = require('./webpack.test.js')({ env: 'test' });

  var configuration = {

    // base path that will be used to resolve all patterns (e.g. files, exclude)
    basePath: '',

    /*
     * Frameworks to use
     *
     * available frameworks: https://npmjs.org/browse/keyword/karma-adapter
     */
    frameworks: ['jasmine'],

    // list of files to exclude
    exclude: [],

    client: {
      captureConsole: false
    },

	/*
     * list of files / patterns to load in the browser
     *
     * we are building the test environment in ./spec-bundle.js
     */
    files: [
      { pattern: './config/spec-bundle.js', watched: false },
      { pattern: './src/assets/**/*', watched: false, included: false, served: true, nocache: false }
    ],

    /*
     * By default all assets are served at http://localhost:[PORT]/base/
     */
    proxies: {
      "/assets/": "/base/src/assets/"
    },

    /*
     * preprocess matching files before serving them to the browser
     * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
     */
    preprocessors: { './config/spec-bundle.js': ['coverage', 'webpack', 'sourcemap'] },

    // Webpack Config at ./webpack.test.js
    webpack: testWebpackConfig,

    coverageReporter: {
      type: 'in-memory'
    },

    remapCoverageReporter: {
      'text-summary': null,
      json: './coverage/coverage.json',
      html: './coverage/html'
    },

    // Webpack please don't spam the console when running in karma!
    webpackMiddleware: {
      // webpack-dev-middleware configuration
      // i.e.
      noInfo: true,
      // and use stats to turn off verbose output
      stats: {
        // options i.e.
        chunks: false
      }
    },

    /*
     * test results reporter to use
     *
     * possible values: 'dots', 'progress'
     * available reporters: https://npmjs.org/browse/keyword/karma-reporter
     */
    reporters: ['mocha', 'coverage', 'remap-coverage'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    /*
     * level of logging
     * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
     */
    logLevel: config.LOG_WARN,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    /*
     * start these browsers
     * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
     */
    browsers: [
      //'Chrome'
	  'PhantomJS'
    ],

    customLaunchers: {
      ChromeTravisCi: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    /*
     * Continuous Integration mode
     * if true, Karma captures browsers, runs the tests and exits
     */
    singleRun: false

	captureTimeout: 60000,
	browserDisconnectTimeout: 2000,
	browserDisconnectTolerance: 0,
	browserNoActivityTimeout: 10000,

	};

  if (process.env.TRAVIS) {
    configuration.browsers = [
      'ChromeTravisCi'
    ];
  }

  config.set(configuration);
};
<commit_msg>tests v12<commit_after>/**
 * @author: @AngularClass
 */

module.exports = function (config) {
  var testWebpackConfig = require('./webpack.test.js')({ env: 'test' });

  var configuration = {
	};

  config.set({
	  // base path that will be used to resolve all patterns (e.g. files, exclude)
    basePath: '',

    /*
     * Frameworks to use
     *
     * available frameworks: https://npmjs.org/browse/keyword/karma-adapter
     */
    frameworks: ['jasmine'],

    // list of files to exclude
    exclude: [],

    client: {
      captureConsole: false
    },

	/*
     * list of files / patterns to load in the browser
     *
     * we are building the test environment in ./spec-bundle.js
     */
    files: [
      { pattern: './config/spec-bundle.js', watched: false },
      { pattern: './src/assets/**/*', watched: false, included: false, served: true, nocache: false }
    ],

    /*
     * By default all assets are served at http://localhost:[PORT]/base/
     */
    proxies: {
      "/assets/": "/base/src/assets/"
    },

    /*
     * preprocess matching files before serving them to the browser
     * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
     */
    preprocessors: { './config/spec-bundle.js': ['coverage', 'webpack', 'sourcemap'] },

    // Webpack Config at ./webpack.test.js
    webpack: testWebpackConfig,

    coverageReporter: {
      type: 'in-memory'
    },

    remapCoverageReporter: {
      'text-summary': null,
      json: './coverage/coverage.json',
      html: './coverage/html'
    },

    // Webpack please don't spam the console when running in karma!
    webpackMiddleware: {
      // webpack-dev-middleware configuration
      // i.e.
      noInfo: true,
      // and use stats to turn off verbose output
      stats: {
        // options i.e.
        chunks: false
      }
    },

    /*
     * test results reporter to use
     *
     * possible values: 'dots', 'progress'
     * available reporters: https://npmjs.org/browse/keyword/karma-reporter
     */
    reporters: ['mocha', 'coverage', 'remap-coverage'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    /*
     * level of logging
     * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
     */
    logLevel: config.LOG_WARN,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    /*
     * start these browsers
     * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
     */
    browsers: [
      //'Chrome'
	  'PhantomJS'
    ],

    customLaunchers: {
      ChromeTravisCi: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    /*
     * Continuous Integration mode
     * if true, Karma captures browsers, runs the tests and exits
     */
    singleRun: false

	captureTimeout: 60000,
	browserDisconnectTimeout: 2000,
	browserDisconnectTolerance: 0,
	browserNoActivityTimeout: 10000
  });

  if (process.env.TRAVIS) {
    configuration.browsers = [
      'ChromeTravisCi'
    ];
  }

  //config.set(configuration);
};
<|endoftext|>


<commit_before>/*!
    Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
    Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
    Created By: dan@reciprocitylabs.com
    Maintained By: dan@reciprocitylabs.com
*/

(function(can) {

  can.Model.Cacheable("CMS.Models.TaskGroup", {
    root_object: "task_group",
    root_collection: "task_groups",
    category: "workflow",
    findAll: "GET /api/task_groups",
    findOne: "GET /api/task_groups/{id}",
    create: "POST /api/task_groups",
    update: "PUT /api/task_groups/{id}",
    destroy: "DELETE /api/task_groups/{id}",

    mixins: ["contactable"],
    attributes: {
      workflow: "CMS.Models.Workflow.stub",
      task_group_tasks: "CMS.Models.TaskGroupTask.stubs",
      tasks: "CMS.Models.Task.stubs",
      task_group_objects: "CMS.Models.TaskGroupObject.stubs",
      objects: "CMS.Models.get_stubs",
      modified_by: "CMS.Models.Person.stub",
      context: "CMS.Models.Context.stub",
      end_date: "date",
    },

    tree_view_options: {
      sort_property: 'sort_index',
      header_view: GGRC.mustache_path + "/task_groups/tree_header.mustache",
      footer_view: GGRC.mustache_path + "/task_groups/tree_footer.mustache",
      add_item_view: GGRC.mustache_path + "/task_groups/tree_add_item.mustache"
    },

    init: function() {
      var that = this;
      this._super && this._super.apply(this, arguments);
      this.validateNonBlank("title");
      this.validateNonBlank("contact");
      this.validateContact(["_transient.contact", "contact"]);

      // Refresh workflow people:
      this.bind("created", function(ev, instance) {
        if (instance instanceof that) {
          instance.refresh_all_force('workflow', 'context');
        }
      });
      this.bind("updated", function(ev, instance) {
        if (instance instanceof that) {
          instance.refresh_all_force('workflow', 'context');
        }
      });
      this.bind("destroyed", function(ev, inst) {
        if(inst instanceof that) {
          can.each(inst.task_group_tasks, function(tgt) {
            if (!tgt) {
              return;
            }
            tgt = tgt.reify();
            can.trigger(tgt, "destroyed");
            can.trigger(tgt.constructor, "destroyed", tgt);
          });
        }
      });
    }
  }, {});

  can.Model.Cacheable("CMS.Models.TaskGroupTask", {
    root_object: "task_group_task",
    root_collection: "task_group_tasks",
    findAll: "GET /api/task_group_tasks",
    create: "POST /api/task_group_tasks",
    update: "PUT /api/task_group_tasks/{id}",
    destroy: "DELETE /api/task_group_tasks/{id}",

    mixins : ["contactable"],
    attributes: {
      context: "CMS.Models.Context.stub",
      modified_by: "CMS.Models.Person.stub",
      task_group: "CMS.Models.TaskGroup.stub",
    },

    init: function() {
      var that = this;
      this._super && this._super.apply(this, arguments);
      this.validateNonBlank("title");
      this.validateNonBlank("contact");
      this.validateContact(["_transient.contact", "contact"]);

      this.validate('start_date end_date'.split(' '), function (newVal, prop) {
        var that = this,
         workflow = GGRC.page_instance(),
         dates_are_valid = true;

        if (!(workflow instanceof CMS.Models.Workflow))
          return;

        // Handle cases of a workflow with start and end dates
        if (workflow.frequency === 'one_time') {
            dates_are_valid =
                 that.start_date && 0 < that.start_date.length
              && that.end_date && 0 < that.end_date.length;
        }

        if (!dates_are_valid) {
          return "Start and/or end date is invalid";
        }
      });

      this.bind("created", function(ev, instance) {
        if (instance instanceof that) {
          if (instance.task_group.reify().selfLink) {
            instance.task_group.reify().refresh();
            instance._refresh_workflow_people();
          }
        }
      });

      this.bind("updated", function(ev, instance) {
        if (instance instanceof that) {
          instance._refresh_workflow_people();
        }
      });

      this.bind("destroyed", function(ev, instance) {
        if (instance instanceof that) {
          if (instance.task_group && instance.task_group.reify().selfLink) {
            instance.task_group.reify().refresh();
            instance._refresh_workflow_people();
          }
        }
      });
    }
  }, {
    init : function() {
      this._super && this._super.apply(this, arguments);
      this.bind('task_group', function (ev, newTask) {
        if (!newTask) {
          return;
        }
        newTask = newTask.reify();
        var task,
            taskGroup = newTask.get_mapping('task_group_tasks').slice(0);

        do {
          task = taskGroup.splice(-1)[0];
          task = task && task.instance;
        } while (task === this);

        if (!task) {
          return;
        }
        can.each('relative_start_day relative_start_month relative_end_day relative_end_month start_date end_date'.split(' '),
          function (prop) {
            if (task[prop] && !this[prop]) {
              this.attr(prop, task.attr(prop) instanceof Date ? new Date(task[prop]) : task[prop]);
            }
        }, this);
      });
    },

    _refresh_workflow_people: function() {
      //  TaskGroupTask assignment may add mappings and role assignments in
      //  the backend, so ensure these changes are reflected.
      var task_group, workflow;
      task_group = this.task_group.reify();
      if (task_group.selfLink) {
        workflow = task_group.workflow.reify();
        return workflow.refresh().then(function(workflow) {
          return workflow.context.reify().refresh();
        });
      }
    },

    response_options_csv: can.compute(function(val) {
      if(val != null) {
        this.attr("response_options", $.map(val.split(","), $.proxy("".trim.call, "".trim)));
      } else {
        return (this.attr("response_options") || []).join(", ");
      }
    })
  });

})(window.can);
<commit_msg>Refresh workflow on TG delete<commit_after>/*!
    Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
    Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
    Created By: dan@reciprocitylabs.com
    Maintained By: dan@reciprocitylabs.com
*/

(function(can) {

  can.Model.Cacheable("CMS.Models.TaskGroup", {
    root_object: "task_group",
    root_collection: "task_groups",
    category: "workflow",
    findAll: "GET /api/task_groups",
    findOne: "GET /api/task_groups/{id}",
    create: "POST /api/task_groups",
    update: "PUT /api/task_groups/{id}",
    destroy: "DELETE /api/task_groups/{id}",

    mixins: ["contactable"],
    attributes: {
      workflow: "CMS.Models.Workflow.stub",
      task_group_tasks: "CMS.Models.TaskGroupTask.stubs",
      tasks: "CMS.Models.Task.stubs",
      task_group_objects: "CMS.Models.TaskGroupObject.stubs",
      objects: "CMS.Models.get_stubs",
      modified_by: "CMS.Models.Person.stub",
      context: "CMS.Models.Context.stub",
      end_date: "date",
    },

    tree_view_options: {
      sort_property: 'sort_index',
      header_view: GGRC.mustache_path + "/task_groups/tree_header.mustache",
      footer_view: GGRC.mustache_path + "/task_groups/tree_footer.mustache",
      add_item_view: GGRC.mustache_path + "/task_groups/tree_add_item.mustache"
    },

    init: function() {
      var that = this;
      this._super && this._super.apply(this, arguments);
      this.validateNonBlank("title");
      this.validateNonBlank("contact");
      this.validateContact(["_transient.contact", "contact"]);

      // Refresh workflow people:
      this.bind("created", function(ev, instance) {
        if (instance instanceof that) {
          instance.refresh_all_force('workflow', 'context');
        }
      });
      this.bind("updated", function(ev, instance) {
        if (instance instanceof that) {
          instance.refresh_all_force('workflow', 'context');
        }
      });
      this.bind("destroyed", function(ev, inst) {
        if(inst instanceof that) {
          can.each(inst.task_group_tasks, function(tgt) {
            if (!tgt) {
              return;
            }
            tgt = tgt.reify();
            can.trigger(tgt, "destroyed");
            can.trigger(tgt.constructor, "destroyed", tgt);
          });
          inst.refresh_all_force('workflow', 'context');
        }
      });
    }
  }, {});

  can.Model.Cacheable("CMS.Models.TaskGroupTask", {
    root_object: "task_group_task",
    root_collection: "task_group_tasks",
    findAll: "GET /api/task_group_tasks",
    create: "POST /api/task_group_tasks",
    update: "PUT /api/task_group_tasks/{id}",
    destroy: "DELETE /api/task_group_tasks/{id}",

    mixins : ["contactable"],
    attributes: {
      context: "CMS.Models.Context.stub",
      modified_by: "CMS.Models.Person.stub",
      task_group: "CMS.Models.TaskGroup.stub",
    },

    init: function() {
      var that = this;
      this._super && this._super.apply(this, arguments);
      this.validateNonBlank("title");
      this.validateNonBlank("contact");
      this.validateContact(["_transient.contact", "contact"]);

      this.validate('start_date end_date'.split(' '), function (newVal, prop) {
        var that = this,
         workflow = GGRC.page_instance(),
         dates_are_valid = true;

        if (!(workflow instanceof CMS.Models.Workflow))
          return;

        // Handle cases of a workflow with start and end dates
        if (workflow.frequency === 'one_time') {
            dates_are_valid =
                 that.start_date && 0 < that.start_date.length
              && that.end_date && 0 < that.end_date.length;
        }

        if (!dates_are_valid) {
          return "Start and/or end date is invalid";
        }
      });

      this.bind("created", function(ev, instance) {
        if (instance instanceof that) {
          if (instance.task_group.reify().selfLink) {
            instance.task_group.reify().refresh();
            instance._refresh_workflow_people();
          }
        }
      });

      this.bind("updated", function(ev, instance) {
        if (instance instanceof that) {
          instance._refresh_workflow_people();
        }
      });

      this.bind("destroyed", function(ev, instance) {
        if (instance instanceof that) {
          if (instance.task_group && instance.task_group.reify().selfLink) {
            instance.task_group.reify().refresh();
            instance._refresh_workflow_people();
          }
        }
      });
    }
  }, {
    init : function() {
      this._super && this._super.apply(this, arguments);
      this.bind('task_group', function (ev, newTask) {
        if (!newTask) {
          return;
        }
        newTask = newTask.reify();
        var task,
            taskGroup = newTask.get_mapping('task_group_tasks').slice(0);

        do {
          task = taskGroup.splice(-1)[0];
          task = task && task.instance;
        } while (task === this);

        if (!task) {
          return;
        }
        can.each('relative_start_day relative_start_month relative_end_day relative_end_month start_date end_date'.split(' '),
          function (prop) {
            if (task[prop] && !this[prop]) {
              this.attr(prop, task.attr(prop) instanceof Date ? new Date(task[prop]) : task[prop]);
            }
        }, this);
      });
    },

    _refresh_workflow_people: function() {
      //  TaskGroupTask assignment may add mappings and role assignments in
      //  the backend, so ensure these changes are reflected.
      var task_group, workflow;
      task_group = this.task_group.reify();
      if (task_group.selfLink) {
        workflow = task_group.workflow.reify();
        return workflow.refresh().then(function(workflow) {
          return workflow.context.reify().refresh();
        });
      }
    },

    response_options_csv: can.compute(function(val) {
      if(val != null) {
        this.attr("response_options", $.map(val.split(","), $.proxy("".trim.call, "".trim)));
      } else {
        return (this.attr("response_options") || []).join(", ");
      }
    })
  });

})(window.can);
<|endoftext|>


<commit_before>var sys = require('sys');
var posix = require('posix');
var path = require('path');

var HTTP301MovedPermanently = require('bomberjs/lib/http_responses').HTTP301MovedPermanently;

exports.index = function(request, response) {
  return "index action";
};
exports.show = function(request, response) {
  if( request.params.id == 2 ) {
    return new HTTP301MovedPermanently('http://google.com');
  }
  else {
    return "show action";
  }
};

// can be accessed at /simple/lorem
exports.lorem = function(request, response) {
  // posix.cat returns a Node promise. Which at this time isn't chainable
  // so this example is pretty simple.  But once we can chain, I'll show
  // how to manipulate the result as you move through the chain.

  var filename = path.join(path.dirname(__filename),'../resources/lorem-ipsum.txt');
  return posix.cat(filename);
};
<commit_msg>Use HTML in example project and fix linking to wrong file<commit_after>var sys = require('sys');
var posix = require('posix');
var path = require('path');

var HTTP301MovedPermanently = require('bomberjs/lib/http_responses').HTTP301MovedPermanently;

function htmlHead () {
    return '<title>Bomber.js example app</title>';
}
function htmlFoot () {
    return '';
}

exports.index = function(request, response) {
  var html = htmlHead();
  html += "
index action

See <tt>routes.js</tt> for more.
";
  html += "
Other actions include:
";
  html += "

section/1000
";
  html += "
section/2 (special case)
";
  html += "
lorem
";
  html += "
";
  html += htmlFoot();
  return html;
};
exports.show = function(request, response) {
  if( request.params.id == 2 ) {
    return new HTTP301MovedPermanently('http://google.com');
  }
  else {
    return htmlHead() + "show action" + htmlFoot();
  }
};

// can be accessed at /simple/lorem
exports.lorem = function(request, response) {
  // posix.cat returns a Node promise. Which at this time isn't chainable
  // so this example is pretty simple.  But once we can chain, I'll show
  // how to manipulate the result as you move through the chain.

  var filename = path.join(path.dirname(__filename),'../resources/text.txt');
  return posix.cat(filename);
};
<|endoftext|>


<commit_before>import cookies from 'cookies-js'
import invariant from 'invariant'
import debug from 'debug'
import _ from 'lodash'

const log = debug('bshed:client:request')

/**
 * RequestPlugin
 * Adds executeRequest(fn, params) to action context
 */
export default function RequestPlugin () {
  return {
    name: 'RequestPlugin',
    plugContext
  }

  function plugContext (contextOptions={}) {
    const request = _.defaults(contextOptions, {
      fetch: global.fetch,
      rootUrl: '',
      cookie: ''
    })

    return {
      plugActionContext
    }

    function plugActionContext (actionContext) {
      actionContext.request = request
      actionContext.executeRequest = executeRequestFactory(request)
    }
  }
}

/**
 * Factory for creating executeRequest
 * @param {Object} config
 * @param {Fetch} config.fetch Fetch
 * @return {Function} executeRequest Request creator
 */
function executeRequestFactory ({fetch, rootUrl, cookie}) {
  // node-fetch exposes Headers on the fetch object
  // whatwg-fetch polyfills Headers on the window
  const Headers = fetch.Headers || global.Headers

  /**
   * Execute a request with payload
   * @param {Function} request Request to execute
   * @param {Object} payload Request payload
   * @returns {Promise}
   */
  return function executeRequest (fn, payload={}) {
    invariant(typeof fn === 'function', 'executeRequest requires a function')
    log(`Executing request ${fn.displayName || fn.name} with payload`, payload)

    return new Promise((resolve, reject) => {
      fn(requestCreator, payload).then(resolve, reject)
    })
  }

  function requestCreator (url='', options={}) {
    if (url.charAt(0) === '/') {
      url = `${rootUrl}${url}`
    }

    _.defaults(options, {
      credentials: 'include'
    })

    options.headers = new Headers(options.headers || {})
    if (!options.headers.has('cookie') && cookie) {
      options.headers.set('cookie', cookie)
    }
    if (!options.headers.has('x-xsrf-token') && shouldSetXsrfToken(options.method)) {
      options.headers.set('x-xsrf-token', cookies.get('XSRF-TOKEN'))
    }

    return fetch(url, options)
      // .then(status)
      // .then(parseJsonBody)
  }
}

/**
 * Check if X-XSRF-TOKEN header should be set
 * @param {Object} options Request creator options
 * @returns {boolean} if it should be set
 */
function shouldSetXsrfToken (method='GET') {
  return ['GET', 'HEAD', 'OPTIONS'].indexOf(method.toUpperCase()) === -1
}

/**
 * Call response.json and add parsedBody
 * @param {Response} response Fetch response
 * @return {Promise}
 */
// function parseJsonBody (res) {
//   return res.json().then(parsedBody => {
//     res.parsedBody = parsedBody
//     return res
//   })
// }

/**
 * Resolve when status code is 2XX, otherwise reject
 * @param {Response} response Fetch response
 * @return {Promise}
 */
// function status (res) {
//   return res.status >= 200 && res.status < 300
//     ? Promise.resolve(res)
//     : Promise.reject(res)
// }
<commit_msg>Avoid pulling in all of lodash<commit_after>import debug from 'debug'
import cookies from 'cookies-js'
import invariant from 'invariant'
import defaults from 'lodash/object/defaults'

const log = debug('bshed:client:request')

/**
 * RequestPlugin
 * Adds executeRequest(fn, params) to action context
 */
export default function RequestPlugin () {
  return {
    name: 'RequestPlugin',
    plugContext
  }

  function plugContext (contextOptions={}) {
    const request = defaults(contextOptions, {
      fetch: global.fetch,
      rootUrl: '',
      cookie: ''
    })

    return {
      plugActionContext
    }

    function plugActionContext (actionContext) {
      actionContext.request = request
      actionContext.executeRequest = executeRequestFactory(request)
    }
  }
}

/**
 * Factory for creating executeRequest
 * @param {Object} config
 * @param {Fetch} config.fetch Fetch
 * @return {Function} executeRequest Request creator
 */
function executeRequestFactory ({fetch, rootUrl, cookie}) {
  // node-fetch exposes Headers on the fetch object
  // whatwg-fetch polyfills Headers on the window
  const Headers = fetch.Headers || global.Headers

  /**
   * Execute a request with payload
   * @param {Function} request Request to execute
   * @param {Object} payload Request payload
   * @returns {Promise}
   */
  return function executeRequest (fn, payload={}) {
    invariant(typeof fn === 'function', 'executeRequest requires a function')
    log(`Executing request ${fn.displayName || fn.name} with payload`, payload)

    return new Promise((resolve, reject) => {
      fn(requestCreator, payload).then(resolve, reject)
    })
  }

  function requestCreator (url='', options={}) {
    if (url.charAt(0) === '/') {
      url = `${rootUrl}${url}`
    }

    defaults(options, { credentials: 'include' })

    options.headers = new Headers(options.headers || {})
    if (!options.headers.has('cookie') && cookie) {
      options.headers.set('cookie', cookie)
    }
    if (!options.headers.has('x-xsrf-token') && shouldSetXsrfToken(options.method)) {
      options.headers.set('x-xsrf-token', cookies.get('XSRF-TOKEN'))
    }

    return fetch(url, options)
      // .then(status)
      // .then(parseJsonBody)
  }
}

/**
 * Check if X-XSRF-TOKEN header should be set
 * @param {Object} options Request creator options
 * @returns {boolean} if it should be set
 */
function shouldSetXsrfToken (method='GET') {
  return ['GET', 'HEAD', 'OPTIONS'].indexOf(method.toUpperCase()) === -1
}

/**
 * Call response.json and add parsedBody
 * @param {Response} response Fetch response
 * @return {Promise}
 */
// function parseJsonBody (res) {
//   return res.json().then(parsedBody => {
//     res.parsedBody = parsedBody
//     return res
//   })
// }

/**
 * Resolve when status code is 2XX, otherwise reject
 * @param {Response} response Fetch response
 * @return {Promise}
 */
// function status (res) {
//   return res.status >= 200 && res.status < 300
//     ? Promise.resolve(res)
//     : Promise.reject(res)
// }
<|endoftext|>


<commit_before>/*
 * Copyright 2017-present, Converse.AI
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

module.exports = class OAuth2HandleCodePayload extends require('../Payload') {
  constructor(oauth2Token, redirect) {
    super();
    this.oauth2Token = oauth2Token || {};
    this.redirect = redirect || {};
  }

  /**
  * Sets the access token for the OAuth2 payload.
  * @param {String} accessToken The OAuth2 access token for the response.
  * @public
  */
  setAccessToken(accessToken) {
    this.oauth2Token.accessToken = accessToken;
  }

  /**
  * Sets the token type for the OAuth2 payload.
  * @param {String} tokenType The OAuth2 token type for the response.
  * @public
  */
  setTokenType(tokenType) {
    this.oauth2Token.tokenType = tokenType;
  }

  /**
  * Sets the refresh token for the OAuth2 payload.
  * @param {String} refreshToken The OAuth2 refresh token for the response.
  * @public
  */
  setRefreshToken(refreshToken) {
    this.oauth2Token.refreshToken = refreshToken;
  }

  /**
  * Sets the expiry time for the OAuth2 payload.
  * @param {String} expiresIn The OAuth2 expiry time for the response.
  * @public
  */
  setExpiresIn(expiresIn) {
    this.oauth2Token.expiresIn = expiresIn;
  }

  /**
  * Sets the expiry time for the OAuth2 payload.
  * @param {String} expiresIn The OAuth2 expiry time for the response.
  * @public
  */
  setGrantType(grantType) {
    this.oauth2Token.grantType = grantType;
  }

  /**
  * Sets the metadata for the OAuth2 payload.
  * @param {Object} [metadata] A Key/Value map of metadata for the OAuth2 response.
  * @public
  */
  setMetadata(metadata) {
    this.oauth2Token.metadata = metadata;
  }

  /**
  * Sets the redirect URL for the OAuth2 payload.
  * @param {String} [url] An OAuth2 redirect URL for the response.
  * @public
  */
  setRedirectURL(url) {
    this.redirect.redirectTo = url;
  }

  /**
  * Sets the success message for the OAuth2 payload.
  * @param {String} [message] An OAuth2 success message for the response.
  * @public
  */
  setMessage(message) {
    this.redirect.message = message;
  }
}
<commit_msg>changing oauth2 setters to use oauth2 spec json values.<commit_after>/*
 * Copyright 2017-present, Converse.AI
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

module.exports = class OAuth2HandleCodePayload extends require('../Payload') {
  constructor(oauth2Token, redirect) {
    super();
    this.oauth2Token = oauth2Token || {};
    this.redirect = redirect || {};
  }

  /**
  * Sets the access token for the OAuth2 payload.
  * @param {String} access_token The OAuth2 access token for the response.
  * @public
  */
  setAccessToken(access_token) {
    this.oauth2Token.access_token = access_token;
  }

  /**
  * Sets the token type for the OAuth2 payload.
  * @param {String} token_type The OAuth2 token type for the response.
  * @public
  */
  setTokenType(token_type) {
    this.oauth2Token.token_type = token_type;
  }

  /**
  * Sets the refresh token for the OAuth2 payload.
  * @param {String} refresh_token The OAuth2 refresh token for the response.
  * @public
  */
  setRefreshToken(refresh_token) {
    this.oauth2Token.refresh_token = refresh_token;
  }

  /**
  * Sets the expiry time for the OAuth2 payload.
  * @param {String} expires_in The OAuth2 expiry time for the response.
  * @public
  */
  setExpiresIn(expires_in) {
    this.oauth2Token.expires_in = expires_in;
  }

  /**
  * Sets the expiry time for the OAuth2 payload.
  * @param {String} grant_type The OAuth2 expiry time for the response.
  * @public
  */
  setGrantType(grant_type) {
    this.oauth2Token.grant_type = grant_type;
  }

  /**
  * Sets the metadata for the OAuth2 payload.
  * @param {Object} [metadata] A Key/Value map of metadata for the OAuth2 response.
  * @public
  */
  setMetadata(metadata) {
    this.oauth2Token.metadata = metadata;
  }

  /**
  * Sets the redirect URL for the OAuth2 payload.
  * @param {String} [url] An OAuth2 redirect URL for the response.
  * @public
  */
  setRedirectURL(url) {
    this.redirect.redirectTo = url;
  }

  /**
  * Sets the success message for the OAuth2 payload.
  * @param {String} [message] An OAuth2 success message for the response.
  * @public
  */
  setMessage(message) {
    this.redirect.message = message;
  }
}
<|endoftext|>