<commit_before>var eof = ["eof"];
function eofp(c) { return eof === c; }

function Stream(string) {
    var length = string.length;
    this.pos = 0;
    this.line = 1;
    this.string = string;
    this.peek_char = function() {
        return (this.pos >= length) ? eof : string[this.pos];
    }
    this.read_char = function() {
        var old_pos = this.pos;
        this.pos++;
        if (string[old_pos] == "\n") { this.line++; }
        return (old_pos >= length) ? eof : string[old_pos];
    }
    this.unread_char = function() {
        if (string[this.pos-1] == "\n") { this.line--; }
        this.pos--;
    }
    this.fork = function() {
        var fork = new Stream(string);
        fork.pos = this.pos;
        fork.line = this.line;
        return fork;
    }
}

function condition(args) {
    this.resume = args.resume;
    this.msg = args.msg;
}

function whitespacep(c) { return /\s+/.test(c); }
function symbolicp(c) { return /[a-zA-Z0-9=\/\\!@#$%^&*_+=\-?.~<>]/.test(c); }
function number_stringp(s) { return /^([0-9]*\.)?[0-9]+$/.test(s); }

function skip_whitespace(input_stream) {
    var c;
    while(true) {
        c = input_stream.read_char();
        if(!whitespacep(c)) { break; }
    }
    input_stream.unread_char();
}

function skip_whitespace_and_comments(input_stream) {
    var c;
    while(true) {
        c = input_stream.read_char();
        if(c == ";") {
            while(!eofp(c)) {
                c = input_stream.read_char();
                if(c == "\n") {
                    break;
                }
            }
        }
        else if(!whitespacep(c)) { break; }
    }
    input_stream.unread_char();
}

function read_symbol(input_stream) {
    var buffer = [input_stream.read_char()];
    var c;
    while(true) {
        c = input_stream.read_char();
        if(!eofp(c) && symbolicp(c)) {
            buffer.push(c);
        } else {
            input_stream.unread_char();
            var result = buffer.join("");
            return (number_stringp(result) ? parseFloat(result) : intern(result));
        }
    }
}

function read_string(input_stream) {
    var buffer = [];
    var c;
    input_stream.read_char();
    while(c = input_stream.read_char()) {
        if(c == '"') {
            return buffer.join("");
        } else if (c == "\\") {
            buffer.push(input_stream.read_char());
        } else {
            buffer.push(c);
        }
    }
}

function read_after_whitespace(input_stream) {
    skip_whitespace(input_stream);
    return read(input_stream);
}

function read_after_comment(input_stream) {
    var c;
    while(true) {
        c = input_stream.read_char();
        if(c == "\n") {  return read(input_stream); }
        else if (c === eof) { throw "eof"; }
    }
}

function read_quoted(input_stream) {
    input_stream.read_char();
    return cons(intern("quote"), cons(read(input_stream), null));
}

function read_quasiquoted(input_stream) {
    input_stream.read_char();
    return cons(intern("quasiquote"), cons(read(input_stream), null));
}

function read_unquoted(input_stream) {
    input_stream.read_char();
    return cons(intern("unquote"), cons(read(input_stream), null));
}

function read_list(input_stream) {
    input_stream.read_char();
    return read_list_aux(null, input_stream);
}

function read_list_aux(sexps, input_stream) {
    while (true) {
        skip_whitespace(input_stream);
        var c = input_stream.peek_char();
        switch (c) {
        case eof:
            throw "unexpected eof";
        case ")":
            input_stream.read_char();
            return reverse_aux(sexps, null);
        case ".":
            return read_after_dot(sexps, input_stream);
        default:
            sexps = cons(read(input_stream), sexps);
        }
    }
}

function read_after_dot(sexps, input_stream) {
    input_stream.read_char();
    var last = read(input_stream);
    skip_whitespace(input_stream);
    var c = input_stream.peek_char();
    switch (c) {
    case eof:
        throw "unexpected eof";
    case ")":
        input_stream.read_char();
        break;
    default:
        throw "too many expressions after dot";
    }
    return reverse_aux(sexps, last);
}

function read_hash(input_stream) {
    input_stream.read_char();
    switch (input_stream.read_char()) {
    case "f": return false;
    case "t": return true;
    case "\\": return input_stream.read_char();
    default: throw  "unknown hash code";
    }
}

function reader_for(c) {
    switch(c) {
    case '"': return read_string;
    case "'": return read_quoted;
    case "`": return read_quasiquoted;
    case ",": return read_unquoted;
    case "(": return read_list;
    case ";": return read_after_comment;
    case "#": return read_hash;
    case eof: return false;
    }
    if (whitespacep(c)) { return read_after_whitespace; }
    if (symbolicp(c)) { return read_symbol; }
    return false;
}

function read(input_stream) {
    var c = input_stream.peek_char();
    var reader = reader_for(c);
    if(reader) { return reader(input_stream); }
    throw "no reader for: " + c;
}

function read_top(sexps, input_stream) {
    while (true) {
        skip_whitespace_and_comments(input_stream);
        var c = input_stream.peek_char();
        if (c === eof) {
            input_stream.read_char();
            return reverse_aux(sexps, null);
        } else {
            sexps = cons(read(input_stream), sexps);
        }
    }
}

function ReaderError(msg) { this.msg = msg; }
function read_program(str) {
    try { return read_top(null, new Stream(str)); }
    catch(err) { throw new ReaderError(err); }
}
<commit_msg>fix ;; at end of list error<commit_after>var eof = ["eof"];
function eofp(c) { return eof === c; }

function Stream(string) {
    var length = string.length;
    this.pos = 0;
    this.line = 1;
    this.string = string;
    this.peek_char = function() {
        return (this.pos >= length) ? eof : string[this.pos];
    }
    this.read_char = function() {
        var old_pos = this.pos;
        this.pos++;
        if (string[old_pos] == "\n") { this.line++; }
        return (old_pos >= length) ? eof : string[old_pos];
    }
    this.unread_char = function() {
        if (string[this.pos-1] == "\n") { this.line--; }
        this.pos--;
    }
    this.fork = function() {
        var fork = new Stream(string);
        fork.pos = this.pos;
        fork.line = this.line;
        return fork;
    }
}

function condition(args) {
    this.resume = args.resume;
    this.msg = args.msg;
}

function whitespacep(c) { return /\s+/.test(c); }
function symbolicp(c) { return /[a-zA-Z0-9=\/\\!@#$%^&*_+=\-?.~<>]/.test(c); }
function number_stringp(s) { return /^([0-9]*\.)?[0-9]+$/.test(s); }

function skip_whitespace(input_stream) {
    var c;
    while(true) {
        c = input_stream.read_char();
        if(!whitespacep(c)) { break; }
    }
    input_stream.unread_char();
}

function skip_whitespace_and_comments(input_stream) {
    var c;
    while(true) {
        c = input_stream.read_char();
        if(c == ";") {
            while(!eofp(c)) {
                c = input_stream.read_char();
                if(c == "\n") {
                    break;
                }
            }
        }
        else if(!whitespacep(c)) { break; }
    }
    input_stream.unread_char();
}

function read_symbol(input_stream) {
    var buffer = [input_stream.read_char()];
    var c;
    while(true) {
        c = input_stream.read_char();
        if(!eofp(c) && symbolicp(c)) {
            buffer.push(c);
        } else {
            input_stream.unread_char();
            var result = buffer.join("");
            return (number_stringp(result) ? parseFloat(result) : intern(result));
        }
    }
}

function read_string(input_stream) {
    var buffer = [];
    var c;
    input_stream.read_char();
    while(c = input_stream.read_char()) {
        if(c == '"') {
            return buffer.join("");
        } else if (c == "\\") {
            buffer.push(input_stream.read_char());
        } else {
            buffer.push(c);
        }
    }
}

function read_after_whitespace(input_stream) {
    skip_whitespace(input_stream);
    return read(input_stream);
}

function read_after_comment(input_stream) {
    var c;
    while(true) {
        c = input_stream.read_char();
        if(c == "\n") {  return read(input_stream); }
        else if (c === eof) { throw "eof"; }
    }
}

function read_quoted(input_stream) {
    input_stream.read_char();
    return cons(intern("quote"), cons(read(input_stream), null));
}

function read_quasiquoted(input_stream) {
    input_stream.read_char();
    return cons(intern("quasiquote"), cons(read(input_stream), null));
}

function read_unquoted(input_stream) {
    input_stream.read_char();
    return cons(intern("unquote"), cons(read(input_stream), null));
}

function read_list(input_stream) {
    input_stream.read_char();
    return read_list_aux(null, input_stream);
}

function read_list_aux(sexps, input_stream) {
    while (true) {
        skip_whitespace_and_comments(input_stream);
        var c = input_stream.peek_char();
        switch (c) {
        case eof:
            throw "unexpected eof";
        case ")":
            input_stream.read_char();
            return reverse_aux(sexps, null);
        case ".":
            return read_after_dot(sexps, input_stream);
        default:
            sexps = cons(read(input_stream), sexps);
        }
    }
}

function read_after_dot(sexps, input_stream) {
    input_stream.read_char();
    var last = read(input_stream);
    skip_whitespace(input_stream);
    var c = input_stream.peek_char();
    switch (c) {
    case eof:
        throw "unexpected eof";
    case ")":
        input_stream.read_char();
        break;
    default:
        throw "too many expressions after dot";
    }
    return reverse_aux(sexps, last);
}

function read_hash(input_stream) {
    input_stream.read_char();
    switch (input_stream.read_char()) {
    case "f": return false;
    case "t": return true;
    case "\\": return input_stream.read_char();
    default: throw  "unknown hash code";
    }
}

function reader_for(c) {
    switch(c) {
    case '"': return read_string;
    case "'": return read_quoted;
    case "`": return read_quasiquoted;
    case ",": return read_unquoted;
    case "(": return read_list;
    case ";": return read_after_comment;
    case "#": return read_hash;
    case eof: return false;
    }
    if (whitespacep(c)) { return read_after_whitespace; }
    if (symbolicp(c)) { return read_symbol; }
    return false;
}

function read(input_stream) {
    var c = input_stream.peek_char();
    var reader = reader_for(c);
    if(reader) { return reader(input_stream); }
    throw "no reader for: " + c;
}

function read_top(sexps, input_stream) {
    while (true) {
        skip_whitespace_and_comments(input_stream);
        var c = input_stream.peek_char();
        if (c === eof) {
            input_stream.read_char();
            return reverse_aux(sexps, null);
        } else {
            sexps = cons(read(input_stream), sexps);
        }
    }
}

function ReaderError(msg) { this.msg = msg; }
function read_program(str) {
    try { return read_top(null, new Stream(str)); }
    catch(err) { throw new ReaderError(err); }
}
<|endoftext|>


<commit_before>/*
 * Return query for one quote, either by passed ID or at random
 *
 *   getQuote.byID(id, function(err, res));
 *   getQuote.atRandom(function(err, res));
 *
 * Author: Peter Martinson
 * Date:   March 10, 2017
*/

const mongoose    = require('mongoose');
const quoteSchema = require('../models/quoteSchema.js');

const Quote = mongoose.model('Quote', quoteSchema);

module.exports = {

  byID:     function(id, callback) {
    Quote.find({ quote_id : id }, function(err, result) {
      if (err) callback(err);
      else     callback(null, result);
    });
  },

  atRandom: function(callback) {
    Quote.count({}, function(err, N) {
      if (err) callback(err);
      var id = Math.floor(Math.random() * N);
      Quote.find({ quote_id : id }, function(err, result) {
        if (err) callback(err);
        else     callback(null, result, id);
      });
    });
  }

}

// Below is for testing purposes

// var getQuoteByID = function(id, callback) {
//     Quote.find({ quote_id : id }, function(err, result) {
//       if (err) { callback(err); }
//       else { callback(null, result); }
//     });
// }

// var getRandomQuote = function(callback) {
//   var id = Math.floor(Math.random() * 70);
//     Quote.find({ quote_id : id }, function(err, result) {
//       if (err) { callback(err); }
//       else { callback(null, result, id); }
//     });
// }

// var test_id = 22;
// getQuoteByID(test_id, function(err, result) {
//   console.log("result from callback: " + result);
// });

// getRandomQuote(function(err, result, id) {
//   console.log("random quote #" + id + ": " + result);
// });

<commit_msg>Catch bad number ID input<commit_after>/*
 * Return query for one quote, either by passed ID or at random
 *
 *   getQuote.byID(id, function(err, res));
 *   getQuote.atRandom(function(err, res));
 *
 * Author: Peter Martinson
 * Date:   March 10, 2017
*/

const mongoose    = require('mongoose');
const quoteSchema = require('../models/quoteSchema.js');

const Quote = mongoose.model('Quote', quoteSchema);

module.exports = {

  // byID:     function(id, callback) {
  //   Quote.find({ quote_id : id }, function(err, result) {
  //     if (err) callback(err);
  //     else     callback(null, result);
  //   });
  // },

  byID:     function(id, callback) {
    Quote.count({}, function(err, N) {
      if (err) callback(err);
      if ( id <= N ) {
        Quote.find({ quote_id : id }, function(err, result) {
          if (err) callback(err);
          else     callback(null, result);
        });
      }
      else {
        // return a BAD NUMBER flag
      }
    });
  },

  atRandom: function(callback) {
    Quote.count({}, function(err, N) {
      if (err) callback(err);
      var id = Math.floor(Math.random() * N);
      Quote.find({ quote_id : id }, function(err, result) {
        if (err) callback(err);
        else     callback(null, result, id);
      });
    });
  }

}

// Below is for testing purposes

// var getQuoteByID = function(id, callback) {
//     Quote.find({ quote_id : id }, function(err, result) {
//       if (err) { callback(err); }
//       else { callback(null, result); }
//     });
// }

// var getRandomQuote = function(callback) {
//   var id = Math.floor(Math.random() * 70);
//     Quote.find({ quote_id : id }, function(err, result) {
//       if (err) { callback(err); }
//       else { callback(null, result, id); }
//     });
// }

// var test_id = 22;
// getQuoteByID(test_id, function(err, result) {
//   console.log("result from callback: " + result);
// });

// getRandomQuote(function(err, result, id) {
//   console.log("random quote #" + id + ": " + result);
// });

<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import Error from '../components/Error';
import withIntl from '../lib/withIntl';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag'
import { DropdownButton, MenuItem, Badge } from 'react-bootstrap';
import Currency from '../components/Currency';
import { FormattedMessage, defineMessages } from 'react-intl';
import ConnectPaypal from '../components/ConnectPaypal';
import AddFundsForm from '../components/AddFundsForm';
import { pick } from 'lodash';

class CollectivePickerWithData extends React.Component {

  static propTypes = {
    hostCollectiveSlug: PropTypes.string.isRequired,
    onChange: PropTypes.func
  }

  constructor(props) {
    super(props);
    this.state = {
      connectingPaypal: false,
      loading: false,
      showAddFunds: false
    };
    this.addFunds = this.addFunds.bind(this);
    this.toggleAddFunds = this.toggleAddFunds.bind(this);
    this.onChange = this.onChange.bind(this);
    this.messages = defineMessages({
      'badge.tooltip.pending': { id: 'expenses.badge.tooltip.pending', defaultMessage: "{pending} {pending, plural, one {expense} other {expenses}} pending approval" },
      'badge.tooltip.approved': { id: 'expenses.badge.tooltip.approved', defaultMessage: "{approved} {approved, plural, one {expense} other {expenses}} ready to be paid" }
    });
  }

  canEdit = () => {
    const { LoggedInUser } = this.props;
    return LoggedInUser && LoggedInUser.canEditCollective(this.hostCollective);
  }

  async addFunds(form) {
    if (form.totalAmount === 0) {
      return console.error("Total amount must be > 0");
    }
    this.setState({ loading: true });
    const hostCollective = this.hostCollective;
    const order = pick(form, ['totalAmount', 'description', 'hostFeePercent', 'platformFeePercent']);
    order.collective = {
      id: this.state.CollectiveId
    };
    if (form.email) {
      order.user = {
        email: form.email,
        name: form.name
      }
    } else if (form.organization) {
      order.fromCollective = {
        name: form.organization,
        website: form.website
      }
    } else {
      order.fromCollective = {
        id: form.FromCollectiveId || hostCollective.id
      }
    }
    const pm = hostCollective.paymentMethods.find(pm => pm.service === 'opencollective');
    if (!pm) {
      this.setState({ error: "This host doesn't have an opencollective payment method", loading: false });
      return console.error(">>> payment methods: ", hostCollective.paymentMethods);
    }
    order.paymentMethod = {
      uuid: pm.uuid
    }
    console.log(">>> add funds order: ", order);
    try {
      await this.props.createOrder(order);
      this.setState({ showAddFunds: false, loading: false });
    } catch (e) {
      const error = e.message && e.message.replace(/GraphQL error:/, "");
      this.setState({ error, loading: false });
    }
  }

  toggleAddFunds() {
    this.setState({ showAddFunds: !this.state.showAddFunds });
  }

  onChange(CollectiveId) {
    const collectives = this.hostCollective.collectives;
    const selectedCollective = CollectiveId > 0 && collectives.find(c => c.id === CollectiveId);
    this.setState({ CollectiveId });
    this.props.onChange(selectedCollective);
  }

  renderCollectiveMenuItem(collective, className) {
    const { intl } = this.props;
    const badgeCount = collective.stats.expenses.pending + collective.stats.expenses.approved;

    const tooltipArray = [];
    if (collective.stats.expenses.pending > 0) {
      tooltipArray.push(intl.formatMessage(this.messages['badge.tooltip.pending'], collective.stats.expenses));
    }
    if (collective.stats.expenses.approved > 0) {
      tooltipArray.push(intl.formatMessage(this.messages['badge.tooltip.approved'], collective.stats.expenses));
    }
    const tooltip = tooltipArray.join(', ') || '';

    return (<div className={`MenuItem-Collective ${className}`} title={tooltip}>

{collective.name}

          <FormattedMessage id="expenses.balance.label" defaultMessage="balance:" />
          <Currency value={collective.stats.balance} currency={collective.currency} />

      { badgeCount > 0 && <Badge pullRight={true}>{badgeCount}</Badge> }

);
  }

  render() {
    const { data: { loading, error, Collective } } = this.props;

    if (error) {
      console.error("graphql error>>>", error.message);
      return (<Error message="GraphQL error" />)
    }

    this.hostCollective = Collective || this.hostCollective;
    if (loading || !this.hostCollective) {
      return (
);
    }

    const collectives = [...this.hostCollective.collectives];

    const selectedCollective = collectives.find(c => c.id === this.state.CollectiveId);
    const selectedTitle = selectedCollective ? this.renderCollectiveMenuItem(selectedCollective, 'selected') :
<FormattedMessage id="expenses.allCollectives" defaultMessage="All Collectives" />
;

    return (

<FormattedMessage id="expenses.collectivePicker.title" defaultMessage="Finances" />

<FormattedMessage id="expenses.collectivePicker.subtitle" defaultMessage="for {n} {n, plural, one {collective} other {collectives}}" values={{n: collectives.length}} />

            { collectives.length > 0 &&

              <DropdownButton id="collectivePicker" bsStyle="default" title={selectedTitle} onSelect={this.onChange}>
                { this.state.CollectiveId &&
                <MenuItem key={null} eventKey={null}>
                  <FormattedMessage id="expenses.allCollectives" defaultMessage="All Collectives" />
                </MenuItem>
                  }
                { collectives.map(collective => (
                  <MenuItem key={collective.id} eventKey={collective.id} title={collective.name}>
                    { this.renderCollectiveMenuItem(collective) }
                  </MenuItem>
                  ))}
              </DropdownButton>
              { selectedCollective && !this.state.showAddFunds && ::this.canEdit() &&
              <FormattedMessage id="addfunds.submit" defaultMessage="Add Funds" />
                }

            }

            { ::this.canEdit() && <ConnectPaypal collective={this.hostCollective} /> }

          { selectedCollective && this.state.showAddFunds &&

            <AddFundsForm
              collective={selectedCollective}
              host={this.hostCollective}
              onSubmit={this.addFunds}
              onCancel={this.toggleAddFunds}
              loading={this.state.loading}
              LoggedInUser={this.props.LoggedInUser}
              />

{this.state.error}

            }

    );
  }
}

const getCollectivesQuery = gql`
query Collective($hostCollectiveSlug: String!, $orderBy: CollectiveOrderField, $orderDirection: OrderDirection) {
  Collective(slug: $hostCollectiveSlug) {
    id
    slug
    name
    paymentMethods {
      id
      uuid
      service
      createdAt
      balance
      currency
    }
    collectives(orderBy: $orderBy, orderDirection: $orderDirection) {
      id
      slug
      name
      currency
      hostFeePercent
      stats {
        id
        balance
        expenses {
          id
          all
          pending
          paid
          rejected
          approved
        }
      }
    }
  }
}
`;

const COLLECTIVES_PER_PAGE = 20;
export const addCollectivesData = graphql(getCollectivesQuery, {
  options(props) {
    return {
      variables: {
        hostCollectiveSlug: props.hostCollectiveSlug,
        offset: 0,
        limit: props.limit || COLLECTIVES_PER_PAGE * 2,
        includeHostedCollectives: true,
        orderBy: 'name',
        orderDirection: 'ASC',
      }
    }
  },
  props: ({ data }) => ({
    data,
    fetchMore: () => {
      return data.fetchMore({
        variables: {
          offset: data.allCollectives.length,
          limit: COLLECTIVES_PER_PAGE
        },
        updateQuery: (previousResult, { fetchMoreResult }) => {
          if (!fetchMoreResult) {
            return previousResult
          }
          return Object.assign({}, previousResult, {
            // Append the new posts results to the old one
            allCollectives: [...previousResult.allCollectives, ...fetchMoreResult.allCollectives]
          })
        }
      })
    }
  })
});

const createOrderQuery = gql`
mutation createOrder($order: OrderInputType!) {
  createOrder(order: $order) {
    id
    collective {
      id
      stats {
        id
        balance
      }
    }
  }
}
`;

const addMutation = graphql(createOrderQuery, {
  props: ({ mutate }) => ({
    createOrder: async (order) => {
      return await mutate({ variables: { order } })
    }
  })
});

const addGraphQL = compose(addMutation, addCollectivesData);

export default addGraphQL(withIntl(CollectivePickerWithData));
<commit_msg>chore(CollectivePickerWithData): Add pagination fields to GQL query<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Error from '../components/Error';
import withIntl from '../lib/withIntl';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag'
import { DropdownButton, MenuItem, Badge } from 'react-bootstrap';
import Currency from '../components/Currency';
import { FormattedMessage, defineMessages } from 'react-intl';
import ConnectPaypal from '../components/ConnectPaypal';
import AddFundsForm from '../components/AddFundsForm';
import { pick } from 'lodash';

class CollectivePickerWithData extends React.Component {

  static propTypes = {
    hostCollectiveSlug: PropTypes.string.isRequired,
    onChange: PropTypes.func
  }

  constructor(props) {
    super(props);
    this.state = {
      connectingPaypal: false,
      loading: false,
      showAddFunds: false
    };
    this.addFunds = this.addFunds.bind(this);
    this.toggleAddFunds = this.toggleAddFunds.bind(this);
    this.onChange = this.onChange.bind(this);
    this.messages = defineMessages({
      'badge.tooltip.pending': { id: 'expenses.badge.tooltip.pending', defaultMessage: "{pending} {pending, plural, one {expense} other {expenses}} pending approval" },
      'badge.tooltip.approved': { id: 'expenses.badge.tooltip.approved', defaultMessage: "{approved} {approved, plural, one {expense} other {expenses}} ready to be paid" }
    });
  }

  canEdit = () => {
    const { LoggedInUser } = this.props;
    return LoggedInUser && LoggedInUser.canEditCollective(this.hostCollective);
  }

  async addFunds(form) {
    if (form.totalAmount === 0) {
      return console.error("Total amount must be > 0");
    }
    this.setState({ loading: true });
    const hostCollective = this.hostCollective;
    const order = pick(form, ['totalAmount', 'description', 'hostFeePercent', 'platformFeePercent']);
    order.collective = {
      id: this.state.CollectiveId
    };
    if (form.email) {
      order.user = {
        email: form.email,
        name: form.name
      }
    } else if (form.organization) {
      order.fromCollective = {
        name: form.organization,
        website: form.website
      }
    } else {
      order.fromCollective = {
        id: form.FromCollectiveId || hostCollective.id
      }
    }
    const pm = hostCollective.paymentMethods.find(pm => pm.service === 'opencollective');
    if (!pm) {
      this.setState({ error: "This host doesn't have an opencollective payment method", loading: false });
      return console.error(">>> payment methods: ", hostCollective.paymentMethods);
    }
    order.paymentMethod = {
      uuid: pm.uuid
    }
    console.log(">>> add funds order: ", order);
    try {
      await this.props.createOrder(order);
      this.setState({ showAddFunds: false, loading: false });
    } catch (e) {
      const error = e.message && e.message.replace(/GraphQL error:/, "");
      this.setState({ error, loading: false });
    }
  }

  toggleAddFunds() {
    this.setState({ showAddFunds: !this.state.showAddFunds });
  }

  onChange(CollectiveId) {
    const collectives = this.hostCollective.collectives.collectives;
    const selectedCollective = CollectiveId > 0 && collectives.find(c => c.id === CollectiveId);
    this.setState({ CollectiveId });
    this.props.onChange(selectedCollective);
  }

  renderCollectiveMenuItem(collective, className) {
    const { intl } = this.props;
    const badgeCount = collective.stats.expenses.pending + collective.stats.expenses.approved;

    const tooltipArray = [];
    if (collective.stats.expenses.pending > 0) {
      tooltipArray.push(intl.formatMessage(this.messages['badge.tooltip.pending'], collective.stats.expenses));
    }
    if (collective.stats.expenses.approved > 0) {
      tooltipArray.push(intl.formatMessage(this.messages['badge.tooltip.approved'], collective.stats.expenses));
    }
    const tooltip = tooltipArray.join(', ') || '';

    return (<div className={`MenuItem-Collective ${className}`} title={tooltip}>

{collective.name}

          <FormattedMessage id="expenses.balance.label" defaultMessage="balance:" />
          <Currency value={collective.stats.balance} currency={collective.currency} />

      { badgeCount > 0 && <Badge pullRight={true}>{badgeCount}</Badge> }

);
  }

  render() {
    const { data: { loading, error, Collective } } = this.props;

    if (error) {
      console.error("graphql error>>>", error.message);
      return (<Error message="GraphQL error" />)
    }

    this.hostCollective = Collective || this.hostCollective;
    if (loading || !this.hostCollective) {
      return (
);
    }

    const collectives = [...this.hostCollective.collectives.collectives];

    const selectedCollective = collectives.find(c => c.id === this.state.CollectiveId);
    const selectedTitle = selectedCollective ? this.renderCollectiveMenuItem(selectedCollective, 'selected') :
<FormattedMessage id="expenses.allCollectives" defaultMessage="All Collectives" />
;

    return (

<FormattedMessage id="expenses.collectivePicker.title" defaultMessage="Finances" />

<FormattedMessage id="expenses.collectivePicker.subtitle" defaultMessage="for {n} {n, plural, one {collective} other {collectives}}" values={{n: collectives.length}} />

            { collectives.length > 0 &&

              <DropdownButton id="collectivePicker" bsStyle="default" title={selectedTitle} onSelect={this.onChange}>
                { this.state.CollectiveId &&
                <MenuItem key={null} eventKey={null}>
                  <FormattedMessage id="expenses.allCollectives" defaultMessage="All Collectives" />
                </MenuItem>
                  }
                { collectives.map(collective => (
                  <MenuItem key={collective.id} eventKey={collective.id} title={collective.name}>
                    { this.renderCollectiveMenuItem(collective) }
                  </MenuItem>
                  ))}
              </DropdownButton>
              { selectedCollective && !this.state.showAddFunds && ::this.canEdit() &&
              <FormattedMessage id="addfunds.submit" defaultMessage="Add Funds" />
                }

            }

            { ::this.canEdit() && <ConnectPaypal collective={this.hostCollective} /> }

          { selectedCollective && this.state.showAddFunds &&

            <AddFundsForm
              collective={selectedCollective}
              host={this.hostCollective}
              onSubmit={this.addFunds}
              onCancel={this.toggleAddFunds}
              loading={this.state.loading}
              LoggedInUser={this.props.LoggedInUser}
              />

{this.state.error}

            }

    );
  }
}

const getCollectivesQuery = gql`
query Collective($hostCollectiveSlug: String!, $orderBy: CollectiveOrderField, $orderDirection: OrderDirection) {
  Collective(slug: $hostCollectiveSlug) {
    id
    slug
    name
    paymentMethods {
      id
      uuid
      service
      createdAt
      balance
      currency
    }
    collectives(orderBy: $orderBy, orderDirection: $orderDirection) {
      total
      collectives {
        id
        slug
        name
        currency
        hostFeePercent
        stats {
          id
          balance
          expenses {
            id
            all
            pending
            paid
            rejected
            approved
          }
        }
      }
    }
  }
}
`;

const COLLECTIVES_PER_PAGE = 20;
export const addCollectivesData = graphql(getCollectivesQuery, {
  options(props) {
    return {
      variables: {
        hostCollectiveSlug: props.hostCollectiveSlug,
        offset: 0,
        limit: props.limit || COLLECTIVES_PER_PAGE * 2,
        includeHostedCollectives: true,
        orderBy: 'name',
        orderDirection: 'ASC',
      }
    }
  },
  props: ({ data }) => ({
    data,
    fetchMore: () => {
      return data.fetchMore({
        variables: {
          offset: data.allCollectives.length,
          limit: COLLECTIVES_PER_PAGE
        },
        updateQuery: (previousResult, { fetchMoreResult }) => {
          if (!fetchMoreResult) {
            return previousResult
          }
          return Object.assign({}, previousResult, {
            // Append the new posts results to the old one
            allCollectives: [...previousResult.allCollectives, ...fetchMoreResult.allCollectives]
          })
        }
      })
    }
  })
});

const createOrderQuery = gql`
mutation createOrder($order: OrderInputType!) {
  createOrder(order: $order) {
    id
    collective {
      id
      stats {
        id
        balance
      }
    }
  }
}
`;

const addMutation = graphql(createOrderQuery, {
  props: ({ mutate }) => ({
    createOrder: async (order) => {
      return await mutate({ variables: { order } })
    }
  })
});

const addGraphQL = compose(addMutation, addCollectivesData);

export default addGraphQL(withIntl(CollectivePickerWithData));
<|endoftext|>


<commit_before>function chartInput(form) {
      var rate = form.rate.value;
      var goal = form.goal.value;

      var rest = goal % rate;
      if (rest == 0) {
            var months = goal / rate;
      } else {
            var months = Math.floor(goal / rate) + 1;
      }

      var i;
      var numMonths = [];
      for (i = 1; i <= months; i++) {
            numMonths.push(i);
      }

      var values = [];
      for (i = 1; i <= months; i++) {
            values.push(rate * (Math.pow(1.004, i) - 1) / 0.004);
      }

      $(function() {
            $('#container').highcharts({
                  title: {
                  text: 'Your Savings',
                  },
                  xAxis: {
                  categories: numMonths
                  },
                  yAxis: {
                  title: {
                        text: 'Amount Reached'
                  },
                  plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                  }]
                  },
                  series: [{
                  data: values
                  }]
            });
      });
      }<commit_msg>format<commit_after>function chartInput(form) {
      var rate = form.rate.value;
      var goal = form.goal.value;

      var rest = goal % rate;
      if (rest == 0) {
            var months = goal / rate;
      } else {
            var months = Math.floor(goal / rate) + 1;
      }

      var i;
      var numMonths = [];
      for (i = 1; i <= months; i++) {
            numMonths.push(i);
      }

      var values = [];
      var interestRate = 1.004;
      for (i = 1; i <= months; i++) {
            values.push(rate * (Math.pow(interestRate, i) - 1) / (interestRate - 1));
      }

      $(function() {
            $('#container').highcharts({
                  title: {
                  text: 'Your Savings',
                  },
                  xAxis: {
                  categories: numMonths
                  },
                  yAxis: {
                  title: {
                        text: 'Amount Reached'
                  },
                  plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                  }]
                  },
                  series: [{
                  data: values
                  }]
            });
      });
      }<|endoftext|>


<commit_before>const path = require('path');
const fs = require('fs-extra');
const chalk = require('chalk');
const Insight = require('insight');
const semver = require('semver');
const replace = require('replace-in-file');
const Generator = require('@ngx-rocket/core');
const asciiLogo = require('@ngx-rocket/ascii-logo');

const pkg = require('../../package.json');
const prompts = require('./prompts.js');
const options = require('./options.js');
const getLanguages = require('./languages.js');
const {deployers} = require('./deployers.js');

const packageJsonFile = 'package.json';
const appPath = 'src/app';

class NgxGenerator extends Generator {
  initializing() {
    this.version = pkg.version;
    this.props = {};

    // Disable automatic env install based on package.json
    this.features.customInstallTask = true;

    // Try to initialize analytics. Insight is broken for some users, so if it fails, proceed as if the --no-analytics flag was present.
    try {
      this.insight =
        !this.options.analytics || process.env.DISABLE_NGX_ANALYTICS
          ? {track: () => {}}
          : new Insight({trackingCode: 'UA-93069862-1', pkg});
    } catch {
      this.insight = {track: () => {}};
      this.log(
        chalk.yellow(
          'There was a problem collecting analytics data. Proceeding without anonymous usage tracking. To suppress this warning in the future, use the --no-analytics flag.'
        )
      );
    }

    if (semver.lt(process.version, '10.9.0')) {
      this.log(chalk.yellow('Angular CLI v8 needs NodeJS v10.9 or greater.'));
      this.log(chalk.yellow(`You are using ${process.version} which is unsupported, please upgrade.\n`));
      // eslint-disable-next-line unicorn/no-process-exit
      process.exit(-1);
    }

    this.argument('appName', {
      description: 'Name of the app to generate',
      type: String,
      required: false
    });

    this.insight.optOut = !this.options.analytics || process.env.DISABLE_NGX_ANALYTICS;

    if (this.options.raw) {
      this.props.ui = 'raw';
    }

    if (this.options['location-strategy']) {
      this.props.location = this.options['location-strategy'];
    }

    this.props.strict = this.options.strict;
    this.props.skipInstall = this.options['skip-install'];
    this.props.skipQuickstart = this.options['skip-quickstart'];
    this.props.initGit = this.options.git;
    this.props.usePrefix = this.options.prefix;

    if (this.options.deploy) {
      this.props.deploy = this.options.deploy;
    }

    // Updating
    let fromVersion = null;

    if (this.options.update) {
      this.props = this.config.get('props') || this.props;
      fromVersion = this.config.get('version');
    }

    if (fromVersion) {
      if (fromVersion >= this.version) {
        this.log(chalk.green('\nNothing to update, it’s all good!\n'));
        // eslint-disable-next-line unicorn/no-process-exit
        process.exit(0);
      }

      this.updating = true;
      this.log(
        `\nUpdating ${chalk.green(this.props.appName)} project (${chalk.yellow(fromVersion)} -> ${chalk.yellow(
          this.version
        )})\n`
      );
      this.log(`${chalk.yellow('Make sure you don’t have uncommitted changes before overwriting files!')}`);
      this.insight.track('update', fromVersion, 'to', this.version);
    } else if (!this.options['skip-welcome']) {
      this.log(asciiLogo(pkg.version));
    }

    // Composition
    const addonsOption = this.options.addons;
    this.addons = addonsOption ? addonsOption.split(' ') : [];
    this.addons.forEach((addon) => {
      try {
        if (/[:/]/.test(addon)) {
          // Fetch addon name from URL/GitHub/Local package format
          let splitIndex = addon.lastIndexOf('/');
          splitIndex = splitIndex === -1 ? addon.lastIndexOf(':') : splitIndex;
          addon = addon.slice(splitIndex + 1);
        }

        if (addon.startsWith('generator-')) {
          // This prefix must be removed for Yeoman to work properly
          addon = addon.slice(10);
        }

        if (addon.endsWith('.git')) {
          // When working with git repos, this suffix must be removed
          addon = addon.slice(0, -4);
        }

        this.composeWith(addon, this.options);
      } catch {
        this.log(chalk.red(`Error: add-on "${addon}" not found.`));
        // eslint-disable-next-line unicorn/no-process-exit
        process.exit(-1);
      }
    });

    this.insight.track('version', this.version);
    this.insight.track('node', process.version);
    this.insight.track('platform', process.platform);
    this.insight.track('addons', addonsOption);
  }

  async prompting() {
    // Allow to pre-set any props in an add-on generator
    Object.assign(this.props, this.sharedProps);

    await super.prompting();
    this.props.mobile = this.props.mobile || [];
    this.props.desktop = this.props.desktop || [];
    this.props.utility = this.props.utility || [];
    this.props.tools = this.props.tools || [];
    this.props.languages = this.props.languages || ['en-US', 'fr-FR'];
    this.props.usePrefix = typeof this.props.usePrefix === 'boolean' ? this.props.usePrefix : true;
    this.props.deploy = this.props.deploy || 'none';
    this.props.features = this.props.features || [];
    this.props.pwa = this.props.features.includes('pwa');
    this.props.auth = this.props.features.includes('auth');
    this.props.lazy = this.props.features.includes('lazy');
    this.props.e2e = this.props.tools.includes('protractor'); // legacy e2e
    this.props.cypress = this.props.features.includes('cypress') && !this.props.e2e;
    this.props.angulartics = this.props.features.includes('angulartics');
    this.shareProps(this.props);
  }

  configuring() {
    // Add prefix rules for languages
    getLanguages().forEach((language) => {
      this._prefixRules[language] = (props) => props.languages.includes(language);
    });

    this.insight.track(
      'generator',
      this.props.target,
      this.props.target.includes('web') && this.props.pwa ? 'pwa' : '',
      this.props.target.includes('cordova') ? this.props.mobile : '',
      this.props.ui,
      this.props.auth ? 'auth' : 'no-auth'
    );
    this.insight.track('package-manager', this.packageManager);

    if (this.props.target.includes('cordova') && this.packageManager === 'yarn') {
      this.log(chalk.yellow('\nWarning: Using Yarn with Cordova is NOT recommended!'));
      this.log(chalk.yellow('Cordova still uses NPM to fetch packages, causing issues with Yarn.\n'));
    }
  }

  install() {
    if (!this.props.usePrefix) {
      this.log(`\nConfiguring prefix, please wait…`);

      const clientPath = this.isFullstack ? process.env.NGX_CLIENT_PATH : '';
      const basePath = this.destinationPath(path.join(clientPath, appPath));

      try {
        // Rename folders
        fs.removeSync(path.join(basePath, 'core'));
        fs.removeSync(path.join(basePath, 'shared'));
        fs.renameSync(path.join(basePath, '@shared'), path.join(basePath, 'shared'));

        // Replace imports in files
        const options = {files: 'src/**/*.ts'};
        replace.sync({...options, from: /@shared/g, to: '@app/shared'});
      } catch (error) {
        this.log(`${chalk.red('An error occured during prefix config:')}\n${error && error.message}`);
      }
    }

    if (this.props.initGit) {
      this.spawnCommandSync('git', ['init', '--quiet']);
    }

    if (!this.props.skipInstall) {
      this.log(`\nRunning ${chalk.yellow(`${this.packageManager} install`)}, please wait…`);

      const install = this.packageManager === 'yarn' ? this.yarnInstall.bind(this) : this.npmInstall.bind(this);
      // When using NPM, force install as peer dependencies with ionic-native packages
      // cause install errors with NPM >= 7.
      const options = this.packageManager === 'yarn' ? null : { force: true };

      if (fs.existsSync(this.destinationPath(packageJsonFile))) {
        install(null, options);
      }

      if (this.isFullstack) {
        if (fs.existsSync(this.destinationPath(path.join(process.env.NGX_CLIENT_PATH, packageJsonFile)))) {
          install(null, options, {cwd: this.destinationPath(process.env.NGX_CLIENT_PATH)});
        }

        if (fs.existsSync(this.destinationPath(path.join(process.env.NGX_SERVER_PATH, packageJsonFile)))) {
          install(null, options, {cwd: this.destinationPath(process.env.NGX_SERVER_PATH)});
        }
      }
    }
  }

  end() {
    const deployer = deployers.find((d) => d.value === this.props.deploy);

    if (this.props.deploy !== 'none') {
      this.log(`\nConfiguring deployment with ${chalk.cyan(deployer.name)}, please wait…\n`);
      const result = this.spawnCommandSync('ng', ['add', deployer.package]);

      if (result.error) {
        this.log(`${chalk.red('Something went wrong during deployment configuration :(')}`);
        this.log(`You can retry manually using ${chalk.yellow(`npx ng add ${deployer.package}`)}`);
      }
    }

    if (this.updating) {
      this.log(`\nUpdated ${chalk.green(this.props.appName)} to ${chalk.yellow(this.version)} successfully!`);
      return;
    }

    if (this.props.skipQuickstart) {
      return;
    }

    this.log('\nAll done! Get started with these tasks:');
    this.log(
      `- $ ${chalk.green(`${this.packageManager} start`)}: start dev server with live reload on http://localhost:4200`
    );

    if (this.props.target.includes('web')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run build`)}: build web app for production`);

      if (this.props.deploy !== 'none') {
        this.log(`- $ ${chalk.green(`${this.packageManager} run deploy`)}: deploy app to ${deployer.name}`);
      }
    }

    if (this.props.target.includes('cordova')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:prepare`)}: prepare for building mobile app`);
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:run`)}: run app on device or simulator`);
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:build`)}: build mobile app for production`);
    }

    if (this.props.target.includes('electron')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run electron:build`)}: build app for electron`);
      this.log(`- $ ${chalk.green(`${this.packageManager} run electron:run`)}: run app in electron`);
      this.log(
        `- $ ${chalk.green(
          `${this.packageManager} run electron:package`
        )}: package executables for all selected platforms`
      );
    }

    this.log(`- $ ${chalk.green(`${this.packageManager} test`)}: run unit tests in watch mode for TDD`);
    this.log(`- $ ${chalk.green(`${this.packageManager} run test:ci`)}: lint code and run units tests with coverage`);
    if (this.props.e2e || this.props.cypress) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run e2e`)}: launch e2e tests`);
    }
    if (this.props.tools.includes('hads')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run docs`)}: show docs and coding guides`);
    }

    if (this.props.tools.includes('compodoc')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run compodoc`)}: generates docs from code`);
    }

    if (this.props.tools.includes('prettier')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run prettier`)}: format your code automatically`);
    }
  }
}

module.exports = Generator.make({
  baseDir: __dirname,
  generator: NgxGenerator,
  options,
  prompts,
  prefixRules: Object.assign(Generator.defaultPrefixRules, {
    'ionic-tabs': (props) => props.ui === 'ionic' && props.layout === 'tabs',
    'ionic-side-menu': (props) => props.ui === 'ionic' && props.layout === 'side-menu',
    'material-simple': (props) => props.ui === 'material' && props.layout === 'simple',
    'material-side-menu': (props) => props.ui === 'material' && props.layout === 'side-menu',
    raw: (props) => props.ui === 'raw',
    'electron-windows': (props) => props.desktop && props.desktop.includes('windows'),
    'electron-mac': (props) => props.desktop && props.desktop.includes('mac'),
    'electron-linux': (props) => props.desktop && props.desktop.includes('linux'),
    'tools-hads': (props) => props.tools && props.tools.includes('hads'),
    'tools-jest': (props) => props.tools && props.tools.includes('jest'),
    'tools-karma': (props) => props.tools && !props.tools.includes('jest'),
    e2e: (props) => !props.features || props.features.includes('e2e'),
    cypress: (props) => !props.features || props.features.includes('cypress'),
    husky: (props) => props.initGit && props.tools.includes('prettier')
  })
});
<commit_msg>fix: cannot update issue (fix #607)<commit_after>const path = require('path');
const fs = require('fs-extra');
const chalk = require('chalk');
const Insight = require('insight');
const semver = require('semver');
const replace = require('replace-in-file');
const Generator = require('@ngx-rocket/core');
const asciiLogo = require('@ngx-rocket/ascii-logo');

const pkg = require('../../package.json');
const prompts = require('./prompts.js');
const options = require('./options.js');
const getLanguages = require('./languages.js');
const {deployers} = require('./deployers.js');

const packageJsonFile = 'package.json';
const appPath = 'src/app';

class NgxGenerator extends Generator {
  initializing() {
    this.version = pkg.version;
    this.props = {};

    // Disable automatic env install based on package.json
    this.features.customInstallTask = true;

    // Try to initialize analytics. Insight is broken for some users, so if it fails, proceed as if the --no-analytics flag was present.
    try {
      this.insight =
        !this.options.analytics || process.env.DISABLE_NGX_ANALYTICS
          ? {track: () => {}}
          : new Insight({trackingCode: 'UA-93069862-1', pkg});
    } catch {
      this.insight = {track: () => {}};
      this.log(
        chalk.yellow(
          'There was a problem collecting analytics data. Proceeding without anonymous usage tracking. To suppress this warning in the future, use the --no-analytics flag.'
        )
      );
    }

    if (semver.lt(process.version, '10.9.0')) {
      this.log(chalk.yellow('Angular CLI v8 needs NodeJS v10.9 or greater.'));
      this.log(chalk.yellow(`You are using ${process.version} which is unsupported, please upgrade.\n`));
      // eslint-disable-next-line unicorn/no-process-exit
      process.exit(-1);
    }

    this.argument('appName', {
      description: 'Name of the app to generate',
      type: String,
      required: false
    });

    this.insight.optOut = !this.options.analytics || process.env.DISABLE_NGX_ANALYTICS;

    if (this.options.raw) {
      this.props.ui = 'raw';
    }

    if (this.options['location-strategy']) {
      this.props.location = this.options['location-strategy'];
    }

    this.props.strict = this.options.strict;
    this.props.skipInstall = this.options['skip-install'];
    this.props.skipQuickstart = this.options['skip-quickstart'];
    this.props.initGit = this.options.git;
    this.props.usePrefix = this.options.prefix;

    if (this.options.deploy) {
      this.props.deploy = this.options.deploy;
    }

    // Updating
    let fromVersion = null;

    if (this.options.update) {
      this.props = this.config.get('props') || this.props;
      fromVersion = this.config.get('version');
    }

    if (fromVersion) {
      if (semver.gte(fromVersion, this.version)) {
        this.log(chalk.green('\nNothing to update, it’s all good!\n'));
        // eslint-disable-next-line unicorn/no-process-exit
        process.exit(0);
      }

      this.updating = true;
      this.log(
        `\nUpdating ${chalk.green(this.props.appName)} project (${chalk.yellow(fromVersion)} -> ${chalk.yellow(
          this.version
        )})\n`
      );
      this.log(`${chalk.yellow('Make sure you don’t have uncommitted changes before overwriting files!')}`);
      this.insight.track('update', fromVersion, 'to', this.version);
    } else if (!this.options['skip-welcome']) {
      this.log(asciiLogo(pkg.version));
    }

    // Composition
    const addonsOption = this.options.addons;
    this.addons = addonsOption ? addonsOption.split(' ') : [];
    this.addons.forEach((addon) => {
      try {
        if (/[:/]/.test(addon)) {
          // Fetch addon name from URL/GitHub/Local package format
          let splitIndex = addon.lastIndexOf('/');
          splitIndex = splitIndex === -1 ? addon.lastIndexOf(':') : splitIndex;
          addon = addon.slice(splitIndex + 1);
        }

        if (addon.startsWith('generator-')) {
          // This prefix must be removed for Yeoman to work properly
          addon = addon.slice(10);
        }

        if (addon.endsWith('.git')) {
          // When working with git repos, this suffix must be removed
          addon = addon.slice(0, -4);
        }

        this.composeWith(addon, this.options);
      } catch {
        this.log(chalk.red(`Error: add-on "${addon}" not found.`));
        // eslint-disable-next-line unicorn/no-process-exit
        process.exit(-1);
      }
    });

    this.insight.track('version', this.version);
    this.insight.track('node', process.version);
    this.insight.track('platform', process.platform);
    this.insight.track('addons', addonsOption);
  }

  async prompting() {
    // Allow to pre-set any props in an add-on generator
    Object.assign(this.props, this.sharedProps);

    await super.prompting();
    this.props.mobile = this.props.mobile || [];
    this.props.desktop = this.props.desktop || [];
    this.props.utility = this.props.utility || [];
    this.props.tools = this.props.tools || [];
    this.props.languages = this.props.languages || ['en-US', 'fr-FR'];
    this.props.usePrefix = typeof this.props.usePrefix === 'boolean' ? this.props.usePrefix : true;
    this.props.deploy = this.props.deploy || 'none';
    this.props.features = this.props.features || [];
    this.props.pwa = this.props.features.includes('pwa');
    this.props.auth = this.props.features.includes('auth');
    this.props.lazy = this.props.features.includes('lazy');
    this.props.e2e = this.props.tools.includes('protractor'); // legacy e2e
    this.props.cypress = this.props.features.includes('cypress') && !this.props.e2e;
    this.props.angulartics = this.props.features.includes('angulartics');
    this.shareProps(this.props);
  }

  configuring() {
    // Add prefix rules for languages
    getLanguages().forEach((language) => {
      this._prefixRules[language] = (props) => props.languages.includes(language);
    });

    this.insight.track(
      'generator',
      this.props.target,
      this.props.target.includes('web') && this.props.pwa ? 'pwa' : '',
      this.props.target.includes('cordova') ? this.props.mobile : '',
      this.props.ui,
      this.props.auth ? 'auth' : 'no-auth'
    );
    this.insight.track('package-manager', this.packageManager);

    if (this.props.target.includes('cordova') && this.packageManager === 'yarn') {
      this.log(chalk.yellow('\nWarning: Using Yarn with Cordova is NOT recommended!'));
      this.log(chalk.yellow('Cordova still uses NPM to fetch packages, causing issues with Yarn.\n'));
    }
  }

  install() {
    if (!this.props.usePrefix) {
      this.log(`\nConfiguring prefix, please wait…`);

      const clientPath = this.isFullstack ? process.env.NGX_CLIENT_PATH : '';
      const basePath = this.destinationPath(path.join(clientPath, appPath));

      try {
        // Rename folders
        fs.removeSync(path.join(basePath, 'core'));
        fs.removeSync(path.join(basePath, 'shared'));
        fs.renameSync(path.join(basePath, '@shared'), path.join(basePath, 'shared'));

        // Replace imports in files
        const options = {files: 'src/**/*.ts'};
        replace.sync({...options, from: /@shared/g, to: '@app/shared'});
      } catch (error) {
        this.log(`${chalk.red('An error occured during prefix config:')}\n${error && error.message}`);
      }
    }

    if (this.props.initGit) {
      this.spawnCommandSync('git', ['init', '--quiet']);
    }

    if (!this.props.skipInstall) {
      this.log(`\nRunning ${chalk.yellow(`${this.packageManager} install`)}, please wait…`);

      const install = this.packageManager === 'yarn' ? this.yarnInstall.bind(this) : this.npmInstall.bind(this);
      // When using NPM, force install as peer dependencies with ionic-native packages
      // cause install errors with NPM >= 7.
      const options = this.packageManager === 'yarn' ? null : { force: true };

      if (fs.existsSync(this.destinationPath(packageJsonFile))) {
        install(null, options);
      }

      if (this.isFullstack) {
        if (fs.existsSync(this.destinationPath(path.join(process.env.NGX_CLIENT_PATH, packageJsonFile)))) {
          install(null, options, {cwd: this.destinationPath(process.env.NGX_CLIENT_PATH)});
        }

        if (fs.existsSync(this.destinationPath(path.join(process.env.NGX_SERVER_PATH, packageJsonFile)))) {
          install(null, options, {cwd: this.destinationPath(process.env.NGX_SERVER_PATH)});
        }
      }
    }
  }

  end() {
    const deployer = deployers.find((d) => d.value === this.props.deploy);

    if (this.props.deploy !== 'none') {
      this.log(`\nConfiguring deployment with ${chalk.cyan(deployer.name)}, please wait…\n`);
      const result = this.spawnCommandSync('ng', ['add', deployer.package]);

      if (result.error) {
        this.log(`${chalk.red('Something went wrong during deployment configuration :(')}`);
        this.log(`You can retry manually using ${chalk.yellow(`npx ng add ${deployer.package}`)}`);
      }
    }

    if (this.updating) {
      this.log(`\nUpdated ${chalk.green(this.props.appName)} to ${chalk.yellow(this.version)} successfully!`);
      return;
    }

    if (this.props.skipQuickstart) {
      return;
    }

    this.log('\nAll done! Get started with these tasks:');
    this.log(
      `- $ ${chalk.green(`${this.packageManager} start`)}: start dev server with live reload on http://localhost:4200`
    );

    if (this.props.target.includes('web')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run build`)}: build web app for production`);

      if (this.props.deploy !== 'none') {
        this.log(`- $ ${chalk.green(`${this.packageManager} run deploy`)}: deploy app to ${deployer.name}`);
      }
    }

    if (this.props.target.includes('cordova')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:prepare`)}: prepare for building mobile app`);
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:run`)}: run app on device or simulator`);
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:build`)}: build mobile app for production`);
    }

    if (this.props.target.includes('electron')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run electron:build`)}: build app for electron`);
      this.log(`- $ ${chalk.green(`${this.packageManager} run electron:run`)}: run app in electron`);
      this.log(
        `- $ ${chalk.green(
          `${this.packageManager} run electron:package`
        )}: package executables for all selected platforms`
      );
    }

    this.log(`- $ ${chalk.green(`${this.packageManager} test`)}: run unit tests in watch mode for TDD`);
    this.log(`- $ ${chalk.green(`${this.packageManager} run test:ci`)}: lint code and run units tests with coverage`);
    if (this.props.e2e || this.props.cypress) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run e2e`)}: launch e2e tests`);
    }
    if (this.props.tools.includes('hads')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run docs`)}: show docs and coding guides`);
    }

    if (this.props.tools.includes('compodoc')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run compodoc`)}: generates docs from code`);
    }

    if (this.props.tools.includes('prettier')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run prettier`)}: format your code automatically`);
    }
  }
}

module.exports = Generator.make({
  baseDir: __dirname,
  generator: NgxGenerator,
  options,
  prompts,
  prefixRules: Object.assign(Generator.defaultPrefixRules, {
    'ionic-tabs': (props) => props.ui === 'ionic' && props.layout === 'tabs',
    'ionic-side-menu': (props) => props.ui === 'ionic' && props.layout === 'side-menu',
    'material-simple': (props) => props.ui === 'material' && props.layout === 'simple',
    'material-side-menu': (props) => props.ui === 'material' && props.layout === 'side-menu',
    raw: (props) => props.ui === 'raw',
    'electron-windows': (props) => props.desktop && props.desktop.includes('windows'),
    'electron-mac': (props) => props.desktop && props.desktop.includes('mac'),
    'electron-linux': (props) => props.desktop && props.desktop.includes('linux'),
    'tools-hads': (props) => props.tools && props.tools.includes('hads'),
    'tools-jest': (props) => props.tools && props.tools.includes('jest'),
    'tools-karma': (props) => props.tools && !props.tools.includes('jest'),
    e2e: (props) => !props.features || props.features.includes('e2e'),
    cypress: (props) => !props.features || props.features.includes('cypress'),
    husky: (props) => props.initGit && props.tools.includes('prettier')
  })
});
<|endoftext|>


<commit_before>
var $ = document.querySelector.bind(document)

var state = {
  theme: window['theme'] || '',
  raw: window['raw'] || false,
  content: window['content'] || {},
  html: '',
  markdown: '',
  toc: ''
}

chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
  if (req.message === 'reload') {
    window.location.reload(true)
  }
  else if (req.message === 'theme') {
    state.theme = req.theme
    m.redraw()
  }
  else if (req.message === 'raw') {
    state.raw = req.raw
    m.redraw()
  }
})

var oncreate = {
  markdown: () => {
    if (state.content.scroll) {
      document.body.scrollTop = parseInt(localStorage.getItem('md-' + location.href))
    }
  },
  html: () => {
    if (state.content.scroll) {
      document.body.scrollTop = parseInt(localStorage.getItem('md-' + location.href))
    }
    if (state.content.toc && !state.toc) {
      state.toc = toc()
      m.redraw()
    }
    setTimeout(() => Prism.highlightAll(), 20)
  }
}

function mount () {
  $('pre').style.display = 'none'
  var md = $('pre').innerText

  m.mount($('body'), {
    oninit: () => {
      ;((done) => {
        if (document.charset === 'UTF-8') {
          done()
          return
        }
        m.request({method: 'GET', url: window.location.href,
          deserialize: (body) => {
            done(body)
            return body
          }
        })
      })((data) => {
        state.markdown = data || md

        chrome.runtime.sendMessage({
          message: 'markdown',
          markdown: state.markdown
        }, (res) => {
          state.html = res.marked
          m.redraw()
        })
      })
    },
    view: () => {
      var dom = []

      if (state.raw) {
        dom.push(m('pre#markdown', {oncreate: oncreate.markdown}, state.markdown))
        $('body').classList.remove('_toc-left', '_toc-right')
      }
      else {
        if (state.theme) {
          dom.push(m('link#theme [rel="stylesheet"] [type="text/css"]', {
            href: chrome.runtime.getURL('/themes/' + state.theme + '.css')
          }))
        }
        if (state.html) {
          dom.push(m('#html', {oncreate: oncreate.html,
            class: /github(-dark)?/.test(state.theme) ? 'markdown-body' : 'markdown-theme'},
            m.trust(state.html)
          ))
          if (state.content.toc && state.toc) {
            dom.push(m.trust(state.toc))
            $('body').classList.add('_toc-left')
          }
        }
      }

      return (dom.length ? dom : m('div'))
    }
  })
}

function scroll () {
  setTimeout(() => {
    var timeout = null
    window.addEventListener('scroll', () => {
      clearTimeout(timeout)
      timeout = setTimeout(() => {
        localStorage.setItem('md-' + location.href, document.body.scrollTop)
      }, 100)
    })
    document.body.scrollTop = parseInt(localStorage.getItem('md-' + location.href))
  }, 100)
}

if (document.readyState === 'complete') {
  mount()
  if (state.content.scroll) {
    scroll()
  }
}
else {
  window.addEventListener('DOMContentLoaded', mount)
  if (state.content.scroll) {
    window.addEventListener('load', scroll)
  }
}

function toc () {
  // extract all headers

  var headers = []

  function walk (nodes) {
    nodes.forEach((node) => {
      var sub = Array.from(node.childNodes)
      if (sub.length) {
        walk(sub)
      }
      if (/h[1-6]/i.test(node.tagName)) {
        headers.push({
          id: node.getAttribute('id'),
          level: parseInt(node.tagName.replace('H', '')),
          title: node.innerText
        })
      }
    })
  }

  walk(Array.from($('body').childNodes))

  // generate TOC

  var link = (header) =>
    '' + header.title + ''

  var html = '

'

  headers.forEach((header, index) => {
    if (index) {
      var prev = headers[index - 1]
    }
    if (!index || prev.level === header.level) {
      html += link(header)
    }
    else if (prev.level > header.level) {
      html += '
' + link(header)
    }
    else if (prev.level < header.level) {
      html += '
' + link(header)
    }
  })

  html += '

'

  return html
}
<commit_msg>Add scroll to fragment<commit_after>
var $ = document.querySelector.bind(document)

var state = {
  theme: window['theme'] || '',
  raw: window['raw'] || false,
  content: window['content'] || {},
  html: '',
  markdown: '',
  toc: ''
}

chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
  if (req.message === 'reload') {
    window.location.reload(true)
  }
  else if (req.message === 'theme') {
    state.theme = req.theme
    m.redraw()
  }
  else if (req.message === 'raw') {
    state.raw = req.raw
    m.redraw()
  }
})

var oncreate = {
  markdown: () => {
    scroll()
  },
  html: () => {
    scroll()
    if (state.content.toc && !state.toc) {
      state.toc = toc()
      m.redraw()
    }
    setTimeout(() => Prism.highlightAll(), 20)
  }
}

function mount () {
  $('pre').style.display = 'none'
  var md = $('pre').innerText

  m.mount($('body'), {
    oninit: () => {
      ;((done) => {
        if (document.charset === 'UTF-8') {
          done()
          return
        }
        m.request({method: 'GET', url: window.location.href,
          deserialize: (body) => {
            done(body)
            return body
          }
        })
      })((data) => {
        state.markdown = data || md

        chrome.runtime.sendMessage({
          message: 'markdown',
          markdown: state.markdown
        }, (res) => {
          state.html = res.marked
          m.redraw()
        })
      })
    },
    view: () => {
      var dom = []

      if (state.raw) {
        dom.push(m('pre#markdown', {oncreate: oncreate.markdown}, state.markdown))
        $('body').classList.remove('_toc-left', '_toc-right')
      }
      else {
        if (state.theme) {
          dom.push(m('link#theme [rel="stylesheet"] [type="text/css"]', {
            href: chrome.runtime.getURL('/themes/' + state.theme + '.css')
          }))
        }
        if (state.html) {
          dom.push(m('#html', {oncreate: oncreate.html,
            class: /github(-dark)?/.test(state.theme) ? 'markdown-body' : 'markdown-theme'},
            m.trust(state.html)
          ))
          if (state.content.toc && state.toc) {
            dom.push(m.trust(state.toc))
            $('body').classList.add('_toc-left')
          }
        }
      }

      return (dom.length ? dom : m('div'))
    }
  })
}

function scroll () {
  if (state.content.scroll) {
    document.body.scrollTop = parseInt(localStorage.getItem('md-' + location.href))
  }
  else if (location.hash) {
    document.body.scrollTop = $(location.hash) && $(location.hash).offsetTop
    setTimeout(() => {
      document.body.scrollTop = $(location.hash) && $(location.hash).offsetTop
    }, 100)
  }
}
scroll.init = () => {
  if (state.content.scroll) {
    var timeout = null
    window.addEventListener('scroll', () => {
      clearTimeout(timeout)
      timeout = setTimeout(() => {
        localStorage.setItem('md-' + location.href, document.body.scrollTop)
      }, 100)
    })
  }
  setTimeout(scroll, 100)
}

if (document.readyState === 'complete') {
  mount()
  scroll.init()
}
else {
  window.addEventListener('DOMContentLoaded', mount)
  window.addEventListener('load', scroll.init)
}

function toc () {
  // extract all headers

  var headers = []

  function walk (nodes) {
    nodes.forEach((node) => {
      var sub = Array.from(node.childNodes)
      if (sub.length) {
        walk(sub)
      }
      if (/h[1-6]/i.test(node.tagName)) {
        headers.push({
          id: node.getAttribute('id'),
          level: parseInt(node.tagName.replace('H', '')),
          title: node.innerText
        })
      }
    })
  }

  walk(Array.from($('body').childNodes))

  // generate TOC

  var link = (header) =>
    '' + header.title + ''

  var html = '

'

  headers.forEach((header, index) => {
    if (index) {
      var prev = headers[index - 1]
    }
    if (!index || prev.level === header.level) {
      html += link(header)
    }
    else if (prev.level > header.level) {
      html += '
' + link(header)
    }
    else if (prev.level < header.level) {
      html += '
' + link(header)
    }
  })

  html += '

'

  return html
}
<|endoftext|>


<commit_before>/*global angular*/

angular.module('andrejson')
	.controller('mainController', function ($scope, $log, $mdSidenav) {
		'use strict';
	});<commit_msg>Adds an automatic redirect from / to /home .<commit_after>/*global angular*/

angular.module('andrejson')
	.controller('mainController', function ($scope, $location, $log, $timeout, $mdSidenav) {
		'use strict';
		$timeout(function () {
			if ($location.path() === '/') {
				$location.path('home');
			}
		});
	});<|endoftext|>


<commit_before>require('colors');
var git  = require( 'gift');

// console.log(process.platform);

// console.log(git);

// https://github.com/notatestuser/gift

var repoPaths = [
  "/home/michieljoris/mysrc/javascript/bb-server",
  "/home/michieljoris/mysrc/javascript/recaster",
  "/home/michieljoris/mysrc/javascript/cachejs",
  "/home/michieljoris/mysrc/javascript/url_washer",
  "/home/michieljoris/mysrc/javascript/node-crawler",
  "/home/michieljoris/mysrc/javascript/bb-blog",

  "/home/michieljoris/mysrc/javascript/html-builder",
  "/home/michieljoris/mysrc/javascript/denodify",
  "/home/michieljoris/mysrc/javascript/denodify-core",

  "/home/michieljoris/mysrc/javascript/cape",
  "/home/michieljoris/www/sites/test-cape",

  "/home/michieljoris/mysrc/javascript/adea",
  "/home/michieljoris/mysrc/javascript/deploy-demo",
  "/home/michieljoris/mysrc/javascript/node-haproxy",
  "/home/michieljoris/mysrc/javascript/serf-rpc",
  "/home/michieljoris/mysrc/javascript/vouchdb",

  "/home/michieljoris/mysrc/javascript/crypto-utils",

  "/home/michieljoris/mysrc/javascript/logthis",

  // "/home/michieljoris/mysrc/javascript/roster/app",  //develop
  "/home/michieljoris/mysrc/javascript/tw",
  "/home/michieljoris/mysrc/javascript/validate_doc_update",
  "/home/michieljoris/mysrc/javascript/trello-export",
  "/home/michieljoris/mysrc/javascript/monad",

  "/home/michieljoris/www/sites/quilt",

  "/home/michieljoris/www/sites/firstdoor", //newlayout branch
  "/home/michieljoris/mysrc/javascript/phantom-sitemap",

  "/home/michieljoris/www/sites/dbeditor",
  "/home/michieljoris/www/sites/greenglass",
  "/home/michieljoris/www/sites/michieljoris.github.io",
  "/home/michieljoris/www/sites/seo_laundry",
  "/home/michieljoris/www/sites/personalinfo",
  "/home/michieljoris/www/sites/roster_help",
  "/home/michieljoris/www/sites/hexo-blog",

  "/home/michieljoris/mysrc/javascript/blog",
  "/home/michieljoris/www/sites/edge4",
  "/home/michieljoris/mysrc/javascript/deploymeteor",
  "/home/michieljoris/mysrc/javascript/less-monitor",

  "/home/michieljoris/www/sites/testsite",

  "/home/michieljoris/mysrc/job_applications",
  "/home/michieljoris/mysrc/lisp/scheme/sicp",
  "/home/michieljoris/mysrc/code-x",

  // "/home/michieljoris/.i3wm",
  // "/home/michieljoris/.emacs.d",

  "/home/michieljoris/mysrc/javascript/js-project",
  "/home/michieljoris/mysrc/javascript/commit"
];

function sync(repoPath, cb) {
    var repo = git(repoPath);
    console.log("Processing:", repo.path);
    repo.status(function(err, repoStatus) {
        if (err) {
            console.log('Error fetching status: '.red , err);
            cb();
        }
        else {
            if (repoStatus.clean) {
                console.log('All up to date'.green);
                cb();
            }
            else if (Object.keys(repoStatus.files).length>0) {
                console.log('Adding files');
                repo.add('-A', function(err) {
                    if (err) {
                        console.log('Error staging files: '.red , err);
                        cb();
                    }
                    else {
                        var message = 'Sync ' + new Date();
                        console.log('Commiting: ' + message);

                        repo.commit(message, function(err) {
                            if (err) {
                                console.log('Error commiting:'.red , err);
                                cb();
                            }
                            else {
                                console.log('Pushing', repo);
                                repo.remote_push('origin', function(err) {
                                    if (err) console.log('Error pushing:'.error , err);
                                    else console.log('Done!'.green);
                                    cb();
                                });

                            }
                        });
                    }
                });

            }
            else cb();

        }
    });
}

function recur() {
    var repoPath = repoPaths.pop();
    if (repoPath) {
        sync(repoPath, function() {
            recur();
        });
    }
}

recur();

<commit_msg>Sync Tue Aug 05 2014 00:38:34 GMT+1000 (EST)<commit_after>require('colors');
var git  = require( 'gift');

// console.log(process.platform);

// console.log(git);

// https://github.com/notatestuser/gift

var repoPaths = [
  "/home/michieljoris/mysrc/javascript/bb-server",
  "/home/michieljoris/mysrc/javascript/recaster",
  "/home/michieljoris/mysrc/javascript/cachejs",
  "/home/michieljoris/mysrc/javascript/url_washer",
  "/home/michieljoris/mysrc/javascript/node-crawler",
  "/home/michieljoris/mysrc/javascript/bb-blog",

  "/home/michieljoris/mysrc/javascript/html-builder",
  "/home/michieljoris/mysrc/javascript/denodify",
  "/home/michieljoris/mysrc/javascript/denodify-core",

  "/home/michieljoris/mysrc/javascript/cape",
  "/home/michieljoris/www/sites/test-cape",

  "/home/michieljoris/mysrc/javascript/adea",
  "/home/michieljoris/mysrc/javascript/deploy-demo",
  "/home/michieljoris/mysrc/javascript/node-haproxy",
  "/home/michieljoris/mysrc/javascript/serf-rpc",
  "/home/michieljoris/mysrc/javascript/vouchdb",

  "/home/michieljoris/mysrc/javascript/crypto-utils",

  "/home/michieljoris/mysrc/javascript/logthis",

  // "/home/michieljoris/mysrc/javascript/roster/app",  //develop
  "/home/michieljoris/mysrc/javascript/tw",
  "/home/michieljoris/mysrc/javascript/validate_doc_update",
  "/home/michieljoris/mysrc/javascript/trello-export",
  "/home/michieljoris/mysrc/javascript/monad",

  "/home/michieljoris/www/sites/quilt",

  "/home/michieljoris/www/sites/firstdoor", //newlayout branch
  "/home/michieljoris/mysrc/javascript/phantom-sitemap",

  "/home/michieljoris/www/sites/dbeditor",
  "/home/michieljoris/www/sites/greenglass",
  "/home/michieljoris/www/sites/michieljoris.github.io",
  "/home/michieljoris/www/sites/seo_laundry",
  "/home/michieljoris/www/sites/personalinfo",
  "/home/michieljoris/www/sites/roster_help",
  "/home/michieljoris/www/sites/hexo-blog",

  "/home/michieljoris/mysrc/javascript/blog",
  "/home/michieljoris/www/sites/edge4",
  "/home/michieljoris/mysrc/javascript/deploymeteor",
  "/home/michieljoris/mysrc/javascript/less-monitor",

  "/home/michieljoris/www/sites/testsite",

  "/home/michieljoris/mysrc/job_applications",
  "/home/michieljoris/mysrc/lisp/scheme/sicp",
  "/home/michieljoris/mysrc/javascript/code-x",

  // "/home/michieljoris/.i3wm",
  // "/home/michieljoris/.emacs.d",

  "/home/michieljoris/mysrc/javascript/js-project",
  "/home/michieljoris/mysrc/javascript/commit"
];

function sync(repoPath, cb) {
    var repo = git(repoPath);
    console.log("Processing:", repo.path);
    repo.status(function(err, repoStatus) {
        if (err) {
            console.log('Error fetching status: '.red , err);
            cb();
        }
        else {
            if (repoStatus.clean) {
                console.log('All up to date'.green);
                cb();
            }
            else if (Object.keys(repoStatus.files).length>0) {
                console.log('Adding files');
                repo.add('-A', function(err) {
                    if (err) {
                        console.log('Error staging files: '.red , err);
                        cb();
                    }
                    else {
                        var message = 'Sync ' + new Date();
                        console.log('Commiting: ' + message);

                        repo.commit(message, function(err) {
                            if (err) {
                                console.log('Error commiting:'.red , err);
                                cb();
                            }
                            else {
                                console.log('Pushing', repo);
                                repo.remote_push('origin', function(err) {
                                    if (err) console.log('Error pushing:'.error , err);
                                    else console.log('Done!'.green);
                                    cb();
                                });

                            }
                        });
                    }
                });

            }
            else cb();

        }
    });
}

function recur() {
    var repoPath = repoPaths.pop();
    if (repoPath) {
        sync(repoPath, function() {
            recur();
        });
    }
}

recur();

<|endoftext|>


<commit_before>if (Meteor.isClient) {
  // counter starts at 0
  //Session.setDefault('winners', 0);

  Template.try.helpers({
    sortedWinners: function () {

      var winners = [0, 0, 0, 0, 0, 0];

      for (step = 0; step < 6; step++) {
        // Calculo random según http://www.w3schools.com/jsref/jsref_random.asp
        var number = Math.floor((Math.random() * 45) + 1);
        winners[step] = number;
      }

      var sortedWinners = winners.sort(ascending);
      //console.log(sortedWinners);
      return sortedWinners;

      // Functions

      // Order a numeric array, taken from http://www.aprenderaprogramar.com/index.php?option=com_content&view=article&id=834:funciones-arrays-javascript-push-sort-ordenar-numeros-concat-join-pop-shift-slice-splice-etc-cu01153e&catid=78:tutorial-basico-programador-web-javascript-desde-&Itemid=206

      function ascending (elem1, elem2) { return elem1 - elem2; }

      // return Session.get('sortedWinners');
    }
  });

  Template.try.events({
    'click button': function () {
      // increment the counter when button is clicked
      //Session.set('sortedWinners', Session.get('sortedWinners'));
      sortedWinners;

    }

  });

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}
<commit_msg>Intermediate saving.<commit_after>if (Meteor.isClient) {
  // counter starts at 0
  //Session.setDefault('winners', 0);

  Template.try.helpers({
    sortedWinners: function () {

      var winners = [0, 0, 0, 0, 0, 0];

      for (step = 0; step < 6; step++) {
        // Calculo random según http://www.w3schools.com/jsref/jsref_random.asp
        var number = Math.floor((Math.random() * 45) + 1);
        winners[step] = number;
      }

      var sortedWinners = winners.sort(ascending);
      //console.log(sortedWinners);
      return sortedWinners;

      // Functions

      // Order a numeric array, taken from http://www.aprenderaprogramar.com/index.php?option=com_content&view=article&id=834:funciones-arrays-javascript-push-sort-ordenar-numeros-concat-join-pop-shift-slice-splice-etc-cu01153e&catid=78:tutorial-basico-programador-web-javascript-desde-&Itemid=206

      function ascending (elem1, elem2) { return elem1 - elem2; }

      // return Session.get('sortedWinners');
    }
  });

  Template.try.events({
    'click button': function () {
      // increment the counter when button is clicked
      //Session.set('sortedWinners', Session.get('sortedWinners'));
      Session.set('sortedWinners');

    }

  });

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}
<|endoftext|>


<commit_before>/*!
 * @author      Angelo Dini - github.com/finalangel/classjs-plugins
 * @copyright	Distributed under the BSD License.
 * @version     1.0.1
 */

// insure namespace is defined
var Cl = window.Cl || {};

(function($){
	'use strict';

	// creating class
	Cl.Uniform = new Class({

		options: {
			'offset': -9999,
			'cls': {
				'prefix': 'uniform',
				'radio': 'radio',
				'checkbox': 'checkbox',
				'file': 'file',
				'select': 'select',
				'disabled': 'disabled',
				'focus': 'focus'
			},
			'lang': {
				'fileBtn': 'Upload',
				'fileStatus': 'Please select a file...'
			},
			'tpl': {
				'radio': '',
				'checkbox': '',
				'file': '{btntext}{statustext}',
				'select': ''
			}
		},

		initialize: function (elements, options) {
			this.elements = $(elements);
			this.options = $.extend(true, {}, this.options, options);

			this._setup();
		},

		_setup: function () {
			var that = this;

			// global vars
			this.callbacks = {};

			// loop through individual entries
			this.elements.each(function (index, item) {
				that._scan($(item));
			});
		},

		update: function () {
			// trigger event
			this._fire('update');

			this.elements.each(function (index, item) {
				var input = $(item);
					if(input.is(':checked')) input.trigger('click');
					input.trigger('change');
			});

			// trigger event
			this._fire('update', this);
		},

		destroy: function () {
			// trigger event
			this._fire('destroy');

			var cls = this.options.cls;

			this.elements.each(function (index, item) {
				var input = $(item);
					input.parent().siblings('span').remove();
					input.unwrap()
						.unwrap()
						.removeAttr('style')
						.off('click.' + cls.prefix)
						.off('change.' + cls.prefix)
						.off('focus.' + cls.prefix)
						.off('blur.' + cls.prefix);
			});

			// trigger event
			this._fire('destroy', this);
		},

		_scan: function (field) {
			// delegate form elements to their responsive setup handlers
			switch(field.attr('type')) {
				case 'checkbox':
					this._setupRadioCheck(field, 'checkbox');
					break;
				case 'radio':
					this._setupRadioCheck(field, 'radio');
					break;
				case 'file':
					this._setupFile(field);
					break;
				case undefined:
					if(field.prop('tagName') === 'SELECT'
						&& field.attr('multiple') === undefined) this._setupSelect(field);
					break;
				default:
					break;
			}
		},

		_setupRadioCheck: function (field, type) {
			var that = this;
			var cls = this.options.cls;
			var clsTpl = cls.prefix + ' ' + cls.prefix + '-' + cls[type];
			var clsKnob = cls.prefix + '-' + cls[type] + '-knob';

			var tpl = $(this.options.tpl[type]
				.replace('{cls}', clsTpl)
				.replace('{knob}', clsKnob));

			// inject element
			field.wrap(tpl).css('left', this.options.offset);
			field.on('click.' + cls.prefix, function (e) {
				// prevent event bubbling
				e.stopPropagation();

				// getting vars
				var input = $(this);
				var knob = $(this).parents('.' + clsKnob);

				// cancel event if element is disabled
				if(input.is(':disabled')) return false;

				if(type === 'checkbox') {
					// we need to check if we should activate or deactivate the checkbox
					if(parseInt(knob.css('left')) === 0) {
						knob.css('left', that.options.offset);
					} else {
						knob.css('left', 0);
					}
				} else { // radio
					// we need to determine the radio group and trigger/enable them at once
					input.closest('form').find('input[type="radio"][name="' + input.attr('name') + '"]')
						.parents('.' + clsKnob)
						.css('left', that.options.offset);
					knob.css('left', 0);
				}

				// api call
				input.trigger(cls.prefix + 'change');

				// change accessibility labels
				(parseInt(knob.css('left')) === 0) ? parent.attr('aria-checked', true) : parent.attr('aria-checked', false);
			});

			// start attaching events
			var parent = field.parents('.' + cls.prefix);
				parent.on('click.' + cls.prefix, function (e) {
					// prevent event bubbling
					e.preventDefault();
					e.stopPropagation();

					// delegate to input
					var input = $(this).find('input');
						input.trigger('click');
				});

			// set initial accessibility labels
			(field.is(':checked')) ? parent.attr('aria-checked', true) : parent.attr('aria-checked', false);
			if(field.attr('required')) parent.attr('aria-required', true);

			// initial state
			if(!field.is(':checked')) field.parents('.' + cls.prefix).children().css('left', this.options.offset);

			// add common elements
			this._common(field, parent);
		},

		_setupFile: function (field) {
			var cls = this.options.cls;
			var clsTpl = cls.prefix + ' ' + cls.prefix + '-' + cls.file;
			var clsInput = cls.prefix + ' ' + cls.prefix + '-input';
			var clsBtn = cls.prefix + '-' + cls.file + '-btn';
			var clsStatus = cls.prefix + '-' + cls.file + '-status';

			var tpl = $(this.options.tpl.file
				.replace('{cls}', clsTpl)
				.replace('{input}', clsInput)
				.replace('{btn}', clsBtn)
				.replace('{btntext}', this.options.lang.fileBtn)
				.replace('{status}', clsStatus)
				.replace('{statustext}', this.options.lang.fileStatus));

			// auto calculate sizes
			tpl.css({
				'width': field.css('width'),
				'height': field.css('height'),
				'padding': field.css('padding'),
				'margin': field.css('margin')
			});

			// inject element
			field.wrap(tpl).css('left', this.options.offset);
			field.on('click.' + cls.prefix, function (e) {
				// prevent event bubbling
				e.stopPropagation();
			});
			field.on('change.' + cls.prefix, function (e) {
				// set new value to status
				var value = $(this).val().replace(/^C:\\fakepath\\/i, '');
				$(this).parents('.' + cls.prefix).find('.' + clsStatus).text(value);
			});

			// start attaching events
			var parent = field.parents('.' + cls.prefix);
				parent.on('click.' + cls.prefix, function (e) {
					// prevent event bubbling
					e.preventDefault();
					e.stopPropagation();

					// delegate to input
					var input = $(this).find('input');
						input.trigger('click');
				});

			// set initial accessibility labels
			if(field.attr('required')) parent.attr('aria-required', true);

			// add common elements
			this._common(field);
		},

		_setupSelect: function (field) {
			var cls = this.options.cls;
			var clsTpl = cls.prefix + ' ' + cls.prefix + '-' + cls.select;
			var clsInput = cls.prefix + ' ' + cls.prefix + '-input';
			var clsStatus = cls.prefix + '-' + cls.select + '-status';
			var clsArrow = cls.prefix + '-' + cls.select + '-arrow';

			var tpl = $(this.options.tpl.select
				.replace('{cls}', clsTpl)
				.replace('{input}', clsInput)
				.replace('{status}', clsStatus)
				.replace('{arrow}', clsArrow));

			// auto calculate sizes
			tpl.css({
				'width': field.css('width'),
				'height': field.css('height'),
				'padding': field.css('padding'),
				'margin': field.css('margin')
			});

			// inject element
			field.wrap(tpl).css('opacity', 0); //  this.options.offset

			// set the correct content
			var parent = field.parents('.' + cls.prefix);
			var text = parent.find('.' + clsStatus);

			// attach change event
			field.on('change', function () {
				text.text($(this).find('option:selected').text());
			});

			// set correct value
			text.text(field.find('option:selected').text());

			// we need to set a fixed with if field is 100%
			field.css('width', tpl.outerWidth(true));

			// set initial accessibility labels
			if(field.attr('required')) parent.attr('aria-required', true);

			// add common elements
			this._common(field);
		},

		_common: function (field, parent) {
			var cls = this.options.cls;

			// add focus event
			field.on('focus.' + cls.prefix + ' blur.' + cls.prefix, function (e) {
				var wrap = $(this).parents('.' + cls.prefix);
				var wrapCls = cls.prefix + '-' + cls.focus;
				(e.type === 'focus') ? wrap.addClass(wrapCls) : wrap.removeClass(wrapCls);
			});

			// add classes depending on the state
			if(field.is(':disabled')) field.parents('.' + cls.prefix).addClass(cls.prefix + '-' + cls.disabled);
		},

		_fire: function (keyword, scope) {
			if(scope) {
				// cancel if there is no callback found
				if(this.callbacks[keyword] === undefined) return false;
				// excecute callback
				this.callbacks[keyword](scope);
			} else {
				// excecute event
				$.event.trigger('uniform-' + keyword);
			}
		}

	});
})(jQuery);<commit_msg>removed not required variables<commit_after>/*!
 * @author      Angelo Dini - github.com/finalangel/classjs-plugins
 * @copyright	Distributed under the BSD License.
 * @version     1.0.1
 */

// insure namespace is defined
var Cl = window.Cl || {};

(function($){
	'use strict';

	// creating class
	Cl.Uniform = new Class({

		options: {
			'offset': -9999,
			'cls': {
				'prefix': 'uniform',
				'radio': 'radio',
				'checkbox': 'checkbox',
				'file': 'file',
				'select': 'select',
				'disabled': 'disabled',
				'focus': 'focus'
			},
			'lang': {
				'fileBtn': 'Upload',
				'fileStatus': 'Please select a file...'
			},
			'tpl': {
				'radio': '',
				'checkbox': '',
				'file': '{btntext}{statustext}',
				'select': ''
			}
		},

		initialize: function (elements, options) {
			this.elements = $(elements);
			this.options = $.extend(true, {}, this.options, options);

			this._setup();
		},

		_setup: function () {
			var that = this;

			// global vars
			this.callbacks = {};

			// loop through individual entries
			this.elements.each(function (index, item) {
				that._scan($(item));
			});
		},

		update: function () {
			// trigger event
			this._fire('update');

			this.elements.each(function (index, item) {
				var input = $(item);
					if(input.is(':checked')) input.trigger('click');
					input.trigger('change');
			});

			// trigger event
			this._fire('update', this);
		},

		destroy: function () {
			// trigger event
			this._fire('destroy');

			var cls = this.options.cls;

			this.elements.each(function (index, item) {
				var input = $(item);
					input.parent().siblings('span').remove();
					input.unwrap()
						.unwrap()
						.removeAttr('style')
						.off('click.' + cls.prefix)
						.off('change.' + cls.prefix)
						.off('focus.' + cls.prefix)
						.off('blur.' + cls.prefix);
			});

			// trigger event
			this._fire('destroy', this);
		},

		_scan: function (field) {
			// delegate form elements to their responsive setup handlers
			switch(field.attr('type')) {
				case 'checkbox':
					this._setupRadioCheck(field, 'checkbox');
					break;
				case 'radio':
					this._setupRadioCheck(field, 'radio');
					break;
				case 'file':
					this._setupFile(field);
					break;
				case undefined:
					if(field.prop('tagName') === 'SELECT'
						&& field.attr('multiple') === undefined) this._setupSelect(field);
					break;
				default:
					break;
			}
		},

		_setupRadioCheck: function (field, type) {
			var that = this;
			var cls = this.options.cls;
			var clsTpl = cls.prefix + ' ' + cls.prefix + '-' + cls[type];
			var clsKnob = cls.prefix + '-' + cls[type] + '-knob';

			var tpl = $(this.options.tpl[type]
				.replace('{cls}', clsTpl)
				.replace('{knob}', clsKnob));

			// inject element
			field.wrap(tpl).css('left', this.options.offset);
			field.on('click.' + cls.prefix, function (e) {
				// prevent event bubbling
				e.stopPropagation();

				// getting vars
				var input = $(this);
				var knob = $(this).parents('.' + clsKnob);

				// cancel event if element is disabled
				if(input.is(':disabled')) return false;

				if(type === 'checkbox') {
					// we need to check if we should activate or deactivate the checkbox
					if(parseInt(knob.css('left')) === 0) {
						knob.css('left', that.options.offset);
					} else {
						knob.css('left', 0);
					}
				} else { // radio
					// we need to determine the radio group and trigger/enable them at once
					input.closest('form').find('input[type="radio"][name="' + input.attr('name') + '"]')
						.parents('.' + clsKnob)
						.css('left', that.options.offset);
					knob.css('left', 0);
				}

				// api call
				input.trigger(cls.prefix + 'change');

				// change accessibility labels
				(parseInt(knob.css('left')) === 0) ? parent.attr('aria-checked', true) : parent.attr('aria-checked', false);
			});

			// start attaching events
			var parent = field.parents('.' + cls.prefix);
				parent.on('click.' + cls.prefix, function (e) {
					// prevent event bubbling
					e.preventDefault();
					e.stopPropagation();

					// delegate to input
					var input = $(this).find('input');
						input.trigger('click');
				});

			// set initial accessibility labels
			(field.is(':checked')) ? parent.attr('aria-checked', true) : parent.attr('aria-checked', false);
			if(field.attr('required')) parent.attr('aria-required', true);

			// initial state
			if(!field.is(':checked')) field.parents('.' + cls.prefix).children().css('left', this.options.offset);

			// add common elements
			this._common(field, parent);
		},

		_setupFile: function (field) {
			var cls = this.options.cls;
			var clsTpl = cls.prefix + ' ' + cls.prefix + '-' + cls.file;
			var clsInput = cls.prefix + ' ' + cls.prefix + '-input';
			var clsBtn = cls.prefix + '-' + cls.file + '-btn';
			var clsStatus = cls.prefix + '-' + cls.file + '-status';

			var tpl = $(this.options.tpl.file
				.replace('{cls}', clsTpl)
				.replace('{input}', clsInput)
				.replace('{btn}', clsBtn)
				.replace('{btntext}', this.options.lang.fileBtn)
				.replace('{status}', clsStatus)
				.replace('{statustext}', this.options.lang.fileStatus));

			// auto calculate sizes
			tpl.css({
				'width': field.css('width'),
				'height': field.css('height'),
				'padding': field.css('padding'),
				'margin': field.css('margin')
			});

			// inject element
			field.wrap(tpl).css('left', this.options.offset);
			field.on('click.' + cls.prefix, function (e) {
				// prevent event bubbling
				e.stopPropagation();
			});
			field.on('change.' + cls.prefix, function () {
				// set new value to status
				var value = $(this).val().replace(/^C:\\fakepath\\/i, '');
				$(this).parents('.' + cls.prefix).find('.' + clsStatus).text(value);
			});

			// start attaching events
			var parent = field.parents('.' + cls.prefix);
				parent.on('click.' + cls.prefix, function (e) {
					// prevent event bubbling
					e.preventDefault();
					e.stopPropagation();

					// delegate to input
					var input = $(this).find('input');
						input.trigger('click');
				});

			// set initial accessibility labels
			if(field.attr('required')) parent.attr('aria-required', true);

			// add common elements
			this._common(field);
		},

		_setupSelect: function (field) {
			var cls = this.options.cls;
			var clsTpl = cls.prefix + ' ' + cls.prefix + '-' + cls.select;
			var clsInput = cls.prefix + ' ' + cls.prefix + '-input';
			var clsStatus = cls.prefix + '-' + cls.select + '-status';
			var clsArrow = cls.prefix + '-' + cls.select + '-arrow';

			var tpl = $(this.options.tpl.select
				.replace('{cls}', clsTpl)
				.replace('{input}', clsInput)
				.replace('{status}', clsStatus)
				.replace('{arrow}', clsArrow));

			// auto calculate sizes
			tpl.css({
				'width': field.css('width'),
				'height': field.css('height'),
				'padding': field.css('padding'),
				'margin': field.css('margin')
			});

			// inject element
			field.wrap(tpl).css('opacity', 0); //  this.options.offset

			// set the correct content
			var parent = field.parents('.' + cls.prefix);
			var text = parent.find('.' + clsStatus);

			// attach change event
			field.on('change', function () {
				text.text($(this).find('option:selected').text());
			});

			// set correct value
			text.text(field.find('option:selected').text());

			// we need to set a fixed with if field is 100%
			field.css('width', tpl.outerWidth(true));

			// set initial accessibility labels
			if(field.attr('required')) parent.attr('aria-required', true);

			// add common elements
			this._common(field);
		},

		_common: function (field) {
			var cls = this.options.cls;

			// add focus event
			field.on('focus.' + cls.prefix + ' blur.' + cls.prefix, function (e) {
				var wrap = $(this).parents('.' + cls.prefix);
				var wrapCls = cls.prefix + '-' + cls.focus;
				(e.type === 'focus') ? wrap.addClass(wrapCls) : wrap.removeClass(wrapCls);
			});

			// add classes depending on the state
			if(field.is(':disabled')) field.parents('.' + cls.prefix).addClass(cls.prefix + '-' + cls.disabled);
		},

		_fire: function (keyword, scope) {
			if(scope) {
				// cancel if there is no callback found
				if(this.callbacks[keyword] === undefined) return false;
				// excecute callback
				this.callbacks[keyword](scope);
			} else {
				// excecute event
				$.event.trigger('uniform-' + keyword);
			}
		}

	});
})(jQuery);<|endoftext|>