<commit_before>import React, {Component, PropTypes} from 'react'
import { Grid, Row, Col, Panel, Button, ButtonToolbar, ButtonGroup, Jumbotron, Badge, FormControl, ListGroup, ListGroupItem, DropdownButton, MenuItem } from 'react-bootstrap'
import Icon from 'react-fa'
import { Link } from 'react-router'
import { LinkContainer } from 'react-router-bootstrap'
import moment from 'moment'
import objectPath from 'object-path'

import ManagerPage from '../../common/components/ManagerPage'
import { getConfigProperty, getComponentMessages, getMessage } from '../../common/util/config'
import { defaultSorter, getProfileLink } from '../../common/util/util'

export default class UserHomePage extends Component {

  static propTypes = {
    user: PropTypes.object,
    projects: PropTypes.array,
    project: PropTypes.object,

    onComponentMount: PropTypes.func,
    logoutHandler: PropTypes.func,
    fetchProjectFeeds: PropTypes.func,

    visibilityFilter: PropTypes.object,
    searchTextChanged: PropTypes.func,
    visibilityFilterChanged: PropTypes.func
  }
  constructor (props) {
    super(props)
    this.state = {}
  }
  componentWillMount () {
    this.props.onComponentMount(this.props)
  }
  componentWillReceiveProps (nextProps) {
    const nextId = objectPath.get(nextProps, 'project.id')
    const id = objectPath.get(this.props, 'project.id')
    if (nextId && nextId !== id) {
      this.props.fetchProjectFeeds(nextProps.project.id)
    }
  }
  componentWillUnmount () {
    this.setState({showLoading: true})
  }
  render () {
    const messages = getComponentMessages('UserHomePage')
    const projectCreationDisabled = !this.props.user.permissions.isApplicationAdmin()
    const feedVisibilityFilter = (feed) => {
      let visible = feed.name.toLowerCase().indexOf((this.props.visibilityFilter.searchText || '').toLowerCase()) !== -1
      switch (this.props.visibilityFilter.filter) {
        case 'ALL':
          return visible
        case 'STARRED':
          return [].indexOf(feed.id) !== -1 // check userMetaData
        case 'PUBLIC':
          return feed.isPublic
        case 'PRIVATE':
          return !feed.isPublic
        default:
          return visible
      }
      // if (feed.isCreating) return true // feeds actively being created are always visible
    }
    const renderFeedItems = (p, fs) => {
      const feedName = `${p.name} / ${fs.name}`
      return (
        <ListGroupItem key={fs.id} bsStyle={fs.isPublic ? 'default' : 'warning'}>
          <Link title={feedName} to={`/feed/${fs.id}`}>
            <Icon className='icon-link' name={fs.isPublic ? 'database' : 'lock'}/>

              {feedName.length > 33 ? `${feedName.substr(0, 33)}...` : feedName}

          </Link>
        </ListGroupItem>
      )
    }
    const visibleProjects = this.props.projects.sort(defaultSorter)
    const activeProject = this.props.project
    const sortByDate = (a, b) => {
      if (a.date  b.date) return -1
      return 0
    }

    return (
      <ManagerPage ref='page'>
        <Grid fluid>
          {this.state.showLoading ? <Icon size='5x' spin name='refresh'/> : null}
          <Row>
            <Col md={8} xs={12}>
              {/* Top Welcome Box */}
              <Jumbotron style={{ padding: 30 }}>

Welcome to {getConfigProperty('application.title')}!

Manage, edit, validate and deploy your data in a streamlined workflow.

                  <ButtonToolbar>
                  <Button bsStyle='primary' bsSize='large' href={getConfigProperty('application.docs_url')}><Icon name='info-circle' /> Take a Tour</Button>
                  <LinkContainer to='/'><Button bsStyle='default' bsSize='large'><Icon name='globe' /> Explore feeds</Button></LinkContainer>
                  </ButtonToolbar>

              </Jumbotron>
              {/* Recent Activity List */}

                  <Icon name='comments-o' /> Recent Activity

                {this.props.user.recentActivity && this.props.user.recentActivity.length
                  ? this.props.user.recentActivity.sort(sortByDate).map(item => renderRecentActivity(item))
                  : No Recent Activity for your subscriptions.
                }
              </Col>

            <Col md={4} xs={12}>
              {/* User Account Info Panel */}
              <Panel>
                <Row>
                <Col xs={12}>

                  <Button className='pull-right' bsSize='small' onClick={() => this.props.logoutHandler()}><Icon name='sign-out'/> Log out</Button>
                  Hello, {this.props.user.profile.nickname}.

                </Col>
                </Row>
                <Row>
                  <Col xs={4}>

                  </Col>
                  <Col md={8}>

<Icon name='user' /> {this.props.user.profile.email}

<Badge className='text-muted'>
                      {this.props.user.permissions.isApplicationAdmin()
                        ? 'Application admin'
                        : 'Standard user'
                      }
                    </Badge>

                      <ButtonToolbar className='pull-right'>
                        <LinkContainer to='/settings/profile'>
                          <Button bsStyle='primary' bsSize='small'>
                            <Icon name='cog' /> Manage account
                          </Button>
                        </LinkContainer>
                        {this.props.user.permissions.isApplicationAdmin()
                          ? <LinkContainer to='/admin/users'>
                              <Button bsStyle='default' bsSize='small'>
                                <Icon name='cog' /> Admin
                              </Button>
                            </LinkContainer>
                          : null
                        }
                      </ButtonToolbar>

                  </Col>
                </Row>
              </Panel>

                {activeProject
                  ? <LinkContainer className='pull-right' to={`/project/${activeProject.id}`}><Button>View {activeProject.name}</Button></LinkContainer>
                  : null
                }
                <DropdownButton
                  title={activeProject
                    ? <Icon name='folder-open-o'/> {activeProject.name}
                    :  {this.props.user.profile.nickname}
                  }
                  // onSelect={(eventKey) => {
                  //   this.props.setActiveProject(eventKey)
                  // }}
                >
                  {activeProject
                    ? [
                      <LinkContainer key='home-link' to={`/home/`}>
                        <MenuItem>
                           {this.props.user.profile.nickname}
                        </MenuItem>
                      </LinkContainer>,
                      <MenuItem key='divider' divider/>
                    ]
                    : null
                  }
                  {visibleProjects.length > 0
                    ? visibleProjects.map((project, index) => {
                      if (activeProject && project.id === activeProject.id) {
                        return null
                      }
                      return (
                        <LinkContainer to={`/home/${project.id}`}>
                          <MenuItem key={project.id} eventKey={project.id}>
                            <Icon name='folder-o'/> {project.name}
                          </MenuItem>
                        </LinkContainer>
                      )
                    })
                    : null
                  }
                  {activeProject && visibleProjects.length > 1 || !activeProject ? <MenuItem divider /> : null}
                  <LinkContainer to='/settings/organizations'><MenuItem><Icon name='users'/> Manage organizations</MenuItem></LinkContainer>
                  <MenuItem divider />
                  <LinkContainer to='/project'><MenuItem><Icon name='plus'/> Create organization</MenuItem></LinkContainer>
                </DropdownButton>

              {/* Starred Feeds Panel */}
              <Panel header={(
Your feeds
)}>
                <ListGroup fill>
                  <ListGroupItem>
                    <FormControl
                      placeholder={getMessage(messages, 'search')}
                      onChange={evt => this.props.searchTextChanged(evt.target.value)}
                    />
                    <ButtonGroup style={{marginTop: 10}} justified>
                      <Button
                        active={this.props.visibilityFilter.filter === 'ALL' || !this.props.visibilityFilter.filter}
                        onClick={() => this.props.visibilityFilterChanged('ALL')}
                        bsSize='xsmall'
                        href='#'>All</Button>
                      <Button
                        active={this.props.visibilityFilter.filter === 'STARRED'}
                        onClick={() => this.props.visibilityFilterChanged('STARRED')}
                        bsSize='xsmall'
                        href='#'>Starred</Button>
                      <Button
                        active={this.props.visibilityFilter.filter === 'PUBLIC'}
                        onClick={() => this.props.visibilityFilterChanged('PUBLIC')}
                        bsSize='xsmall'
                        href='#'>Public</Button>
                      <Button
                        active={this.props.visibilityFilter.filter === 'PRIVATE'}
                        onClick={() => this.props.visibilityFilterChanged('PRIVATE')}
                        bsSize='xsmall'
                        href='#'>Private</Button>
                    </ButtonGroup>
                  </ListGroupItem>
                  {activeProject && activeProject.feedSources
                    ? activeProject.feedSources.filter(feedVisibilityFilter).map(fs => renderFeedItems(activeProject, fs))
                    : <ListGroupItem>
Choose a project to view feed sources
</ListGroupItem>
                      // this.props.projects && this.props.projects.map(p => {
                      //   return p.feedSources && p.feedSources.filter(feedVisibilityFilter).map(fs => renderFeedItems(p, fs))
                      // })
                  }
                </ListGroup>
              </Panel>
            </Col>
          </Row>
        </Grid>
      </ManagerPage>
    )
  }
}

function renderRecentActivity (item) {
  const containerStyle = {
    marginTop: 10,
    paddingBottom: 12,
    borderBottom: '1px solid #ddd'
  }

  const iconStyle = {
    float: 'left',
    fontSize: 20,
    color: '#bbb'
  }

  const dateStyle = {
    color: '#999',
    fontSize: 11,
    marginBottom: 2
  }

  const innerContainerStyle = {
    marginLeft: 36
  }

  const commentStyle = {
    backgroundColor: '#f0f0f0',
    marginTop: 8,
    padding: 8,
    fontSize: 12
  }

  switch (item.type) {
    case 'feed-commented-on':
      return (

            <Icon name='comment' />

{moment(item.date).fromNow()}

{item.userName} commented on feed <Link to={`/feed/${item.targetId}`}>{item.targetName}</Link>:

{item.body}

      )
  }
}
<commit_msg>only fetch feeds if not fetched<commit_after>import React, {Component, PropTypes} from 'react'
import { Grid, Row, Col, Panel, Button, ButtonToolbar, ButtonGroup, Jumbotron, Badge, FormControl, ListGroup, ListGroupItem, DropdownButton, MenuItem } from 'react-bootstrap'
import Icon from 'react-fa'
import { Link } from 'react-router'
import { LinkContainer } from 'react-router-bootstrap'
import moment from 'moment'
import objectPath from 'object-path'

import ManagerPage from '../../common/components/ManagerPage'
import { getConfigProperty, getComponentMessages, getMessage } from '../../common/util/config'
import { defaultSorter, getProfileLink } from '../../common/util/util'

export default class UserHomePage extends Component {

  static propTypes = {
    user: PropTypes.object,
    projects: PropTypes.array,
    project: PropTypes.object,

    onComponentMount: PropTypes.func,
    logoutHandler: PropTypes.func,
    fetchProjectFeeds: PropTypes.func,

    visibilityFilter: PropTypes.object,
    searchTextChanged: PropTypes.func,
    visibilityFilterChanged: PropTypes.func
  }
  constructor (props) {
    super(props)
    this.state = {}
  }
  componentWillMount () {
    this.props.onComponentMount(this.props)
  }
  componentWillReceiveProps (nextProps) {
    const nextId = objectPath.get(nextProps, 'project.id')
    const id = objectPath.get(this.props, 'project.id')
    if (nextId && nextId !== id && !nextProps.project.feedSources) {
      this.props.fetchProjectFeeds(nextProps.project.id)
    }
  }
  componentWillUnmount () {
    this.setState({showLoading: true})
  }
  render () {
    const messages = getComponentMessages('UserHomePage')
    const projectCreationDisabled = !this.props.user.permissions.isApplicationAdmin()
    const feedVisibilityFilter = (feed) => {
      let visible = feed.name.toLowerCase().indexOf((this.props.visibilityFilter.searchText || '').toLowerCase()) !== -1
      switch (this.props.visibilityFilter.filter) {
        case 'ALL':
          return visible
        case 'STARRED':
          return [].indexOf(feed.id) !== -1 // check userMetaData
        case 'PUBLIC':
          return feed.isPublic
        case 'PRIVATE':
          return !feed.isPublic
        default:
          return visible
      }
      // if (feed.isCreating) return true // feeds actively being created are always visible
    }
    const renderFeedItems = (p, fs) => {
      const feedName = `${p.name} / ${fs.name}`
      return (
        <ListGroupItem key={fs.id} bsStyle={fs.isPublic ? 'default' : 'warning'}>
          <Link title={feedName} to={`/feed/${fs.id}`}>
            <Icon className='icon-link' name={fs.isPublic ? 'database' : 'lock'}/>

              {feedName.length > 33 ? `${feedName.substr(0, 33)}...` : feedName}

          </Link>
        </ListGroupItem>
      )
    }
    const visibleProjects = this.props.projects.sort(defaultSorter)
    const activeProject = this.props.project
    const sortByDate = (a, b) => {
      if (a.date  b.date) return -1
      return 0
    }

    return (
      <ManagerPage ref='page'>
        <Grid fluid>
          {this.state.showLoading ? <Icon size='5x' spin name='refresh'/> : null}
          <Row>
            <Col md={8} xs={12}>
              {/* Top Welcome Box */}
              <Jumbotron style={{ padding: 30 }}>

Welcome to {getConfigProperty('application.title')}!

Manage, edit, validate and deploy your data in a streamlined workflow.

                  <ButtonToolbar>
                  <Button bsStyle='primary' bsSize='large' href={getConfigProperty('application.docs_url')}><Icon name='info-circle' /> Take a Tour</Button>
                  <LinkContainer to='/'><Button bsStyle='default' bsSize='large'><Icon name='globe' /> Explore feeds</Button></LinkContainer>
                  </ButtonToolbar>

              </Jumbotron>
              {/* Recent Activity List */}

                  <Icon name='comments-o' /> Recent Activity

                {this.props.user.recentActivity && this.props.user.recentActivity.length
                  ? this.props.user.recentActivity.sort(sortByDate).map(item => renderRecentActivity(item))
                  : No Recent Activity for your subscriptions.
                }
              </Col>

            <Col md={4} xs={12}>
              {/* User Account Info Panel */}
              <Panel>
                <Row>
                <Col xs={12}>

                  <Button className='pull-right' bsSize='small' onClick={() => this.props.logoutHandler()}><Icon name='sign-out'/> Log out</Button>
                  Hello, {this.props.user.profile.nickname}.

                </Col>
                </Row>
                <Row>
                  <Col xs={4}>

                  </Col>
                  <Col md={8}>

<Icon name='user' /> {this.props.user.profile.email}

<Badge className='text-muted'>
                      {this.props.user.permissions.isApplicationAdmin()
                        ? 'Application admin'
                        : 'Standard user'
                      }
                    </Badge>

                      <ButtonToolbar className='pull-right'>
                        <LinkContainer to='/settings/profile'>
                          <Button bsStyle='primary' bsSize='small'>
                            <Icon name='cog' /> Manage account
                          </Button>
                        </LinkContainer>
                        {this.props.user.permissions.isApplicationAdmin()
                          ? <LinkContainer to='/admin/users'>
                              <Button bsStyle='default' bsSize='small'>
                                <Icon name='cog' /> Admin
                              </Button>
                            </LinkContainer>
                          : null
                        }
                      </ButtonToolbar>

                  </Col>
                </Row>
              </Panel>

                {activeProject
                  ? <LinkContainer className='pull-right' to={`/project/${activeProject.id}`}><Button>View {activeProject.name}</Button></LinkContainer>
                  : null
                }
                <DropdownButton
                  title={activeProject
                    ? <Icon name='folder-open-o'/> {activeProject.name}
                    :  {this.props.user.profile.nickname}
                  }
                  // onSelect={(eventKey) => {
                  //   this.props.setActiveProject(eventKey)
                  // }}
                >
                  {activeProject
                    ? [
                      <LinkContainer key='home-link' to={`/home/`}>
                        <MenuItem>
                           {this.props.user.profile.nickname}
                        </MenuItem>
                      </LinkContainer>,
                      <MenuItem key='divider' divider/>
                    ]
                    : null
                  }
                  {visibleProjects.length > 0
                    ? visibleProjects.map((project, index) => {
                      if (activeProject && project.id === activeProject.id) {
                        return null
                      }
                      return (
                        <LinkContainer to={`/home/${project.id}`}>
                          <MenuItem key={project.id} eventKey={project.id}>
                            <Icon name='folder-o'/> {project.name}
                          </MenuItem>
                        </LinkContainer>
                      )
                    })
                    : null
                  }
                  {activeProject && visibleProjects.length > 1 || !activeProject ? <MenuItem divider /> : null}
                  <LinkContainer to='/settings/organizations'><MenuItem><Icon name='users'/> Manage organizations</MenuItem></LinkContainer>
                  <MenuItem divider />
                  <LinkContainer to='/project'><MenuItem><Icon name='plus'/> Create organization</MenuItem></LinkContainer>
                </DropdownButton>

              {/* Starred Feeds Panel */}
              <Panel header={(
Your feeds
)}>
                <ListGroup fill>
                  <ListGroupItem>
                    <FormControl
                      placeholder={getMessage(messages, 'search')}
                      onChange={evt => this.props.searchTextChanged(evt.target.value)}
                    />
                    <ButtonGroup style={{marginTop: 10}} justified>
                      <Button
                        active={this.props.visibilityFilter.filter === 'ALL' || !this.props.visibilityFilter.filter}
                        onClick={() => this.props.visibilityFilterChanged('ALL')}
                        bsSize='xsmall'
                        href='#'>All</Button>
                      <Button
                        active={this.props.visibilityFilter.filter === 'STARRED'}
                        onClick={() => this.props.visibilityFilterChanged('STARRED')}
                        bsSize='xsmall'
                        href='#'>Starred</Button>
                      <Button
                        active={this.props.visibilityFilter.filter === 'PUBLIC'}
                        onClick={() => this.props.visibilityFilterChanged('PUBLIC')}
                        bsSize='xsmall'
                        href='#'>Public</Button>
                      <Button
                        active={this.props.visibilityFilter.filter === 'PRIVATE'}
                        onClick={() => this.props.visibilityFilterChanged('PRIVATE')}
                        bsSize='xsmall'
                        href='#'>Private</Button>
                    </ButtonGroup>
                  </ListGroupItem>
                  {activeProject && activeProject.feedSources
                    ? activeProject.feedSources.filter(feedVisibilityFilter).map(fs => renderFeedItems(activeProject, fs))
                    : <ListGroupItem>
Choose a project to view feeds
</ListGroupItem>
                      // this.props.projects && this.props.projects.map(p => {
                      //   return p.feedSources && p.feedSources.filter(feedVisibilityFilter).map(fs => renderFeedItems(p, fs))
                      // })
                  }
                </ListGroup>
              </Panel>
            </Col>
          </Row>
        </Grid>
      </ManagerPage>
    )
  }
}

function renderRecentActivity (item) {
  const containerStyle = {
    marginTop: 10,
    paddingBottom: 12,
    borderBottom: '1px solid #ddd'
  }

  const iconStyle = {
    float: 'left',
    fontSize: 20,
    color: '#bbb'
  }

  const dateStyle = {
    color: '#999',
    fontSize: 11,
    marginBottom: 2
  }

  const innerContainerStyle = {
    marginLeft: 36
  }

  const commentStyle = {
    backgroundColor: '#f0f0f0',
    marginTop: 8,
    padding: 8,
    fontSize: 12
  }

  switch (item.type) {
    case 'feed-commented-on':
      return (

            <Icon name='comment' />

{moment(item.date).fromNow()}

{item.userName} commented on feed <Link to={`/feed/${item.targetId}`}>{item.targetName}</Link>:

{item.body}

      )
  }
}
<|endoftext|>


<commit_before>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/
/*
 * Copyright (c) 2014, Yahoo! Inc. All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 *
 * Library which supports opening , closing  and listing open sessions
 */

var fs = require("fs");
var util = require("util");
var log4js = require("log4js");
var WdSession = require("../lib/session/wdsession");
var wd = require("../lib/util/wd-wrapper");
var CapabilityManager = require("../lib/util/capabilitymanager");
var logger = log4js.getLogger("selLib");

/**
 *
 * @param config
 * @constructor
 */
function SelLib(config) {
    this.config = config;
    this.hub = new WdSession(config);
}

/**
 *  Build webdriver object based on properties set in webdriverConfObj
 * @param webdriverConfObj
 * @returns webdriver object
 */
SelLib.prototype.buildWebDriver = function(webdriverConfObj) {

    var webdriver;

    if (webdriverConfObj) {

        webdriver = new wd.Builder().
            usingServer(webdriverConfObj.seleniumHost).
            usingSession(webdriverConfObj.sessionId).
            withCapabilities(webdriverConfObj.capabilities).
            build();
    }

    return webdriver;
};

/**
 * Lists the open sessions
 * @param arrSessions
 * @param cb
 */
SelLib.prototype.listSessions = function (arrSessions, cb) {

    if (!arrSessions) {
        logger.info('No sessions found');
        cb();
    }

    if (arrSessions.length > 0) {

        var sessionId = arrSessions[0],
            self = this,
            webdriver,
            webdriverConfObj = {};

        arrSessions.shift();

        // Build webdriver object
        webdriverConfObj.seleniumHost = self.config.seleniumHost;
        webdriverConfObj.sessionId = sessionId;
        webdriver = self.buildWebDriver(webdriverConfObj);

        webdriver.getCapabilities().then(function(sessionCaps) {

            if (sessionCaps) {
                console.log('\n');
                console.log(sessionCaps.toJSON());
            }
            self.listSessions(arrSessions, cb);

        }, function(err) {
            logger.error('Error while listing sessions:' + err);
            self.listSessions(arrSessions, cb);
        });

    } else {
        cb();
    }

};

/**
 * Help !!
 */
SelLib.prototype.listHelp = function () {
    console.info("\nCommandline Options :" + "\n" +
        "--list : Lists all selenium browser sessions" + "\n" +
        "--open=<browser1[, browser2]> : Comma seperated list of browsers to launch" + "\n" +
        "--open=<browser> : browser to choose from capabilities.json" + " --capabilities= path to capabilities.json" + "\n" +
        "--close : Close all selenium controller browser sessions" + "\n\n" +
        "Examples:\n" +
        "Open Firefox and Chrome browser instances:\n" +
        "arrow_selenium --open=firefox,chrome\n"  +
        "Open Firefox with given capabilities:\n" +
        "arrow_selenium --open=firefox --capabilities=./cap.json\n"
        );
};

/**
 *
 * @param capabilities
 * @param browser
 * @returns capability object based on pass capabilities and browser
 */
SelLib.prototype.getCapabilityObject = function(capabilities, browser) {

    var caps,
        cm,
        browserInfo,
        browserName,
        browserVersion;

    if (browser) {

        browserInfo = browser.split("-", 2);
        if (browserInfo.length > 1) {
            browserName = browserInfo[0];
            browserVersion = browserInfo[1];
        } else {
            browserName = browser;
            browserVersion = '';
        }

    }

    // If user has passed capabilities
    if (capabilities) {
        caps = {
            "platform": "ANY",
            "javascriptEnabled": true,
            "seleniumProtocol": "WebDriver"
        };
        caps.browserName = browserName;
        caps.browserVersion = browserVersion;

        if (!caps.browserName) {
            logger.error("No Browser is specified");
            process.exit(1);
        }

        cm = new CapabilityManager();
        capabilities = cm.getCapability(capabilities, caps.browserName);

        if (capabilities === null) {
            logger.error("No related capability for " + caps.browserName + " in " + capabilities);
            process.exit(1);
        }
    } else {
        // default capabilities
        capabilities = {
            "browserName": browserName,
            "version": browserVersion,
            "platform": "ANY",
            "javascriptEnabled": true
        };
    }
    return capabilities;

};

/**
 *
 * @param browserList - Browsers to open
 * @param openBrowserList - Already open browsers
 * @param capabilities - capabilities object
 * @param cb
 */
SelLib.prototype.openBrowsers = function(browserList, openBrowserList, capabilities, cb) {

    var webdriver,
        browserToOpen,
        self = this,
        webdriverConfObj = {},
        caps;

    if (browserList && browserList.length > 0) {

        browserToOpen = browserList[0];

        browserList.shift();

        if (openBrowserList.indexOf(browserToOpen) !== -1) {
            logger.info('Browser ' + browserToOpen + ' is already open');
            self.openBrowsers(browserList, openBrowserList, capabilities, cb);
        } else {
            logger.info('Opening browser..' + browserToOpen);
//            logger.info('capabilities..' + JSON.stringify(capabilities));

            caps = self.getCapabilityObject(capabilities, browserToOpen);
            logger.info('Capabilities::' + JSON.stringify(caps));

            // Build webdriver object
            webdriverConfObj.seleniumHost = self.config.seleniumHost;
            webdriverConfObj.capabilities = caps;

            webdriver = self.buildWebDriver(webdriverConfObj);

            webdriver.getCapabilities().then(function(sessionCaps) {
                console.log(sessionCaps);

                openBrowserList.push(browserToOpen);
                logger.info('Session created for the browser ' + browserToOpen);
                // Open another browser, if asked for
                self.openBrowsers(browserList, openBrowserList, capabilities, cb);

            }, function(err) {
                logger.error('Error encountered while opening browser ' + browserToOpen +  ' - Error :'  + err);
                // Open another browser, if asked for
                self.openBrowsers(browserList, openBrowserList, capabilities, cb);
            });

        }

    } else {
        cb();
    }

};

/**
 * Get browser name for the webdriver object
 * @param webdriver
 * @param cb
 */
SelLib.prototype.getBrowserName = function(webdriver, cb) {

    if (webdriver) {
        webdriver.getCapabilities().then(function(val) {

            if (val) {
                var browserName = val.get("browserName");
                console.log('****browserName..' + JSON.stringify(browserName));
                cb(browserName);
            }

        }, function(err) {
            logger.error('Error in getBrowserName getting browser name :' + err);
            cb();
        });
    } else {
        cb();
    }

};

/**
 *
 * @param arrSessions - Already open sessions
 * @param openBrowserList - List of open browsers
 * @param cb
 */
SelLib.prototype.getListOfOpenBrowsers = function(arrSessions, openBrowserList, cb) {

    var
        webdriver,
        self = this,
        sessionId,
        webdriverConfObj = {};

    if (arrSessions.length === 0) {
        cb(openBrowserList);
    } else {

        sessionId = arrSessions[0];
        arrSessions.shift();

        // Build webdriver object
        webdriverConfObj.seleniumHost = self.config.seleniumHost;
        webdriverConfObj.sessionId = sessionId;
        webdriver = self.buildWebDriver(webdriverConfObj);

        self.getBrowserName(webdriver, function(browserName) {
            if (browserName) {
                openBrowserList.push(browserName);
            }
            self.getListOfOpenBrowsers(arrSessions, openBrowserList, cb);
        });
    }
};

/**
 *
 * @param arrSessions
 * @param cb
 */
SelLib.prototype.closeBrowsers = function (arrSessions, cb) {

    var
        sessionId,
        self = this,
        webdriver,
        webdriverConfObj = {};

    if (arrSessions) {

        if (arrSessions.length === 0) {
            cb();
        } else {

            sessionId = arrSessions[0];
            arrSessions.shift();

            // Build webdriver object
            webdriverConfObj.seleniumHost = self.config.seleniumHost;
            webdriverConfObj.sessionId = sessionId;
            webdriver = self.buildWebDriver(webdriverConfObj);

            logger.info("Killing Session ID :" + sessionId);

            webdriver.quit().then(function() {
                self.closeBrowsers(arrSessions, cb);
            }, function(err) {
                logger.info("Error in Killing Session ID :" + sessionId + " , error :" + err);
                self.closeBrowsers(arrSessions, cb);
            });

        }

    }

};

/**
 *
 * @param browsers - comma separated list of arguments to --open e.g firefox,chrome
 * @param capabilities - passed by the user
 */
SelLib.prototype.open = function (browsers, capabilities, cb) {

    var self = this;

    self.hub.getSessions(function (error, arrSessions) {

        if (error) {
            logger.info('Error:' + error);
            if (cb) {
                cb(error);
            }
        } else {
            var browserList = browsers.split(","),
                openBrowserList = [];

            if (arrSessions) {
                logger.info("Found " + arrSessions.length + " browsers.");
            }
            self.getListOfOpenBrowsers(arrSessions, openBrowserList, function(openBrowserList) {

                self.openBrowsers(browserList, openBrowserList, capabilities, function() {
                    logger.info('Done opening all browsers...' + browsers.split(","));

                    if (cb) {
                        cb();
                    }
                });

            });

        }

    }, true);

};

/**
 * Close all open browsers
 */
SelLib.prototype.close = function (cb) {
    var self = this;
    self.hub.getSessions(function (error, arrSessions) {

        if (error) {
            logger.info(error);
        } else if (arrSessions && arrSessions.length > 0) {

            logger.info("Found " + arrSessions.length + " browsers.");
            self.closeBrowsers(arrSessions, function() {
                logger.info('Closed all open browsers on host ' + self.config.seleniumHost);
                if (cb) {
                    cb();
                }
            });
        }
    });

};

/**
 * List all open sessions
 */
SelLib.prototype.list = function () {

    var self = this;
    self.hub.getSessions(function (error, arrSessions) {
        if (error) {
            logger.info(error);
        } else {
            self.listSessions(arrSessions, function() {
                logger.info('Listed all sessions');
            });
        }
    }, false);

};

module.exports = SelLib;<commit_msg>Cleanup<commit_after>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/
/*
 * Copyright (c) 2014, Yahoo! Inc. All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 *
 * Library which supports opening , closing  and listing open sessions
 */

var fs = require("fs");
var util = require("util");
var log4js = require("log4js");
var WdSession = require("../lib/session/wdsession");
var wd = require("../lib/util/wd-wrapper");
var CapabilityManager = require("../lib/util/capabilitymanager");
var logger = log4js.getLogger("selLib");

/**
 *
 * @param config
 * @constructor
 */
function SelLib(config) {
    this.config = config;
    this.hub = new WdSession(config);
}

/**
 *  Build webdriver object based on properties set in webdriverConfObj
 * @param webdriverConfObj
 * @returns webdriver object
 */
SelLib.prototype.buildWebDriver = function(webdriverConfObj) {

    var webdriver;

    if (webdriverConfObj) {

        webdriver = new wd.Builder().
            usingServer(webdriverConfObj.seleniumHost).
            usingSession(webdriverConfObj.sessionId).
            withCapabilities(webdriverConfObj.capabilities).
            build();
    }

    return webdriver;
};

/**
 * Lists the open sessions
 * @param arrSessions
 * @param cb
 */
SelLib.prototype.listSessions = function (arrSessions, cb) {

    if (!arrSessions) {
        logger.info('No sessions found');
        cb();
    }

    if (arrSessions.length > 0) {

        var sessionId = arrSessions[0],
            self = this,
            webdriver,
            webdriverConfObj = {};

        arrSessions.shift();

        // Build webdriver object
        webdriverConfObj.seleniumHost = self.config.seleniumHost;
        webdriverConfObj.sessionId = sessionId;
        webdriver = self.buildWebDriver(webdriverConfObj);

        webdriver.getCapabilities().then(function(sessionCaps) {

            if (sessionCaps) {
                console.log('\n');
                console.log(sessionCaps.toJSON());
            }
            self.listSessions(arrSessions, cb);

        }, function(err) {
            logger.error('Error while listing sessions:' + err);
            self.listSessions(arrSessions, cb);
        });

    } else {
        cb();
    }

};

/**
 * Help !!
 */
SelLib.prototype.listHelp = function () {
    console.info("\nCommandline Options :" + "\n" +
        "--list : Lists all selenium browser sessions" + "\n" +
        "--open=<browser1[, browser2]> : Comma seperated list of browsers to launch" + "\n" +
        "--open=<browser> : browser to choose from capabilities.json" + " --capabilities= path to capabilities.json" + "\n" +
        "--close : Close all selenium controller browser sessions" + "\n\n" +
        "Examples:\n" +
        "Open Firefox and Chrome browser instances:\n" +
        "arrow_selenium --open=firefox,chrome\n"  +
        "Open Firefox with given capabilities:\n" +
        "arrow_selenium --open=firefox --capabilities=./cap.json\n"
        );
};

/**
 *
 * @param capabilities
 * @param browser
 * @returns capability object based on pass capabilities and browser
 */
SelLib.prototype.getCapabilityObject = function(capabilities, browser) {

    var caps,
        cm,
        browserInfo,
        browserName,
        browserVersion;

    if (browser) {

        browserInfo = browser.split("-", 2);
        if (browserInfo.length > 1) {
            browserName = browserInfo[0];
            browserVersion = browserInfo[1];
        } else {
            browserName = browser;
            browserVersion = '';
        }

    }

    // If user has passed capabilities
    if (capabilities) {
        caps = {
            "platform": "ANY",
            "javascriptEnabled": true,
            "seleniumProtocol": "WebDriver"
        };
        caps.browserName = browserName;
        caps.browserVersion = browserVersion;

        if (!caps.browserName) {
            logger.error("No Browser is specified");
            process.exit(1);
        }

        cm = new CapabilityManager();
        capabilities = cm.getCapability(capabilities, caps.browserName);

        if (capabilities === null) {
            logger.error("No related capability for " + caps.browserName + " in " + capabilities);
            process.exit(1);
        }
    } else {
        // default capabilities
        capabilities = {
            "browserName": browserName,
            "version": browserVersion,
            "platform": "ANY",
            "javascriptEnabled": true
        };
    }
    return capabilities;

};

/**
 *
 * @param browserList - Browsers to open
 * @param openBrowserList - Already open browsers
 * @param capabilities - capabilities object
 * @param cb
 */
SelLib.prototype.openBrowsers = function(browserList, openBrowserList, capabilities, cb) {

    var webdriver,
        browserToOpen,
        self = this,
        webdriverConfObj = {},
        caps;

    if (browserList && browserList.length > 0) {

        browserToOpen = browserList[0];

        browserList.shift();

        if (openBrowserList.indexOf(browserToOpen) !== -1) {
            logger.info('Browser ' + browserToOpen + ' is already open');
            self.openBrowsers(browserList, openBrowserList, capabilities, cb);
        } else {
            logger.info('Opening browser..' + browserToOpen);
//            logger.info('capabilities..' + JSON.stringify(capabilities));

            caps = self.getCapabilityObject(capabilities, browserToOpen);
            logger.info('Capabilities::' + JSON.stringify(caps));

            // Build webdriver object
            webdriverConfObj.seleniumHost = self.config.seleniumHost;
            webdriverConfObj.capabilities = caps;

            webdriver = self.buildWebDriver(webdriverConfObj);

            webdriver.getCapabilities().then(function(sessionCaps) {
                console.log(sessionCaps);

                openBrowserList.push(browserToOpen);
                logger.info('Session created for the browser ' + browserToOpen);
                // Open another browser, if asked for
                self.openBrowsers(browserList, openBrowserList, capabilities, cb);

            }, function(err) {
                logger.error('Error encountered while opening browser ' + browserToOpen +  ' - Error :'  + err);
                // Open another browser, if asked for
                self.openBrowsers(browserList, openBrowserList, capabilities, cb);
            });

        }

    } else {
        cb();
    }

};

/**
 * Get browser name for the webdriver object
 * @param webdriver
 * @param cb
 */
SelLib.prototype.getBrowserName = function(webdriver, cb) {

    if (webdriver) {
        webdriver.getCapabilities().then(function(val) {

            if (val) {
                var browserName = val.get("browserName");
                cb(browserName);
            }

        }, function(err) {
            logger.error('Error in getBrowserName getting browser name :' + err);
            cb();
        });
    } else {
        cb();
    }

};

/**
 *
 * @param arrSessions - Already open sessions
 * @param openBrowserList - List of open browsers
 * @param cb
 */
SelLib.prototype.getListOfOpenBrowsers = function(arrSessions, openBrowserList, cb) {

    var
        webdriver,
        self = this,
        sessionId,
        webdriverConfObj = {};

    if (arrSessions.length === 0) {
        cb(openBrowserList);
    } else {

        sessionId = arrSessions[0];
        arrSessions.shift();

        // Build webdriver object
        webdriverConfObj.seleniumHost = self.config.seleniumHost;
        webdriverConfObj.sessionId = sessionId;
        webdriver = self.buildWebDriver(webdriverConfObj);

        self.getBrowserName(webdriver, function(browserName) {
            if (browserName) {
                openBrowserList.push(browserName);
            }
            self.getListOfOpenBrowsers(arrSessions, openBrowserList, cb);
        });
    }
};

/**
 *
 * @param arrSessions
 * @param cb
 */
SelLib.prototype.closeBrowsers = function (arrSessions, cb) {

    var
        sessionId,
        self = this,
        webdriver,
        webdriverConfObj = {};

    if (arrSessions) {

        if (arrSessions.length === 0) {
            cb();
        } else {

            sessionId = arrSessions[0];
            arrSessions.shift();

            // Build webdriver object
            webdriverConfObj.seleniumHost = self.config.seleniumHost;
            webdriverConfObj.sessionId = sessionId;
            webdriver = self.buildWebDriver(webdriverConfObj);

            logger.info("Killing Session ID :" + sessionId);

            webdriver.quit().then(function() {
                self.closeBrowsers(arrSessions, cb);
            }, function(err) {
                logger.info("Error in Killing Session ID :" + sessionId + " , error :" + err);
                self.closeBrowsers(arrSessions, cb);
            });

        }

    }

};

/**
 *
 * @param browsers - comma separated list of arguments to --open e.g firefox,chrome
 * @param capabilities - passed by the user
 */
SelLib.prototype.open = function (browsers, capabilities, cb) {

    var self = this;

    self.hub.getSessions(function (error, arrSessions) {

        if (error) {
            logger.info('Error:' + error);
            if (cb) {
                cb(error);
            }
        } else {
            var browserList = browsers.split(","),
                openBrowserList = [];

            if (arrSessions) {
                logger.info("Found " + arrSessions.length + " browsers.");
            }
            self.getListOfOpenBrowsers(arrSessions, openBrowserList, function(openBrowserList) {

                self.openBrowsers(browserList, openBrowserList, capabilities, function() {
                    logger.info('Done opening all browsers...' + browsers.split(","));

                    if (cb) {
                        cb();
                    }
                });

            });

        }

    }, true);

};

/**
 * Close all open browsers
 */
SelLib.prototype.close = function (cb) {
    var self = this;
    self.hub.getSessions(function (error, arrSessions) {

        if (error) {
            logger.info(error);
        } else if (arrSessions && arrSessions.length > 0) {

            logger.info("Found " + arrSessions.length + " browsers.");
            self.closeBrowsers(arrSessions, function() {
                logger.info('Closed all open browsers on host ' + self.config.seleniumHost);
                if (cb) {
                    cb();
                }
            });
        }
    });

};

/**
 * List all open sessions
 */
SelLib.prototype.list = function () {

    var self = this;
    self.hub.getSessions(function (error, arrSessions) {
        if (error) {
            logger.info(error);
        } else {
            self.listSessions(arrSessions, function() {
                logger.info('Listed all sessions');
            });
        }
    }, false);

};

module.exports = SelLib;<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	config: {}

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		this.initMyAccount();
	} // init()

, initMyAccount: function() {
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		$('body').on('click', '#spl-update-email', function(e) {
			e.preventDefault();

			console.log( $(this).val() );
		});

  } // initMyAccount();

};
<commit_msg>profile<commit_after>// account.js

var org = {

	// added on script load
	config: {}

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		this.initMyAccount();
	} // init()

, initMyAccount: function() {
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		/*
		// this is the input field
		$('body').on('click', '#spl-update-email', function(e) {
			e.preventDefault();

			console.log( $(this).val() );
		});
		*/

  } // initMyAccount();

};
<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/request/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		this.setUser();

		// init ui
		this.initRequestItem();

	} // init()

, setUser: function(user) {
		if ( !ORG.user ) {
			ORG.setUser(user);
		}
		this.user = ORG.user;
}

, initRequestItem: function() {

		/*
		$('body').on('change', 'input:radio[name = "spl-form[material]"]', function() {
			var materialTypeDescription = $(this).parent().text();
			console.log(materialTypeDescription);
		});
		*/

		// hide material type selectors and generic request form on select
		$('body').on('show.bs.collapse', '#spl-form-request-panels', function() {
			$('#spl-form-request-panel-choose').collapse('hide');
			//$('#spl-form-panel-request').collapse('hide');
			$('#spl-form-panel-request').collapse('show');

			$('#spl-form-request-submit-item').collapse('hide');
			$('#spl-form-request-submit-download').collapse('hide');
		});

		// show generic request form when requested
		$('body').on('shown.bs.collapse', '.spl-form-request-generic', function() {
			//$('#spl-form-panel-request').collapse('show');
			$('#spl-form-request-submit-item').collapse('show');
		});

		// hide generic request form when not requested
		$('body').on('shown.bs.collapse', '.spl-form-request-specific', function() {
			$('#spl-form-panel-request').collapse('hide');
		});

		$('body').on('shown.bs.collapse', '.spl-form-request-download', function() {
			$('#spl-form-request-submit-download').collapse('show');
		});

  } // initRequestItem()

};
<commit_msg>request<commit_after>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/request/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		this.setUser();

		// init ui
		this.initRequestItem();

	} // init()

, setUser: function(user) {
		if ( !ORG.user ) {
			ORG.setUser(user);
		}
		this.user = ORG.user;
}

, initRequestItem: function() {

		/*
		$('body').on('change', 'input:radio[name = "spl-form[material]"]', function() {
			var materialTypeDescription = $(this).parent().text();
			console.log(materialTypeDescription);
		});
		*/

		// hide material type selectors and generic request form on select
		$('body').on('show.bs.collapse', '#spl-form-request-panels', function() {
			$('#spl-form-request-panel-choose').collapse('hide');
			//$('#spl-form-panel-request').collapse('hide');
			$('#spl-form-panel-request').collapse('show');

			$('#spl-form-request-submit-item').collapse('show');
			$('#spl-form-request-submit-download').collapse('hide');
		});

		/*
		// show generic request form when requested
		$('body').on('shown.bs.collapse', '.spl-form-request-generic', function() {
			//$('#spl-form-panel-request').collapse('show');
		});
		*/

		// hide generic request form when not requested
		$('body').on('shown.bs.collapse', '.spl-form-request-specific', function() {
			$('#spl-form-panel-request').collapse('hide');
		});

		$('body').on('shown.bs.collapse', '.spl-form-request-download', function() {
			$('#spl-form-request-submit-item').collapse('hide');
			$('#spl-form-request-submit-download').collapse('show');
		});

  } // initRequestItem()

};
<|endoftext|>


<commit_before>QUnit.config.reorder = false;

test("List creation", function () {
    var list = new W.List();
    ok(list, "created");
});

var list = new W.List();
var obj1 = {cid:1};
var obj2 = {cid:2};
var obj3 = {cid:3};
var obj4 = {cid:4};

test("Length", function () {
    equal(list.length, 0, "Zero length");
    equal(list.append(obj1), list, "Simple append returns the list");
    equal(list.length, 1, "One length");
    equal(list.append(obj2).append(obj3), list, "Chained appened returns the list");
    equal(list.length, 3, "Three length");
    list.append(obj4);
    equal(list.length, 4, "Four length");
});

test("Remove", function () {
    equal(list.remove(obj3).length, 3, "Removed");
    equal(list.remove(obj4).length, 2, "Removed again");
});

var objAfter = {cid:100};
test("Insert after", function () {
    var objAfterThat = {cid:101};
    equal(list.append({cid:102}).length, 3, "Simple append returns the list");
    equal(list.append(objAfter).length, 4, "Simple append returns the list");
    equal(list.append({cid:103}).length, 5, "Simple append returns the list");
    equal(list.append({cid:104}).length, 6, "Simple append returns the list");
    equal(list.insertAfter(objAfter, objAfterThat).length, 7, "Insert after bumps length");
    equal(objAfter.next, objAfterThat, "right order");
    equal(objAfterThat.prev, objAfter, "right order");
});

test("at", function () {
    equal(list.at(1000), false, "couldn't find to big index");
    deepEqual(list.at(0).cid, obj1.cid, "zero index ok");
    deepEqual(list.at(1).cid, obj2.cid, "three index ok");
    deepEqual(list.at(3).cid, objAfter.cid, "three index ok");
});

test("each", function () {
    // flaky test
    var counter = 0;
    list.each(function (node, i) {
        console.log(node, i);
        counter += node.cid;
    }, this);
    equal(counter, 513, "executes on each");
});<commit_msg>Removed console.log<commit_after>QUnit.config.reorder = false;

test("List creation", function () {
    var list = new W.List();
    ok(list, "created");
});

var list = new W.List();
var obj1 = {cid:1};
var obj2 = {cid:2};
var obj3 = {cid:3};
var obj4 = {cid:4};

test("Length", function () {
    equal(list.length, 0, "Zero length");
    equal(list.append(obj1), list, "Simple append returns the list");
    equal(list.length, 1, "One length");
    equal(list.append(obj2).append(obj3), list, "Chained appened returns the list");
    equal(list.length, 3, "Three length");
    list.append(obj4);
    equal(list.length, 4, "Four length");
});

test("Remove", function () {
    equal(list.remove(obj3).length, 3, "Removed");
    equal(list.remove(obj4).length, 2, "Removed again");
});

var objAfter = {cid:100};
test("Insert after", function () {
    var objAfterThat = {cid:101};
    equal(list.append({cid:102}).length, 3, "Simple append returns the list");
    equal(list.append(objAfter).length, 4, "Simple append returns the list");
    equal(list.append({cid:103}).length, 5, "Simple append returns the list");
    equal(list.append({cid:104}).length, 6, "Simple append returns the list");
    equal(list.insertAfter(objAfter, objAfterThat).length, 7, "Insert after bumps length");
    equal(objAfter.next, objAfterThat, "right order");
    equal(objAfterThat.prev, objAfter, "right order");
});

test("at", function () {
    equal(list.at(1000), false, "couldn't find to big index");
    deepEqual(list.at(0).cid, obj1.cid, "zero index ok");
    deepEqual(list.at(1).cid, obj2.cid, "three index ok");
    deepEqual(list.at(3).cid, objAfter.cid, "three index ok");
});

test("each", function () {
    // flaky test
    var counter = 0;
    list.each(function (node, i) {
        counter += node.cid;
    }, this);
    equal(counter, 513, "executes on each");
});<|endoftext|>


<commit_before>// Inspired by https://bl.ocks.org/mbostock/4060954
import React, { Component, PureComponent } from 'react'
import { Motion } from '../../../src'
import Demo from '../Demo'
import { scaleLinear } from 'd3-scale'
import { min, max } from 'd3-array'
import { randomUniform } from 'd3-random'
const WOBBLY_SPRING = { stiffness: 60, damping: 15 }

const radiusGenerator = randomUniform(2, 8)
function randomRadius () {
  return radiusGenerator()
}

const width = 800
const height = 450

class Scatterplot extends PureComponent {
  render () {
    const { points } = this.props
    const maxY = max(points, d => d[1])
    const minY = min(points, d => d[1])
    const maxX = max(points, d => d[0])
    const xScale = scaleLinear().domain([0, maxX]).range([0, width])
    const yScale = scaleLinear().domain([minY, maxY]).range([height, 0])

    return (
      <svg
        viewBox={`0 0 ${width} ${height}`}
        width={width}
        height={height}
        style={{ width: '100%', height: '100%' }}
      >
        <Layer
          data={points}
          xScale={xScale}
          yScale={yScale}
          minY={minY}
          maxY={maxY}
          maxX={maxX}
        />
      </svg>
    )
  }
}

class Layer extends Component {
  render () {
    return (
      <Motion
        data={this.props.data}
        component={<g />}
        getKey={this.getKey}
        onComponentMount={this.onCpm}
        onRender={this.onRender}
        onRemount={this.onRe}
        onUnmount={this.onUn}
        render={this.renderCircle}
      />
    )
  }

  getKey = (data, i) => i + '-' + (randomUniform(1, 2)() | 0);

  onCpm = (data, i) => {
    return {
      opacity: 0,
      r: 0,
      x: this.props.xScale(0),
      y: this.props.yScale(i % 2 ? this.props.maxY : 0)
    }
  };

  onRender = (data, i, spring) => {
    return {
      opacity: spring(1),
      r: spring(data.radius),
      x: spring(this.props.xScale(data[0]), WOBBLY_SPRING),
      y: spring(this.props.yScale(data[1]), WOBBLY_SPRING)
    }
  };

  onRe = ({ key, data, style }, i) => {
    return {
      opacity: 0,
      r: 0,
      x: this.props.xScale(0),
      y: this.props.yScale(i % 2 ? this.props.maxY : 0)
    }
  };

  onUn = ({ key, data, style }, spring) => {
    return {
      opacity: spring(0),
      r: spring(0),
      x: spring(this.props.xScale(this.props.maxX), WOBBLY_SPRING),
      y: spring(this.props.yScale(this.props.minY), WOBBLY_SPRING)
    }
  };

  renderCircle = (key, data, style, dataIndex) => {
    return (
      <circle
        key={key}
        r={style.r}
        cx={style.x}
        cy={style.y}
        fill={`hsl(${dataIndex % 360}, 100%, 71%)`}
        fillOpacity={style.opacity}
      />
    )
  };
}

export default class extends Component {
  constructor (props) {
    super(props)

    this.state = {
      points: this.generateLayers(5)
    }
  }

  componentDidMount () {
    this.interval = window.setInterval(
      () => {
        return this.setState({ points: this.generateLayers(randomUniform(1, 360)() | 0) })
      },
      1000
    )
  }

  componentWillUnmount () {
    window.clearInterval(this.interval)
  }

  render () {
    return (
      <Demo>

          {`Animating ${this.state.points.length} circle elements`}

        <Scatterplot points={this.state.points} />
      </Demo>
    )
  }

  generateLayers = itemCount => {
    let points = []
    for (let i = itemCount; i > -1; i--) {
      points[i] = [i, Math.random() * 100 | 0]
      points[i].radius = randomRadius()
    }

    return points
  };
}

const buttonStyle = {
  position: 'absolute',
  top: 8,
  right: 8,
  backgroundColor: 'transparent',
  color: '#37b24d',
  fontWeight: 'bold',
  borderRadius: 4,
  height: 32,
  lineHeight: 2.5,
  paddingLeft: 16,
  paddingRight: 16,
  outline: 'none'
}
<commit_msg>1000 element max<commit_after>// Inspired by https://bl.ocks.org/mbostock/4060954
import React, { Component, PureComponent } from 'react'
import { Motion } from '../../../src'
import Demo from '../Demo'
import { scaleLinear } from 'd3-scale'
import { min, max } from 'd3-array'
import { randomUniform } from 'd3-random'
const WOBBLY_SPRING = { stiffness: 60, damping: 15 }

const radiusGenerator = randomUniform(2, 8)
function randomRadius () {
  return radiusGenerator()
}

const width = 800
const height = 450

class Scatterplot extends PureComponent {
  render () {
    const { points } = this.props
    const maxY = max(points, d => d[1])
    const minY = min(points, d => d[1])
    const maxX = max(points, d => d[0])
    const xScale = scaleLinear().domain([0, maxX]).range([0, width])
    const yScale = scaleLinear().domain([minY, maxY]).range([height, 0])

    return (
      <svg
        viewBox={`0 0 ${width} ${height}`}
        width={width}
        height={height}
        style={{ width: '100%', height: '100%' }}
      >
        <Layer
          data={points}
          xScale={xScale}
          yScale={yScale}
          minY={minY}
          maxY={maxY}
          maxX={maxX}
        />
      </svg>
    )
  }
}

class Layer extends Component {
  render () {
    return (
      <Motion
        data={this.props.data}
        component={<g />}
        getKey={this.getKey}
        onComponentMount={this.onCpm}
        onRender={this.onRender}
        onRemount={this.onRe}
        onUnmount={this.onUn}
        render={this.renderCircle}
      />
    )
  }

  getKey = (data, i) => i + '-' + (randomUniform(1, 2)() | 0);

  onCpm = (data, i) => {
    return {
      opacity: 0,
      r: 0,
      x: this.props.xScale(0),
      y: this.props.yScale(i % 2 ? this.props.maxY : 0)
    }
  };

  onRender = (data, i, spring) => {
    return {
      opacity: spring(1),
      r: spring(data.radius),
      x: spring(this.props.xScale(data[0]), WOBBLY_SPRING),
      y: spring(this.props.yScale(data[1]), WOBBLY_SPRING)
    }
  };

  onRe = ({ key, data, style }, i) => {
    return {
      opacity: 0,
      r: 0,
      x: this.props.xScale(0),
      y: this.props.yScale(i % 2 ? this.props.maxY : 0)
    }
  };

  onUn = ({ key, data, style }, spring) => {
    return {
      opacity: spring(0),
      r: spring(0),
      x: spring(this.props.xScale(this.props.maxX), WOBBLY_SPRING),
      y: spring(this.props.yScale(this.props.minY), WOBBLY_SPRING)
    }
  };

  renderCircle = (key, data, style, dataIndex) => {
    return (
      <circle
        key={key}
        r={style.r}
        cx={style.x}
        cy={style.y}
        fill={`hsl(${dataIndex % 360}, 100%, 71%)`}
        fillOpacity={style.opacity}
      />
    )
  };
}

export default class extends Component {
  constructor (props) {
    super(props)

    this.state = {
      points: this.generateLayers(5)
    }
  }

  componentDidMount () {
    this.interval = window.setInterval(
      () => {
        return this.setState({ points: this.generateLayers(randomUniform(1, 1000)() | 0) })
      },
      1000
    )
  }

  componentWillUnmount () {
    window.clearInterval(this.interval)
  }

  render () {
    return (
      <Demo>

          {`Animating ${this.state.points.length} circle elements`}

        <Scatterplot points={this.state.points} />
      </Demo>
    )
  }

  generateLayers = itemCount => {
    let points = []
    for (let i = itemCount; i > -1; i--) {
      points[i] = [i, Math.random() * 100 | 0]
      points[i].radius = randomRadius()
    }

    return points
  };
}

const buttonStyle = {
  position: 'absolute',
  top: 8,
  right: 8,
  backgroundColor: 'transparent',
  color: '#37b24d',
  fontWeight: 'bold',
  borderRadius: 4,
  height: 32,
  lineHeight: 2.5,
  paddingLeft: 16,
  paddingRight: 16,
  outline: 'none'
}
<|endoftext|>


<commit_before>UniAnyJoin = new UniCollection('anyJoin');

UniAnyJoin.TYPE_JOIN_REQUEST = 'join_request'; // first must be sent request, moderator accept members
UniAnyJoin.TYPE_JOIN_INVITATION = 'join_invitation'; // only invited can join
UniAnyJoin.TYPE_JOIN_OPEN = 'join_open'; // everyone, who sees can join

UniAnyJoin.STATUS_JOINED = 'joined'; //already joined
UniAnyJoin.STATUS_INVITED = 'invited'; //sent invited
UniAnyJoin.STATUS_REQUESTED = 'requested'; // sent request
UniAnyJoin.STATUS_REJECTED = 'rejected'; // sent request

UniAnyJoin.setSchema(new SimpleSchema({
        joiningName: {
            type: String
        },
        subjectId: {
            type: String
        },
        subjectCollectionName: {
            type: String
        },
        possessorId: {
            type: String
        },
        status: {
            type: String,
            allowedValues: [
                UniAnyJoin.STATUS_JOINED,
                UniAnyJoin.STATUS_INVITED,
                UniAnyJoin.STATUS_REQUESTED,
                UniAnyJoin.STATUS_REJECTED
            ]
        },
        type: {
            type: String,
            allowedValues: [
                UniAnyJoin.TYPE_JOIN_REQUEST,
                UniAnyJoin.TYPE_JOIN_INVITATION,
                UniAnyJoin.TYPE_JOIN_OPEN
            ]
        },
        originatorId: {
            type: String,
            autoValue: function () {
                if (this.isInsert || this.isUpsert) {
                    return this.value || this.userId;
                }
            },
            denyUpdate: true,
            optional: true
        },
        createdAt: {
            type: Date,
            autoValue: function () {
                if (this.isInsert) {
                    return new Date();
                }
            },
            optional: true
        },
        acceptorId: {
            type: String,
            optional: true
        }
    })
);

UniAnyJoin.setDefaultSort({createdAt: -1});

UniAnyJoin.allow({
    publish: function (userId, doc, publicationName) {
        return userId;
    }
});

var _no = function () {
    "use strict";
    return true;
};

UniAnyJoin.deny({
    insert: _no,
    update: _no,
    remove: _no
});

UniAnyJoin._collections = {};

/**
 * Return registered joinable collection
 * @param name name of collection
 * @returns {UniCollection#}
 */
UniAnyJoin.getSubjectCollection = function (name) {
    "use strict";
    return name && UniAnyJoin._collections[name];
};

UniAnyJoin.helpers({
    getSubject: function (options) {
        "use strict";
        var coll = UniAnyJoin.getSubjectCollection(this.subjectCollectionName);
        var doc = coll.findOne({_id: this.subjectId}, options || {});
        return coll.ensureUniDoc(doc);
    },
    getSubjectCollection: function () {
        "use strict";
        return UniAnyJoin.getSubjectCollection(this.subjectCollectionName);
    },
    getPossessorOfEntry: function (options) {
        "use strict";
        return UniUsers.findOne({_id: this.possessorId}, options || {});
    },
    getOriginatorOfEntry: function (options) {
        "use strict";
        return this.originatorId && UniUsers.findOne({_id: this.originatorId}, options || {});
    },
    getAcceptorOfEntry: function (options) {
        "use strict";
        return this.acceptorId && UniUsers.findOne({_id: this.acceptorId}, options || {});
    }
});<commit_msg>fix for universe<commit_after>UniAnyJoin = new UniCollection('anyJoin');

UniAnyJoin.TYPE_JOIN_REQUEST = 'join_request'; // first must be sent request, moderator accept members
UniAnyJoin.TYPE_JOIN_INVITATION = 'join_invitation'; // only invited can join
UniAnyJoin.TYPE_JOIN_OPEN = 'join_open'; // everyone, who sees can join

UniAnyJoin.STATUS_JOINED = 'joined'; //already joined
UniAnyJoin.STATUS_INVITED = 'invited'; //sent invited
UniAnyJoin.STATUS_REQUESTED = 'requested'; // sent request
UniAnyJoin.STATUS_REJECTED = 'rejected'; // sent request

UniAnyJoin.setSchema(new SimpleSchema({
        joiningName: {
            type: String
        },
        subjectId: {
            type: String
        },
        subjectCollectionName: {
            type: String
        },
        possessorId: {
            type: String
        },
        status: {
            type: String,
            allowedValues: [
                UniAnyJoin.STATUS_JOINED,
                UniAnyJoin.STATUS_INVITED,
                UniAnyJoin.STATUS_REQUESTED,
                UniAnyJoin.STATUS_REJECTED
            ]
        },
        type: {
            type: String,
            allowedValues: [
                UniAnyJoin.TYPE_JOIN_REQUEST,
                UniAnyJoin.TYPE_JOIN_INVITATION,
                UniAnyJoin.TYPE_JOIN_OPEN
            ]
        },
        originatorId: {
            type: String,
            autoValue: function () {
                if (this.isInsert || this.isUpsert) {
                    return this.value || this.userId;
                }
                this.value = undefined;
                this.unset();
            },
            optional: true
        },
        createdAt: {
            type: Date,
            autoValue: function () {
                if (this.isInsert) {
                    return new Date();
                }
            },
            optional: true
        },
        acceptorId: {
            type: String,
            optional: true
        }
    })
);

UniAnyJoin.setDefaultSort({createdAt: -1});

UniAnyJoin.allow({
    publish: function (userId, doc, publicationName) {
        return userId;
    }
});

var _no = function () {
    "use strict";
    return true;
};

UniAnyJoin.deny({
    insert: _no,
    update: _no,
    remove: _no
});

UniAnyJoin._collections = {};

/**
 * Return registered joinable collection
 * @param name name of collection
 * @returns {UniCollection#}
 */
UniAnyJoin.getSubjectCollection = function (name) {
    "use strict";
    return name && UniAnyJoin._collections[name];
};

UniAnyJoin.helpers({
    getSubject: function (options) {
        "use strict";
        var coll = UniAnyJoin.getSubjectCollection(this.subjectCollectionName);
        var doc = coll.findOne({_id: this.subjectId}, options || {});
        return coll.ensureUniDoc(doc);
    },
    getSubjectCollection: function () {
        "use strict";
        return UniAnyJoin.getSubjectCollection(this.subjectCollectionName);
    },
    getPossessorOfEntry: function (options) {
        "use strict";
        return UniUsers.findOne({_id: this.possessorId}, options || {});
    },
    getOriginatorOfEntry: function (options) {
        "use strict";
        return this.originatorId && UniUsers.findOne({_id: this.originatorId}, options || {});
    },
    getAcceptorOfEntry: function (options) {
        "use strict";
        return this.acceptorId && UniUsers.findOne({_id: this.acceptorId}, options || {});
    }
});<|endoftext|>


<commit_before><commit_msg>New listing<commit_after><|endoftext|>


<commit_before>var path = require('path')
var config = require('../config')
var utils = require('./utils')
var projectRoot = path.resolve(__dirname, '../')

var env = process.env.NODE_ENV
// check env & config/index.js to decide weither to enable CSS Sourcemaps for the
// various preprocessor loaders added to vue-loader at the end of this file
var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap)
var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap)
var useCssSourceMap = cssSourceMapDev || cssSourceMapProd

module.exports = {
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath,
    filename: '[name].js'
  },
  resolve: {
    extensions: ['', '.js', '.vue'],
    fallback: [path.join(__dirname, '../node_modules')],
    alias: {
      'vue$': 'vue/dist/vue.common.js',
      'src': path.resolve(__dirname, '../src'),
      'assets': path.resolve(__dirname, '../src/assets'),
      'components': path.resolve(__dirname, '../src/components')
    }
  },
  resolveLoader: {
    fallback: [path.join(__dirname, '../node_modules')]
  },
  module: {
    preLoaders: [
      {
        test: /\.vue$/,
        loader: 'eslint',
        include: projectRoot,
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        loader: 'eslint',
        include: projectRoot,
        exclude: /node_modules/
      }
    ],
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      },
      {
        test: /\.js$/,
        loader: 'babel',
        include: projectRoot,
        exclude: /node_modules/
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  eslint: {
    formatter: require('eslint-friendly-formatter')
  },
  vue: {
    loaders: utils.cssLoaders({ sourceMap: useCssSourceMap }),
    postcss: [
      require('autoprefixer')({
        browsers: ['last 2 versions']
      })
    ]
  }
}
<commit_msg>Remove child_process and fs modules from webpack build<commit_after>var path = require('path')
var config = require('../config')
var utils = require('./utils')
var projectRoot = path.resolve(__dirname, '../')

var env = process.env.NODE_ENV
// check env & config/index.js to decide weither to enable CSS Sourcemaps for the
// various preprocessor loaders added to vue-loader at the end of this file
var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap)
var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap)
var useCssSourceMap = cssSourceMapDev || cssSourceMapProd

module.exports = {
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath,
    filename: '[name].js'
  },
  resolve: {
    extensions: ['', '.js', '.vue'],
    fallback: [path.join(__dirname, '../node_modules')],
    alias: {
      'vue$': 'vue/dist/vue.common.js',
      'src': path.resolve(__dirname, '../src'),
      'assets': path.resolve(__dirname, '../src/assets'),
      'components': path.resolve(__dirname, '../src/components')
    }
  },
  resolveLoader: {
    fallback: [path.join(__dirname, '../node_modules')]
  },
  module: {
    preLoaders: [
      {
        test: /\.vue$/,
        loader: 'eslint',
        include: projectRoot,
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        loader: 'eslint',
        include: projectRoot,
        exclude: /node_modules/
      }
    ],
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      },
      {
        test: /\.js$/,
        loader: 'babel',
        include: projectRoot,
        exclude: /node_modules/
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  eslint: {
    formatter: require('eslint-friendly-formatter')
  },
  vue: {
    loaders: utils.cssLoaders({ sourceMap: useCssSourceMap }),
    postcss: [
      require('autoprefixer')({
        browsers: ['last 2 versions']
      })
    ]
  },
  node: {
    child_process: 'empty',
    fs: 'empty',
  }
}
<|endoftext|>


<commit_before>;(function(exports) {
  var GOLDEN_RATIO = 1.61803398875;

  var SpinningShapesGame = function() {
    var autoFocus = false
    this.c = new Coquette(this, "canvas", 500, 500 / GOLDEN_RATIO, "white", autoFocus);
    this.dragger = new Dragger(this.c); // controls dragging of shapes with mouse
  };

  SpinningShapesGame.prototype = {
    update: function() {
      this.dragger.update();
      if (this.c.entities.all().length < 10) {
        var viewSize = this.c.renderer.getViewSize();
        var Shape = Math.random() > 0.5 ? Rectangle : Circle;
        this.c.entities.create(Shape, { // make one
          center: { x: Math.random() * viewSize.x, y: Math.random() * viewSize.y }
        });
      }

      // destroy entities that are off screen
      var entities = this.c.entities.all();
      for (var i = 0; i < entities.length; i++) {
        if (!this.c.renderer.onScreen(entities[i])) {
          this.c.entities.destroy(entities[i]);
        }
      }
    },
  };

  var Rectangle = function(game, settings) {
    this.c = game.c;
    this.angle = Math.random() * 360;
    this.center = settings.center;
    this.size = { x: 0, y: 0 }; // slowly grows

    this.vec = { x: Math.random() * 2 - 1, y: Math.random() * 2 - 1 };
    this.turnSpeed = 2 * Math.random() - 1;

    mixin(countCurrentColliders, this);
  };

  Rectangle.prototype = {
    update: function() {
      // move
      this.center.x += this.vec.x;
      this.center.y += this.vec.y;
      this.angle += this.turnSpeed;

      // grow until full size
      if (this.size.x < 70) {
        this.size.x += 2;
        this.size.y += 2 / GOLDEN_RATIO;
      }
    },

    draw: function(ctx) {
      if (this.colliderCount > 0) {
        ctx.strokeStyle = "black";
        ctx.strokeRect(this.center.x - this.size.x / 2, this.center.y - this.size.y / 2,
                       this.size.x, this.size.y);

      } else {
        ctx.strokeStyle = "#aaa";
        ctx.strokeRect(this.center.x - this.size.x / 2, this.center.y - this.size.y / 2,
                       this.size.x, this.size.y);
      }
    },

    startDrag: function() {
      this.vec = { x: 0, y: 0 };
      this.turnSpeed = 0;
    }
  };

  var Circle = function(game, settings) {
    this.c = game.c;
    this.boundingBox = this.c.collider.CIRCLE;
    this.center = settings.center;
    this.size = { x: 0, y: 0 }; // slowly grows

    this.vec = { x: Math.random() * 2 - 1, y: Math.random() * 2 - 1 };

    mixin(countCurrentColliders, this);
  };

  Circle.prototype = {
    update: function() {
      // move
      this.center.x += this.vec.x;
      this.center.y += this.vec.y;

      // grow until full size
      if (this.size.x < 55) {
        this.size.x = this.size.y = this.size.x + 2;
      }
    },

    draw: function(ctx) {
      ctx.beginPath();
      ctx.arc(this.center.x, this.center.y, this.size.x / 2, 0, Math.PI * 2, true);
      ctx.closePath();

      if (this.colliderCount > 0) {
        ctx.strokeStyle = "black";
        ctx.stroke();
      } else {
        ctx.strokeStyle = "#aaa";
        ctx.stroke();
      }
    },

    startDrag: function() {
      this.vec = { x: 0, y: 0 };
    }
  };

  var Dragger = function(c) {
    this.c = c;
    this._currentDrag;
    var self = this;

    c.inputter.bindMouseMove(function(e) {
      if (self.isDragging()) {
        self._currentDrag.target.center = {
          x: e.x + self._currentDrag.centerOffset.x,
          y: e.y + self._currentDrag.centerOffset.y
        };
      }
    });
  };

  Dragger.prototype = {
    update: function() {
      if (this.c.inputter.isDown(this.c.inputter.LEFT_MOUSE)) {
        if (!this.isDragging()) {
          var mousePosition = this.c.inputter.getMousePosition();
          var target = this._getTarget(this.c.entities.all(), mousePosition)
          if (target !== undefined) {
            this._startDrag(target, mousePosition);
          }
        }
      } else {
        this._stopDrag();
      }
    },

    isDragging: function() {
      return this._currentDrag !== undefined;
    },

    _getTarget: function(targets, e) {
      for (var i = 0; i < targets.length; i++) {
        if (Coquette.Collider.Maths.pointInsideObj(e, targets[i])) {
          return targets[i];
        }
      }
    },

    _startDrag: function(target, e) {
      this._currentDrag = {
        target: target,
        centerOffset: {
          x: target.center.x - e.x,
          y: target.center.y - e.y
        }
      };

      target.startDrag();
    },

    _stopDrag: function() {
      if (this.isDragging()) {
        this._currentDrag = undefined;
      }
    }
  };

  var mixin = function(from, to) {
    for (var i in from) {
      to[i] = from[i];
    }
  };

  var countCurrentColliders = {
    colliderCount: 0, // number of other shapes currently touching this shape

    collision: function(_, type) {
      if (type === this.c.collider.INITIAL) {
        this.colliderCount++;
      }
    },

    uncollision: function() {
      this.colliderCount--;
    }
  };

  exports.SpinningShapesGame = SpinningShapesGame;
})(this);
<commit_msg>Make shape outlines thicken on collision<commit_after>;(function(exports) {
  var GOLDEN_RATIO = 1.61803398875;

  var SpinningShapesGame = function() {
    var autoFocus = false
    this.c = new Coquette(this, "canvas", 500, 500 / GOLDEN_RATIO, "white", autoFocus);
    this.dragger = new Dragger(this.c); // controls dragging of shapes with mouse
  };

  SpinningShapesGame.prototype = {
    update: function() {
      this.dragger.update();
      if (this.c.entities.all().length < 10) {
        var viewSize = this.c.renderer.getViewSize();
        var Shape = Math.random() > 0.5 ? Rectangle : Circle;
        this.c.entities.create(Shape, { // make one
          center: { x: Math.random() * viewSize.x, y: Math.random() * viewSize.y }
        });
      }

      // destroy entities that are off screen
      var entities = this.c.entities.all();
      for (var i = 0; i < entities.length; i++) {
        if (!this.c.renderer.onScreen(entities[i])) {
          this.c.entities.destroy(entities[i]);
        }
      }
    },
  };

  var Rectangle = function(game, settings) {
    this.c = game.c;
    this.angle = Math.random() * 360;
    this.center = settings.center;
    this.size = { x: 0, y: 0 }; // slowly grows

    this.vec = { x: Math.random() * 2 - 1, y: Math.random() * 2 - 1 };
    this.turnSpeed = 2 * Math.random() - 1;

    mixin(countCurrentColliders, this);
  };

  Rectangle.prototype = {
    update: function() {
      // move
      this.center.x += this.vec.x;
      this.center.y += this.vec.y;
      this.angle += this.turnSpeed;

      // grow until full size
      if (this.size.x < 70) {
        this.size.x += 2;
        this.size.y += 2 / GOLDEN_RATIO;
      }
    },

    draw: function(ctx) {
      if (this.colliderCount > 0) {
        ctx.lineWidth = 2;
      } else {
        ctx.lineWidth = 1;
      }

      ctx.strokeStyle = "black";
      ctx.strokeRect(this.center.x - this.size.x / 2, this.center.y - this.size.y / 2,
                     this.size.x, this.size.y);
    },

    startDrag: function() {
      this.vec = { x: 0, y: 0 };
      this.turnSpeed = 0;
    }
  };

  var Circle = function(game, settings) {
    this.c = game.c;
    this.boundingBox = this.c.collider.CIRCLE;
    this.center = settings.center;
    this.size = { x: 0, y: 0 }; // slowly grows

    this.vec = { x: Math.random() * 2 - 1, y: Math.random() * 2 - 1 };

    mixin(countCurrentColliders, this);
  };

  Circle.prototype = {
    update: function() {
      // move
      this.center.x += this.vec.x;
      this.center.y += this.vec.y;

      // grow until full size
      if (this.size.x < 55) {
        this.size.x = this.size.y = this.size.x + 2;
      }
    },

    draw: function(ctx) {
      if (this.colliderCount > 0) {
        ctx.lineWidth = 2;
      } else {
        ctx.lineWidth = 1;
      }

      ctx.beginPath();
      ctx.arc(this.center.x, this.center.y, this.size.x / 2, 0, Math.PI * 2, true);
      ctx.closePath();
      ctx.strokeStyle = "black";
      ctx.stroke();
    },

    startDrag: function() {
      this.vec = { x: 0, y: 0 };
    }
  };

  var Dragger = function(c) {
    this.c = c;
    this._currentDrag;
    var self = this;

    c.inputter.bindMouseMove(function(e) {
      if (self.isDragging()) {
        self._currentDrag.target.center = {
          x: e.x + self._currentDrag.centerOffset.x,
          y: e.y + self._currentDrag.centerOffset.y
        };
      }
    });
  };

  Dragger.prototype = {
    update: function() {
      if (this.c.inputter.isDown(this.c.inputter.LEFT_MOUSE)) {
        if (!this.isDragging()) {
          var mousePosition = this.c.inputter.getMousePosition();
          var target = this._getTarget(this.c.entities.all(), mousePosition)
          if (target !== undefined) {
            this._startDrag(target, mousePosition);
          }
        }
      } else {
        this._stopDrag();
      }
    },

    isDragging: function() {
      return this._currentDrag !== undefined;
    },

    _getTarget: function(targets, e) {
      for (var i = 0; i < targets.length; i++) {
        if (Coquette.Collider.Maths.pointInsideObj(e, targets[i])) {
          return targets[i];
        }
      }
    },

    _startDrag: function(target, e) {
      this._currentDrag = {
        target: target,
        centerOffset: {
          x: target.center.x - e.x,
          y: target.center.y - e.y
        }
      };

      target.startDrag();
    },

    _stopDrag: function() {
      if (this.isDragging()) {
        this._currentDrag = undefined;
      }
    }
  };

  var mixin = function(from, to) {
    for (var i in from) {
      to[i] = from[i];
    }
  };

  var countCurrentColliders = {
    colliderCount: 0, // number of other shapes currently touching this shape

    collision: function(_, type) {
      if (type === this.c.collider.INITIAL) {
        this.colliderCount++;
      }
    },

    uncollision: function() {
      this.colliderCount--;
    }
  };

  exports.SpinningShapesGame = SpinningShapesGame;
})(this);
<|endoftext|>


<commit_before><commit_msg>chore: build dist<commit_after><|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const async = require('./async');
const cp = require('child_process');
const report = require('./report').report;

const hardwareCode = process.argv[2];
const machineCode = process.argv[3];

const packagePath = '/tmp/extract/package/subpackage'

const path = hardwareCode === 'upboard' ?
  `${packagePath}/hardware/${hardwareCode}/${machineCode}` :
  `${packagePath}/hardware/${hardwareCode}`

const supervisorPath = hardwareCode === 'upboard' ?
  `${packagePath}/supervisor/${hardwareCode}/${machineCode}` :
  `${packagePath}/supervisor/${hardwareCode}`

const udevPath = `${packagePath}/udev/aaeon`

const TIMEOUT = 600000;
const applicationParentFolder = hardwareCode === 'aaeon' ? '/opt/apps/machine' : '/opt'

function command(cmd, cb) {
  cp.exec(cmd, {timeout: TIMEOUT}, function(err) {
    cb(err);
  });
}

function updateUdev (cb) {
  if (hardwareCode !== 'aaeon') return cb()

  async.series([
    async.apply(command, `cp ${udevPath}/* /etc/udev/rules.d/`),
    async.apply(command, 'udevadm control --reload-rules && udevadm trigger'),
  ], (err) => {
    if (err) throw err;
    cb()
  })
}

function updateSupervisor (cb) {
  if (hardwareCode === 'aaeon') return cb()
  cp.exec('systemctl enable supervisor', {timeout: TIMEOUT}, function(err) {
    if (err) {
      console.log('failure activating systemctl')
    }

    async.series([
      async.apply(command, 'rm /etc/supervisor/conf.d/*'),
      async.apply(command, `cp ${supervisorPath}/* /etc/supervisor/conf.d/`),
      async.apply(command, 'supervisorctl update'),
    ], (err) => {
      if (err) throw err;
      cb()
    })
  })
}

function updateAcpChromium (cb) {
  if (hardwareCode !== 'aaeon') return cb()

  cp.exec(`chromium-browser --version | grep -o -E '[0-9]+' | head -1 | sed -e 's/^0\+//'`, {timeout: TIMEOUT}, (err, stdout) => {
    if (err) {
      console.log('failure getting chromim version', err)
      throw err
    }

    if (Number(stdout) >= '65') return cb()

    async.series([
      async.apply(command, 'apt update || apt install chromium-browser -y'),
      async.apply(command, `cp ${path}/sencha-chrome.conf /home/iva/.config/upstart/` ),
      async.apply(command, `cp ${path}/start-chrome /home/iva/` ),
    ], function(err) {
      if (err) throw err;
      cb()
    });
  })
}

function installDeviceConfig (cb) {
  try {
    const currentDeviceConfigPath = `${applicationParentFolder}/lamassu-machine/device_config.json`
    const newDeviceConfigPath = `${path}/device_config.json`

    // Updates don't necessarily need to carry a device_config.json file
    if (!fs.existsSync(newDeviceConfigPath)) return cb()

    const currentDeviceConfig = require(currentDeviceConfigPath)
    const newDeviceConfig = require(newDeviceConfigPath)

    if (currentDeviceConfig.billDispenser && newDeviceConfig.billDispenser) {
      newDeviceConfig.billDispenser.model = currentDeviceConfig.billDispenser.model
      newDeviceConfig.billDispenser.device = currentDeviceConfig.billDispenser.device
    }
    if (currentDeviceConfig.billValidator) {
      newDeviceConfig.billValidator.deviceType = currentDeviceConfig.billValidator.deviceType
      newDeviceConfig.billValidator.rs232.device = currentDeviceConfig.billValidator.rs232.device
    }
    if (currentDeviceConfig.kioskPrinter) {
      newDeviceConfig.kioskPrinter.model = currentDeviceConfig.kioskPrinter.model
      newDeviceConfig.kioskPrinter.address = currentDeviceConfig.kioskPrinter.address

      if (currentDeviceConfig.kioskPrinter.maker) {
        newDeviceConfig.kioskPrinter.maker = currentDeviceConfig.kioskPrinter.maker
      }

      if (currentDeviceConfig.kioskPrinter.protocol) {
        newDeviceConfig.kioskPrinter.protocol = currentDeviceConfig.kioskPrinter.protocol
      }
    }
    if (currentDeviceConfig.compliance) {
      newDeviceConfig.compliance = currentDeviceConfig.compliance
    }

    // Pretty-printing the new configuration to retain its usual form.
    const adjustedDeviceConfig = JSON.stringify(newDeviceConfig, null, 2)
    fs.writeFileSync(currentDeviceConfigPath, adjustedDeviceConfig)

    cb()
  }
  catch (err) {
    cb(err)
  }
}

async.series([
  async.apply(command, 'tar zxf /tmp/extract/package/subpackage.tgz -C /tmp/extract/package/'), async.apply(command, `cp -PR /tmp/extract/package/subpackage/lamassu-machine ${applicationParentFolder}`),
  async.apply(command, `cp -PR /tmp/extract/package/subpackage/hardware/${hardwareCode}/node_modules ${applicationParentFolder}/lamassu-machine/`),
  async.apply(installDeviceConfig),
  async.apply(updateSupervisor),
  async.apply(updateUdev),
  async.apply(updateAcpChromium),
  async.apply(report, null, 'finished.')
], function(err) {
  if (err) throw err;
});
<commit_msg>fix: use correct username on browser supervisor (#522)<commit_after>'use strict';

const fs = require('fs');
const async = require('./async');
const cp = require('child_process');
const report = require('./report').report;

const hardwareCode = process.argv[2];
const machineCode = process.argv[3];

const packagePath = '/tmp/extract/package/subpackage'

const path = hardwareCode === 'upboard' ?
  `${packagePath}/hardware/${hardwareCode}/${machineCode}` :
  `${packagePath}/hardware/${hardwareCode}`

const supervisorPath = hardwareCode === 'upboard' ?
  `${packagePath}/supervisor/${hardwareCode}/${machineCode}` :
  `${packagePath}/supervisor/${hardwareCode}`

const udevPath = `${packagePath}/udev/aaeon`

const TIMEOUT = 600000;
const applicationParentFolder = hardwareCode === 'aaeon' ? '/opt/apps/machine' : '/opt'

function command(cmd, cb) {
  cp.exec(cmd, {timeout: TIMEOUT}, function(err) {
    cb(err);
  });
}

function updateUdev (cb) {
  if (hardwareCode !== 'aaeon') return cb()

  async.series([
    async.apply(command, `cp ${udevPath}/* /etc/udev/rules.d/`),
    async.apply(command, 'udevadm control --reload-rules && udevadm trigger'),
  ], (err) => {
    if (err) throw err;
    cb()
  })
}

function updateSupervisor (cb) {
  if (hardwareCode === 'aaeon') return cb()
  cp.exec('systemctl enable supervisor', {timeout: TIMEOUT}, function(err) {
    if (err) {
      console.log('failure activating systemctl')
    }

    async.series([
      async.apply(command, 'rm /etc/supervisor/conf.d/*'),
      async.apply(command, `cp ${supervisorPath}/* /etc/supervisor/conf.d/`),
      async.apply(command, `users | grep -q ubilinux && sed -i 's/user=machine/user=ubilinux/g' /etc/supervisor/conf.d/lamassu-browser.conf || true`),
      async.apply(command, 'supervisorctl update'),
    ], (err) => {
      if (err) throw err;
      cb()
    })
  })
}

function updateAcpChromium (cb) {
  if (hardwareCode !== 'aaeon') return cb()

  cp.exec(`chromium-browser --version | grep -o -E '[0-9]+' | head -1 | sed -e 's/^0\+//'`, {timeout: TIMEOUT}, (err, stdout) => {
    if (err) {
      console.log('failure getting chromim version', err)
      throw err
    }

    if (Number(stdout) >= '65') return cb()

    async.series([
      async.apply(command, 'apt update || apt install chromium-browser -y'),
      async.apply(command, `cp ${path}/sencha-chrome.conf /home/iva/.config/upstart/` ),
      async.apply(command, `cp ${path}/start-chrome /home/iva/` ),
    ], function(err) {
      if (err) throw err;
      cb()
    });
  })
}

function installDeviceConfig (cb) {
  try {
    const currentDeviceConfigPath = `${applicationParentFolder}/lamassu-machine/device_config.json`
    const newDeviceConfigPath = `${path}/device_config.json`

    // Updates don't necessarily need to carry a device_config.json file
    if (!fs.existsSync(newDeviceConfigPath)) return cb()

    const currentDeviceConfig = require(currentDeviceConfigPath)
    const newDeviceConfig = require(newDeviceConfigPath)

    if (currentDeviceConfig.billDispenser && newDeviceConfig.billDispenser) {
      newDeviceConfig.billDispenser.model = currentDeviceConfig.billDispenser.model
      newDeviceConfig.billDispenser.device = currentDeviceConfig.billDispenser.device
    }
    if (currentDeviceConfig.billValidator) {
      newDeviceConfig.billValidator.deviceType = currentDeviceConfig.billValidator.deviceType
      newDeviceConfig.billValidator.rs232.device = currentDeviceConfig.billValidator.rs232.device
    }
    if (currentDeviceConfig.kioskPrinter) {
      newDeviceConfig.kioskPrinter.model = currentDeviceConfig.kioskPrinter.model
      newDeviceConfig.kioskPrinter.address = currentDeviceConfig.kioskPrinter.address

      if (currentDeviceConfig.kioskPrinter.maker) {
        newDeviceConfig.kioskPrinter.maker = currentDeviceConfig.kioskPrinter.maker
      }

      if (currentDeviceConfig.kioskPrinter.protocol) {
        newDeviceConfig.kioskPrinter.protocol = currentDeviceConfig.kioskPrinter.protocol
      }
    }
    if (currentDeviceConfig.compliance) {
      newDeviceConfig.compliance = currentDeviceConfig.compliance
    }

    // Pretty-printing the new configuration to retain its usual form.
    const adjustedDeviceConfig = JSON.stringify(newDeviceConfig, null, 2)
    fs.writeFileSync(currentDeviceConfigPath, adjustedDeviceConfig)

    cb()
  }
  catch (err) {
    cb(err)
  }
}

async.series([
  async.apply(command, 'tar zxf /tmp/extract/package/subpackage.tgz -C /tmp/extract/package/'), async.apply(command, `cp -PR /tmp/extract/package/subpackage/lamassu-machine ${applicationParentFolder}`),
  async.apply(command, `cp -PR /tmp/extract/package/subpackage/hardware/${hardwareCode}/node_modules ${applicationParentFolder}/lamassu-machine/`),
  async.apply(installDeviceConfig),
  async.apply(updateSupervisor),
  async.apply(updateUdev),
  async.apply(updateAcpChromium),
  async.apply(report, null, 'finished.')
], function(err) {
  if (err) throw err;
});
<|endoftext|>


<commit_before>var apiServices = angular.module('apiServices',['ngResource']);

apiServices.factory('garageService', function($resource){
    return {
        garage : function(){
            return $resource('http://localhost::port/garage/:id', {id: '@id', port: 3000});
        }
    };
});<commit_msg>factory method created for garageService<commit_after>var apiServices = angular.module('apiServices',['ngResource']);

apiServices.factory('garageService', function($resource){
    var getResource = function (url, params){

        // if web_app running on server
        if(ENV.type == 'local'){
            params.port = ENV.port;
            return  $resource(ENV.APIUrl + '::port' + url, params);
        }

        // if web_app running on server
        else {
            return  $resource(ENV.APIUrl + url, params);
        }
    }

    return {
        garage : function(){
            return getResource('/garage/:id', {id: '@id'});
        }
    };
});

<|endoftext|>