<commit_before>import React from 'react';
import classes from './Component.scss';
import moment from 'moment';

/* eslint-disable */
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

/* eslint-enable */

const listElement = (ctx, e) => (

          {e.login}

              Followers
              {e.followers}

              Gists
              {e.public_gists}

              Repos
              {e.public_repos}

              Registered since
              {new Date(e.created_at).getUTCFullYear()}

              Estimated price (hourly)
              {e.appAdded.price}$

              Ordered hours
              {e.appAdded.orderedHours}

Cost: {e.appAdded.totalSum}$

);

const loadInitialState = (props) => {
  if (props.token) {
    return;
  }

  setTimeout(() => {
    const token = getParameterByName('token');
    if (token) {
      props.loadState(token);
    }
  }, 500);
};

export const ShoppingCard = (props) => (

    {loadInitialState(props)}

      Your shopping card from {moment(props.timestamp).format('HH:mm DD-MM-YYYY')} with a value of {props.sum}$

    {props.shoppingcard.map(listElement.bind(null, props))}

);

ShoppingCard.propTypes = {
  shoppingcard: React.PropTypes.array.isRequired,
  loadState: React.PropTypes.func.isRequired,
};

export default ShoppingCard;
<commit_msg>added id for protractor<commit_after>import React from 'react';
import classes from './Component.scss';
import moment from 'moment';

/* eslint-disable */
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

/* eslint-enable */

const listElement = (ctx, e) => (

          {e.login}

              Followers
              {e.followers}

              Gists
              {e.public_gists}

              Repos
              {e.public_repos}

              Registered since
              {new Date(e.created_at).getUTCFullYear()}

              Estimated price (hourly)
              {e.appAdded.price}$

              Ordered hours
              {e.appAdded.orderedHours}

Cost: {e.appAdded.totalSum}$

);

const loadInitialState = (props) => {
  if (props.token) {
    return;
  }

  setTimeout(() => {
    const token = getParameterByName('token');
    if (token) {
      props.loadState(token);
    }
  }, 500);
};

export const ShoppingCard = (props) => (

    {loadInitialState(props)}

      Your shopping card from {moment(props.timestamp).format('HH:mm DD-MM-YYYY')} with a value of {props.sum}$

    {props.shoppingcard.map(listElement.bind(null, props))}

);

ShoppingCard.propTypes = {
  shoppingcard: React.PropTypes.array.isRequired,
  loadState: React.PropTypes.func.isRequired,
};

export default ShoppingCard;
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import TextField from 'material-ui/TextField';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import messages from '../../resources/messages';
import * as fetchConstants from '../../lib/fetchConstants';
import { SaveButton } from './IconButton';
import { saveToNotebook } from '../../actions/notebookActions';
import { getAppName } from '../../config';
import { updateFeedback } from '../../actions/appActions';
import ConfirmationDialog from '../common/ConfirmationDialog';
import { WarningNotice, InfoNotice, ErrorNotice } from '../common/Notice';

const localMessages = {
  saving: { id: 'notebook.save.inProgress', defaultMessage: 'Saving to the server...' },
  failed: { id: 'notebook.save.failed', defaultMessage: 'Sorry, this failed for some reason. Reload the page and try again.' },
  saveDialogTitle: { id: 'notebook.save.title', defaultMessage: 'Save to Your Notebook' },
  saveDialogText: { id: 'notebook.save.text', defaultMessage: 'You can save this data view to your notebook.  Add a note to yourself about why you want to save it.  After you save it, you\'ll be able to see a frozen-in-time version of it in your Notebook.' },
  saveInvation: { id: 'notebook.save.invitation', defaultMessage: 'Save to Your Notebook' },
  savedToNotebook: { id: 'notebook.save.confirm', defaultMessage: 'We saved this to your notebook' },
  noteToSelf: { id: 'notebook.save.noteToSelf', defaultMessage: 'Note to self...' },
};

/**
 * Exposes two things to childen:
 * 1) setDataCallback: call this with a function that returns the data to save
 * 1) savedFeedback: a div with info about whether this has been saved or not
 * 2) saveToNotebookButton: a button that can be displayed to request this content be saved
 */
const withSaving = (ChildComponent) => {
  class SaveableContainer extends React.Component {
    state = {
      open: false,
    };
    setDataToSave = (data) => {
      this.dataToSave = data;
    };
    dataToSave = null;
    handleSaveButtonClick = () => this.setState({ open: true });
    handleSave = () => {
      const { handleSaveToNotebook } = this.props;
      this.setState({ open: false });
      handleSaveToNotebook(this.dataToSave);
    };
    render() {
      const { fetchStatus, notebookEntryId } = this.props;
      const { formatMessage } = this.props.intl;
      const saveToNotebookButton = <SaveButton onClick={this.handleSaveButtonClick} />;
      let savedFeedback = null;
      switch (fetchStatus) {
        case fetchConstants.FETCH_ONGOING:
          savedFeedback = <WarningNotice><FormattedMessage {...localMessages.saving} /></WarningNotice>;
          break;
        case fetchConstants.FETCH_SUCCEEDED:
          savedFeedback = (
            <InfoNotice>
              <FormattedMessage {...localMessages.savedToNotebook} />

              ({notebookEntryId})
            </InfoNotice>
          );
          // TODO: add link based on id
          break;
        case fetchConstants.FETCH_FAILED:
          savedFeedback = <ErrorNotice><FormattedMessage {...localMessages.failed} /></ErrorNotice>;
          break;
        default:
          savedFeedback = '';
          break;
      }
      return (

          <ChildComponent
            {...this.props}
            saveToNotebookButton={saveToNotebookButton}
            setDataToSave={this.setDataToSave}
            savedFeedback={savedFeedback}
          />
          <ConfirmationDialog
            open={this.state.open}
            title={formatMessage(localMessages.saveDialogTitle)}
            okText={formatMessage(messages.save)}
            onOk={this.handleSave}
            onCancel={() => this.setState({ open: false })}
          >

<FormattedMessage {...localMessages.saveDialogText} />

            <TextField
              id="saveToNotebookNotes"
              hintText={formatMessage(localMessages.noteToSelf)}
              multiLine
              fullWidth
              rows={1}
            />
          </ConfirmationDialog>

      );
    }
  }
  SaveableContainer.propTypes = {
    intl: PropTypes.object.isRequired,
    handleSaveToNotebook: PropTypes.func.isRequired,
    fetchStatus: PropTypes.string.isRequired,
    notebookEntryId: PropTypes.string,
  };
  const mapStateToProps = state => ({
    fetchStatus: state.notebook.current.fetchStatus,
    notebookEntryId: state.notebook.current.id,
  });
  const mapDispatchToProps = (dispatch, ownProps) => ({
    handleSaveToNotebook: (info) => {
      const notes = document.getElementById('saveToNotebookNotes').value;
      const contentToSave = {
        ...info,
        app: getAppName(),  // add app name in for filtering later
        notes,
        // TODO: add in url hash
      };
      dispatch(saveToNotebook(contentToSave))
        .then(() => {
          updateFeedback({ open: true, message: ownProps.intl.formatMessage(localMessages.savedToNotebook) });
        });
    },
  });
  return injectIntl(
    connect(mapStateToProps, mapDispatchToProps)(
      SaveableContainer
    )
  );
};

export default withSaving;
<commit_msg>#1143 delete unused file<commit_after><|endoftext|>


<commit_before>// @flow
import React, { createContext, useContext, useReducer } from "react"
import { cartTypes } from "constants/cart"

const storageKey = "dscCart"

const CartContext: Object = createContext()

const initialState = {
  addedItems: JSON.parse(localStorage.getItem(storageKey) || "[]"),
  showCartDialog: false,
}

type CartItem = {
  id: string,
  name: string,
  summary: string,
  type: string,
}

const cartReducer = (
  state: Object,
  action: {
    type: string,
    payload: {
      ...CartItem,
      fee: string,
      id: string, // used to remove item
    },
  },
) => {
  switch (action.type) {
    case cartTypes.ADD_TO_CART:
      const newItems = state.addedItems.concat({
        id: action.payload.id,
        name: action.payload.name,
        summary: action.payload.summary,
        fee: action.payload.fee,
      })
      localStorage.setItem(storageKey, JSON.stringify(newItems))
      return {
        addedItems: newItems,
        showCartDialog: true,
      }
    case cartTypes.REMOVE_FROM_CART:
      const updatedItems = [
        ...state.addedItems.filter(item => item.id !== action.payload.id),
      ]
      localStorage.setItem(storageKey, JSON.stringify(updatedItems))
      return {
        addedItems: updatedItems,
      }
    case cartTypes.HIDE_CART_DIALOG:
      return {
        ...state,
        showCartDialog: false,
      }
    default:
      return state
  }
}

/**
 * CartProvider contains global state used for the shopping cart.
 */

const CartProvider = ({ children }: any) => {
  const [state, dispatch] = useReducer(cartReducer, initialState)

  return (
    <CartContext.Provider value={[state, dispatch]}>
      {children}
    </CartContext.Provider>
  )
}

const useCartStore = () => {
  const context = useContext(CartContext)
  if (!context) {
    throw new Error("useCartStore must be used within a CartProvider")
  }
  return context
}

export { CartContext, cartReducer, CartProvider, useCartStore }
<commit_msg>refactor: add reducer check for 12 items in cart #245<commit_after>// @flow
import React, { createContext, useContext, useReducer } from "react"
import { cartTypes } from "constants/cart"

const storageKey = "dscCart"

const CartContext: Object = createContext()

const initialState = {
  addedItems: JSON.parse(localStorage.getItem(storageKey) || "[]"),
  showCartDialog: false,
  maxItemsInCart: false,
}

type CartItem = {
  id: string,
  name: string,
  summary: string,
  type: string,
}

const cartReducer = (
  state: Object,
  action: {
    type: string,
    payload: {
      ...CartItem,
      fee: string,
      id: string, // used to remove item
    },
  },
) => {
  switch (action.type) {
    case cartTypes.ADD_TO_CART:
      if (state.addedItems.length >= 12) {
        return {
          ...state,
          maxItemsInCart: true,
        }
      }
      const newItems = state.addedItems.concat({
        id: action.payload.id,
        name: action.payload.name,
        summary: action.payload.summary,
        fee: action.payload.fee,
      })
      localStorage.setItem(storageKey, JSON.stringify(newItems))
      return {
        addedItems: newItems,
        showCartDialog: true,
        maxItemsInCart: false,
      }
    case cartTypes.REMOVE_FROM_CART:
      const updatedItems = [
        ...state.addedItems.filter(item => item.id !== action.payload.id),
      ]
      localStorage.setItem(storageKey, JSON.stringify(updatedItems))
      return {
        addedItems: updatedItems,
      }
    case cartTypes.HIDE_CART_DIALOG:
      return {
        ...state,
        showCartDialog: false,
      }
    default:
      return state
  }
}

/**
 * CartProvider contains global state used for the shopping cart.
 */

const CartProvider = ({ children }: any) => {
  const [state, dispatch] = useReducer(cartReducer, initialState)

  return (
    <CartContext.Provider value={[state, dispatch]}>
      {children}
    </CartContext.Provider>
  )
}

const useCartStore = () => {
  const context = useContext(CartContext)
  if (!context) {
    throw new Error("useCartStore must be used within a CartProvider")
  }
  return context
}

export { CartContext, cartReducer, CartProvider, useCartStore }
<|endoftext|>


<commit_before>/*
	Persist JS 0.0.3
    Author: Pim Brouwers
	License: MIT
*/
(function (root, factory) {
    if (typeof define === "function" && define.amd) {
        define(factory);
    } else if (typeof module === "object" && module.exports) {
        module.exports = (root.PersistJS = factory());
    } else {
        root.PersistJS = factory();
    }
}(this, function () {
    function Persist(){
        var self = this;

        self.Local = {
            Set: self.setLocal,
            Read: self.readLocal,
            ReadJSON: self.readJSONLocal,
            Remove: self.removeLocal
        };

        self.Session = {
            Set: self.setSession,
            Read: self.readSession,
            ReadJSON: self.readJSONSession,
            Remove: self.removeSession
        };
    };

    /**
    * Local Storage Hooks
    */
    Persist.prototype.setLocal = function (key, data) {
        if (key && data) {
            var data = JSON.stringify(data);

            if (typeof (Storage) !== "undefined") {
                window.localStorage.setItem(key, data);
            }
        }
    };

    Persist.prototype.readLocal =  function (key) {
        if (window.localStorage[key]) {
            return JSON.parse(window.localStorage[key]);
        }
    };

    Persist.prototype.readJSONLocal =  function(key) {
        if (window.localStorage[key]) {
            return window.localStorage[key];
        }
    };

    Persist.prototype.removeLocal = function (key, callback) {
        if (window.localStorage[key]) {
            window.localStorage.removeItem(key);
            if (callback) callback();
        }
        else
            if (callback) callback();
    };

    /**
    * Session Storage Hooks
    */
    Persist.prototype.setSession = function (key, data) {
            if (key && data) {
                var data = JSON.stringify(data);

                if (typeof (Storage) !== "undefined") {
                    window.sessionStorage.setItem(key, data);
                }
            }
        };

    Persist.prototype.readSession = function (key) {
        if (window.sessionStorage[key]) {
            return JSON.parse(window.sessionStorage[key]);
        }
    };

    Persist.prototype.readJSONSession =  function(key) {
        if (window.sessionStorage[key]) {
            return window.sessionStorage[key];
        }
    };

    Persist.prototype.removeSession = function (key, callback) {
        if (window.sessionStorage[key]) {
            window.sessionStorage.removeItem(key);
            if (callback) callback();
        }
        else
            if (callback) callback();

    };

    return new Persist();
}));

<commit_msg>Added Push support for Session & Local<commit_after>/*
	Persist JS 0.0.4
	Author: Pim Brouwers
	License: MIT
*/
(function (root, factory) {
    if (typeof define === "function" && define.amd) {
        define(factory);
    } else if (typeof module === "object" && module.exports) {
        module.exports = (root.PersistJS = factory());
    } else {
        root.PersistJS = factory();
    }
}(this, function () {
    function Persist() {
        var self = this;

        self.Local = {
            Clear: self.clearLocal,
            Push: self.pushLocal,
            Set: self.setLocal,
            Read: self.readLocal,
            ReadJSON: self.readJSONLocal,
            Remove: self.removeLocal
        };

        self.Session = {
            Clear: self.clearSession,
            Push: self.pushSession,
            Set: self.setSession,
            Read: self.readSession,
            ReadJSON: self.readJSONSession,
            Remove: self.removeSession
        };
    };

    /**
    * Local Storage Hooks
    */
    Persist.prototype.setLocal = function (key, data) {
        if (typeof key !== 'undefined' &&
            key !== null &&
            typeof data !== 'undefined' &&
            data !== null)
        {
            var data = JSON.stringify(data);

            if (typeof (Storage) !== "undefined") {
                window.localStorage.setItem(key, data);
            }
        }
    };

    Persist.prototype.readLocal = function (key) {
        if (window.localStorage[key]) {
            return JSON.parse(window.localStorage[key]);
        }
    };

    Persist.prototype.readJSONLocal = function (key) {
        if (window.localStorage[key]) {
            return window.localStorage[key];
        }
    };

    Persist.prototype.removeLocal = function (key, callback) {
        if (window.localStorage[key]) {
            window.localStorage.removeItem(key);
            if (callback) callback();
        }
        else
            if (callback) callback();
    };

    Persist.prototype.clearLocal = function(){
        if(window.localStorage) {
            window.localStorage.clear();
        }
    };

    Persist.prototype.pushLocal = function (key, data){
        var self = this;

        (typeof key !== 'undefined' &&
            key !== null &&
            typeof data !== 'undefined' &&
            data !== null)
        {
            var ary = [];
            ary = self.Read(key);

            if(ary && ary.constructor === Array){
                ary.push(data);
            }
            else if (typeof ary === 'undefined' || ary === null){
                ary = [data];
            }

            self.Set(key, ary);
        }
    };

    /**
    * Session Storage Hooks
    */
    Persist.prototype.setSession = function (key, data) {
        (typeof key !== 'undefined' &&
            key !== null &&
            typeof data !== 'undefined' &&
            data !== null)
        {
            var data = JSON.stringify(data);

            if (typeof (Storage) !== "undefined") {
                window.sessionStorage.setItem(key, data);
            }
        }
    };

    Persist.prototype.readSession = function (key) {
        if (window.sessionStorage[key]) {
            return JSON.parse(window.sessionStorage[key]);
        }
    };

    Persist.prototype.readJSONSession = function (key) {
        if (window.sessionStorage[key]) {
            return window.sessionStorage[key];
        }
    };

    Persist.prototype.removeSession = function (key, callback) {
        if (window.sessionStorage[key]) {
            window.sessionStorage.removeItem(key);
            if (callback) callback();
        }
        else
            if (callback) callback();

    };

    Persist.prototype.clearSession = function(){
        if(window.sessionStorage) {
            window.sessionStorage.clear();
        }
    };

    Persist.prototype.pushSession = function (key, data){
        var self = this;

        (typeof key !== 'undefined' &&
            key !== null &&
            typeof data !== 'undefined' &&
            data !== null)
        {
            var ary = [];
            ary = self.Read(key);

            if(ary && ary.constructor === Array){
                ary.push(data);
            }
            else if (typeof ary === 'undefined' || ary === null){
                ary = [data];
            }

            self.Set(key, ary);
        }
    };

    return new Persist();
}));

<|endoftext|>


<commit_before>var Divider = require('../divider');
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;

describe('Divider', function() {
  var component;
  beforeEach(function() {
    component = TestUtils.renderIntoDocument(
      <Divider />
    );
  });

  it('is of type "Divider"', function() {
    expect(TestUtils.isElementOfType(component, Divider)).toBeDefined();
  });
  it('is an svg line element', function() {
    expect(TestUtils.findRenderedDOMComponentWithTag(component, 'line')).toBeDefined();
  });
  it('has the class name "divider"', function() {
    expect(TestUtils.findRenderedDOMComponentWithClass(component, 'divider')).toBeDefined();
  });
  it('has the expected props', function() {
    expect(component.props.hasOwnProperty('className')).toBeTruthy();
    expect(component.props.hasOwnProperty('x1')).toBeTruthy();
    expect(component.props.hasOwnProperty('x2')).toBeTruthy();
    expect(component.props.hasOwnProperty('y1')).toBeTruthy();
    expect(component.props.hasOwnProperty('y2')).toBeTruthy();
  });

  var node;
  describe('given x and y values for start and end points', function() {
    it('renders to the requested height', function() {
      component = TestUtils.renderIntoDocument(
        <Divider
          x1={0}
          x2={0}
          y1={0}
          y2={100}/>
      );
      node = React.findDOMNode(component);
      expect(node.getAttribute('x1')).toEqual('0');
      expect(node.getAttribute('x2')).toEqual('0');
      expect(node.getAttribute('y1')).toEqual('0');
      expect(node.getAttribute('y2')).toEqual('100');
    });
    it('renders to the requested width', function() {
      component = TestUtils.renderIntoDocument(
        <Divider
          x1={0}
          x2={100}
          y1={0}
          y2={0}/>
      );
      node = React.findDOMNode(component);
      expect(node.getAttribute('x1')).toEqual('0');
      expect(node.getAttribute('x2')).toEqual('100');
      expect(node.getAttribute('y1')).toEqual('0');
      expect(node.getAttribute('y2')).toEqual('0');
    });
  });
});
<commit_msg>updated divider test<commit_after>var Divider = require('../divider');
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;

describe('Divider', () => {
  var component;
  var node;

  it('is of type Divider', () => {
    component = TestUtils.renderIntoDocument(<Divider />);
    expect(TestUtils.isElementOfType(component, Divider)).toBeDefined();
  });

  it('is an svg line element', () => {
    component = TestUtils.renderIntoDocument(<Divider />);
    expect(TestUtils.findRenderedDOMComponentWithTag(component, 'line')).toBeDefined();
  });

  it('has the expected class name', () => {
    component = TestUtils.renderIntoDocument(<Divider />);
    expect(TestUtils.findRenderedDOMComponentWithClass(component, 'divider')).toBeDefined();
  });

  it('has the expected props', () => {
    component = TestUtils.renderIntoDocument(<Divider />);
    expect(component.props.hasOwnProperty('className')).toBeTruthy();
    expect(component.props.hasOwnProperty('x1')).toBeTruthy();
    expect(component.props.hasOwnProperty('x2')).toBeTruthy();
    expect(component.props.hasOwnProperty('y1')).toBeTruthy();
    expect(component.props.hasOwnProperty('y2')).toBeTruthy();
  });

  it('has the expected default prop values', () => {
    component = TestUtils.renderIntoDocument(<Divider />);
    expect(component.props.className).toEqual('');
    expect(component.props.x1).toEqual(0);
    expect(component.props.x2).toEqual(0);
    expect(component.props.y1).toEqual(0);
    expect(component.props.y2).toEqual(0);
  });

  it('consumes the className prop', () => {
    component = TestUtils.renderIntoDocument(<Divider className={'foo'} />);
    expect(TestUtils.findRenderedDOMComponentWithClass(component, 'foo')).toBeDefined();
  });

  it('consumes the x1, x2, y1, and y2 props', () => {
    var x1 = 123;
    var x2 = 456;
    var y1 = 789;
    var y2 = 101;
    component = TestUtils.renderIntoDocument(
      <Divider
        x1={x1}
        x2={x2}
        y1={y1}
        y2={y2}/>
    );
    node = React.findDOMNode(component);
    expect(node.getAttribute('x1')).toEqual(x1.toString());
    expect(node.getAttribute('x2')).toEqual(x2.toString());
    expect(node.getAttribute('y1')).toEqual(y1.toString());
    expect(node.getAttribute('y2')).toEqual(y2.toString());
  });

});
<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('civic.common')
    .directive('addDrugForm', addDrugForm);

  // @ngInject
  function addDrugForm() {
    var directive = {
      restrict: 'E',
      templateUrl: 'components/directives/addDrugForm.tpl.html',
      replace: true,
      controller: addDrugFormController
    };

    return directive;
  }

  function addDrugFormController($rootScope,
                                 $scope,
                                 Drugs,
                                 ConfigService,
                                 _) {
    var vm = $scope.vm = { };
    vm.parentField = _.find($scope.fields, { key: $scope.options.key }); // ref to parent's form field object
    vm.index = $scope.$index; // $index value assigned by angular-formly
    vm.replaceItem = $scope.replaceItem; // ref to replaceItem function on multiInput controller
    vm.suggestions = [];

    vm.showForm = true;
    vm.showSuccess = false;
    vm.showConflict = false;

    vm.newDrug = {
      drug_name: ''
    };

    vm.newDrugFields = [
      {
        key: 'drug_name',
        type: 'input',
        templateOptions: {
          label: 'Drug Name',
          required: true
        }
      }
    ];

    vm.close = function() {
      $scope.$parent.addFormIsOpen = false;
    };

    vm.submit = function() {
      console.log('new drug submitted.');
      Drugs.add(this.newDrug)
        .then(
          function(response) { // success
            console.log('Drug successfully added.');
            vm.createdDrug = response;
            vm.showForm = false;
            vm.showSuccess = true;
          },
          function(response) {
            console.log('Error adding new drug.');
            var status = vm.errorStatus = response.status;
            vm.showForm = false;
            vm.showConflict = true;
            switch(status) {
            case 409: // conflict, drug exists.
              vm.conflictDrug = response.data;
              break;
            case 500: // server error
              break;
            default: // general error
            }
          });
    };

    vm.addDrug= function() {
      console.log('Replacing model drug name.');
      vm.replaceItem(this.parentField.value(), this.index, this.newDrug.drug_name);
    };
  }
})();
<commit_msg>'add drug to list' feature uses created drug name properly<commit_after>(function() {
  'use strict';
  angular.module('civic.common')
    .directive('addDrugForm', addDrugForm);

  // @ngInject
  function addDrugForm() {
    var directive = {
      restrict: 'E',
      templateUrl: 'components/directives/addDrugForm.tpl.html',
      replace: true,
      controller: addDrugFormController
    };

    return directive;
  }

  function addDrugFormController($rootScope,
                                 $scope,
                                 Drugs,
                                 ConfigService,
                                 _) {
    var vm = $scope.vm = { };
    vm.parentField = _.find($scope.fields, { key: $scope.options.key }); // ref to parent's form field object
    vm.index = $scope.$index; // $index value assigned by angular-formly
    vm.replaceItem = $scope.replaceItem; // ref to replaceItem function on multiInput controller
    vm.suggestions = [];

    vm.showForm = true;
    vm.showSuccess = false;
    vm.showConflict = false;

    vm.newDrug = {
      drug_name: ''
    };

    vm.newDrugFields = [
      {
        key: 'drug_name',
        type: 'input',
        templateOptions: {
          label: 'Drug Name',
          required: true
        }
      }
    ];

    vm.close = function() {
      $scope.$parent.addFormIsOpen = false;
    };

    vm.submit = function() {
      console.log('new drug submitted.');
      Drugs.add(this.newDrug)
        .then(
          function(response) { // success
            console.log('Drug successfully added.');
            vm.createdDrug = response;
            vm.showForm = false;
            vm.showSuccess = true;
          },
          function(response) {
            console.log('Error adding new drug.');
            var status = vm.errorStatus = response.status;
            vm.showForm = false;
            vm.showConflict = true;
            switch(status) {
            case 409: // conflict, drug exists.
              vm.conflictDrug = response.data;
              break;
            case 500: // server error
              break;
            default: // general error
            }
          });
    };

    vm.addDrug= function() {
      console.log('Replacing model drug name.');
      vm.replaceItem(this.parentField.value(), this.index, vm.createdDrug.name);
    };
  }
})();
<|endoftext|>


<commit_before>//2015-03-08
//Copyright: Justin Visser
var cheerio = require("cheerio");
var request = require('request');
var fs = require('fs');

function doResultsRequest(year, dir, url, csv) {
	request(url, function(err, resp, data){
		if (!err) {
			//console.log(data);
			var $ = cheerio.load(data);

			csv += "date,vistor,vistorAbrv,vistorGoals,home,homeAbrv,homeGoals,notes";
			$("#div_games table tr").each(function() {
				$('td',this).each(function(index,element) {
					if($(this).attr("align") != ("center")) {
						if(index == 5)
							csv += '"' + $(this).text() + '"';
						else {
							if(index == 6 && $(this).text() != '')
								csv += '"' + $(this).text() + '"';
							else if(index != 6)
								csv += '"' + $(this).text() + '"' + ',';
						}
						if(index == 1 || index == 3) {
							var re = /\/([A-Z]*)\//g;
							var match = re.exec($("a",this).attr("href"));
							csv += '"' + match[1] + '"' + ",";
						}
					}
				});
				csv += "\n";
			});

			if (!fs.existsSync(dir)){
				fs.mkdirSync(dir);
			}

			fs.writeFile(dir + "results.csv", csv, function(err) {
				if(err) {
					console.log(err);
				} else {
					console.log("The file was saved!");
				}
			});
		}
	});
}

function doPlayersRequest(year, dir, url, csv) {
	request(url, function(err, resp, data){
		if (!err) {
			//console.log(data);
			var $ = cheerio.load(data);

			csv += "rank,player,age,teamName,position,gamesPlayed,goals,assists,points,plusMinus,penaltyMinutes,evenStrengthGoals,powerPlayGoals,shortHandedGoals,gameWinningPoints,evenStrengthAssists,powerPlayAssits,shortHandedAssists,shots,shootingPercentage,timeOnIce,averageTimeOnIce\n";
			$("#div_stats table tbody tr").each(function() {
				//Only take if not one of the headings.
				if(!($(this).hasClass("no_ranker"))) {
					$('td',this).each(function(index,element) {
						if(index >= 21)
							var field = '"' + $(this).text().replace('*','') + '"';
						else
							var field = '"' + $(this).text().replace('*','') + '"' +',';
						csv += field;
					});
					csv += "\n";
				}
			});
			if (!fs.existsSync(dir)){
				fs.mkdirSync(dir);
			}

			fs.writeFile(dir + "players.csv", csv, function(err) {
				if(err) {
					console.log(err);
				} else {
					console.log("The file was saved!");
				}
			});
		}
	});
}

function getResults() {
	var year = 1917;
	var dir = "";
	var url = "";
	var csv = "";
	while (year < 2015) {
		dir = "../../data/" + year + "/";
		url = "http://www.hockey-reference.com/leagues/NHL_"+ (year+1) +"_games.html";

		csv = "";
		doResultsRequest(year, dir, url, csv);
		url = "http://www.hockey-reference.com/leagues/NHL_"+ (year+1) +"_skaters.html";
		csv = "";
		doPlayersRequest(year, dir, url, csv);

		year++;
	}
}

function testing() {
	var year = 1917;
	var dir = "";
	var url = "";
	var csv = "";

	dir = "../../data/" + year + "/";
	url = "http://www.hockey-reference.com/leagues/NHL_"+ (year+1) +"_skaters.html";
	csv = "";
	doPlayersRequest(year, dir, url, csv);

	year++;
}

//testing();
getResults();<commit_msg>Now scrapes team data<commit_after>//2015-03-08
//Copyright: Justin Visser
var cheerio = require("cheerio");
var request = require('request');
var fs = require('fs');

function doResultsRequest(year, dir, url, csv) {
	request(url, function(err, resp, data){
		if (!err) {
			var $ = cheerio.load(data);

			csv += "date,vistor,vistorAbrv,vistorGoals,home,homeAbrv,homeGoals,notes";
			$("#div_games table tr").each(function() {
				$('td',this).each(function(index,element) {
					if($(this).attr("align") != ("center")) {
						if(index == 5)
							csv += '"' + $(this).text() + '"';
						else {
							if(index == 6 && $(this).text() != '')
								csv += '"' + $(this).text() + '"';
							else if(index != 6)
								csv += '"' + $(this).text() + '"' + ',';
						}
						if(index == 1 || index == 3) {
							var re = /\/([A-Z]*)\//g;
							var match = re.exec($("a",this).attr("href"));
							csv += '"' + match[1] + '"' + ",";
						}
					}
				});
				csv += "\n";
			});

			if (!fs.existsSync(dir)){
				fs.mkdirSync(dir);
			}

			fs.writeFile(dir + "results.csv", csv, function(err) {
				if(err) {
					console.log(err);
				} else {
					console.log("The file was saved!");
				}
			});
		}
	});
}

function doPlayersRequest(year, dir, url, csv) {
	request(url, function(err, resp, data){
		if (!err) {
			var $ = cheerio.load(data);

			csv += "rank,player,age,teamName,position,gamesPlayed,goals,assists,points,plusMinus,penaltyMinutes,evenStrengthGoals,powerPlayGoals,shortHandedGoals,gameWinningPoints,evenStrengthAssists,powerPlayAssits,shortHandedAssists,shots,shootingPercentage,timeOnIce,averageTimeOnIce\n";
			$("#div_stats table tbody tr").each(function() {
				//Only take if not one of the headings.
				if(!($(this).hasClass("no_ranker"))) {
					$('td',this).each(function(index,element) {
						if(index >= 21)
							var field = '"' + $(this).text().replace('*','') + '"';
						else
							var field = '"' + $(this).text().replace('*','') + '"' +',';
						csv += field;
					});
					csv += "\n";
				}
			});
			if (!fs.existsSync(dir)){
				fs.mkdirSync(dir);
			}

			fs.writeFile(dir + "players.csv", csv, function(err) {
				if(err) {
					console.log(err);
				} else {
					console.log("The file was saved!");
				}
			});
		}
	});
}

function doTeamRequest(year, dir, url, csv) {
	request(url, function(err, resp, data){
		if (!err) {
			var $ = cheerio.load(data);

			csv += "rank,teamName,teamAbrv,gamesPlayed,wins,losses,ties,points,pointsPercentage,goalsFor,goalsAgainst,simpleRatingSystem,strengthOfSchedule,totalGoalsPerGame,powerPlayGoals,powerPlayChances,powerPlayPercentage,powerPlayGoalsAgainst,powerPlayChancesAgainst,penaltyKillingPercentage,shortHandedGoals,shortHandedGoalsAgainst,shots,shootingPercentage,shotsAgainst,savePercentage,pdo\n";
			$("#div_teams table tbody tr").each(function() {
				//Only take if not one of the headings.
				if(!($(this).hasClass("no_ranker"))) {
					$('td',this).each(function(index,element) {
						if(index >= 25)
							var field = '"' + $(this).text().replace('*','') + '"';
						else
							var field = '"' + $(this).text().replace('*','') + '"' + ',';
						csv += field;

						if(index == 1) {
							var re = /\/([A-Z]*)\//g;
							var match = re.exec($("a",this).attr("href"));
							csv += '"' + match[1] + '"' + ",";
						}
					});
					csv += "\n";
				}
			});

			if (!fs.existsSync(dir)){
				fs.mkdirSync(dir);
			}

			fs.writeFile(dir + "teams.csv", csv, function(err) {
				if(err) {
					console.log(err);
				} else {
					console.log("The file was saved!");
				}
			});
		}
	});
}

function getResults() {
	var year = 1917;
	var dir = "";
	var url = "";
	var csv = "";
	while (year < 2015) {
		dir = "../../data/" + year + "/";

		url = "http://www.hockey-reference.com/leagues/NHL_"+ (year+1) +"_games.html";
		csv = "";
		doResultsRequest(year, dir, url, csv);

		url = "http://www.hockey-reference.com/leagues/NHL_"+ (year+1) +"_skaters.html";
		csv = "";
		doPlayersRequest(year, dir, url, csv);

		url = "http://www.hockey-reference.com/leagues/NHL_"+ (year+1) +".html";
		csv = "";
		doTeamRequest(year, dir, url, csv);

		year++;
	}
}

function testing() {
	var year = 1917;
	var dir = "";
	var url = "";
	var csv = "";

	dir = "../../data/" + year + "/";
	url = "http://www.hockey-reference.com/leagues/NHL_"+ (year+1) +".html";
	csv = "";
	doTeamRequest(year, dir, url, csv);

	year++;
}

//testing();
getResults();<|endoftext|>


<commit_before>import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { mount } from 'enzyme';

import ParallaxWrapper, { Parallax } from './parallax';

const defaultProps = {
  classes: {},
  img: 'img',
};

test('should render a div with an img and a div inside', (t) => {
  const wrapper = mount(<ParallaxWrapper img="image" />);

  t.deepEqual(wrapper.find('Jss(Parallax)').length, 1);
  t.deepEqual(wrapper.find('img').length, 1);
  t.deepEqual(wrapper.find('.parallax--content').length, 1);
});

test('should warn against changing the img prop', (t) => {
  const wrapper = mount(<ParallaxWrapper img="img" />);

  t.throws(() => wrapper.setProps({ img: 'img2' }));
});

test('should remove event listeners from the document when the component unmounts', (t) => {
  const wrapper = mount(<ParallaxWrapper img="img" />);
  const spy = sinon.spy(window, 'removeEventListener');

  wrapper.unmount();

  t.deepEqual(spy.callCount, 2);
});

test('should call the positionImage function when the user scrolls', (t) => {
  const wrapper = mount(<Parallax {...defaultProps} />);
  const instance = wrapper.instance();
  const spy = sinon.spy(instance, 'positionImage');

  instance.handleScroll();

  t.deepEqual(spy.callCount, 1);
});

test('should call the positionImage and computeValues function when the window resizes', (t) => {
  const wrapper = mount(<Parallax {...defaultProps} />);
  const instance = wrapper.instance();
  const positionImage = sinon.spy(instance, 'positionImage');
  const computeValues = sinon.spy(instance, 'computeValues');

  instance.handleResize();

  t.deepEqual(positionImage.callCount, 1);
  t.deepEqual(computeValues.callCount, 1);
});

test('should not position the image when the image is not in the viewport ', (t) => {
  window.innerHeight = -100;

  const wrapper = mount(<Parallax {...defaultProps} />);
  const instance = wrapper.instance();

  instance.positionImage();

  // eslint-disable-next-line no-undefined
  t.deepEqual(instance.image.style.transform, undefined);
});
<commit_msg>Fix tests<commit_after>import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { mount } from 'enzyme';

import ParallaxWrapper, { Parallax } from './parallax';

const defaultProps = {
  classes: {},
  img: 'img',
};

test('should render a div with an img and a div inside', (t) => {
  const wrapper = mount(<ParallaxWrapper img="image" />);

  t.deepEqual(wrapper.find('Jss(Parallax)').length, 1);
  t.deepEqual(wrapper.find('img').length, 1);
  t.deepEqual(wrapper.find('.parallax--content').length, 1);
});

test('should warn against changing the img prop', (t) => {
  const wrapper = mount(<ParallaxWrapper img="img" />);

  t.throws(() => wrapper.setProps({ img: 'img2' }));
});

test('should remove event listeners from the document when the component unmounts', (t) => {
  const wrapper = mount(<ParallaxWrapper img="img" />);
  const spy = sinon.spy(window, 'removeEventListener');

  wrapper.unmount();

  t.deepEqual(spy.callCount, 2);
});

test('should call the positionImage function when the user scrolls', (t) => {
  const wrapper = mount(<Parallax {...defaultProps} />);
  const instance = wrapper.instance();
  const spy = sinon.spy(instance, 'positionImage');

  instance.handleScroll();

  t.deepEqual(spy.callCount, 1);
});

test('should call the positionImage and computeValues function when the window resizes', (t) => {
  const wrapper = mount(<Parallax {...defaultProps} />);
  const instance = wrapper.instance();
  const positionImage = sinon.spy(instance, 'positionImage');
  const computeValues = sinon.spy(instance, 'computeValues');

  instance.handleResize();

  t.deepEqual(positionImage.callCount, 1);
  t.deepEqual(computeValues.callCount, 1);
});

test('should default position the parallax to the end', (t) => {
  window.innerHeight = -100;

  const wrapper = mount(<Parallax {...defaultProps} />);
  const instance = wrapper.instance();

  instance.positionImage();

  // In this case the overflowImageHeight is 0 which means that second
  // parameter will be zero
  t.deepEqual(instance.image.style.transform, 'translate3D(0, 0px, 0)');
});
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @flow
import React, { PureComponent } from 'react';
import classNames from 'classnames';

import './IdleSearchField.css';

type Props = {|
  +onIdleAfterChange: string => void,
  +onSubmit?: () => void,
  +onFocus?: () => void,
  +onBlur?: (Element | null) => void,
  +idlePeriod: number,
  +defaultValue: ?string,
  +className: ?string,
  +title: ?string,
|};

type State = {
  value: string,
};

class IdleSearchField extends PureComponent<Props, State> {
  _timeout: number;
  _previouslyNotifiedValue: string;

  constructor(props: Props) {
    super(props);
    (this: any)._onSearchFieldChange = this._onSearchFieldChange.bind(this);
    (this: any)._onSearchFieldFocus = this._onSearchFieldFocus.bind(this);
    (this: any)._onSearchFieldBlur = this._onSearchFieldBlur.bind(this);
    (this: any)._onClearButtonClick = this._onClearButtonClick.bind(this);
    (this: any)._onTimeout = this._onTimeout.bind(this);
    this._timeout = 0;
    this.state = {
      value: props.defaultValue || '',
    };
    this._previouslyNotifiedValue = this.state.value;
  }

  _onSearchFieldFocus(e: SyntheticFocusEvent<HTMLInputElement>) {
    e.currentTarget.select();

    if (this.props.onFocus) {
      this.props.onFocus();
    }
  }

  _onSearchFieldBlur(e: { relatedTarget: Element | null }) {
    if (this.props.onBlur) {
      this.props.onBlur(e.relatedTarget);
    }
  }

  _onSearchFieldChange(e: SyntheticEvent<HTMLInputElement>) {
    this.setState({
      value: e.currentTarget.value,
    });

    if (this._timeout) {
      clearTimeout(this._timeout);
    }
    this._timeout = setTimeout(this._onTimeout, this.props.idlePeriod);
  }

  _onTimeout() {
    this._timeout = 0;
    this._notifyIfChanged(this.state.value);
  }

  _notifyIfChanged(value: string) {
    if (value !== this._previouslyNotifiedValue) {
      this._previouslyNotifiedValue = value;
      this.props.onIdleAfterChange(value);
    }
  }

  _onClearButtonClick() {
    clearTimeout(this._timeout);
    this._timeout = 0;

    this.setState({ value: '' });
    this._notifyIfChanged('');
  }

  _onClearButtonFocus(
    e: SyntheticEvent<HTMLElement> & { relatedTarget: HTMLElement }
  ) {
    // prevent the focus on the clear button
    if (e.relatedTarget) {
      e.relatedTarget.focus();
    } else {
      e.currentTarget.blur();
    }
  }

  _onFormSubmit(e: SyntheticEvent<HTMLFormElement>) {
    e.preventDefault();
  }

  componentWillReceiveProps(nextProps: Props) {
    if (nextProps.defaultValue !== this.props.defaultValue) {
      this._notifyIfChanged(nextProps.defaultValue || '');
      this.setState({
        value: nextProps.defaultValue || '',
      });
    }
  }

  render() {
    const { className, title } = this.props;
    return (
      <form
        className={classNames('idleSearchField', className)}
        onSubmit={this._onFormSubmit}
      >
        <input
          type="search"
          name="search"
          className="idleSearchFieldInput"
          required="required"
          title={title}
          value={this.state.value}
          onChange={this._onSearchFieldChange}
          onFocus={this._onSearchFieldFocus}
          onBlur={this._onSearchFieldBlur}
        />
        <input
          type="reset"
          className="idleSearchFieldButton"
          onClick={this._onClearButtonClick}
          onFocus={this._onClearButtonFocus}
        />
      </form>
    );
  }
}

export default IdleSearchField;
<commit_msg>IdleSearchField: unused prop<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @flow
import React, { PureComponent } from 'react';
import classNames from 'classnames';

import './IdleSearchField.css';

type Props = {|
  +onIdleAfterChange: string => void,
  +onFocus?: () => void,
  +onBlur?: (Element | null) => void,
  +idlePeriod: number,
  +defaultValue: ?string,
  +className: ?string,
  +title: ?string,
|};

type State = {
  value: string,
};

class IdleSearchField extends PureComponent<Props, State> {
  _timeout: number;
  _previouslyNotifiedValue: string;

  constructor(props: Props) {
    super(props);
    (this: any)._onSearchFieldChange = this._onSearchFieldChange.bind(this);
    (this: any)._onSearchFieldFocus = this._onSearchFieldFocus.bind(this);
    (this: any)._onSearchFieldBlur = this._onSearchFieldBlur.bind(this);
    (this: any)._onClearButtonClick = this._onClearButtonClick.bind(this);
    (this: any)._onTimeout = this._onTimeout.bind(this);
    this._timeout = 0;
    this.state = {
      value: props.defaultValue || '',
    };
    this._previouslyNotifiedValue = this.state.value;
  }

  _onSearchFieldFocus(e: SyntheticFocusEvent<HTMLInputElement>) {
    e.currentTarget.select();

    if (this.props.onFocus) {
      this.props.onFocus();
    }
  }

  _onSearchFieldBlur(e: { relatedTarget: Element | null }) {
    if (this.props.onBlur) {
      this.props.onBlur(e.relatedTarget);
    }
  }

  _onSearchFieldChange(e: SyntheticEvent<HTMLInputElement>) {
    this.setState({
      value: e.currentTarget.value,
    });

    if (this._timeout) {
      clearTimeout(this._timeout);
    }
    this._timeout = setTimeout(this._onTimeout, this.props.idlePeriod);
  }

  _onTimeout() {
    this._timeout = 0;
    this._notifyIfChanged(this.state.value);
  }

  _notifyIfChanged(value: string) {
    if (value !== this._previouslyNotifiedValue) {
      this._previouslyNotifiedValue = value;
      this.props.onIdleAfterChange(value);
    }
  }

  _onClearButtonClick() {
    clearTimeout(this._timeout);
    this._timeout = 0;

    this.setState({ value: '' });
    this._notifyIfChanged('');
  }

  _onClearButtonFocus(
    e: SyntheticEvent<HTMLElement> & { relatedTarget: HTMLElement }
  ) {
    // prevent the focus on the clear button
    if (e.relatedTarget) {
      e.relatedTarget.focus();
    } else {
      e.currentTarget.blur();
    }
  }

  _onFormSubmit(e: SyntheticEvent<HTMLFormElement>) {
    e.preventDefault();
  }

  componentWillReceiveProps(nextProps: Props) {
    if (nextProps.defaultValue !== this.props.defaultValue) {
      this._notifyIfChanged(nextProps.defaultValue || '');
      this.setState({
        value: nextProps.defaultValue || '',
      });
    }
  }

  render() {
    const { className, title } = this.props;
    return (
      <form
        className={classNames('idleSearchField', className)}
        onSubmit={this._onFormSubmit}
      >
        <input
          type="search"
          name="search"
          className="idleSearchFieldInput"
          required="required"
          title={title}
          value={this.state.value}
          onChange={this._onSearchFieldChange}
          onFocus={this._onSearchFieldFocus}
          onBlur={this._onSearchFieldBlur}
        />
        <input
          type="reset"
          className="idleSearchFieldButton"
          onClick={this._onClearButtonClick}
          onFocus={this._onClearButtonFocus}
        />
      </form>
    );
  }
}

export default IdleSearchField;
<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var React = require('react');
var ContentRepo = require("matrix-js-sdk").ContentRepo;
var MatrixClientPeg = require('../../../MatrixClientPeg');
var Avatar = require('../../../Avatar');
var sdk = require("../../../index");

module.exports = React.createClass({
    displayName: 'RoomAvatar',

    // Room may be left unset here, but if it is,
    // oobData.avatarUrl should be set (else there
    // would be nowhere to get the avatar from)
    propTypes: {
        room: React.PropTypes.object,
        oobData: React.PropTypes.object,
        width: React.PropTypes.number,
        height: React.PropTypes.number,
        resizeMethod: React.PropTypes.string
    },

    getDefaultProps: function() {
        return {
            width: 36,
            height: 36,
            resizeMethod: 'crop',
            oobData: {},
        };
    },

    getInitialState: function() {
        return {
            urls: this.getImageUrls(this.props)
        };
    },

    componentWillReceiveProps: function(newProps) {
        this.setState({
            urls: this.getImageUrls(newProps)
        });
    },

    getImageUrls: function(props) {
        return [
            ContentRepo.getHttpUriForMxc(
                MatrixClientPeg.get().getHomeserverUrl(),
                props.oobData.avatarUrl,
                Math.floor(props.width * window.devicePixelRatio),
                Math.floor(props.height * window.devicePixelRatio),
                props.resizeMethod
            ), // highest priority
            this.getRoomAvatarUrl(props),
            this.getOneToOneAvatar(props),
            this.getFallbackAvatar(props) // lowest priority
        ].filter(function(url) {
            return (url != null && url != "");
        });
    },

    getRoomAvatarUrl: function(props) {
        if (!this.props.room) return null;

        return props.room.getAvatarUrl(
            MatrixClientPeg.get().getHomeserverUrl(),
            Math.floor(props.width * window.devicePixelRatio),
            Math.floor(props.height * window.devicePixelRatio),
            props.resizeMethod,
            false
        );
    },

    getOneToOneAvatar: function(props) {
        if (!this.props.room) return null;

        var mlist = props.room.currentState.members;
        var userIds = [];
        // for .. in optimisation to return early if there are >2 keys
        for (var uid in mlist) {
            if (mlist.hasOwnProperty(uid)) {
                userIds.push(uid);
            }
            if (userIds.length > 2) {
                return null;
            }
        }

        if (userIds.length == 2) {
            var theOtherGuy = null;
            if (mlist[userIds[0]].userId == MatrixClientPeg.get().credentials.userId) {
                theOtherGuy = mlist[userIds[1]];
            } else {
                theOtherGuy = mlist[userIds[0]];
            }
            return theOtherGuy.getAvatarUrl(
                MatrixClientPeg.get().getHomeserverUrl(),
                Math.floor(props.width * window.devicePixelRatio),
                Math.floor(props.height * window.devicePixelRatio),
                props.resizeMethod,
                false
            );
        } else if (userIds.length == 1) {
            return mlist[userIds[0]].getAvatarUrl(
                MatrixClientPeg.get().getHomeserverUrl(),
                Math.floor(props.width * window.devicePixelRatio),
                Math.floor(props.height * window.devicePixelRatio),
                props.resizeMethod,
                false
            );
        } else {
           return null;
        }
    },

    getFallbackAvatar: function(props) {
        let roomId = null;
        if (props.oobData && props.oobData.roomId) {
            roomId = this.props.oobData.roomId;
        } else if (props.room) {
            roomId = props.room.roomId;
        } else {
            return null;
        }

        return Avatar.defaultAvatarUrlForString(roomId);
    },

    render: function() {
        var BaseAvatar = sdk.getComponent("avatars.BaseAvatar");

        var {room, oobData, ...otherProps} = this.props;

        var roomName = room ? room.name : oobData.name;

        return (
            <BaseAvatar {...otherProps} name={roomName}
                idName={room ? room.roomId : null}
                urls={this.state.urls} />
        );
    }
});
<commit_msg>Change incorrect refs to this.props<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var React = require('react');
var ContentRepo = require("matrix-js-sdk").ContentRepo;
var MatrixClientPeg = require('../../../MatrixClientPeg');
var Avatar = require('../../../Avatar');
var sdk = require("../../../index");

module.exports = React.createClass({
    displayName: 'RoomAvatar',

    // Room may be left unset here, but if it is,
    // oobData.avatarUrl should be set (else there
    // would be nowhere to get the avatar from)
    propTypes: {
        room: React.PropTypes.object,
        oobData: React.PropTypes.object,
        width: React.PropTypes.number,
        height: React.PropTypes.number,
        resizeMethod: React.PropTypes.string
    },

    getDefaultProps: function() {
        return {
            width: 36,
            height: 36,
            resizeMethod: 'crop',
            oobData: {},
        };
    },

    getInitialState: function() {
        return {
            urls: this.getImageUrls(this.props)
        };
    },

    componentWillReceiveProps: function(newProps) {
        this.setState({
            urls: this.getImageUrls(newProps)
        });
    },

    getImageUrls: function(props) {
        return [
            ContentRepo.getHttpUriForMxc(
                MatrixClientPeg.get().getHomeserverUrl(),
                props.oobData.avatarUrl,
                Math.floor(props.width * window.devicePixelRatio),
                Math.floor(props.height * window.devicePixelRatio),
                props.resizeMethod
            ), // highest priority
            this.getRoomAvatarUrl(props),
            this.getOneToOneAvatar(props),
            this.getFallbackAvatar(props) // lowest priority
        ].filter(function(url) {
            return (url != null && url != "");
        });
    },

    getRoomAvatarUrl: function(props) {
        if (!props.room) return null;

        return props.room.getAvatarUrl(
            MatrixClientPeg.get().getHomeserverUrl(),
            Math.floor(props.width * window.devicePixelRatio),
            Math.floor(props.height * window.devicePixelRatio),
            props.resizeMethod,
            false
        );
    },

    getOneToOneAvatar: function(props) {
        if (!props.room) return null;

        var mlist = props.room.currentState.members;
        var userIds = [];
        // for .. in optimisation to return early if there are >2 keys
        for (var uid in mlist) {
            if (mlist.hasOwnProperty(uid)) {
                userIds.push(uid);
            }
            if (userIds.length > 2) {
                return null;
            }
        }

        if (userIds.length == 2) {
            var theOtherGuy = null;
            if (mlist[userIds[0]].userId == MatrixClientPeg.get().credentials.userId) {
                theOtherGuy = mlist[userIds[1]];
            } else {
                theOtherGuy = mlist[userIds[0]];
            }
            return theOtherGuy.getAvatarUrl(
                MatrixClientPeg.get().getHomeserverUrl(),
                Math.floor(props.width * window.devicePixelRatio),
                Math.floor(props.height * window.devicePixelRatio),
                props.resizeMethod,
                false
            );
        } else if (userIds.length == 1) {
            return mlist[userIds[0]].getAvatarUrl(
                MatrixClientPeg.get().getHomeserverUrl(),
                Math.floor(props.width * window.devicePixelRatio),
                Math.floor(props.height * window.devicePixelRatio),
                props.resizeMethod,
                false
            );
        } else {
           return null;
        }
    },

    getFallbackAvatar: function(props) {
        let roomId = null;
        if (props.oobData && props.oobData.roomId) {
            roomId = this.props.oobData.roomId;
        } else if (props.room) {
            roomId = props.room.roomId;
        } else {
            return null;
        }

        return Avatar.defaultAvatarUrlForString(roomId);
    },

    render: function() {
        var BaseAvatar = sdk.getComponent("avatars.BaseAvatar");

        var {room, oobData, ...otherProps} = this.props;

        var roomName = room ? room.name : oobData.name;

        return (
            <BaseAvatar {...otherProps} name={roomName}
                idName={room ? room.roomId : null}
                urls={this.state.urls} />
        );
    }
});
<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2016, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

import _ from 'lodash';
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import * as actions from '../../../redux/actions/';
import LabeledCheckbox from '../../common/controls/LabeledCheckbox';

import styles from './RangeSelect.css';

export const RangeSelect = (props) =>
  (

    <LabeledCheckbox
      checked={props.displayFlags.cbg100Enabled}
      name="hundred"
      label="100% of Readings"
      onFn={_.partial(props.turnOnCbgRange, '100')}
      offFn={_.partial(props.turnOffCbgRange, '100')}
    />
    <LabeledCheckbox
      checked={props.displayFlags.cbg80Enabled}
      name="eighty"
      label="80% of Readings"
      onFn={_.partial(props.turnOnCbgRange, '80')}
      offFn={_.partial(props.turnOffCbgRange, '80')}
    />
    <LabeledCheckbox
      checked={props.displayFlags.cbg50Enabled}
      name="fifty"
      label="50% of Readings"
      onFn={_.partial(props.turnOnCbgRange, '50')}
      offFn={_.partial(props.turnOffCbgRange, '50')}
    />
    <LabeledCheckbox
      checked={props.displayFlags.cbgMedianEnabled}
      name="median"
      label="Median"
      onFn={_.partial(props.turnOnCbgRange, 'median')}
      offFn={_.partial(props.turnOffCbgRange, 'median')}
    />

);

RangeSelect.propTypes = {
  displayFlags: PropTypes.shape({
    cbg100Enabled: PropTypes.bool.isRequired,
    cbg80Enabled: PropTypes.bool.isRequired,
    cbg50Enabled: PropTypes.bool.isRequired,
    cbgMedianEnabled: PropTypes.bool.isRequired,
  }).isRequired,
  turnOnCbgRange: PropTypes.func.isRequired,
  turnOffCbgRange: PropTypes.func.isRequired,
  currentPatientInViewId: PropTypes.string.isRequired,
};

export function mapDispatchToProps(dispatch, ownProps) {
  return bindActionCreators({
    turnOnCbgRange: _.partial(
      actions.turnOnCbgRange, ownProps.currentPatientInViewId
    ),
    turnOffCbgRange: _.partial(
      actions.turnOffCbgRange, ownProps.currentPatientInViewId
    ),
  }, dispatch);
}

export default connect(
  () => {},
  mapDispatchToProps,
  (stateProps, dispatchProps, ownProps) => (_.assign({}, ownProps, stateProps, dispatchProps)),
)(RangeSelect);
<commit_msg>simplify prop requirements<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2016, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

import _ from 'lodash';
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import * as actions from '../../../redux/actions/';
import LabeledCheckbox from '../../common/controls/LabeledCheckbox';

import styles from './RangeSelect.css';

export const RangeSelect = (props) =>
  (

    <LabeledCheckbox
      checked={props.displayFlags.cbg100Enabled}
      name="hundred"
      label="100% of Readings"
      onFn={_.partial(props.turnOnCbgRange, '100')}
      offFn={_.partial(props.turnOffCbgRange, '100')}
    />
    <LabeledCheckbox
      checked={props.displayFlags.cbg80Enabled}
      name="eighty"
      label="80% of Readings"
      onFn={_.partial(props.turnOnCbgRange, '80')}
      offFn={_.partial(props.turnOffCbgRange, '80')}
    />
    <LabeledCheckbox
      checked={props.displayFlags.cbg50Enabled}
      name="fifty"
      label="50% of Readings"
      onFn={_.partial(props.turnOnCbgRange, '50')}
      offFn={_.partial(props.turnOffCbgRange, '50')}
    />
    <LabeledCheckbox
      checked={props.displayFlags.cbgMedianEnabled}
      name="median"
      label="Median"
      onFn={_.partial(props.turnOnCbgRange, 'median')}
      offFn={_.partial(props.turnOffCbgRange, 'median')}
    />

);

RangeSelect.propTypes = {
  displayFlags: PropTypes.shape({
    cbg100Enabled: PropTypes.bool.isRequired,
    cbg80Enabled: PropTypes.bool.isRequired,
    cbg50Enabled: PropTypes.bool.isRequired,
    cbgMedianEnabled: PropTypes.bool.isRequired,
  }).isRequired,
  turnOnCbgRange: PropTypes.func.isRequired,
  turnOffCbgRange: PropTypes.func.isRequired,
};

export function mapDispatchToProps(dispatch, ownProps) {
  return bindActionCreators({
    turnOnCbgRange: _.partial(
      actions.turnOnCbgRange, ownProps.currentPatientInViewId
    ),
    turnOffCbgRange: _.partial(
      actions.turnOffCbgRange, ownProps.currentPatientInViewId
    ),
  }, dispatch);
}

export default connect(
  () => {},
  mapDispatchToProps,
  (stateProps, dispatchProps, ownProps) => (_.assign({}, ownProps, stateProps, dispatchProps)),
)(RangeSelect);
<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var React = require('react');
var ContentRepo = require("matrix-js-sdk").ContentRepo;
var MatrixClientPeg = require('../../../MatrixClientPeg');
var Avatar = require('../../../Avatar');
var sdk = require("../../../index");

module.exports = React.createClass({
    displayName: 'RoomAvatar',

    // Room may be left unset here, but if it is,
    // oobData.avatarUrl should be set (else there
    // would be nowhere to get the avatar from)
    propTypes: {
        room: React.PropTypes.object,
        oobData: React.PropTypes.object,
        width: React.PropTypes.number,
        height: React.PropTypes.number,
        resizeMethod: React.PropTypes.string
    },

    getDefaultProps: function() {
        return {
            width: 36,
            height: 36,
            resizeMethod: 'crop',
            oobData: {},
        }
    },

    getInitialState: function() {
        return {
            urls: this.getImageUrls(this.props)
        };
    },

    componentWillReceiveProps: function(newProps) {
        this.setState({
            urls: this.getImageUrls(newProps)
        })
    },

    getImageUrls: function(props) {
        return [
            ContentRepo.getHttpUriForMxc(
                MatrixClientPeg.get().getHomeserverUrl(),
                props.oobData.avatarUrl,
                props.width, props.height, props.resizeMethod
            ), // highest priority
            this.getRoomAvatarUrl(props),
            this.getOneToOneAvatar(props),
            this.getFallbackAvatar(props) // lowest priority
        ].filter(function(url) {
            return (url != null && url != "");
        });
    },

    getRoomAvatarUrl: function(props) {
        if (!this.props.room) return null;

        return props.room.getAvatarUrl(
            MatrixClientPeg.get().getHomeserverUrl(),
            props.width, props.height, props.resizeMethod,
            false
        );
    },

    getOneToOneAvatar: function(props) {
        if (!this.props.room) return null;

        var mlist = props.room.currentState.members;
        var userIds = [];
        var leftUserIds = [];
        // for .. in optimisation to return early if there are >2 keys
        for (var uid in mlist) {
            if (mlist.hasOwnProperty(uid)) {
                if (["join", "invite"].includes(mlist[uid].membership)) {
                    userIds.push(uid);
                } else {
                    leftUserIds.push(uid);
                }
            }
            if (userIds.length > 2) {
                return null;
            }
        }

        if (userIds.length == 2) {
            var theOtherGuy = null;
            if (mlist[userIds[0]].userId == MatrixClientPeg.get().credentials.userId) {
                theOtherGuy = mlist[userIds[1]];
            } else {
                theOtherGuy = mlist[userIds[0]];
            }

            return theOtherGuy.getAvatarUrl(
                MatrixClientPeg.get().getHomeserverUrl(),
                props.width, props.height, props.resizeMethod,
                false
            );
        } else if (userIds.length == 1) {
            // The other 1-1 user left, leaving just the current user, so show the left user's avatar
            if (leftUserIds.length === 1) {
                return mlist[leftUserIds[0]].getAvatarUrl(
                    MatrixClientPeg.get().getHomeserverUrl(),
                    props.width, props.height, props.resizeMethod,
                        false
                );
            }
            return mlist[userIds[0]].getAvatarUrl(
                MatrixClientPeg.get().getHomeserverUrl(),
                props.width, props.height, props.resizeMethod,
                    false
            );
        } else {
           return null;
        }
    },

    getFallbackAvatar: function(props) {
        if (!this.props.room) return null;

        return Avatar.defaultAvatarUrlForString(props.room.roomId);
    },

    render: function() {
        var BaseAvatar = sdk.getComponent("avatars.BaseAvatar");

        var {room, oobData, ...otherProps} = this.props;

        var roomName = room ? room.name : oobData.name;

        return (
            <BaseAvatar {...otherProps} name={roomName}
                idName={room ? room.roomId : null}
                urls={this.state.urls} />
        );
    }
});
<commit_msg>Remove empty line<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var React = require('react');
var ContentRepo = require("matrix-js-sdk").ContentRepo;
var MatrixClientPeg = require('../../../MatrixClientPeg');
var Avatar = require('../../../Avatar');
var sdk = require("../../../index");

module.exports = React.createClass({
    displayName: 'RoomAvatar',

    // Room may be left unset here, but if it is,
    // oobData.avatarUrl should be set (else there
    // would be nowhere to get the avatar from)
    propTypes: {
        room: React.PropTypes.object,
        oobData: React.PropTypes.object,
        width: React.PropTypes.number,
        height: React.PropTypes.number,
        resizeMethod: React.PropTypes.string
    },

    getDefaultProps: function() {
        return {
            width: 36,
            height: 36,
            resizeMethod: 'crop',
            oobData: {},
        }
    },

    getInitialState: function() {
        return {
            urls: this.getImageUrls(this.props)
        };
    },

    componentWillReceiveProps: function(newProps) {
        this.setState({
            urls: this.getImageUrls(newProps)
        })
    },

    getImageUrls: function(props) {
        return [
            ContentRepo.getHttpUriForMxc(
                MatrixClientPeg.get().getHomeserverUrl(),
                props.oobData.avatarUrl,
                props.width, props.height, props.resizeMethod
            ), // highest priority
            this.getRoomAvatarUrl(props),
            this.getOneToOneAvatar(props),
            this.getFallbackAvatar(props) // lowest priority
        ].filter(function(url) {
            return (url != null && url != "");
        });
    },

    getRoomAvatarUrl: function(props) {
        if (!this.props.room) return null;

        return props.room.getAvatarUrl(
            MatrixClientPeg.get().getHomeserverUrl(),
            props.width, props.height, props.resizeMethod,
            false
        );
    },

    getOneToOneAvatar: function(props) {
        if (!this.props.room) return null;

        var mlist = props.room.currentState.members;
        var userIds = [];
        var leftUserIds = [];
        // for .. in optimisation to return early if there are >2 keys
        for (var uid in mlist) {
            if (mlist.hasOwnProperty(uid)) {
                if (["join", "invite"].includes(mlist[uid].membership)) {
                    userIds.push(uid);
                } else {
                    leftUserIds.push(uid);
                }
            }
            if (userIds.length > 2) {
                return null;
            }
        }

        if (userIds.length == 2) {
            var theOtherGuy = null;
            if (mlist[userIds[0]].userId == MatrixClientPeg.get().credentials.userId) {
                theOtherGuy = mlist[userIds[1]];
            } else {
                theOtherGuy = mlist[userIds[0]];
            }
            return theOtherGuy.getAvatarUrl(
                MatrixClientPeg.get().getHomeserverUrl(),
                props.width, props.height, props.resizeMethod,
                false
            );
        } else if (userIds.length == 1) {
            // The other 1-1 user left, leaving just the current user, so show the left user's avatar
            if (leftUserIds.length === 1) {
                return mlist[leftUserIds[0]].getAvatarUrl(
                    MatrixClientPeg.get().getHomeserverUrl(),
                    props.width, props.height, props.resizeMethod,
                        false
                );
            }
            return mlist[userIds[0]].getAvatarUrl(
                MatrixClientPeg.get().getHomeserverUrl(),
                props.width, props.height, props.resizeMethod,
                    false
            );
        } else {
           return null;
        }
    },

    getFallbackAvatar: function(props) {
        if (!this.props.room) return null;

        return Avatar.defaultAvatarUrlForString(props.room.roomId);
    },

    render: function() {
        var BaseAvatar = sdk.getComponent("avatars.BaseAvatar");

        var {room, oobData, ...otherProps} = this.props;

        var roomName = room ? room.name : oobData.name;

        return (
            <BaseAvatar {...otherProps} name={roomName}
                idName={room ? room.roomId : null}
                urls={this.state.urls} />
        );
    }
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Row, Col } from 'react-flexbox-grid';
import { Avatar } from 'react-toolbox';
import ConversationStyles from './Conversation.css';

console.log('ConversationStyles', ConversationStyles)

const Conversation = (props) => (
  <Row onClick={props.onClick} style={styles.container} className={ConversationStyles.Conversation}>
    <Col xs={3}>
      <Avatar title={props.image.toString()} />
    </Col>
    <Col xs={9}>
      <Row style={styles.firstLine}>
        <Col xs={9} style={styles.headline}>
          {props.name}
        </Col>
        <Col xs={3} style={styles.time}>
          {props.time}
        </Col>
      </Row>
      <Row>
        <Col xs={10} style={styles.message} onClick={(e) => console.log(e)}>
          {props.message}
        </Col>
        <Col xs={2} >

        </Col>
      </Row>
    </Col>
  </Row>
)

const styles = {
  container: {
    maxHeight: '90px',
    padding: '0.2rem 0',
    cursor: 'pointer'
  },
  firstLine: {
    marginTop: '0.1rem',
    marginBottom: '0.4rem'
  },
  headline: {
    fontWeight: 'bold'
  },
  time: {
    fontSize: '0.7rem',
    textAlign: 'right'
  },
  message: {
    fontSize: '0.9rem',
    lineHeight: '1.1rem',
    maxHeight: '2rem',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    // whiteSpace: 'nowrap'
  },
  active: {
    borderRadius: '100%',
    backgroundColor: 'green',
    width: '7px',
    height: '7px',
    display: 'inline-block',
    textAlign: 'right'
  }
}

export default Conversation;<commit_msg>Play with avatar positioning<commit_after>import React, { Component } from 'react';
import { Row, Col } from 'react-flexbox-grid';
import { Avatar } from 'react-toolbox';
import ConversationStyles from './Conversation.css';

console.log('ConversationStyles', ConversationStyles)

const Conversation = (props) => (
  <Row onClick={props.onClick} style={styles.container} className={ConversationStyles.Conversation}>
    <Col xs={3}>
      <Avatar style={styles.avatar} title={props.image.toString()} />
    </Col>
    <Col xs={9}>
      <Row style={styles.firstLine}>
        <Col xs={9} style={styles.headline}>
          {props.name}
        </Col>
        <Col xs={3} style={styles.time}>
          {props.time}
        </Col>
      </Row>
      <Row>
        <Col xs={10} style={styles.message} onClick={(e) => console.log(e)}>
          {props.message}
        </Col>
        <Col xs={2} >

        </Col>
      </Row>
    </Col>
  </Row>
)

const styles = {
  container: {
    maxHeight: '90px',
    padding: '0.2rem 0',
    cursor: 'pointer'
  },
  avatar: {
    // padding: '0.5rem'
  },
  firstLine: {
    marginTop: '0.1rem',
    marginBottom: '0.4rem'
  },
  headline: {
    fontWeight: 'bold'
  },
  time: {
    fontSize: '0.7rem',
    textAlign: 'right'
  },
  message: {
    fontSize: '0.9rem',
    lineHeight: '1.1rem',
    maxHeight: '2rem',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    // whiteSpace: 'nowrap'
  },
  active: {
    borderRadius: '100%',
    backgroundColor: 'green',
    width: '7px',
    height: '7px',
    display: 'inline-block',
    textAlign: 'right'
  }
}

export default Conversation;<|endoftext|>


<commit_before>import MenuView from '../../view/menu/MenuView'
import StackingLayout from '../../view/menu/layouts/StackingLayout'
import Style from '../../view/menu/Style'
import Controller from './Controller'

/**
 * Generic menu with title, description and buttons
 */
export default class MenuBuilder {
  constructor (game, backgroundAsset, startHeight, config) {
    game.stage.backgroundColor = 0x6B8E23

    var menu = new MenuView({
      game: game,
      layout: new StackingLayout({
        menuRect: {
          x: game.camera.width / 4,
          y: 0,
          width: game.camera.width / 2,
          height: game.camera.height
        },
        linePadding: 16,
        sectionPadding: startHeight,
        vertical: true
      }),
      background: backgroundAsset,
      backgroundInTheMiddle: true
    })

    this.c = new Controller(game, new Style({
      smallFont: 16,
      mediumFont: 32,
      largeFont: 64,
      buttonHeight: config.sideMenuSettings.buttonHeight,
      buttonWidth: config.sideMenuSettings.buttonWidth
    }), menu)

    this.c.initialize()
  }

  /**
   * Menu title
   * @param {string} text - Title text
   */
  createTitle (text) {
    this.c.text(text, 'large')
  }

  /**
   * Creates final score
   * @param {string} text - score text
   */
  createScore (fields) {
    for (var i = 0; i < fields.length; i++) {
      this.c.text(fields[i], 'medium')
    }
  }

  /**
   * Menu description
   * @param {string} text - Description that is displayed in the menu
   */
  createDescription (text) {
    this.c.text(text, 'small')
  }

  /**
   * Adds a new button to the menu
   * @param {string} text - Button text
   * @param {function} call - Function that is called when pressed
   */
  createButton (text, call) {
    this.c.button(text, call, this)
  }

  createInputField (parameters) {
    this.c.inputField(parameters)
  }

  finishMenu () {
    this.c.finish()
  }
}
<commit_msg>ohjeet fixed<commit_after>import MenuView from '../../view/menu/MenuView'
import StackingLayout from '../../view/menu/layouts/StackingLayout'
import Style from '../../view/menu/Style'
import Controller from './Controller'

/**
 * Generic menu with title, description and buttons
 */
export default class MenuBuilder {
  constructor (game, backgroundAsset, startHeight, config) {
    game.stage.backgroundColor = 0x6B8E23

    var menu = new MenuView({
      game: game,
      layout: new StackingLayout({
        menuRect: {
          x: game.camera.width / 4,
          y: 0,
          width: game.camera.width / 2,
          height: game.camera.height
        },
        linePadding: 16,
        sectionPadding: startHeight,
        vertical: true
      }),
      background: backgroundAsset,
      backgroundInTheMiddle: true
    })

    this.c = new Controller(game, new Style({
      smallFont: 16,
      mediumFont: 32,
      largeFont: 64,
      buttonHeight: config.sideMenuSettings.buttonHeight,
      buttonWidth: config.sideMenuSettings.buttonWidth
    }), menu)

    this.c.initialize()
  }

  /**
   * Menu title
   * @param {string} text - Title text
   */
  createTitle (text) {
    this.c.text(text, 'large')
  }

  /**
   * Creates final score
   * @param {string} text - score text
   */
  createScore (fields) {
    for (var i = 0; i < fields.length; i++) {
      this.c.text(fields[i], 'medium')
    }
  }

  /**
   * Menu description
   * @param {string} text - Description that is displayed in the menu
   */
  createDescription (text) {
    let rows = text.split('\n')
    for (var i = 0; i < rows.length; i++) {
      this.c.text(rows[i], 'small')
    }
  }

  /**
   * Adds a new button to the menu
   * @param {string} text - Button text
   * @param {function} call - Function that is called when pressed
   */
  createButton (text, call) {
    this.c.button(text, call, this)
  }

  createInputField (parameters) {
    this.c.inputField(parameters)
  }

  finishMenu () {
    this.c.finish()
  }
}
<|endoftext|>


<commit_before>import phantomjs from 'phantomjs-prebuilt'
import { spawn } from 'child_process'
import os from 'os'
import Linerstream from 'linerstream'
import Page from './page'
import Command from './command'

export default class Phantom {
    constructor() {
        //console.log(`${new Date()} Starting ${phantomjs.path} ${__dirname + '/shim.js'}`);
        this.process = spawn(phantomjs.path, [__dirname + '/shim.js']);
        this.commands = new Map();

        this.process.stdin.setEncoding('utf-8');

        this.process.stdout.pipe(new Linerstream()).on('data', (data) => {
            const message = data.toString('utf8');
            if (message[0] === '>') {
                let json = message.substr(1);
                console.log('Parsing: start|%s|end', json);

                const command = JSON.parse(json);
                this.commands.get(command.id).deferred.resolve(command.response);
                this.commands.delete(command.id);
            } else {
                console.log(message);
            }
        });

        this.process.stderr.on('data', (data) => {
            console.log('Error:' + data);
        });

        this.process.on('exit', (code) => {
            //console.log(`Child exited with code ${code}`);
        });
    }

    createPage() {
        return Promise.resolve(new Page(this));
    }

    execute(command) {
        command.deferred = Promise.defer();
        this.commands.set(command.id, command);
        //console.log('Sending: %s', JSON.stringify(command));
        this.process.stdin.write(JSON.stringify(command) + os.EOL, 'utf8');

        return command.deferred.promise;
    }

    exit() {
        this.execute(new Command(null, 'phantom', 'exit'));
    }
}<commit_msg>Removes console.log<commit_after>import phantomjs from 'phantomjs-prebuilt'
import { spawn } from 'child_process'
import os from 'os'
import Linerstream from 'linerstream'
import Page from './page'
import Command from './command'

export default class Phantom {
    constructor() {
        //console.log(`${new Date()} Starting ${phantomjs.path} ${__dirname + '/shim.js'}`);
        this.process = spawn(phantomjs.path, [__dirname + '/shim.js']);
        this.commands = new Map();

        this.process.stdin.setEncoding('utf-8');

        this.process.stdout.pipe(new Linerstream()).on('data', (data) => {
            const message = data.toString('utf8');
            if (message[0] === '>') {
                let json = message.substr(1);
                //console.log('Parsing: start|%s|end', json);
                const command = JSON.parse(json);
                this.commands.get(command.id).deferred.resolve(command.response);
                this.commands.delete(command.id);
            } else {
                console.log(message);
            }
        });

        this.process.stderr.on('data', (data) => {
            console.log('Error:' + data);
        });

        this.process.on('exit', (code) => {
            //console.log(`Child exited with code ${code}`);
        });
    }

    createPage() {
        return Promise.resolve(new Page(this));
    }

    execute(command) {
        command.deferred = Promise.defer();
        this.commands.set(command.id, command);
        //console.log('Sending: %s', JSON.stringify(command));
        this.process.stdin.write(JSON.stringify(command) + os.EOL, 'utf8');

        return command.deferred.promise;
    }

    exit() {
        this.execute(new Command(null, 'phantom', 'exit'));
    }
}<|endoftext|>


<commit_before>//   Copyright 2012 Abraham Smith
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

(function () {
    // Modularize your applications with cement.js
    var cement = {},
        modules = {},
        moduleInitialisers = {}; // functions that create modules
    // all modules can dispatch events with base.dispatch("eventName") and listened to with module.on("eventname")
    function addDispatchAndOnMethods(moduleBase, moduleExports, moduleEventHandlers) {
        moduleBase.dispatch = function (eventName, data1, data2, data3, data4) {
            if (moduleEventHandlers[eventName]) {
                moduleEventHandlers[eventName](data1, data2, data3, data4);
            }
        };
        moduleExports.on = function (eventName, eventHandler) {
            moduleEventHandlers[eventName] = eventHandler;
        };
    }
    cement.define = function (moduleName, moduleInitialiser) {
        var moduleBase = {},
            moduleExports = {},
            moduleEventHandlers = {};
        moduleInitialisers[moduleName] = moduleInitialiser;
        addDispatchAndOnMethods(moduleBase, moduleExports, moduleEventHandlers);
        moduleInitialiser(moduleBase, moduleExports);
        modules[moduleName] = moduleExports;
    };
    cement.createInstance = function (moduleName) {
        var moduleBase = {},
            moduleExports = {},
            moduleEventHandlers = {};
        addDispatchAndOnMethods(moduleBase, moduleExports, moduleEventHandlers);
        moduleInitialisers[moduleName](moduleBase, moduleExports);
        return moduleExports;
    };
    cement.require = function (moduleName) {
        if (modules[moduleName]) {
            return modules[moduleName];
        } else {
            throw new Error("module : " + moduleName + " is not defined.\n ");
        }
    };
    // testing putting something on develop branch
    window.cmt = window.cement = cement;
}());
<commit_msg>test feature branch<commit_after>//   Copyright 2012 Abraham Smith
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

(function () {
    // Modularize your applications with cement.js
    var cement = {},
        modules = {},
        moduleInitialisers = {}; // functions that create modules
    // all modules can dispatch events with base.dispatch("eventName") and listened to with module.on("eventname")
    function addDispatchAndOnMethods(moduleBase, moduleExports, moduleEventHandlers) {
        moduleBase.dispatch = function (eventName, data1, data2, data3, data4) {
            if (moduleEventHandlers[eventName]) {
                moduleEventHandlers[eventName](data1, data2, data3, data4);
            }
        };
        moduleExports.on = function (eventName, eventHandler) {
            moduleEventHandlers[eventName] = eventHandler;
        };
    }
    cement.define = function (moduleName, moduleInitialiser) {
        var moduleBase = {},
            moduleExports = {},
            moduleEventHandlers = {};
        moduleInitialisers[moduleName] = moduleInitialiser;
        addDispatchAndOnMethods(moduleBase, moduleExports, moduleEventHandlers);
        moduleInitialiser(moduleBase, moduleExports);
        modules[moduleName] = moduleExports;
    };
    cement.createInstance = function (moduleName) {
        var moduleBase = {},
            moduleExports = {},
            moduleEventHandlers = {};
        addDispatchAndOnMethods(moduleBase, moduleExports, moduleEventHandlers);
        moduleInitialisers[moduleName](moduleBase, moduleExports);
        return moduleExports;
    };
    cement.require = function (moduleName) {
        if (modules[moduleName]) {
            return modules[moduleName];
        } else {
            throw new Error("module : " + moduleName + " is not defined.\n ");
        }
    };
    // testing putting something on develop branch
    window.cmt = window.cement = cement;
    // test adding line on build_script feature branch
}());
<|endoftext|>