<commit_before>import React, {Component} from 'react'
import NavbarContainer from '../containers/NavbarContainer'

export default class Header extends Component {
  render () {
    return (

              Alchemetsy

Sign In

Register

My Cart

        <NavbarContainer />

      {this.props.children}

    )
  }
}
<commit_msg>refactor(header): removes use of children prop<commit_after>import React, {Component} from 'react'
import NavbarContainer from '../containers/NavbarContainer'

export default class Header extends Component {
  render () {
    return (

              Alchemetsy

Sign In

Register

My Cart

        <NavbarContainer />

    )
  }
}
<|endoftext|>


<commit_before>import AppBar from 'material-ui/AppBar';
import Avatar from 'material-ui/Avatar';
import CircularProgress from 'material-ui/CircularProgress';
import Drawer from 'material-ui/Drawer';
import FlatButton from 'material-ui/FlatButton';
import IconButton from 'material-ui/IconButton';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import React, {Component, PropTypes} from 'react';
import SettingsIcon from 'material-ui/svg-icons/action/settings';
import Snackbar from 'material-ui/Snackbar';
import c from 'classnames';
import injectTapEventPlugin from 'react-tap-event-plugin';
import {connect} from 'react-redux';

import PageImportCsv from './../../containers/PageImportCsv/PageImportCsv';
import ipc from './../../helpers/ipc';
import injectF from './../../helpers/injectF';
import injectPush from './../../helpers/injectPush';
import muiTheme from './../../constants/muiTheme';
import {login, logout} from './../../redux/modules/auth';
import {setDrawerOpen, setSnackBarParams} from './../../redux/modules/ui';
import {setIntl} from './../../redux/modules/main';

const styles = require('./App.scss');

injectTapEventPlugin();

@connect(({auth, main, ui}) => ({
  appLocale: main.get('appLocale'),
  auth: auth.get('auth'),
  isDrawerOpen: ui.get('isDrawerOpen'),
  isLoadingAuth: auth.get('isLoadingAuth'),
  isSnackBarOpen: ui.get('isSnackBarOpen'),
  snackBarMessage: ui.get('snackBarMessage')
}), {setDrawerOpen, setIntl, setSnackBarParams, login, logout})
@injectF
@injectPush
export default class App extends Component {

  static propTypes = {
    appLocale: PropTypes.string.isRequired,
    auth: PropTypes.object,
    children: PropTypes.object.isRequired,
    f: PropTypes.func.isRequired,
    isDrawerOpen: PropTypes.bool.isRequired,
    isLoadingAuth: PropTypes.bool.isRequired,
    isSnackBarOpen: PropTypes.bool.isRequired,
    login: PropTypes.func.isRequired,
    logout: PropTypes.func.isRequired,
    push: PropTypes.func.isRequired,
    setDrawerOpen: PropTypes.func.isRequired,
    setIntl: PropTypes.func.isRequired,
    setSnackBarParams: PropTypes.func.isRequired,
    snackBarMessage: PropTypes.string.isRequired,
  };

  handleCsvProcessingDone = (event, data) => {
    const {setSnackBarParams, f} = this.props;
    setSnackBarParams(true, f('csv-imported-done', {filename: data.filename}));
  };

  componentDidMount() {
    ipc.on('csv-processing-done', this.handleCsvProcessingDone);
  }

  componentWillUnmount() {
    ipc.off('csv-pocessing-done', this.handleCsvProcessingDone);
  }

  renderIconElementRight() {
    const {auth, isLoadingAuth, login, logout, f} = this.props;

    if (isLoadingAuth) {
      return <CircularProgress mode="indeterminate" color="white" style={{marginTop: '16px', marginRight: '12px'}} size={30} />;
    }

    if (auth) {

      const {profile} = auth;
      const iconButtonStyle = {
        width: 'initial',
        height: 'initial',
        border: 0,
        paddingTop: '12px',
        paddingBottom: '12px',
        marginRight: 0,
        marginTop: 0
      };

      const iconButton = (
        <IconButton style={iconButtonStyle} disableTouchRipple>
          <Avatar src={profile.image.url} size={30} />
        </IconButton>
      );

      return (
        <IconMenu
          iconButtonElement={iconButton}
          targetOrigin={{horizontal: 'right', vertical: 'top'}}
          anchorOrigin={{horizontal: 'right', vertical: 'bottom'}}>
          <MenuItem primaryText="Account" onTouchTap={this.goToAccountPage} />
          <MenuItem primaryText="Sign out" onTouchTap={logout} />
        </IconMenu>
      );
    }
    return <FlatButton style={{marginTop: '9px', color: '#fff'}} onClick={login} label={f('login')} />;
  }

  handleDrawerChange = (open) => this.props.setDrawerOpen(open);

  handleHamburgerTouchTap = () => this.props.setDrawerOpen(true);

  handleMenuItemTouchTap = (route) => {
    return () => {
      this.props.setDrawerOpen(false);
      this.props.push(route);
    };
  };

  handleSnackBarRequestClose = () => this.props.setSnackBarParams(false);

  render() {

    const {children, isDrawerOpen, f, isSnackBarOpen, snackBarMessage, appLocale} = this.props;

    return (
      <MuiThemeProvider muiTheme={muiTheme}>

         <AppBar title={f('garchen')} iconElementRight={this.renderIconElementRight()}
            titleStyle={{cusror: 'pointer'}} iconStyleRight={{marginTop: 0, marginRight: 0, marginLeft: 0}}
            onLeftIconButtonTouchTap={this.handleHamburgerTouchTap} onTitleTouchTap={this.handleTitleTouchTap} />

{children}

          <Drawer docked={false} open={isDrawerOpen} onRequestChange={this.handleDrawerChange}>
            <MenuItem primaryText={f('folders')} onTouchTap={this.handleMenuItemTouchTap('/')} />
            <MenuItem primaryText={f('about')} onTouchTap={this.handleMenuItemTouchTap('/about')} />
            <MenuItem primaryText={f('import-csv-file')} onTouchTap={this.handleMenuItemTouchTap('/import-csv')} />

            <MenuItem primaryText={f('settings')} leftIcon={(<SettingsIcon />)} onTouchTap={this.handleMenuItemTouchTap('/settings')} />
          </Drawer>
          <Snackbar open={isSnackBarOpen} message={snackBarMessage} autoHideDuration={4000} onRequestClose={this.handleSnackBarRequestClose} />

      </MuiThemeProvider>
    );
  }
}
<commit_msg>remove un-used import<commit_after>import AppBar from 'material-ui/AppBar';
import Avatar from 'material-ui/Avatar';
import CircularProgress from 'material-ui/CircularProgress';
import Drawer from 'material-ui/Drawer';
import FlatButton from 'material-ui/FlatButton';
import IconButton from 'material-ui/IconButton';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import React, {Component, PropTypes} from 'react';
import SettingsIcon from 'material-ui/svg-icons/action/settings';
import Snackbar from 'material-ui/Snackbar';
import c from 'classnames';
import injectTapEventPlugin from 'react-tap-event-plugin';
import {connect} from 'react-redux';

import ipc from './../../helpers/ipc';
import injectF from './../../helpers/injectF';
import injectPush from './../../helpers/injectPush';
import muiTheme from './../../constants/muiTheme';
import {login, logout} from './../../redux/modules/auth';
import {setDrawerOpen, setSnackBarParams} from './../../redux/modules/ui';
import {setIntl} from './../../redux/modules/main';

const styles = require('./App.scss');

injectTapEventPlugin();

@connect(({auth, main, ui}) => ({
  appLocale: main.get('appLocale'),
  auth: auth.get('auth'),
  isDrawerOpen: ui.get('isDrawerOpen'),
  isLoadingAuth: auth.get('isLoadingAuth'),
  isSnackBarOpen: ui.get('isSnackBarOpen'),
  snackBarMessage: ui.get('snackBarMessage')
}), {setDrawerOpen, setIntl, setSnackBarParams, login, logout})
@injectF
@injectPush
export default class App extends Component {

  static propTypes = {
    appLocale: PropTypes.string.isRequired,
    auth: PropTypes.object,
    children: PropTypes.object.isRequired,
    f: PropTypes.func.isRequired,
    isDrawerOpen: PropTypes.bool.isRequired,
    isLoadingAuth: PropTypes.bool.isRequired,
    isSnackBarOpen: PropTypes.bool.isRequired,
    login: PropTypes.func.isRequired,
    logout: PropTypes.func.isRequired,
    push: PropTypes.func.isRequired,
    setDrawerOpen: PropTypes.func.isRequired,
    setIntl: PropTypes.func.isRequired,
    setSnackBarParams: PropTypes.func.isRequired,
    snackBarMessage: PropTypes.string.isRequired,
  };

  handleCsvProcessingDone = (event, data) => {
    const {setSnackBarParams, f} = this.props;
    setSnackBarParams(true, f('csv-imported-done', {filename: data.filename}));
  };

  componentDidMount() {
    ipc.on('csv-processing-done', this.handleCsvProcessingDone);
  }

  componentWillUnmount() {
    ipc.off('csv-pocessing-done', this.handleCsvProcessingDone);
  }

  renderIconElementRight() {
    const {auth, isLoadingAuth, login, logout, f} = this.props;

    if (isLoadingAuth) {
      return <CircularProgress mode="indeterminate" color="white" style={{marginTop: '16px', marginRight: '12px'}} size={30} />;
    }

    if (auth) {

      const {profile} = auth;
      const iconButtonStyle = {
        width: 'initial',
        height: 'initial',
        border: 0,
        paddingTop: '12px',
        paddingBottom: '12px',
        marginRight: 0,
        marginTop: 0
      };

      const iconButton = (
        <IconButton style={iconButtonStyle} disableTouchRipple>
          <Avatar src={profile.image.url} size={30} />
        </IconButton>
      );

      return (
        <IconMenu
          iconButtonElement={iconButton}
          targetOrigin={{horizontal: 'right', vertical: 'top'}}
          anchorOrigin={{horizontal: 'right', vertical: 'bottom'}}>
          <MenuItem primaryText="Account" onTouchTap={this.goToAccountPage} />
          <MenuItem primaryText="Sign out" onTouchTap={logout} />
        </IconMenu>
      );
    }
    return <FlatButton style={{marginTop: '9px', color: '#fff'}} onClick={login} label={f('login')} />;
  }

  handleDrawerChange = (open) => this.props.setDrawerOpen(open);

  handleHamburgerTouchTap = () => this.props.setDrawerOpen(true);

  handleMenuItemTouchTap = (route) => {
    return () => {
      this.props.setDrawerOpen(false);
      this.props.push(route);
    };
  };

  handleSnackBarRequestClose = () => this.props.setSnackBarParams(false);

  render() {

    const {children, isDrawerOpen, f, isSnackBarOpen, snackBarMessage, appLocale} = this.props;

    return (
      <MuiThemeProvider muiTheme={muiTheme}>

         <AppBar title={f('garchen')} iconElementRight={this.renderIconElementRight()}
            titleStyle={{cusror: 'pointer'}} iconStyleRight={{marginTop: 0, marginRight: 0, marginLeft: 0}}
            onLeftIconButtonTouchTap={this.handleHamburgerTouchTap} onTitleTouchTap={this.handleTitleTouchTap} />

{children}

          <Drawer docked={false} open={isDrawerOpen} onRequestChange={this.handleDrawerChange}>
            <MenuItem primaryText={f('folders')} onTouchTap={this.handleMenuItemTouchTap('/')} />
            <MenuItem primaryText={f('about')} onTouchTap={this.handleMenuItemTouchTap('/about')} />
            <MenuItem primaryText={f('import-csv-file')} onTouchTap={this.handleMenuItemTouchTap('/import-csv')} />

            <MenuItem primaryText={f('settings')} leftIcon={(<SettingsIcon />)} onTouchTap={this.handleMenuItemTouchTap('/settings')} />
          </Drawer>
          <Snackbar open={isSnackBarOpen} message={snackBarMessage} autoHideDuration={4000} onRequestClose={this.handleSnackBarRequestClose} />

      </MuiThemeProvider>
    );
  }
}
<|endoftext|>


<commit_before>var watch = require('node-watch'),
    fs = require('fs-extra');

function initConfig(config) {
    config.declarations = config.declarations !== undefined ? config.declarations : false;
    config.configFile = config.configFile ? config.configFile : 'package.json';
    config.tempFolder = config.tempFolder ? config.tempFolder : 'dist';
    config.browserify = config.browserify !== undefined ? config.browserify : true;
    config.rootFile = config.rootFile ? config.rootFile : 'boot';
    config.options = config.options ? config.options : {};
    config.files = config.files ? config.files : [];
    config.dest = config.dest ? config.dest : 'script.js';
}

function createCommand(config) {
    var cmd = 'tsc';

    if(config.declarations)
        cmd += ' --declaration';

    var keys = Object.keys(config.options);
    for(var k in keys)
    {
        cmd += ' --' + keys[k];
        var value = config.options[keys[k]];
        if(value !== null)
            cmd += ' "' + value.toString() + '"';
    }

    if(config.files.length > 0)
        for(var k in config.files)
            cmd += ' "' + config.files[k] + '"';
    else
        cmd += ' --p "' + config.configFile + '"';

    return cmd;
}

module.exports = function(config) {
    return {
        prodRun: function(config) {
            initConfig(config);

            config.exec(createCommand(config), () => {
                if(!config.browserify)
                    return;

                fs.ensureDir(config.tempFolder)

                var srcFile = config.tempFolder + '/' + config.rootFile + '.js';
                console.log(' [ ] ' + config.dest + ' updating from ' + srcFile);
                config.exec('browserify -s main ' + srcFile + ' -o ' + config.dest, () => {
                    console.log(' [o] ' + config.dest + ' updated');
                });
            });
        },
        devRun: function(config) {
            initConfig(config);

            config.exec(createCommand(config) + ' --watch');

            if(!config.browserify)
                return;

            fs.ensureDir(config.tempFolder)

            var countOut = 0;
            config.watch(config.tempFolder, { recursive: true }, function(event, filename) {
                ++countOut;
                setTimeout(function() {
                    if(--countOut > 0)
                        return;
                    var srcFile = config.tempFolder + '/' + config.rootFile + '.js';
                    console.log(' [o] ' + filename + ' updated');
                    console.log(' [ ] compiling ' + srcFile + ' to ' + config.dest);
                    config.exec('browserify -s main ' + srcFile + ' -o ' + config.dest, () => {
                        console.log(' [o] ' + config.dest + ' updated');
                    });
                }, 200);
            });
        },
        clean: (config) => {
            initConfig(config);
            config.rmdir(config.tempFolder);
        },
        configSample: {
            type: 'typescript',
            tempFolder: 'react/bin',
            rootFile: 'root',
            dest: 'public/react.js',
            browserify: true,
            declarations : false,
            options: {
                outDir: "..."
            },
            files: [ '...' ]
        }
    }
}<commit_msg>Added browerify as dependency<commit_after>var watch = require('node-watch'),
    fs = require('fs-extra'),
    browserify = require('browserify');

function initConfig(config) {
    config.declarations = config.declarations !== undefined ? config.declarations : false;
    config.configFile = config.configFile ? config.configFile : 'package.json';
    config.tempFolder = config.tempFolder ? config.tempFolder : 'dist';
    config.browserify = config.browserify !== undefined ? config.browserify : true;
    config.rootFile = config.rootFile ? config.rootFile : 'boot';
    config.options = config.options ? config.options : {};
    config.files = config.files ? config.files : [];
    config.dest = config.dest ? config.dest : 'script.js';
}

function createCommand(config) {
    var cmd = 'tsc';

    if(config.declarations)
        cmd += ' --declaration';

    var keys = Object.keys(config.options);
    for(var k in keys)
    {
        cmd += ' --' + keys[k];
        var value = config.options[keys[k]];
        if(value !== null)
            cmd += ' "' + value.toString() + '"';
    }

    if(config.files.length > 0)
        for(var k in config.files)
            cmd += ' "' + config.files[k] + '"';
    else
        cmd += ' --p "' + config.configFile + '"';

    return cmd;
}

function runBrowserify(src, dest, callback)
{
    if(!callback)
        callback = () => console.log(' [o] ' + dest + ' updated');

    var stream = fs.createWriteStream(dest);
    var srcStream = browserify({ standalone: 'main' }).add(src).bundle();
    srcStream.on('end', callback);
    srcStream.pipe(stream);
}

module.exports = function(config) {
    return {
        prodRun: function(config) {
            initConfig(config);

            config.exec(createCommand(config), () => {
                if(!config.browserify)
                    return;

                fs.ensureDir(config.tempFolder)

                var srcFile = config.tempFolder + '/' + config.rootFile + '.js';
                console.log(' [ ] ' + config.dest + ' updating from ' + srcFile);

                runBrowserify(srcFile, config.dest);
            });
        },
        devRun: function(config) {
            initConfig(config);

            config.exec(createCommand(config) + ' --watch');

            if(!config.browserify)
                return;

            fs.ensureDir(config.tempFolder)

            var countOut = 0;
            config.watch(config.tempFolder, { recursive: true }, function(event, filename) {
                ++countOut;
                setTimeout(function() {
                    if(--countOut > 0)
                        return;
                    var srcFile = config.tempFolder + '/' + config.rootFile + '.js';
                    console.log(' [o] ' + filename + ' updated');
                    console.log(' [ ] compiling ' + srcFile + ' to ' + config.dest);
                    runBrowserify(srcFile, config.dest);

                }, 200);
            });
        },
        clean: (config) => {
            initConfig(config);
            config.rmdir(config.tempFolder);
        },
        configSample: {
            type: 'typescript',
            tempFolder: 'react/bin',
            rootFile: 'root',
            dest: 'public/react.js',
            browserify: true,
            declarations : false,
            options: {
                outDir: "..."
            },
            files: [ '...' ]
        }
    }
}<|endoftext|>


<commit_before>import { EditorState } from 'draft-js';
import setSelection from './modifiers/setSelection';
import createDecorator from './createDecorator';
import createStore from './utils/createStore';
import blockInSelection from './utils/blockInSelection';
import defaultTheme from './style.css';

const store = createStore({});

const oneAtomicBlockIsSelected = (editorState) => {
  const selection = editorState.getSelection();
  if (selection.getAnchorKey() !== selection.getFocusKey()) {
    return false;
  }
  const content = editorState.getCurrentContent();
  const block = content.getBlockForKey(selection.getAnchorKey());
  // check for atomic block and for entity
  return block.getType() === 'atomic';
};

// TODO make sure to remove the native selection of a text when the user clicks on the block
const focusPlugin = (config = {}) => {
  const theme = config.theme ? config.theme : defaultTheme;
  let lastSelection;

  return {
    initialize: ({ getEditorState, setEditorState }) => {
      store.updateItem('getEditorState', getEditorState);
      store.updateItem('setEditorState', setEditorState);
    },
    onChange: (editorState) => {
      const selection = editorState.getSelection();
      if (lastSelection && selection.equals(lastSelection)) {
        lastSelection = editorState.getSelection();
        return editorState;
      }

      // TODO check for if an atomic block is affected that has a focus entity
      lastSelection = editorState.getSelection();
      // By forcing the selection the editor will trigger the blockRendererFn which is
      // necessary
      return EditorState.forceSelection(editorState, editorState.getSelection());
    },
    keyBindingFn(evt, { getEditorState, setEditorState }) {
      const editorState = getEditorState();
      // TODO match by entitiy instead of block type
      if (oneAtomicBlockIsSelected(editorState)) {
        // arrow left
        if (evt.keyCode === 37) {
          setSelection(store, getEditorState, setEditorState, 'up', evt);
        }
        // arrow right
        if (evt.keyCode === 39) {
          setSelection(store, getEditorState, setEditorState, 'down', evt);
        }
      }
    },
    // Wrap all block-types in block-focus decorator
    blockRendererFn: (contentBlock, { getEditorState, setEditorState, getReadOnly }) => {
      if (contentBlock.getType() !== 'atomic') {
        return undefined;
      }

      const unsetFocus = (direction, event) => {
        if (getReadOnly()) return;

        if (direction) {
          setSelection(store, getEditorState, setEditorState, contentBlock, direction, event);
          // TODO why has the editorstate be set again?
          const editorState = getEditorState();
          setEditorState(EditorState.forceSelection(editorState, editorState.getSelection()));
        } else {
          const editorState = getEditorState();
          setEditorState(EditorState.forceSelection(editorState, editorState.getSelection()));
        }
      };

      // TODO is getReadOnly correct here?
      const editorState = getEditorState();
      const isFocused = !getReadOnly() && blockInSelection(editorState, contentBlock.getKey());

      return {
        props: {
          unsetFocus,
          isFocused,
          isCollapsedSelection: editorState.getSelection().isCollapsed(),
        }
      };
    },
    // Handle down/up arrow events and set activeBlock/selection if necessary
    onDownArrow: (event, { getEditorState, setEditorState }) => {
      // TODO if one block is selected and the user wants to expand the selection using the shift key

      // TODO match by entitiy instead of block type
      const editorState = getEditorState();
      if (oneAtomicBlockIsSelected(editorState)) {
        setSelection(store, getEditorState, setEditorState, 'down', event);
        return;
      }

      // Don't manually overwrite in case the shift key is used to avoid breaking
      // native behaviour that works anyway.
      if (event.shiftKey) {
        return;
      }

      // Covering the case to select the after block with arrow down
      const selectionKey = editorState.getSelection().getAnchorKey();
      const afterBlock = editorState.getCurrentContent().getBlockAfter(selectionKey);
      if (afterBlock && afterBlock.getType() === 'atomic') {
        setSelection(store, getEditorState, setEditorState, 'down', event);
      }
    },
    onUpArrow: (event, { getEditorState, setEditorState }) => {
      // TODO if one block is selected and the user wants to expand the selection using the shift key

      // TODO match by entitiy instead of block type
      const editorState = getEditorState();
      if (oneAtomicBlockIsSelected(editorState)) {
        setSelection(store, getEditorState, setEditorState, 'up', event);
      }

      // Don't manually overwrite in case the shift key is used to avoid breaking
      // native behaviour that works anyway.
      if (event.shiftKey) {
        return;
      }

      // Covering the case to select the before block with arrow up
      const selectionKey = editorState.getSelection().getAnchorKey();
      const beforeBlock = editorState.getCurrentContent().getBlockBefore(selectionKey);
      if (beforeBlock && beforeBlock.getType() === 'atomic') {
        setSelection(store, getEditorState, setEditorState, 'up', event);
      }
    },
    decorator: createDecorator({ theme, store }),
  };
};

export default focusPlugin;
<commit_msg>make sure left/right cases are covered<commit_after>import { EditorState } from 'draft-js';
import setSelection from './modifiers/setSelection';
import createDecorator from './createDecorator';
import createStore from './utils/createStore';
import blockInSelection from './utils/blockInSelection';
import defaultTheme from './style.css';

const store = createStore({});

const oneAtomicBlockIsSelected = (editorState) => {
  const selection = editorState.getSelection();
  if (selection.getAnchorKey() !== selection.getFocusKey()) {
    return false;
  }
  const content = editorState.getCurrentContent();
  const block = content.getBlockForKey(selection.getAnchorKey());
  // check for atomic block and for entity
  return block.getType() === 'atomic';
};

// TODO make sure to remove the native selection of a text when the user clicks on the block
const focusPlugin = (config = {}) => {
  const theme = config.theme ? config.theme : defaultTheme;
  let lastSelection;

  return {
    initialize: ({ getEditorState, setEditorState }) => {
      store.updateItem('getEditorState', getEditorState);
      store.updateItem('setEditorState', setEditorState);
    },
    onChange: (editorState) => {
      const selection = editorState.getSelection();
      if (lastSelection && selection.equals(lastSelection)) {
        lastSelection = editorState.getSelection();
        return editorState;
      }

      // TODO check for if an atomic block is affected that has a focus entity
      lastSelection = editorState.getSelection();
      // By forcing the selection the editor will trigger the blockRendererFn which is
      // necessary
      return EditorState.forceSelection(editorState, editorState.getSelection());
    },
    keyBindingFn(evt, { getEditorState, setEditorState }) {
      const editorState = getEditorState();
      // TODO match by entitiy instead of block type
      if (oneAtomicBlockIsSelected(editorState)) {
        // arrow left
        if (evt.keyCode === 37) {
          setSelection(store, getEditorState, setEditorState, 'up', evt);
        }
        // arrow right
        if (evt.keyCode === 39) {
          setSelection(store, getEditorState, setEditorState, 'down', evt);
        }
      }

      // Don't manually overwrite in case the shift key is used to avoid breaking
      // native behaviour that works anyway.
      if (evt.shiftKey) {
        return;
      }

      // arrow left
      if (evt.keyCode === 37) {
        // Covering the case to select the before block
        const selection = editorState.getSelection();
        const selectionKey = selection.getAnchorKey();
        const beforeBlock = editorState.getCurrentContent().getBlockBefore(selectionKey);
        // only if the selection caret is a the left most position
        if (beforeBlock && selection.getAnchorOffset() === 0 && beforeBlock.getType() === 'atomic') {
          setSelection(store, getEditorState, setEditorState, 'up', evt);
        }
      }
      // arrow right
      if (evt.keyCode === 39) {
        // Covering the case to select the after block
        const selection = editorState.getSelection();
        const selectionKey = selection.getFocusKey();
        const currentBlock = editorState.getCurrentContent().getBlockForKey(selectionKey);
        const afterBlock = editorState.getCurrentContent().getBlockAfter(selectionKey);
        const notAtomicAndLastPost =
          currentBlock.getType() !== 'atomic' &&
          currentBlock.getLength() === selection.getFocusOffset();
        if (afterBlock && notAtomicAndLastPost && afterBlock.getType() === 'atomic') {
          setSelection(store, getEditorState, setEditorState, 'down', evt);
        }
      }
    },
    // Wrap all block-types in block-focus decorator
    blockRendererFn: (contentBlock, { getEditorState, setEditorState, getReadOnly }) => {
      if (contentBlock.getType() !== 'atomic') {
        return undefined;
      }

      const unsetFocus = (direction, event) => {
        if (getReadOnly()) return;

        if (direction) {
          setSelection(store, getEditorState, setEditorState, contentBlock, direction, event);
          // TODO why has the editorstate be set again?
          const editorState = getEditorState();
          setEditorState(EditorState.forceSelection(editorState, editorState.getSelection()));
        } else {
          const editorState = getEditorState();
          setEditorState(EditorState.forceSelection(editorState, editorState.getSelection()));
        }
      };

      // TODO is getReadOnly correct here?
      const editorState = getEditorState();
      const isFocused = !getReadOnly() && blockInSelection(editorState, contentBlock.getKey());

      return {
        props: {
          unsetFocus,
          isFocused,
          isCollapsedSelection: editorState.getSelection().isCollapsed(),
        }
      };
    },
    // Handle down/up arrow events and set activeBlock/selection if necessary
    onDownArrow: (event, { getEditorState, setEditorState }) => {
      // TODO if one block is selected and the user wants to expand the selection using the shift key

      // TODO match by entitiy instead of block type
      const editorState = getEditorState();
      if (oneAtomicBlockIsSelected(editorState)) {
        setSelection(store, getEditorState, setEditorState, 'down', event);
        return;
      }

      // Don't manually overwrite in case the shift key is used to avoid breaking
      // native behaviour that works anyway.
      if (event.shiftKey) {
        return;
      }

      // Covering the case to select the after block with arrow down
      const selectionKey = editorState.getSelection().getAnchorKey();
      const afterBlock = editorState.getCurrentContent().getBlockAfter(selectionKey);
      if (afterBlock && afterBlock.getType() === 'atomic') {
        setSelection(store, getEditorState, setEditorState, 'down', event);
      }
    },
    onUpArrow: (event, { getEditorState, setEditorState }) => {
      // TODO if one block is selected and the user wants to expand the selection using the shift key

      // TODO match by entitiy instead of block type
      const editorState = getEditorState();
      if (oneAtomicBlockIsSelected(editorState)) {
        setSelection(store, getEditorState, setEditorState, 'up', event);
      }

      // Don't manually overwrite in case the shift key is used to avoid breaking
      // native behaviour that works anyway.
      if (event.shiftKey) {
        return;
      }

      // Covering the case to select the before block with arrow up
      const selectionKey = editorState.getSelection().getAnchorKey();
      const beforeBlock = editorState.getCurrentContent().getBlockBefore(selectionKey);
      if (beforeBlock && beforeBlock.getType() === 'atomic') {
        setSelection(store, getEditorState, setEditorState, 'up', event);
      }
    },
    decorator: createDecorator({ theme, store }),
  };
};

export default focusPlugin;
<|endoftext|>


<commit_before>// Plotter.js v0.1.3

var plotter = {
	bounds: new google.maps.LatLngBounds(),
	listener: null,
	map: null,
	multiple: 10.7639104,
	paths: null,
	plot: null,
	points: [],
	report: null,
	bind: function(settings){
		plotter.map = settings.map;
		plotter.multiple = settings.multiple;
		plotter.report = settings.report;
		plotter.plot = new google.maps.Polygon({ strokeWeight: settings.strokeWeight, fillColor: settings.fillColor });
		plotter.paths = new google.maps.MVCArray;
		plotter.plot.setMap(plotter.map);
		plotter.plot.setPath(new google.maps.MVCArray([plotter.paths]));
	},
	on: function(){
		plotter.listener = google.maps.event.addListener(plotter.map, 'click', function(event){
			plotter.paths.insertAt(plotter.paths.length, event.latLng);
			var point = new google.maps.Marker({
				icon: 'marker.png',
				position: event.latLng,
				map: plotter.map,
				draggable: true
			});
			point.setTitle("Point #" + plotter.paths.length);
			google.maps.event.addListener(point, 'click', function() {
				point.setMap(null);
				for (var i = 0, I = plotter.points.length; i < I && plotter.points[i] != point; ++i);
					plotter.points.splice(i, 1);
					plotter.paths.removeAt(i);
					plotter.calc();
			});
			google.maps.event.addListener(point, 'dragend', function() {
				for (var i = 0, I = plotter.points.length; i < I && plotter.points[i] != point; ++i);
					plotter.paths.setAt(i, point.getPosition());
					plotter.calc();
			});
			plotter.points.push(point);
			return plotter.calc();
		});
		plotter.map.setOptions({draggableCursor: 'crosshair'});
	},
	calc: function(){
		area_met = google.maps.geometry.spherical.computeArea(plotter.plot.getPath());
		var area_ft = (area_met * plotter.multiple).toFixed(2);
		var x = area_ft.split('.');
		var x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2') }
		if (plotter.report){
			$(plotter.report).html(x1 + x2 + " sq ft");
		} else {
			return x1 + x2 + " sq ft";
		}
	},
	data: function(){
		var output = '{coords: [';
		$(plotter.points).each(function(index){
			output += this.position.toString().replace("(", "{lat:").replace(",", ", lng:").replace(")", "}");
			if ( (index+1) != plotter.points.length ){ output +=  ", " }
		});
		output += "] }";
		return output;
	},
	off: function(){
		google.maps.event.removeListener(plotter.listener);
		$(plotter.points).each(function(index){
			for (index in plotter.points) {
				google.maps.event.trigger(plotter.points[index], 'click');
			}
		});
		plotter.map.setOptions({draggableCursor: ''});
	}
};
<commit_msg>Updated plotter.js to make config options actually optional.. otherwise resort to defalt<commit_after>// Plotter.js

var plotter = {
	bounds: new google.maps.LatLngBounds(),
	icon: "marker.png",
	listener: null,
	map: null,
	multiple: 10.7639104,
	paths: null,
	plot: null,
	points: [],
	style: { fill: "#3FA9F5", stroke: 1 },
	report: null,
	bind: function(settings){
		if (settings.icon) { plotter.icon = settings.icon }
		if (settings.map) { plotter.map = settings.map }
		if (settings.multiple) { plotter.multiple = settings.multiple }
		if (settings.report) { plotter.report = settings.report }
		if (settings.strokeWeight) { plotter.style.stroke = settings.strokeWeight }
		if (settings.fillColor) { plotter.style.fill = settings.fillColor }
		plotter.plot = new google.maps.Polygon({ strokeWeight: plotter.style.stroke, fillColor: plotter.style.fill });
		plotter.paths = new google.maps.MVCArray;
		plotter.plot.setMap(plotter.map);
		plotter.plot.setPath(new google.maps.MVCArray([plotter.paths]));
	},
	on: function(){
		plotter.listener = google.maps.event.addListener(plotter.map, 'click', function(event){
			plotter.paths.insertAt(plotter.paths.length, event.latLng);
			var point = new google.maps.Marker({
				icon: plotter.icon,
				position: event.latLng,
				map: plotter.map,
				draggable: true
			});
			point.setTitle("Point #" + plotter.paths.length);
			google.maps.event.addListener(point, 'click', function() {
				point.setMap(null);
				for (var i = 0, I = plotter.points.length; i < I && plotter.points[i] != point; ++i);
					plotter.points.splice(i, 1);
					plotter.paths.removeAt(i);
					plotter.calc();
			});
			google.maps.event.addListener(point, 'dragend', function() {
				for (var i = 0, I = plotter.points.length; i < I && plotter.points[i] != point; ++i);
					plotter.paths.setAt(i, point.getPosition());
					plotter.calc();
			});
			plotter.points.push(point);
			return plotter.calc();
		});
		plotter.map.setOptions({draggableCursor: 'crosshair'});
	},
	calc: function(){
		area_met = google.maps.geometry.spherical.computeArea(plotter.plot.getPath());
		var area_ft = (area_met * plotter.multiple).toFixed(2);
		var x = area_ft.split('.');
		var x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2') }
		if (plotter.report){
			$(plotter.report).html(x1 + x2 + " sq ft");
		} else {
			return x1 + x2 + " sq ft";
		}
	},
	data: function(){
		var output = '{coords: [';
		$(plotter.points).each(function(index){
			output += this.position.toString().replace("(", "{lat:").replace(",", ", lng:").replace(")", "}");
			if ( (index+1) != plotter.points.length ){ output +=  ", " }
		});
		output += "] }";
		return output;
	},
	off: function(){
		google.maps.event.removeListener(plotter.listener);
		$(plotter.points).each(function(index){
			for (index in plotter.points) {
				google.maps.event.trigger(plotter.points[index], 'click');
			}
		});
		plotter.map.setOptions({draggableCursor: ''});
	}
};<|endoftext|>


<commit_before>var dart;
(function (dart) {
  var defineProperty = Object.defineProperty;
  var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  var getOwnPropertyNames = Object.getOwnPropertyNames;

  // Adapted from Angular.js
  var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  var FN_ARG_SPLIT = /,/;
  var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;

  function formalParameterList(fn) {
    var fnText,argDecl;
    var args=[];
    fnText = fn.toString().replace(STRIP_COMMENTS, '');
    argDecl = fnText.match(FN_ARGS);

    var r = argDecl[1].split(FN_ARG_SPLIT);
    for(var a in r){
      var arg = r[a];
      arg.replace(FN_ARG, function(all, underscore, name){
        args.push(name);
      });
    }
    return args;
  }

  function dload(obj, field) {
    if (!(field in obj)) {
      throw new dart_core.NoSuchMethodError(obj, field);
    }
    return obj[field];
  }
  dart.dload = dload;

  function dinvokef(f, args) {
    var formals = formalParameterList(f);
    // TODO(vsm): Type check args!  We need to encode sufficient type info on f.
    if (formals.length < args.length) {
      throw new dart_core.NoSuchMethodError(f, args);
    } else if (formals.length > args.length) {
      for (var i = args.length; i < formals.length; ++i) {
        if (formals[i].indexOf("opt$") != 0)
          throw new dart_core.NoSuchMethodError(f, args);
      }
    }
    return f.apply(void 0, args);
  }
  dart.dinvokef = dinvokef;

  function dextend(sub, _super) {
    sub.prototype = Object.create(_super.prototype);
    sub.prototype.constructor = sub;
  }
  dart.dextend = dextend;

  function cast(obj, type) {
    if (obj == null || instanceOf(obj, type)) return obj;
    throw new dart_core.CastError();
  }
  dart.cast = cast;

  function instanceOf(obj, type) {
    // TODO(vsm): Implement.
    throw new dart_core.UnimplementedError();
  }
  dart.instanceOf = instanceOf;

  function isGroundType(type) {
    // TODO(vsm): Implement.
    throw new dart_core.UnimplementedError();
  }
  dart.isGroundType = isGroundType;

  function arity(f) {
    // TODO(vsm): Implement.
    throw new dart_core.UnimplementedError();
  }
  dart.arity = arity;

  function equals(x, y) {
    if (x === null || y === null) return x === y;
    var eq = x.__equals;
    return eq ? eq.call(x, y) : x === y;
  }
  dart.equals = equals;

  /** Checks that `x` is not null or undefined. */
  function notNull(x) {
    if (x == null) throw 'expected not-null value';
    return x;
  }
  dart.notNull = notNull;

  /**
   * Defines a lazy property.
   * After initial get or set, it will replace itself with a value property.
   */
  // TODO(jmesserly): is this the best implementation for JS engines?
  // TODO(jmesserly): reusing descriptor objects has been shown to improve
  // performance in other projects (e.g. webcomponents.js ShadowDOM polyfill).
  function defineLazyProperty(to, name, desc) {
    var init = desc.get;
    var writable = !!desc.set;
    function lazySetter(value) {
      defineProperty(to, name, { value: value, writable: writable });
    }
    function lazyGetter() {
      // Clear the init function to detect circular initialization.
      var f = init;
      if (f === null) throw 'circular initialization for field ' + name;
      init = null;

      // Compute and store the value.
      var value = f();
      lazySetter(value);
      return value;
    }
    desc.get = lazyGetter;
    desc.configurable = true;
    if (writable) desc.set = lazySetter;
    defineProperty(to, name, desc);
  }

  function defineLazyProperties(to, from) {
    var names = getOwnPropertyNames(from);
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      defineLazyProperty(to, name, getOwnPropertyDescriptor(from, name));
    }
  }
  dart.defineLazyProperties = defineLazyProperties;

  /**
   * Copy properties from source to destination object.
   * This operation is commonly called `mixin` in JS.
   */
  function copyProperties(to, from) {
    var names = getOwnPropertyNames(from);
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      defineProperty(to, name, getOwnPropertyDescriptor(from, name));
    }
    return to;
  }
  dart.copyProperties = copyProperties;

  /**
   * Returns a new type that mixes members from base and all mixins.
   *
   * Each mixin applies in sequence, with further to the right ones overriding
   * previous entries.
   *
   * For each mixin, we only take its own properties, not anything from its
   * superclass (prototype).
   */
  function mixin(base/*, ...mixins*/) {
    // Inherit statics from Base to simulate ES6 class inheritance
    // Conceptually this is: `class Mixin extends base {}`
    function Mixin() {
      base.apply(this, arguments);
    }
    Mixin.__proto__ = base;
    Mixin.prototype = Object.create(base.prototype);
    // Copy each mixin, with later ones overwriting earlier entires.
    for (var i = 1; i < arguments.length; i++) {
      var from = arguments[i];
      copyProperties(Mixin.prototype, from.prototype);
    }
    return Mixin;
  }
  dart.mixin = mixin;

  function assert(condition) {
    // TODO(jmesserly): throw assertion error.
    if (!condition) throw 'assertion failed';
  }
  dart.assert = assert;

})(dart || (dart = {}));
<commit_msg>fix typo<commit_after>var dart;
(function (dart) {
  var defineProperty = Object.defineProperty;
  var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  var getOwnPropertyNames = Object.getOwnPropertyNames;

  // Adapted from Angular.js
  var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  var FN_ARG_SPLIT = /,/;
  var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;

  function formalParameterList(fn) {
    var fnText,argDecl;
    var args=[];
    fnText = fn.toString().replace(STRIP_COMMENTS, '');
    argDecl = fnText.match(FN_ARGS);

    var r = argDecl[1].split(FN_ARG_SPLIT);
    for(var a in r){
      var arg = r[a];
      arg.replace(FN_ARG, function(all, underscore, name){
        args.push(name);
      });
    }
    return args;
  }

  function dload(obj, field) {
    if (!(field in obj)) {
      throw new dart_core.NoSuchMethodError(obj, field);
    }
    return obj[field];
  }
  dart.dload = dload;

  function dinvokef(f, args) {
    var formals = formalParameterList(f);
    // TODO(vsm): Type check args!  We need to encode sufficient type info on f.
    if (formals.length < args.length) {
      throw new dart_core.NoSuchMethodError(f, args);
    } else if (formals.length > args.length) {
      for (var i = args.length; i < formals.length; ++i) {
        if (formals[i].indexOf("opt$") != 0)
          throw new dart_core.NoSuchMethodError(f, args);
      }
    }
    return f.apply(void 0, args);
  }
  dart.dinvokef = dinvokef;

  function dextend(sub, _super) {
    sub.prototype = Object.create(_super.prototype);
    sub.prototype.constructor = sub;
  }
  dart.dextend = dextend;

  function cast(obj, type) {
    if (obj == null || instanceOf(obj, type)) return obj;
    throw new dart_core.CastError();
  }
  dart.cast = cast;

  function instanceOf(obj, type) {
    // TODO(vsm): Implement.
    throw new dart_core.UnimplementedError();
  }
  dart.instanceOf = instanceOf;

  function isGroundType(type) {
    // TODO(vsm): Implement.
    throw new dart_core.UnimplementedError();
  }
  dart.isGroundType = isGroundType;

  function arity(f) {
    // TODO(vsm): Implement.
    throw new dart_core.UnimplementedError();
  }
  dart.arity = arity;

  function equals(x, y) {
    if (x === null || y === null) return x === y;
    var eq = x.__equals;
    return eq ? eq.call(x, y) : x === y;
  }
  dart.equals = equals;

  /** Checks that `x` is not null or undefined. */
  function notNull(x) {
    if (x == null) throw 'expected not-null value';
    return x;
  }
  dart.notNull = notNull;

  /**
   * Defines a lazy property.
   * After initial get or set, it will replace itself with a value property.
   */
  // TODO(jmesserly): is this the best implementation for JS engines?
  // TODO(jmesserly): reusing descriptor objects has been shown to improve
  // performance in other projects (e.g. webcomponents.js ShadowDOM polyfill).
  function defineLazyProperty(to, name, desc) {
    var init = desc.get;
    var writable = !!desc.set;
    function lazySetter(value) {
      defineProperty(to, name, { value: value, writable: writable });
    }
    function lazyGetter() {
      // Clear the init function to detect circular initialization.
      var f = init;
      if (f === null) throw 'circular initialization for field ' + name;
      init = null;

      // Compute and store the value.
      var value = f();
      lazySetter(value);
      return value;
    }
    desc.get = lazyGetter;
    desc.configurable = true;
    if (writable) desc.set = lazySetter;
    defineProperty(to, name, desc);
  }

  function defineLazyProperties(to, from) {
    var names = getOwnPropertyNames(from);
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      defineLazyProperty(to, name, getOwnPropertyDescriptor(from, name));
    }
  }
  dart.defineLazyProperties = defineLazyProperties;

  /**
   * Copy properties from source to destination object.
   * This operation is commonly called `mixin` in JS.
   */
  function copyProperties(to, from) {
    var names = getOwnPropertyNames(from);
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      defineProperty(to, name, getOwnPropertyDescriptor(from, name));
    }
    return to;
  }
  dart.copyProperties = copyProperties;

  /**
   * Returns a new type that mixes members from base and all mixins.
   *
   * Each mixin applies in sequence, with further to the right ones overriding
   * previous entries.
   *
   * For each mixin, we only take its own properties, not anything from its
   * superclass (prototype).
   */
  function mixin(base/*, ...mixins*/) {
    // Inherit statics from Base to simulate ES6 class inheritance
    // Conceptually this is: `class Mixin extends base {}`
    function Mixin() {
      base.apply(this, arguments);
    }
    Mixin.__proto__ = base;
    Mixin.prototype = Object.create(base.prototype);
    // Copy each mixin, with later ones overwriting earlier entries.
    for (var i = 1; i < arguments.length; i++) {
      var from = arguments[i];
      copyProperties(Mixin.prototype, from.prototype);
    }
    return Mixin;
  }
  dart.mixin = mixin;

  function assert(condition) {
    // TODO(jmesserly): throw assertion error.
    if (!condition) throw 'assertion failed';
  }
  dart.assert = assert;

})(dart || (dart = {}));
<|endoftext|>


<commit_before>'use strict';

const async = require('async');
const assert = require('assert');
const scrypt = require('scrypt');
const crypto = require('crypto');
const BN = require('bn.js');

const CHALLENGE_TTL_SECONDS = 3600;
const DEFAULT_STATS = {
  count: 0,
  timestamp: Date.now(),
  target: '00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'
};

function getPOWMiddleware(db) {

  return function(req, res, next) {

    const challenge = req.headers['x-challenge'];
    const nonce = req.headers['x-challenge-nonce'];

    let salt = Buffer.alloc(8, 0);
    salt.writeDoubleBE(parseInt(nonce));

    const key = 'contact-' + challenge;
    const scryptOpts = { N: Math.pow(2, 10), r: 1, p: 1 };

    db.get(key, function(err, target) {
      if (err) {
        return next(err);
      }

      if (!target) {
        return next(new Error('Challenge not found'));
      }

      scrypt.hash(challenge, scryptOpts, 32, salt, function(err, result) {
        if (err) {
          return next(err);
        }

        // Check the proof of work
        if (result.toString('hex') > target) {
          return next(new Error('Invalid proof of work'));
        }

        // Increase the count and remove the challenge
        db.hincrby('contact-stats', 'count', 1);
        db.del(key);

        return next();
      });
    });
  };
}

function getTarget(db, opts, callback) {

  const precision = 100000000;
  const precisionBN = new BN(precision);
  const retargetPeriod = opts.retargetPeriod;
  const count = opts.retargetCount;

  assert(Number.isSafeInteger(count),
         'retargetCount is expected to be a safe integer');
  assert(Number.isSafeInteger(retargetPeriod),
         'retargetPeriod is expected to be a safe integer');

  db.hgetall('contact-stats', function(err, stats) {
    if (err) {
      return callback(err);
    }

    if (!stats) {
      stats = DEFAULT_STATS;
    } else if (!Number.isSafeInteger(parseInt(stats.count)) ||
               !Number.isSafeInteger(parseInt(stats.timestamp))) {
      // TODO fix this case
      stats = DEFAULT_STATS;
    }

    const now = Date.now();
    const actual = parseInt(stats.count) || 1000;
    const timestamp = parseInt(stats.timestamp);

    if (now > timestamp + retargetPeriod) {
      const timeDelta = now - timestamp;
      const expectedRatio = retargetPeriod / count;
      const actualRatio = timeDelta / actual;

      const adjustmentAmount = actualRatio / expectedRatio;

      const adjustment = new BN(adjustmentAmount * precision);

      const target = new BN(stats.target, 16);
      const newTarget = target.mul(adjustment).div(precisionBN).toString(16, 32);

      async.series([
        (next) => {
          db.hset('contact-stats', 'target', newTarget, next);
        },
        (next) => {
          db.hset('contact-stats', 'timestamp', now, next);
        },
        (next) => {
          db.hset('contact-stats', 'count', 0, next);
        },
      ], (err) => {
        if (err) {
          return callback(err);
        }
        callback(null, newTarget);
      });

    } else {
      callback(null, stats.target);
    }

  });

}

function getChallenge(db, opts, callback) {
  module.exports.getTarget(db, opts, function(err, target) {
    if (err) {
      return callback(err);
    }

    const challenge = crypto.randomBytes(32).toString('hex');
    const key = 'contact-' + challenge;

    db.set(key, target, 'EX', CHALLENGE_TTL_SECONDS, function(err) {
      if (err) {
        return callback(err);
      }
      callback(null, {
        challenge: challenge,
        target: target
      });
    });
  });
}

module.exports = {
  getChallenge: getChallenge,
  getTarget: getTarget,
  getPOWMiddleware: getPOWMiddleware
};
<commit_msg>Set start pow settings<commit_after>'use strict';

const async = require('async');
const assert = require('assert');
const scrypt = require('scrypt');
const crypto = require('crypto');
const BN = require('bn.js');

const CHALLENGE_TTL_SECONDS = 3600;

function getPOWMiddleware(db) {

  return function(req, res, next) {

    const challenge = req.headers['x-challenge'];
    const nonce = req.headers['x-challenge-nonce'];

    let salt = Buffer.alloc(8, 0);
    salt.writeDoubleBE(parseInt(nonce));

    const key = 'contact-' + challenge;
    const scryptOpts = { N: Math.pow(2, 10), r: 1, p: 1 };

    db.get(key, function(err, target) {
      if (err) {
        return next(err);
      }

      if (!target) {
        return next(new Error('Challenge not found'));
      }

      scrypt.hash(challenge, scryptOpts, 32, salt, function(err, result) {
        if (err) {
          return next(err);
        }

        // Check the proof of work
        if (result.toString('hex') > target) {
          return next(new Error('Invalid proof of work'));
        }

        // Increase the count and remove the challenge
        db.hincrby('contact-stats', 'count', 1);
        db.del(key);

        return next();
      });
    });
  };
}

function getTarget(db, opts, callback) {

  const precision = 100000000;
  const precisionBN = new BN(precision);
  const retargetPeriod = opts.retargetPeriod;
  const count = opts.retargetCount;

  assert(Number.isSafeInteger(count),
         'retargetCount is expected to be a safe integer');
  assert(Number.isSafeInteger(retargetPeriod),
         'retargetPeriod is expected to be a safe integer');

  db.hgetall('contact-stats', function(err, stats) {
    if (err) {
      return callback(err);
    }

    if (!stats) {
      stats = {
        count: 0,
        timestamp: Date.now() - 1000,
        target: '00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'
      };
    }

    if (!Number.isSafeInteger(parseInt(stats.count)) ||
        !Number.isSafeInteger(parseInt(stats.timestamp))) {
      return callback(new Error('Invalid pow settings'));
    }

    const now = Date.now();
    const actual = parseInt(stats.count) || 1000;
    const timestamp = parseInt(stats.timestamp);

    if (now > timestamp + retargetPeriod) {
      const timeDelta = now - timestamp;
      const expectedRatio = retargetPeriod / count;
      const actualRatio = timeDelta / actual;

      const adjustmentAmount = actualRatio / expectedRatio;

      const adjustment = new BN(adjustmentAmount * precision);

      const target = new BN(stats.target, 16);
      const newTarget = target.mul(adjustment).div(precisionBN).toString(16, 32);

      async.series([
        (next) => {
          db.hset('contact-stats', 'target', newTarget, next);
        },
        (next) => {
          db.hset('contact-stats', 'timestamp', now, next);
        },
        (next) => {
          db.hset('contact-stats', 'count', 0, next);
        },
      ], (err) => {
        if (err) {
          return callback(err);
        }
        callback(null, newTarget);
      });

    } else {
      callback(null, stats.target);
    }

  });

}

function getChallenge(db, opts, callback) {
  module.exports.getTarget(db, opts, function(err, target) {
    if (err) {
      return callback(err);
    }

    const challenge = crypto.randomBytes(32).toString('hex');
    const key = 'contact-' + challenge;

    db.set(key, target, 'EX', CHALLENGE_TTL_SECONDS, function(err) {
      if (err) {
        return callback(err);
      }
      callback(null, {
        challenge: challenge,
        target: target
      });
    });
  });
}

module.exports = {
  getChallenge: getChallenge,
  getTarget: getTarget,
  getPOWMiddleware: getPOWMiddleware
};
<|endoftext|>


<commit_before>/*
The class is used to manage the database drivers
 */
var driverManager=function(){

    var config=require('/config/storage.json');
    var utility=require('/modules/utility.js').rxt_utility();
    var bundler=require('/modules/bundler.js').bundle_logic();
    var log=new Log('driver.manager');

    var FILE_QP='query.provider.js';
    var FILE_QT='query.translator.js';
    var FILE_DRIVER='driver.js';
    var DEFAULT_DRIVER='default';

    var dsm=org.wso2.carbon.ndatasource.core.DataSourceManager;

    var DB_DRIVERS={
        MYSQL_DRIVER:'jdbc:mysql',
        ORACLE_DRIVER:'jdbc:oracle',
        H2_DRIVER:'jdbc:h2',
        UNSUPPORTED:'none'
    };

    /*
   Paths
     */
    var defaultPath='/modules/data/';
    var driverPath=config.driverPath||'/drivers/';

    function DriverManager(){
        this.defaultBundleManager=new bundler.BundleManager({
             path:defaultPath
        });
        this.driverMap={};
        this.defaultQP=null;
        this.defaultQT=null;
        this.dataSourceManager=new DataSourceManager();

        //Create the default which will be used to build all other drivers
        this.createDefaultDriver();
    }

    /*
    The function constructs a default driver based on the modules/data implementation
     */
    DriverManager.prototype.createDefaultDriver=function(){

        var defaultRootBundle=this.defaultBundleManager.getRoot();

        //Read the modules/data directory to get the default drivers
        var driverBundle=defaultRootBundle.get({name:FILE_DRIVER}).result();

        if(!driverBundle){
            throw 'unable to create default db driver';
        }

        var driver=require(defaultPath+FILE_DRIVER).driver();
        var driverInstance=new driver.DBDriver();

        //Obtain the default query providers
        var queryProviderBundle=defaultRootBundle.get({name:FILE_QP}).result();

        if(!queryProviderBundle){
            throw 'unable to create a default query provider';
        }

        this.defaultQP=require(defaultPath+FILE_QP).queryProvider();

        var queryTranslatorBundle=defaultRootBundle.get({name:FILE_QT}).result();

        if(!queryTranslatorBundle){
            throw 'unable to create default query translator';
        }

        this.defaultQT=require(defaultPath+FILE_QT).queryTranslator();

        this.driverMap[DEFAULT_DRIVER]=driverInstance;
    };

    /*
    The function loads drivers in the driver directory
     */
    DriverManager.prototype.loadDrivers=function(){

        var bundleManager=new bundler.BundleManager({
            path:driverPath
        });
    };

    /*
    The function returns a database driver after calling the drivers initialize method
    @driverType: The type of driver
    @return: A driver instance
     */
    DriverManager.prototype.get=function(driverType){

        //Check if the driver is supported
        if(this.driverMap.hasOwnProperty(driverType)){
            this.driverMap[driverType].init({queryProvider:this.defaultQP, queryTranslator:this.defaultQT});
            return this.driverMap[driverType];
        }

        log.info('driver for '+driverType+' not found.');
        return null;
    };

    /*
    The function is used to locate a driver that supports the provided datasource
    @name: The name of a datasource to be accessed
     */
    DriverManager.prototype.getDriver=function(name){
        var datasource=this.dataSourceManager.get(name);
        var driverType=datasource.getDriver();

        if(datasource==DB_DRIVERS.UNSUPPORTED){
            throw 'Cannot find a driver for '+name;
        }

    };

    /*
    The class is used to store information on a DataSource used by a driver
     */
    function DataSource(dsObject){
       this.instance=dsObject;
    }

    /*
    The function returns the type of driver required by the datasource by looking
    at the connection url
    @return: The driver type based on the connection string.If there is no match UNSUPPORTED
            is returned.If there is no connection url the unsupported value is returned.
     */
    DataSource.prototype.getDriver=function(){

       var connectionUrl=this.instance.getUrl();

       if(!connectionUrl){
           return DB_DRIVERS.UNSUPPORTED;
       }

       for(var key in DB_DRIVERS){

           //Check if the url matches one of the DB_DRIVERS
           if(connectionUrl.indexOf(DB_DRIVERS[key])!=-1){
               return key;
           }
       }

       return DB_DRIVERS.UNSUPPORTED;

    };

    /*
    The class is used to access the carbon datasources repository
     */
    function DataSourceManager(){
        this.instance=new dsm();
    }

    /*
    The function is used to obtain a reference to a datasource defined in the
    master.datasources.xml.
    @name: The name of the datasource
    @return: A DataSource object
     */
    DataSourceManager.prototype.get=function(name){

        var datasource=this.instance.getInstance().getDataSourceRepository().getDataSource(name);
        var dsObject=datasource.getDSObject();

        //If the datasource is not found
        if(!datasource){
           return null;
        }

        return new DataSource(dsObject);
    };

    return{
        DriverManager:DriverManager,
        DataSourceManager:DataSourceManager
    }
};
<commit_msg>added debug message<commit_after>/*
The class is used to manage the database drivers
 */
var driverManager=function(){

    var config=require('/config/storage.json');
    var utility=require('/modules/utility.js').rxt_utility();
    var bundler=require('/modules/bundler.js').bundle_logic();
    var log=new Log('driver.manager');

    var FILE_QP='query.provider.js';
    var FILE_QT='query.translator.js';
    var FILE_DRIVER='driver.js';
    var DEFAULT_DRIVER='default';

    var dsm=org.wso2.carbon.ndatasource.core.DataSourceManager;

    var DB_DRIVERS={
        MYSQL_DRIVER:'jdbc:mysql',
        ORACLE_DRIVER:'jdbc:oracle',
        H2_DRIVER:'jdbc:h2',
        UNSUPPORTED:'none'
    };

    /*
   Paths
     */
    var defaultPath='/modules/data/';
    var driverPath=config.driverPath||'/drivers/';

    function DriverManager(){
        this.defaultBundleManager=new bundler.BundleManager({
             path:defaultPath
        });
        this.driverMap={};
        this.defaultQP=null;
        this.defaultQT=null;
        this.dataSourceManager=new DataSourceManager();

        //Create the default which will be used to build all other drivers
        this.createDefaultDriver();
    }

    /*
    The function constructs a default driver based on the modules/data implementation
     */
    DriverManager.prototype.createDefaultDriver=function(){

        var defaultRootBundle=this.defaultBundleManager.getRoot();

        //Read the modules/data directory to get the default drivers
        var driverBundle=defaultRootBundle.get({name:FILE_DRIVER}).result();

        if(!driverBundle){
            throw 'unable to create default db driver';
        }

        var driver=require(defaultPath+FILE_DRIVER).driver();
        var driverInstance=new driver.DBDriver();

        //Obtain the default query providers
        var queryProviderBundle=defaultRootBundle.get({name:FILE_QP}).result();

        if(!queryProviderBundle){
            throw 'unable to create a default query provider';
        }

        this.defaultQP=require(defaultPath+FILE_QP).queryProvider();

        var queryTranslatorBundle=defaultRootBundle.get({name:FILE_QT}).result();

        if(!queryTranslatorBundle){
            throw 'unable to create default query translator';
        }

        this.defaultQT=require(defaultPath+FILE_QT).queryTranslator();

        this.driverMap[DEFAULT_DRIVER]=driverInstance;
    };

    /*
    The function loads drivers in the driver directory
     */
    DriverManager.prototype.loadDrivers=function(){

        var bundleManager=new bundler.BundleManager({
            path:driverPath
        });
    };

    /*
    The function returns a database driver after calling the drivers initialize method
    @driverType: The type of driver
    @return: A driver instance
     */
    DriverManager.prototype.get=function(driverType){

        //Check if the driver is supported
        if(this.driverMap.hasOwnProperty(driverType)){
            this.driverMap[driverType].init({queryProvider:this.defaultQP, queryTranslator:this.defaultQT});
            return this.driverMap[driverType];
        }

        log.info('driver for '+driverType+' not found.');
        return null;
    };

    /*
    The function is used to locate a driver that supports the provided datasource
    @name: The name of a datasource to be accessed
     */
    DriverManager.prototype.getDriver=function(name){
        var datasource=this.dataSourceManager.get(name);
        var driverType=datasource.getDriver();

        if(datasource==DB_DRIVERS.UNSUPPORTED){
            throw 'Cannot find a driver for '+name;
        }

    };

    /*
    The class is used to store information on a DataSource used by a driver
     */
    function DataSource(dsObject){
       this.instance=dsObject;
    }

    /*
    The function returns the type of driver required by the datasource by looking
    at the connection url
    @return: The driver type based on the connection string.If there is no match UNSUPPORTED
            is returned.If there is no connection url the unsupported value is returned.
     */
    DataSource.prototype.getDriver=function(){

       var connectionUrl=this.instance.getUrl();

       if(!connectionUrl){
           return DB_DRIVERS.UNSUPPORTED;
       }

       for(var key in DB_DRIVERS){

           //Check if the url matches one of the DB_DRIVERS
           if(connectionUrl.indexOf(DB_DRIVERS[key])!=-1){
               return key;
           }
       }
       log.info('driver type in '+connectionUrl+' not found.');
       return DB_DRIVERS.UNSUPPORTED;

    };

    /*
    The class is used to access the carbon datasources repository
     */
    function DataSourceManager(){
        this.instance=new dsm();
    }

    /*
    The function is used to obtain a reference to a datasource defined in the
    master.datasources.xml.
    @name: The name of the datasource
    @return: A DataSource object
     */
    DataSourceManager.prototype.get=function(name){

        var datasource=this.instance.getInstance().getDataSourceRepository().getDataSource(name);
        var dsObject=datasource.getDSObject();

        //If the datasource is not found
        if(!datasource){
           return null;
        }

        return new DataSource(dsObject);
    };

    return{
        DriverManager:DriverManager,
        DataSourceManager:DataSourceManager
    }
};
<|endoftext|>


<commit_before>define("dojox/socket", ["dojo", "dojo/cookie"], function(dojo) {

var WebSocket = window.WebSocket;

dojox.socket = Socket;
function Socket(/*dojo.__XhrArgs*/ argsOrUrl){
	// summary:
	//		Provides a simple socket connection using WebSocket, or alternate
	// 		communication mechanisms in legacy browsers for comet-style communication. This is based
	//		on the WebSocket API and returns an object that implements the WebSocket interface:
	//		http://dev.w3.org/html5/websockets/#websocket
	//	description:
	//		Provides socket connections. This can be used with virtually any Comet protocol.
	//	argsOrUrl:
	//		This uses the same arguments as the other I/O functions in Dojo, or a
	// 		URL to connect to. The URL should be a relative URL in order to properly
	//		work with WebSockets (it can still be host relative, like //other-site.org/endpoint)
	// returns:
	// 		An object that implements the WebSocket API
	// example:
	//		| dojo.require("dojox.socket");
	//		| var socket = dojox.socket({"//comet-server/comet");
	//		| // we could also add auto-reconnect support
	//		| // now we can connect to standard HTML5 WebSocket-style events
	//		| dojo.connect(socket, "onmessage", function(event){
	//		|    var message = event.data;
	//		|    // do something with the message
	//		| });
	//		| // send something
	//		| socket.send("hi there");
	//		| whenDone(function(){
	//		|   socket.close();
	//		| });
	//		You can also use the Reconnect module:
	//		| dojo.require("dojox.socket");
	//		| dojo.require("dojox.socket.Reconnect");
	//		| var socket = dojox.socket({url:"/comet"});
	//		| // add auto-reconnect support
	//		| socket = dojox.socket.Reconnect(socket);
	if(typeof argsOrUrl == "string"){
		argsOrUrl = {url: argsOrUrl};
	}
	return WebSocket ? dojox.socket.WebSocket(argsOrUrl) : dojox.socket.LongPoll(argsOrUrl);
};

Socket.WebSocket = function(args){
	// summary:
	//		A wrapper for WebSocket, than handles standard args and relative URLs
	var ws = new WebSocket(new dojo._Url(document.baseURI.replace(/^http/i,'ws'), args.url));
	ws.on = ws.addEventListener;
	var opened;
	dojo.connect(ws, "onopen", function(event){
		opened = true;
	});
	dojo.connect(ws, "onclose", function(event){
		if(opened){
			return;
		}
		WebSocket = null;
		Socket.replace(ws, dojox.socket(args), true);
	});
	return ws;
};
Socket.replace = function(socket, newSocket, listenForOpen){
	// make the original socket a proxy for the new socket
	socket.send = dojo.hitch(newSocket, "send");
	socket.close = dojo.hitch(newSocket, "close");
	if(listenForOpen){
		proxyEvent("open");
	}
	// redirect the events as well
	dojo.forEach(["message", "close", "error", "open"], proxyEvent);
	function proxyEvent(type){
		(newSocket.addEventListener || newSocket.on).call(newSocket, type, function(event){
			socket.dispatchEvent(event);
		});
	}
};
Socket.LongPoll = function(/*dojo.__XhrArgs*/ args){
	// summary:
	//		Provides a simple long-poll based comet-style socket/connection to a server and returns an
	// 		object implementing the WebSocket interface:
	//		http://dev.w3.org/html5/websockets/#websocket
	//	args:
	//		This uses the same arguments as the other I/O functions in Dojo, with this addition:
	//	args.interval:
	//		Indicates the amount of time (in milliseconds) after a response was received
	//		before another request is made. By default, a request is made immediately
	//		after getting a response. The interval can be increased to reduce load on the
	//		server or to do simple time-based polling where the server always responds
	// 		immediately.
	//	args.transport:
	//		Provide an alternate transport like dojo.io.script.get
	// returns:
	// 		An object that implements the WebSocket API
	// example:
	//		| dojo.require("dojox.socket.LongPoll");
	//		| var socket = dojox.socket.LongPoll({url:"/comet"});
	//		or:
	//		| dojo.require("dojox.socket.LongPoll");
	//		| dojox.socket.LongPoll.add();
	//		| var socket = dojox.socket({url:"/comet"});

var cancelled = false,
		first = true,
		timeoutId,
		connections = [];

	// create the socket object
	var socket = {
		send: function(data){
			// summary:
			// 		Send some data using XHR or provided transport
			var sendArgs = dojo.delegate(args);
			sendArgs.rawBody = data;
			clearTimeout(timeoutId);
			var deferred = first ? (first = false) || socket.firstRequest(sendArgs) :
				socket.transport(sendArgs);
			connections.push(deferred);
			deferred.then(function(response){
				// got a response
				socket.readyState = 1;
				// remove the current connection
				connections.splice(dojo.indexOf(connections, deferred), 1);
				// reconnect to listen for the next message if there are no active connections,
				// we queue it up in case one of the onmessage handlers has a message to send
				if(!connections.length){
					timeoutId = setTimeout(connect, args.interval);
				}
				if(response){
					// now send the message along to listeners
					fire("message", {data: response}, deferred);
				}
			}, function(error){
				connections.splice(dojo.indexOf(connections, deferred), 1);
				// an error occurred, fire the appropriate event listeners
				if(!cancelled){
					fire("error", {error:error}, deferred);
					if(!connections.length){
						socket.readyState = 3;
						fire("close", {wasClean:false}, deferred);
					}
				}
			});
			return deferred;
		},
		close: function(){
			// summary:
			// 		Close the connection
			socket.readyState = 2;
			cancelled = true;
			for(var i = 0; i < connections.length; i++){
				connections[i].cancel();
			}
			socket.readyState = 3;
			fire("close", {wasClean:true});
		},
		transport: args.transport || dojo.xhrPost,
		args: args,
		url: args.url,
		readyState: 0,
		CONNECTING: 0,
		OPEN: 1,
		CLOSING: 2,
		CLOSED: 3,
		dispatchEvent: function(event){
			fire(event.type, event);
		},
		on: function(type, callback){
			return dojo.connect(this, "on" + type, callback);
		},
		firstRequest: function(args){
			// summary:
			// 		This allows for special handling for the first request. This is useful for
			//		providing information to disambiguate between the first request and
			//		subsequent long-poll requests so the server can properly setup a
			// 		connection on the first connection or reject a request for an expired
			// 		connection if the request is not expecting to be the first for a connection.
			//		This method can be overriden. The default behavior is to include a Pragma
			//		header with a value of "start-long-poll"
			var headers = (args.headers || (args.headers = {}));
			headers.Pragma = "start-long-poll";
			try{
				return this.transport(args);
			}finally{
				// cleanup the header so it is not used on subsequent requests
				delete headers.Pragma;
			}
		}
	};
	function connect(){
		if(socket.readyState == 0){
			// we fire the open event now because we really don't know when the "socket"
			// is truly open, and this gives us a to do a send() and get it included in the
			// HTTP request
			fire("open",{});
		}
		// make the long-poll connection, to wait for response from the server
		if(!connections.length){
			socket.send();
		}
	}
	function fire(type, object, deferred){
		if(socket["on" + type]){
			var event = document.createEvent("HTMLEvents");
			event.initEvent(type);
			dojo.mixin(event, object);
			event.ioArgs = deferred && deferred.ioArgs;
			socket["on" + type](event);
		}
	}
	// provide an alias for Dojo's connect method
	socket.connect = socket.on;
	// do the initial connection
	setTimeout(connect);
	return socket;
};
return Socket;
});<commit_msg>Removed duplicate "open" event !strict<commit_after>define("dojox/socket", ["dojo", "dojo/cookie"], function(dojo) {

var WebSocket = window.WebSocket;

dojox.socket = Socket;
function Socket(/*dojo.__XhrArgs*/ argsOrUrl){
	// summary:
	//		Provides a simple socket connection using WebSocket, or alternate
	// 		communication mechanisms in legacy browsers for comet-style communication. This is based
	//		on the WebSocket API and returns an object that implements the WebSocket interface:
	//		http://dev.w3.org/html5/websockets/#websocket
	//	description:
	//		Provides socket connections. This can be used with virtually any Comet protocol.
	//	argsOrUrl:
	//		This uses the same arguments as the other I/O functions in Dojo, or a
	// 		URL to connect to. The URL should be a relative URL in order to properly
	//		work with WebSockets (it can still be host relative, like //other-site.org/endpoint)
	// returns:
	// 		An object that implements the WebSocket API
	// example:
	//		| dojo.require("dojox.socket");
	//		| var socket = dojox.socket({"//comet-server/comet");
	//		| // we could also add auto-reconnect support
	//		| // now we can connect to standard HTML5 WebSocket-style events
	//		| dojo.connect(socket, "onmessage", function(event){
	//		|    var message = event.data;
	//		|    // do something with the message
	//		| });
	//		| // send something
	//		| socket.send("hi there");
	//		| whenDone(function(){
	//		|   socket.close();
	//		| });
	//		You can also use the Reconnect module:
	//		| dojo.require("dojox.socket");
	//		| dojo.require("dojox.socket.Reconnect");
	//		| var socket = dojox.socket({url:"/comet"});
	//		| // add auto-reconnect support
	//		| socket = dojox.socket.Reconnect(socket);
	if(typeof argsOrUrl == "string"){
		argsOrUrl = {url: argsOrUrl};
	}
	return WebSocket ? dojox.socket.WebSocket(argsOrUrl) : dojox.socket.LongPoll(argsOrUrl);
};

Socket.WebSocket = function(args){
	// summary:
	//		A wrapper for WebSocket, than handles standard args and relative URLs
	var ws = new WebSocket(new dojo._Url(document.baseURI.replace(/^http/i,'ws'), args.url));
	ws.on = ws.addEventListener;
	var opened;
	dojo.connect(ws, "onopen", function(event){
		opened = true;
	});
	dojo.connect(ws, "onclose", function(event){
		if(opened){
			return;
		}
		WebSocket = null;
		Socket.replace(ws, dojox.socket(args), true);
	});
	return ws;
};
Socket.replace = function(socket, newSocket, listenForOpen){
	// make the original socket a proxy for the new socket
	socket.send = dojo.hitch(newSocket, "send");
	socket.close = dojo.hitch(newSocket, "close");
	if(listenForOpen){
		proxyEvent("open");
	}
	// redirect the events as well
	dojo.forEach(["message", "close", "error"], proxyEvent);
	function proxyEvent(type){
		(newSocket.addEventListener || newSocket.on).call(newSocket, type, function(event){
			socket.dispatchEvent(event);
		});
	}
};
Socket.LongPoll = function(/*dojo.__XhrArgs*/ args){
	// summary:
	//		Provides a simple long-poll based comet-style socket/connection to a server and returns an
	// 		object implementing the WebSocket interface:
	//		http://dev.w3.org/html5/websockets/#websocket
	//	args:
	//		This uses the same arguments as the other I/O functions in Dojo, with this addition:
	//	args.interval:
	//		Indicates the amount of time (in milliseconds) after a response was received
	//		before another request is made. By default, a request is made immediately
	//		after getting a response. The interval can be increased to reduce load on the
	//		server or to do simple time-based polling where the server always responds
	// 		immediately.
	//	args.transport:
	//		Provide an alternate transport like dojo.io.script.get
	// returns:
	// 		An object that implements the WebSocket API
	// example:
	//		| dojo.require("dojox.socket.LongPoll");
	//		| var socket = dojox.socket.LongPoll({url:"/comet"});
	//		or:
	//		| dojo.require("dojox.socket.LongPoll");
	//		| dojox.socket.LongPoll.add();
	//		| var socket = dojox.socket({url:"/comet"});

var cancelled = false,
		first = true,
		timeoutId,
		connections = [];

	// create the socket object
	var socket = {
		send: function(data){
			// summary:
			// 		Send some data using XHR or provided transport
			var sendArgs = dojo.delegate(args);
			sendArgs.rawBody = data;
			clearTimeout(timeoutId);
			var deferred = first ? (first = false) || socket.firstRequest(sendArgs) :
				socket.transport(sendArgs);
			connections.push(deferred);
			deferred.then(function(response){
				// got a response
				socket.readyState = 1;
				// remove the current connection
				connections.splice(dojo.indexOf(connections, deferred), 1);
				// reconnect to listen for the next message if there are no active connections,
				// we queue it up in case one of the onmessage handlers has a message to send
				if(!connections.length){
					timeoutId = setTimeout(connect, args.interval);
				}
				if(response){
					// now send the message along to listeners
					fire("message", {data: response}, deferred);
				}
			}, function(error){
				connections.splice(dojo.indexOf(connections, deferred), 1);
				// an error occurred, fire the appropriate event listeners
				if(!cancelled){
					fire("error", {error:error}, deferred);
					if(!connections.length){
						socket.readyState = 3;
						fire("close", {wasClean:false}, deferred);
					}
				}
			});
			return deferred;
		},
		close: function(){
			// summary:
			// 		Close the connection
			socket.readyState = 2;
			cancelled = true;
			for(var i = 0; i < connections.length; i++){
				connections[i].cancel();
			}
			socket.readyState = 3;
			fire("close", {wasClean:true});
		},
		transport: args.transport || dojo.xhrPost,
		args: args,
		url: args.url,
		readyState: 0,
		CONNECTING: 0,
		OPEN: 1,
		CLOSING: 2,
		CLOSED: 3,
		dispatchEvent: function(event){
			fire(event.type, event);
		},
		on: function(type, callback){
			return dojo.connect(this, "on" + type, callback);
		},
		firstRequest: function(args){
			// summary:
			// 		This allows for special handling for the first request. This is useful for
			//		providing information to disambiguate between the first request and
			//		subsequent long-poll requests so the server can properly setup a
			// 		connection on the first connection or reject a request for an expired
			// 		connection if the request is not expecting to be the first for a connection.
			//		This method can be overriden. The default behavior is to include a Pragma
			//		header with a value of "start-long-poll"
			var headers = (args.headers || (args.headers = {}));
			headers.Pragma = "start-long-poll";
			try{
				return this.transport(args);
			}finally{
				// cleanup the header so it is not used on subsequent requests
				delete headers.Pragma;
			}
		}
	};
	function connect(){
		if(socket.readyState == 0){
			// we fire the open event now because we really don't know when the "socket"
			// is truly open, and this gives us a to do a send() and get it included in the
			// HTTP request
			fire("open",{});
		}
		// make the long-poll connection, to wait for response from the server
		if(!connections.length){
			socket.send();
		}
	}
	function fire(type, object, deferred){
		if(socket["on" + type]){
			var event = document.createEvent("HTMLEvents");
			event.initEvent(type);
			dojo.mixin(event, object);
			event.ioArgs = deferred && deferred.ioArgs;
			socket["on" + type](event);
		}
	}
	// provide an alias for Dojo's connect method
	socket.connect = socket.on;
	// do the initial connection
	setTimeout(connect);
	return socket;
};
return Socket;
});<|endoftext|>


<commit_before>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };

        self.routes['/dev.html'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('dev.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        //self.app = express.createServer();
        // var express = require("express");
        self.app = express();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<commit_msg>added zcache<commit_after>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
        self.zcache['dev.html'] = fs.readFileSync('./dev.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };

        self.routes['/dev.html'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('dev.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        //self.app = express.createServer();
        // var express = require("express");
        self.app = express();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<|endoftext|>


<commit_before><commit_msg>Update DhtmlXQ_www_dpxq_com.js<commit_after><|endoftext|>


<commit_before>import React from 'react'

export default (props) => {
  return (

George Francis

  )
}
<commit_msg>Make header links<commit_after>import React from 'react'
import { Link } from 'react-router'

export default (props) => {
  return (

George Francis

          <Link to='/projects' activeClassName='active-link'>Projects</Link>
          <Link to='/about' activeClassName='active-link'>About</Link>
          <Link to='/contact' activeClassName='active-link'>Contact</Link>

  )
}
<|endoftext|>