<commit_before>import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {Link} from 'react-router';
import {getKapacitor} from 'src/shared/apis';
import * as kapacitorActionCreators from '../actions/view';
import NoKapacitorError from '../../shared/components/NoKapacitorError';

const {
  arrayOf,
  func,
  shape,
  string,
} = PropTypes;

export const KapacitorRulesPage = React.createClass({
  propTypes: {
    source: shape({
      id: string.isRequired,
      links: shape({
        proxy: string.isRequired,
        self: string.isRequired,
        kapacitors: string.isRequired,
      }),
    }),
    rules: arrayOf(shape({
      name: string.isRequired,
      trigger: string.isRequired,
      message: string.isRequired,
      alerts: arrayOf(string.isRequired).isRequired,
    })).isRequired,
    actions: shape({
      fetchRules: func.isRequired,
      deleteRule: func.isRequired,
      updateRuleStatus: func.isRequired,
    }).isRequired,
    addFlashMessage: func,
  },

  getInitialState() {
    return {
      hasKapacitor: false,
      loading: true,
    };
  },

  componentDidMount() {
    getKapacitor(this.props.source).then((kapacitor) => {
      if (kapacitor) {
        this.props.actions.fetchRules(kapacitor);
      }
      this.setState({loading: false, hasKapacitor: !!kapacitor});
    });
  },

  handleDeleteRule(rule) {
    const {actions} = this.props;
    actions.deleteRule(rule);
  },

  handleRuleStatus(e, rule) {
    const {actions} = this.props;
    const status = e.target.checked ? 'enabled' : 'disabled';

    actions.updateRuleStatusSuccess(rule.id, status);
    actions.updateRuleStatus(rule, {status});
  },

  renderSubComponent() {
    const {source} = this.props;
    const {hasKapacitor, loading} = this.state;

    let component;
    if (loading) {
      component = (
Loading...
);
    } else if (hasKapacitor) {
      component = (

Alert Rules

            <Link to={`/sources/${source.id}/alert-rules/new`} className="btn btn-sm btn-primary">Create New Rule</Link>

                  Name
                  Trigger
                  Message
                  Alerts
                  Enabled

                {this.renderAlertsTableRows()}

      );
    } else {
      component = <NoKapacitorError source={source} />;
    }
    return component;
  },

  render() {
    return (

Kapacitor Rules

            {this.renderSubComponent()}

    );
  },

  renderAlertsTableRows() {
    const {rules, source} = this.props;
    const numRules = rules.length;

    if (numRules === 0) {
      return (

You don't have any Kapacitor
Rules, why not create one?

            <Link to={`/sources/${source.id}/alert-rules/new`} className="btn btn-primary">Create New Rule</Link>

      );
    }

    return rules.map((rule) => {
      return (

          <Link to={`/sources/${source.id}/alert-rules/${rule.id}`}>{rule.name}</Link>
          {rule.trigger}
          {rule.message}
          {rule.alerts.join(', ')}

              <input id="kapacitor-enabled" className="form-control-static" type="checkbox" ref={(r) => this.enabled = r} checked={rule.status === "enabled"} onClick={(e) => this.handleRuleStatus(e, rule)} />

          <button className="btn btn-danger btn-xs" onClick={() => this.handleDeleteRule(rule)}>Delete</button>

      );
    });
  },
});

function mapStateToProps(state) {
  return {
    rules: Object.values(state.rules),
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(kapacitorActionCreators, dispatch),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(KapacitorRulesPage);
<commit_msg>Fix kapacitor rules page checkbox JSX.<commit_after>import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {Link} from 'react-router';
import {getKapacitor} from 'src/shared/apis';
import * as kapacitorActionCreators from '../actions/view';
import NoKapacitorError from '../../shared/components/NoKapacitorError';

const {
  arrayOf,
  func,
  shape,
  string,
} = PropTypes;

export const KapacitorRulesPage = React.createClass({
  propTypes: {
    source: shape({
      id: string.isRequired,
      links: shape({
        proxy: string.isRequired,
        self: string.isRequired,
        kapacitors: string.isRequired,
      }),
    }),
    rules: arrayOf(shape({
      name: string.isRequired,
      trigger: string.isRequired,
      message: string.isRequired,
      alerts: arrayOf(string.isRequired).isRequired,
    })).isRequired,
    actions: shape({
      fetchRules: func.isRequired,
      deleteRule: func.isRequired,
      updateRuleStatus: func.isRequired,
    }).isRequired,
    addFlashMessage: func,
  },

  getInitialState() {
    return {
      hasKapacitor: false,
      loading: true,
    };
  },

  componentDidMount() {
    getKapacitor(this.props.source).then((kapacitor) => {
      if (kapacitor) {
        this.props.actions.fetchRules(kapacitor);
      }
      this.setState({loading: false, hasKapacitor: !!kapacitor});
    });
  },

  handleDeleteRule(rule) {
    const {actions} = this.props;
    actions.deleteRule(rule);
  },

  handleRuleStatus(e, rule) {
    const {actions} = this.props;
    const status = e.target.checked ? 'enabled' : 'disabled';

    actions.updateRuleStatusSuccess(rule.id, status);
    actions.updateRuleStatus(rule, {status});
  },

  renderSubComponent() {
    const {source} = this.props;
    const {hasKapacitor, loading} = this.state;

    let component;
    if (loading) {
      component = (
Loading...
);
    } else if (hasKapacitor) {
      component = (

Alert Rules

            <Link to={`/sources/${source.id}/alert-rules/new`} className="btn btn-sm btn-primary">Create New Rule</Link>

                  Name
                  Trigger
                  Message
                  Alerts
                  Enabled

                {this.renderAlertsTableRows()}

      );
    } else {
      component = <NoKapacitorError source={source} />;
    }
    return component;
  },

  render() {
    return (

Kapacitor Rules

            {this.renderSubComponent()}

    );
  },

  renderAlertsTableRows() {
    const {rules, source} = this.props;
    const numRules = rules.length;

    if (numRules === 0) {
      return (

You don't have any Kapacitor
Rules, why not create one?

            <Link to={`/sources/${source.id}/alert-rules/new`} className="btn btn-primary">Create New Rule</Link>

      );
    }

    return rules.map((rule) => {
      return (

          <Link to={`/sources/${source.id}/alert-rules/${rule.id}`}>{rule.name}</Link>
          {rule.trigger}
          {rule.message}
          {rule.alerts.join(', ')}

              <input
                id="kapacitor-enabled"
                className="form-control-static"
                type="checkbox"
                ref={(r) => this.enabled = r}
                defaultChecked={rule.status === "enabled"}
                onClick={(e) => this.handleRuleStatus(e, rule)}
              />

          <button className="btn btn-danger btn-xs" onClick={() => this.handleDeleteRule(rule)}>Delete</button>

      );
    });
  },
});

function mapStateToProps(state) {
  return {
    rules: Object.values(state.rules),
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(kapacitorActionCreators, dispatch),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(KapacitorRulesPage);
<|endoftext|>


<commit_before>var musicId = null;
var author = null;
var title = null;
var link = "music/";
var change = '';
var random = null;
var random2 = null;
var intVar = null;
var timeDisplay = null;
var minutes = 0;
var hours = 0;
var minuteChecker = 0;
var secondChecker = 0;
var timeAudio = null;
var afterVolume = 0;
var checkIfDisable = 1;
var saveLast = '';
var fS = 1;
var adTimeLeft = 10;
var adTimeKeeper = 60;
var mId = {
  0: '<option class="option" title="All Songs" 															value="0" selected>Random</option>',
  1: '<option class="option" title="Iwey" 																value="1">Cut Throat</option>',
  2: '<option class="option" title="Trap Nation & Jordan Comolli" 										value="2">Contrast</option>',
  3: '<option class="option" title="Lyric 313" 															value="3">Trap Challenge</option>',
  4: '<option class="option" title="SYNIK" 																value="4">TrapShitFreeBeat2</option>',
  5: '<option class="option" title="Trap Nation & KXA" 													value="5">Gladius</option>',
  6: '<option class="option" title="Trap Nation & Lookas" 												value="6">Samurai</option>',
  7: '<option class="option" title="KINGDEE" 															value="7">THE TRAPPER</option>',
  8: '<option class="option" title="The Remix ft. The Game" 											value="8">T.H.O.T. (Clarice Diss)</option>',
  9: '<option class="option" title="" 																	value="9">Chiraq Instrumental</option>',
 10: '<option class="option" title="Kodak Black" 														value="10">Skrilla Instrumental</option>',
 11: '<option class="option" title="DISTO" 																value="11">Killa</option>',
 12: '<option class="option" title="NextRo" 															value="12">Saintz</option>',
 13: '<option class="option" title="Onderkoffer" 														value="13">Beast</option>',
 14: '<option class="option" title="Onderkoffer" 														value="14">FRNDZN</option>',
 15: '<option class="option" title="Drake"		 														value="15">10 Bands</option>',
 16: '<option class="option" title="LAXX" 																value="16">TWITCH</option>',
 17: '<option class="option" title="21 Savage"															value="17">Picky</option>',
 18: '<option class="option" title="Riskit" 															value="18">Adding Fuel To Fire</option>',
 19: '<option class="option" title="The Imp" 															value="19">Thanatus</option>',
 20: '<option class="option" title="Accept17" 															value="20">1. Exordium</option>',
 21: '<option class="option" title="TripleMT"	 														value="21">Angels And Demons,</option>',
 22: '<option class="option" title="cjnoll" 															value="22">ATL Yuletide</option>',
 23: '<option class="option" title="TripleMT" 															value="23">Dark Night,</option>',
 24: '<option class="option" title="Axel Thesleff & Trap Nation"										value="24">Bad Karma</option>',
 25: '<option class="option" title="Jed*" 																value="25">Plastik</option>',
 26: '<option class="option" title="Drake"     															value="26">Headlines</option>',
 27: '<option class="option" title="Synikal Beatz" 		   												value="27">She Tatted Up</option>',
 28: '<option class="option" title="Lex Kegger"		   													value="28">eXtincTioN Prophe(Y</option>',
 29: '<option class="option" title="lokosDj" 		   													value="29">Viaje.profundo</option>',
 30: '<option class="option" title="BeatzByLeepz"          												value="30">Love&hustle.</option>',
 31: '<option class="option" title="21 Savage & Metro Boomin"         		 							value="31">X ft Future</option>',
 32: '<option class="option" title="DarkHeart527 & Loafy"      											value="32">Break In!</option>',
 33: '<option class="option" title="Denzel Curry" 			 											value="33">Ultimate</option>',
 34: '<option class="option" title="21 Savage" 															value="34">Dip Dip</option>',
 35: '<option class="option" title="21 Savage" 															value="35">Red Opps</option>',
 36: '<option class="option" title="21 Savage & Metro Boomin"   										value="36">No Heart</option>',
 37: '<option class="option" title="Lil Yachty" 														value="37">1Night</option>',
 38: '<option class="option" title="Kodak Black, 21 Savage, Lil Uzi Vert, Lil Yachty & Denzel Curry" 	value="38">2016 XXL Freshmen Cypher</option>',
 39: '<option class="option" title="ScHoolboy Q" 		   												value="39">THat Part ft. Kanye West</option>',
 40: '<option class="option" title="Young M.A." 														value="40">OOOUUU (Remix)</option>',
 41: '<option class="option" title="Lil Yachty & 21 Savage" 											value="41">Guap</option>',
 42: '<option class="option" title="Ricegum"				    										value="42">Creepy Clowns Diss Track</option>',
 43: '<option class="option" title="Drake" 																value="43">Energy</option>',
 44: '<option class="option" title="Kodak Black" 														value="44">No Flockin</option>',
 45: '<option class="option" title="DJ O.T.C" 															value="45">Lost Boi Redemption</option>',
 46: '<option class="option" title="Kodak Black" 														value="46">Hollyhood</option>',
 47: '<option class="option" title="DarkHeart527" 														value="47">Dark Death</option>',
 48: '<option class="option" title="Trap City, DJ Snake, & Lil Jon" 									value="48">Turn Down For What (Remix)</option>',
 49: '<option class="option" title="Iwey" 																value="49">System 7.</option>',
 50: '<option class="option" title="Meek Mill" 															value="50">R.I.C.O. Feat. Drake</option>',
 51: '<option class="option" title="White Zombie" 														value="51">More Human Than Human</option>',
 52: '<option class="option" title="Statik Empire & Styleblast" 																	value="52">Fuck Da Law...</option>',
 53: '<option class="option" title="" 																	value="53"></option>',
 54: '<option class="option" title="" 																	value="54"></option>',
 55: '<option class="option" title="" 																	value="55"></option>',
 }
<commit_msg>Update variables.js<commit_after>var musicId = null;
var author = null;
var title = null;
var link = "music/";
var change = '';
var random = null;
var random2 = null;
var intVar = null;
var timeDisplay = null;
var minutes = 0;
var hours = 0;
var minuteChecker = 0;
var secondChecker = 0;
var timeAudio = null;
var afterVolume = 0;
var checkIfDisable = 1;
var saveLast = '';
var fS = 1;
var adTimeLeft = 10;
var adTimeKeeper = 60;
var mId = {
  0: '<option class="option" title="All Songs" 															value="0" selected>Random</option>',
  1: '<option class="option" title="Iwey" 																value="1">Cut Throat</option>',
  2: '<option class="option" title="Trap Nation & Jordan Comolli" 										value="2">Contrast</option>',
  3: '<option class="option" title="Lyric 313" 															value="3">Trap Challenge</option>',
  4: '<option class="option" title="SYNIK" 																value="4">TrapShitFreeBeat2</option>',
  5: '<option class="option" title="Trap Nation & KXA" 													value="5">Gladius</option>',
  6: '<option class="option" title="Trap Nation & Lookas" 												value="6">Samurai</option>',
  7: '<option class="option" title="KINGDEE" 															value="7">THE TRAPPER</option>',
  8: '<option class="option" title="The Remix ft. The Game" 											value="8">T.H.O.T. (Clarice Diss)</option>',
  9: '<option class="option" title="" 																	value="9">Chiraq Instrumental</option>',
 10: '<option class="option" title="Kodak Black" 														value="10">Skrilla Instrumental</option>',
 11: '<option class="option" title="DISTO" 																value="11">Killa</option>',
 12: '<option class="option" title="NextRo" 															value="12">Saintz</option>',
 13: '<option class="option" title="Onderkoffer" 														value="13">Beast</option>',
 14: '<option class="option" title="Onderkoffer" 														value="14">FRNDZN</option>',
 15: '<option class="option" title="Drake"		 														value="15">10 Bands</option>',
 16: '<option class="option" title="LAXX" 																value="16">TWITCH</option>',
 17: '<option class="option" title="21 Savage"															value="17">Picky</option>',
 18: '<option class="option" title="Riskit" 															value="18">Adding Fuel To Fire</option>',
 19: '<option class="option" title="The Imp" 															value="19">Thanatus</option>',
 20: '<option class="option" title="Accept17" 															value="20">1. Exordium</option>',
 21: '<option class="option" title="TripleMT"	 														value="21">Angels And Demons,</option>',
 22: '<option class="option" title="cjnoll" 															value="22">ATL Yuletide</option>',
 23: '<option class="option" title="TripleMT" 															value="23">Dark Night,</option>',
 24: '<option class="option" title="Axel Thesleff & Trap Nation"										value="24">Bad Karma</option>',
 25: '<option class="option" title="Jed*" 																value="25">Plastik</option>',
 26: '<option class="option" title="Drake"     															value="26">Headlines</option>',
 27: '<option class="option" title="Synikal Beatz" 		   												value="27">She Tatted Up</option>',
 28: '<option class="option" title="Lex Kegger"		   													value="28">eXtincTioN Prophe(Y</option>',
 29: '<option class="option" title="lokosDj" 		   													value="29">Viaje.profundo</option>',
 30: '<option class="option" title="BeatzByLeepz"          												value="30">Love&hustle.</option>',
 31: '<option class="option" title="21 Savage & Metro Boomin"         		 							value="31">X ft Future</option>',
 32: '<option class="option" title="DarkHeart527 & Loafy"      											value="32">Break In!</option>',
 33: '<option class="option" title="Denzel Curry" 			 											value="33">Ultimate</option>',
 34: '<option class="option" title="21 Savage" 															value="34">Dip Dip</option>',
 35: '<option class="option" title="21 Savage" 															value="35">Red Opps</option>',
 36: '<option class="option" title="21 Savage & Metro Boomin"   										value="36">No Heart</option>',
 37: '<option class="option" title="Lil Yachty" 														value="37">1Night</option>',
 38: '<option class="option" title="Kodak Black, 21 Savage, Lil Uzi Vert, Lil Yachty & Denzel Curry" 	value="38">2016 XXL Freshmen Cypher</option>',
 39: '<option class="option" title="ScHoolboy Q" 		   												value="39">THat Part ft. Kanye West</option>',
 40: '<option class="option" title="Young M.A." 														value="40">OOOUUU (Remix)</option>',
 41: '<option class="option" title="Lil Yachty & 21 Savage" 											value="41">Guap</option>',
 42: '<option class="option" title="Ricegum"				    										value="42">Creepy Clowns Diss Track</option>',
 43: '<option class="option" title="Drake" 																value="43">Energy</option>',
 44: '<option class="option" title="Kodak Black" 														value="44">No Flockin</option>',
 45: '<option class="option" title="DJ O.T.C" 															value="45">Lost Boi Redemption</option>',
 46: '<option class="option" title="Kodak Black" 														value="46">Hollyhood</option>',
 47: '<option class="option" title="DarkHeart527" 														value="47">Dark Death</option>',
 48: '<option class="option" title="Trap City, DJ Snake, & Lil Jon" 									value="48">Turn Down For What (Remix)</option>',
 49: '<option class="option" title="Iwey" 																value="49">System 7.</option>',
 50: '<option class="option" title="Meek Mill" 															value="50">R.I.C.O. Feat. Drake</option>',
 51: '<option class="option" title="White Zombie" 														value="51">More Human Than Human</option>',
 52: '<option class="option" title="Statik Empire & Styleblast" 																	value="52">Fuck Da Law...</option>',
 53: '<option class="option" title="Montana Of 300" 																	value="53">Holy Ghost</option>',
 54: '<option class="option" title="" 																	value="54"></option>',
 55: '<option class="option" title="" 																	value="55"></option>',
 }
<|endoftext|>


<commit_before>/**
 * @file Date methods polyfill
 * @since 0.1.5
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfArrayForEach*/ // Almost like [].forEach (undefined are also enumerated)
/*global _gpfCompatibilityInstallMethods*/ // Define and install compatible methods on standard objects
/*global _gpfMainContext*/ // Main context object
/*global _gpfNewApply*/ // Apply new operator with an array of parameters
/*exported _gpfIsISO8601String*/ // Check if the string is an ISO 8601 representation of a date
/*#endif*/

var _GPF_COMPATIBILITY_DATE_KEEP_2_DIGITS = 2,
    _GPF_COMPATIBILITY_DATE_KEEP_3_DIGITS = 3;

function _pad (number, digits) {
    var padded = "00" + number;
    return padded.substr(padded.length - digits);
}

function _gpfDateToISOString (date) {
    return date.getUTCFullYear()
        + "-"
        + _pad(date.getUTCMonth() + 1, _GPF_COMPATIBILITY_DATE_KEEP_2_DIGITS)
        + "-"
        + _pad(date.getUTCDate(), _GPF_COMPATIBILITY_DATE_KEEP_2_DIGITS)
        + "T"
        + _pad(date.getUTCHours(), _GPF_COMPATIBILITY_DATE_KEEP_2_DIGITS)
        + ":"
        + _pad(date.getUTCMinutes(), _GPF_COMPATIBILITY_DATE_KEEP_2_DIGITS)
        + ":"
        + _pad(date.getUTCSeconds(), _GPF_COMPATIBILITY_DATE_KEEP_2_DIGITS)
        + "."
        + _pad(date.getUTCMilliseconds(), _GPF_COMPATIBILITY_DATE_KEEP_3_DIGITS)
        + "Z";
}

_gpfCompatibilityInstallMethods("Date", {
    on: Date,

    methods: {

        // Introduced with JavaScript 1.8
        toISOString: function () {
            return _gpfDateToISOString(this);
        }

    },

    statics: {

        now: function () {
            return new Date().getTime();
        }

    }

});

//region Date override

var _gpfISO8601RegExp = new RegExp("^([0-9][0-9][0-9][0-9])\\-([0-9][0-9])\\-([0-9][0-9])"
    + "(?:T([0-9][0-9])\\:([0-9][0-9])\\:([0-9][0-9])(?:\\.([0-9][0-9][0-9])Z)?)?$"),
    _GPF_COMPATIBILITY_DATE_MONTH_PART = 1,
    _GPF_COMPATIBILITY_DATE_MAX_MONTH = 11,
    _GPF_COMPATIBILITY_DATE_DATE_PART = 2,
    _GPF_COMPATIBILITY_DATE_MAX_DATE = 31,
    _GPF_COMPATIBILITY_DATE_HOURS_PART = 3,
    _GPF_COMPATIBILITY_DATE_MAX_HOURS = 23,
    _GPF_COMPATIBILITY_DATE_MINUTES_PART = 4,
    _GPF_COMPATIBILITY_DATE_MAX_MINUTES = 59,
    _GPF_COMPATIBILITY_DATE_SECONDS_PART = 5,
    _GPF_COMPATIBILITY_DATE_MAX_SECONDS = 59;

function _gpfIsValidDateInDateArray (dateArray) {
    return dateArray[_GPF_COMPATIBILITY_DATE_MONTH_PART] <= _GPF_COMPATIBILITY_DATE_MAX_MONTH
        && dateArray[_GPF_COMPATIBILITY_DATE_DATE_PART] <= _GPF_COMPATIBILITY_DATE_MAX_DATE;
}

function _gpfIsValidTimeInDateArray (dateArray) {
    return dateArray[_GPF_COMPATIBILITY_DATE_HOURS_PART] <= _GPF_COMPATIBILITY_DATE_MAX_HOURS
        && dateArray[_GPF_COMPATIBILITY_DATE_MINUTES_PART] <= _GPF_COMPATIBILITY_DATE_MAX_MINUTES
        && dateArray[_GPF_COMPATIBILITY_DATE_SECONDS_PART] <= _GPF_COMPATIBILITY_DATE_MAX_SECONDS;
}

function _gpfCheckDateArray (dateArray) {
    if (_gpfIsValidDateInDateArray(dateArray) && _gpfIsValidTimeInDateArray(dateArray)) {
        return dateArray;
    }
}

function _gpfAddDatePartToArray (dateArray, datePart) {
    if (datePart) {
        dateArray.push(parseInt(datePart, 10));
    } else {
        dateArray.push(0);
    }
}

function _gpfToDateArray (matchResult) {
    var dateArray = [],
        len = matchResult.length, // 0 is the recognized string
        idx;
    for (idx = 1; idx < len; ++idx) {
        _gpfAddDatePartToArray(dateArray, matchResult[idx]);
    }
    return dateArray;
}

function _gpfProcessISO8601MatchResult (matchResult) {
    var dateArray;
    if (matchResult) {
        dateArray = _gpfToDateArray(matchResult);
        // Month must be corrected (0-based)
        --dateArray[1];
        // Some validation
        return _gpfCheckDateArray(dateArray);
    }

}

/**
 * Check if the value is a string respecting the ISO 8601 representation of a date. If so, the string is parsed and the
 * date details is returned.
 *
 * The function supports supports long and short syntax.
 *
 * @param {*} value Value to test
 * @return {Number[]|undefined} 7 numbers composing the date (Month is 0-based). undefined if not matching.
 * @since 0.1.5
 */
function _gpfIsISO8601String (value) {
    if (typeof value === "string") {
        _gpfISO8601RegExp.lastIndex = 0;
        return _gpfProcessISO8601MatchResult(_gpfISO8601RegExp.exec(value));
    }
}

// Backup original Date constructor
var _GpfGenuineDate = _gpfMainContext.Date;

/**
 * Date constructor supporting ISO 8601 format
 *
 * @constructor
 * @since 0.1.5
 */
function _GpfDate () {
    var firstArgument = arguments[0],
        values = _gpfIsISO8601String(firstArgument);
    if (values) {
        return new _GpfGenuineDate(_GpfGenuineDate.UTC.apply(_GpfGenuineDate.UTC, values));
    }
    return _gpfNewApply(_GpfGenuineDate, arguments);
}

function _gpfCopyDateStatics () {
    _gpfArrayForEach([
        "prototype", // Ensure instanceof
        "UTC",
        "parse",
        "now"
    ], function (member) {
        _GpfDate[member] = _GpfGenuineDate[member];
    });
}

function _gpfInstallCompatibleDate () {
    _gpfCopyDateStatics();
    // Test if ISO 8601 format variations are supported
    var longDateAsString,
        shortDateAsString;
    try {
        longDateAsString = _gpfDateToISOString(new Date("2003-01-22T22:45:34.075Z"));
        shortDateAsString = _gpfDateToISOString(new Date("2003-01-22"));
    } catch (e) {} //eslint-disable-line no-empty
    if (longDateAsString !== "2003-01-22T22:45:34.075Z"
        || shortDateAsString !== "2003-01-22T00:00:00.000Z") {
        // Replace constructor with new one
        _gpfMainContext.Date = _GpfDate;
    }
}

_gpfInstallCompatibleDate();

//endregion

/*#ifndef(UMD)*/

gpf.internals._gpfIsISO8601String = _gpfIsISO8601String;
gpf.internals._GpfDate = _GpfDate;

/*#endif*/
<commit_msg>no-magic-numbers (#280)<commit_after>/**
 * @file Date methods polyfill
 * @since 0.1.5
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_START*/ // 0
/*global _gpfArrayForEach*/ // Almost like [].forEach (undefined are also enumerated)
/*global _gpfCompatibilityInstallMethods*/ // Define and install compatible methods on standard objects
/*global _gpfMainContext*/ // Main context object
/*global _gpfNewApply*/ // Apply new operator with an array of parameters
/*exported _gpfIsISO8601String*/ // Check if the string is an ISO 8601 representation of a date
/*#endif*/

var _GPF_COMPATIBILITY_DATE_MONTH_OFFSET = 1,
    _GPF_COMPATIBILITY_DATE_2_DIGITS = 2,
    _GPF_COMPATIBILITY_DATE_3_DIGITS = 3;

function _gpfDatePad (value, count) {
    return value.toString().padStart(count, "0");
}

function _gpfDateToISOString (date) {
    return date.getUTCFullYear()
        + "-"
        + _gpfDatePad(date.getUTCMonth() + _GPF_COMPATIBILITY_DATE_MONTH_OFFSET, _GPF_COMPATIBILITY_DATE_2_DIGITS)
        + "-"
        + _gpfDatePad(date.getUTCDate(), _GPF_COMPATIBILITY_DATE_2_DIGITS)
        + "T"
        + _gpfDatePad(date.getUTCHours(), _GPF_COMPATIBILITY_DATE_2_DIGITS)
        + ":"
        + _gpfDatePad(date.getUTCMinutes(), _GPF_COMPATIBILITY_DATE_2_DIGITS)
        + ":"
        + _gpfDatePad(date.getUTCSeconds(), _GPF_COMPATIBILITY_DATE_2_DIGITS)
        + "."
        + _gpfDatePad(date.getUTCMilliseconds(), _GPF_COMPATIBILITY_DATE_3_DIGITS)
        + "Z";
}

_gpfCompatibilityInstallMethods("Date", {
    on: Date,

    methods: {

        // Introduced with JavaScript 1.8
        toISOString: function () {
            return _gpfDateToISOString(this);
        }

    },

    statics: {

        now: function () {
            return new Date().getTime();
        }

    }

});

//region Date override

var _gpfISO8601RegExp = new RegExp("^([0-9][0-9][0-9][0-9])\\-([0-9][0-9])\\-([0-9][0-9])"
    + "(?:T([0-9][0-9])\\:([0-9][0-9])\\:([0-9][0-9])(?:\\.([0-9][0-9][0-9])Z)?)?$"),
    _GPF_COMPATIBILITY_DATE_MONTH_PART = 1,
    _GPF_COMPATIBILITY_DATE_MAX_MONTH = 11,
    _GPF_COMPATIBILITY_DATE_DATE_PART = 2,
    _GPF_COMPATIBILITY_DATE_MAX_DATE = 31,
    _GPF_COMPATIBILITY_DATE_HOURS_PART = 3,
    _GPF_COMPATIBILITY_DATE_MAX_HOURS = 23,
    _GPF_COMPATIBILITY_DATE_MINUTES_PART = 4,
    _GPF_COMPATIBILITY_DATE_MAX_MINUTES = 59,
    _GPF_COMPATIBILITY_DATE_SECONDS_PART = 5,
    _GPF_COMPATIBILITY_DATE_MAX_SECONDS = 59;

function _gpfIsValidDateInDateArray (dateArray) {
    return dateArray[_GPF_COMPATIBILITY_DATE_MONTH_PART] <= _GPF_COMPATIBILITY_DATE_MAX_MONTH
        && dateArray[_GPF_COMPATIBILITY_DATE_DATE_PART] <= _GPF_COMPATIBILITY_DATE_MAX_DATE;
}

function _gpfIsValidTimeInDateArray (dateArray) {
    return dateArray[_GPF_COMPATIBILITY_DATE_HOURS_PART] <= _GPF_COMPATIBILITY_DATE_MAX_HOURS
        && dateArray[_GPF_COMPATIBILITY_DATE_MINUTES_PART] <= _GPF_COMPATIBILITY_DATE_MAX_MINUTES
        && dateArray[_GPF_COMPATIBILITY_DATE_SECONDS_PART] <= _GPF_COMPATIBILITY_DATE_MAX_SECONDS;
}

function _gpfCheckDateArray (dateArray) {
    if (_gpfIsValidDateInDateArray(dateArray) && _gpfIsValidTimeInDateArray(dateArray)) {
        return dateArray;
    }
}

var _GPF_COMPATIBILITY_DATE_PART_NOT_SET = 0;

function _gpfAddDatePartToArray (dateArray, datePart) {
    if (datePart) {
        dateArray.push(parseInt(datePart, 10));
    } else {
        dateArray.push(_GPF_COMPATIBILITY_DATE_PART_NOT_SET);
    }
}

function _gpfToDateArray (matchResult) {
    var dateArray = [],
        len = matchResult.length, // 0 is the recognized string
        idx = 1;
    for (; idx < len; ++idx) {
        _gpfAddDatePartToArray(dateArray, matchResult[idx]);
    }
    return dateArray;
}

var _GPF_COMPATIBILITY_DATE_MONTH_INDEX = 1;

function _gpfProcessISO8601MatchResult (matchResult) {
    var dateArray;
    if (matchResult) {
        dateArray = _gpfToDateArray(matchResult);
        // Month must be corrected (0-based)
        --dateArray[_GPF_COMPATIBILITY_DATE_MONTH_INDEX];
        // Some validation
        return _gpfCheckDateArray(dateArray);
    }
}

/**
 * Check if the value is a string respecting the ISO 8601 representation of a date. If so, the string is parsed and the
 * date details is returned.
 *
 * The function supports supports long and short syntax.
 *
 * @param {*} value Value to test
 * @return {Number[]|undefined} 7 numbers composing the date (Month is 0-based). undefined if not matching.
 * @since 0.1.5
 */
function _gpfIsISO8601String (value) {
    if (typeof value === "string") {
        _gpfISO8601RegExp.lastIndex = 0;
        return _gpfProcessISO8601MatchResult(_gpfISO8601RegExp.exec(value));
    }
}

// Backup original Date constructor
var _GpfGenuineDate = _gpfMainContext.Date;

/**
 * Date constructor supporting ISO 8601 format
 *
 * @constructor
 * @since 0.1.5
 */
function _GpfDate () {
    var firstArgument = arguments[_GPF_START],
        values = _gpfIsISO8601String(firstArgument);
    if (values) {
        return new _GpfGenuineDate(_GpfGenuineDate.UTC.apply(_GpfGenuineDate.UTC, values));
    }
    return _gpfNewApply(_GpfGenuineDate, arguments);
}

function _gpfCopyDateStatics () {
    _gpfArrayForEach([
        "prototype", // Ensure instanceof
        "UTC",
        "parse",
        "now"
    ], function (member) {
        _GpfDate[member] = _GpfGenuineDate[member];
    });
}

var _GPF_COMPATIBILITY_DATE_ISO_TEST = "2003-01-22T22:45:34.075Z",
    _GPF_COMPATIBILITY_DATE_SHORT_TEST = "2003-01-22";

function _gpfInstallCompatibleDate () {
    _gpfCopyDateStatics();
    // Test if ISO 8601 format variations are supported
    var longDateAsString,
        shortDateAsString;
    try {
        longDateAsString = _gpfDateToISOString(new Date(_GPF_COMPATIBILITY_DATE_ISO_TEST));
        shortDateAsString = _gpfDateToISOString(new Date());
    } catch (e) {} //eslint-disable-line no-empty
    if (longDateAsString !== _GPF_COMPATIBILITY_DATE_ISO_TEST
        || shortDateAsString !== _GPF_COMPATIBILITY_DATE_SHORT_TEST + "T00:00:00.000Z") {
        // Replace constructor with new one
        _gpfMainContext.Date = _GpfDate;
    }
}

_gpfInstallCompatibleDate();

//endregion

/*#ifndef(UMD)*/

gpf.internals._gpfIsISO8601String = _gpfIsISO8601String;
gpf.internals._GpfDate = _GpfDate;

/*#endif*/
<|endoftext|>


<commit_before>/**
 * Programming language popularity chart based on Highcharts
 * Please note that this file is dual licensed since Highcharts
 * is licensed under CC BY-NC 3.0
 * If Highcharts gets replaced in the future this class
 * will be licensed under AGPL-3.0 only
 * @author Fabian Beuke <mail@beuke.org>
 * @license AGPL-3.0 everything except Highcharts
 * @license CC BY-NC 3.0 Highcharts
 * @see {@link https://creativecommons.org/licenses/by-nc/3.0/}
 */

import React, { useState, useEffect } from "react"
import { update, range, sortBy, includes, uniqBy, reject } from "lodash/fp"
import { size, max, flatten, map, take, zipWith, divide } from "lodash/fp"
import { unzip, sum, filter, drop, isEqual, pipe } from "lodash/fp"
import { LangChartStore } from "../stores/LangChartStore"
import Highcharts from "highcharts"
import HighchartsReact from "highcharts-react-official"
import GitHubColors from "github-colors"

export default function LangChart(props) {
    const store = new LangChartStore()
    const [state, setState] = useState(store.getConfig())
    let dataLength = 0
    let top50 = []
    let visible
    const style = {
        width: "100%",
        margin: "auto",
        maxWidth: 1360,
    }

    /**
     * Creates Highcharts xAxis categories since 2012
     * quarter wise: 2012/Q1, 2012/Q2, ...
     * @returns {Object} xAxis categories (year/quarter)
     */
    function categories() {
        return pipe(
            map((y) => map((q) => (q === 1 ? y : "")), range(1, 5)),
            flatten,
            drop(1)
        )(range(2012, 2050))
    }

    /**
     * Calculates relative / percentage of series data
     * Example: Pull Request -> JavaScript 22.2%, C# 4%, ..
     * @param {Object} current - GitHub api data set
     * @returns {Object} Data series with percentage data
     */
    function percentageData(data) {
        const total = pipe(map("data"), unzip, map(sum))(data)
        const zipTotal = (x) => zipWith(divide, x)(total)
        const zipData = pipe(update("data"))(zipTotal)
        return map(zipData, data)
    }

    /**
     * Adds zeros if we dont have enough historical data. For example,
     * there is no data for Typescript in 2012/Q2.
     * @param {Object} current - GitHub api data set
     * @returns {Object} Data series filled with zeros if required
     */
    function fillZeros(data) {
        const HistSize = pipe(map("data"), map(size), max)(data)
        const fill = (d) => new Array(HistSize - size(d)).fill(0).concat(d)
        return map(update("data", fill))(data)
    }

    /**
     * Creates a data series for highcharts based on GitHub raw api data
     * Filters top 10 languages
     * @param {Object} current - GitHub api data set
     * @returns {Object} Data series for top 10 languages
     */
    function createSeries(data) {
        return pipe(
            uniqBy("name"),
            reject((o) => !includes(o.name)(top50)),
            map.convert({ cap: 0 })((d, i) => ({
                name: d.name,
                color: GitHubColors.get(d.name)
                    ? GitHubColors.get(d.name).color // or random color
                    : "#" + Math.floor(Math.random() * 16777215).toString(16),
                visible: visible ? visible.includes(d.name) : i < 7,
                data: map("count")(filter({ name: d.name })(data)),
            })),
            fillZeros
        )(data)
    }

    /*
     * Updates react state if state has changed
     */
    function updateState(newState) {
        if (!isEqual(state, newState)) {
            setState(newState)
        }
    }

    /*
     * Creates a new percentage series of data
     */
    function createSeriesPercentage(data) {
        return pipe(
            map(update("count")(Math.floor)),
            createSeries,
            percentageData
        )(data)
    }

    /**
     * Creates a new chart if state has changed
     */
    function constructChart(data, title, top) {
        if (
            (data.length === dataLength || isEqual(top50, top)) &&
            size(top) === 0
        ) {
            return
        }

        top50 = top
        dataLength = data.length
        const newState = {
            ...state,
            yAxis: {
                ...state.yAxis,
                title: { text: title },
            },
            series: createSeriesPercentage(data),
            xAxis: { tickLength: 0, categories: categories() },
        }
        updateState(newState)
    }

    /**
     * Native react function, called on component mount and
     * on every prop change event
     */
    useEffect(() => {
            const { lang } = props.match.params
            visible = lang ? lang.split(",") : undefined
            const [store, _] = props.store
            const data = store.data
            const title = store.name
            const top = pipe(
                take(50),
                sortBy("name"),
                map("name")
            )(props.table[0].data)
            constructChart(data, title, top)
    }, [props.hist, props.store, props.table])

    if (state && state.series && state.series.length === 0) return null
    return (

            <HighchartsReact highcharts={Highcharts} options={state} />

    )
}
<commit_msg>debounce langchart update<commit_after>/**
 * Programming language popularity chart based on Highcharts
 * Please note that this file is dual licensed since Highcharts
 * is licensed under CC BY-NC 3.0
 * If Highcharts gets replaced in the future this class
 * will be licensed under AGPL-3.0 only
 * @author Fabian Beuke <mail@beuke.org>
 * @license AGPL-3.0 everything except Highcharts
 * @license CC BY-NC 3.0 Highcharts
 * @see {@link https://creativecommons.org/licenses/by-nc/3.0/}
 */

import React, { useState, useEffect } from "react"
import { update, range, sortBy, includes, uniqBy, reject } from "lodash/fp"
import { size, max, flatten, map, take, zipWith, divide } from "lodash/fp"
import { unzip, sum, filter, drop, isEqual, pipe } from "lodash/fp"
import _ from "lodash"
import { LangChartStore } from "../stores/LangChartStore"
import Highcharts from "highcharts"
import HighchartsReact from "highcharts-react-official"
import GitHubColors from "github-colors"

export default function LangChart(props) {
    const store = new LangChartStore()
    const [state, setState] = useState(store.getConfig())
    const [debounce, ] = useState(() => _.debounce(setState, 200))
    let dataLength = 0
    let visible
    const style = {
        width: "100%",
        margin: "auto",
        maxWidth: 1360,
    }

    /**
     * Creates Highcharts xAxis categories since 2012
     * quarter wise: 2012/Q1, 2012/Q2, ...
     * @returns {Object} xAxis categories (year/quarter)
     */
    function categories() {
        return pipe(
            map((y) => map((q) => (q === 1 ? y : "")), range(1, 5)),
            flatten,
            drop(1)
        )(range(2012, 2050))
    }

    /**
     * Calculates relative / percentage of series data
     * Example: Pull Request -> JavaScript 22.2%, C# 4%, ..
     * @param {Object} current - GitHub api data set
     * @returns {Object} Data series with percentage data
     */
    function percentageData(data) {
        const total = pipe(map("data"), unzip, map(sum))(data)
        const zipTotal = (x) => zipWith(divide, x)(total)
        const zipData = pipe(update("data"))(zipTotal)
        return map(zipData, data)
    }

    /**
     * Adds zeros if we dont have enough historical data. For example,
     * there is no data for Typescript in 2012/Q2.
     * @param {Object} current - GitHub api data set
     * @returns {Object} Data series filled with zeros if required
     */
    function fillZeros(data) {
        const HistSize = pipe(map("data"), map(size), max)(data)
        const fill = (d) => new Array(HistSize - size(d)).fill(0).concat(d)
        return map(update("data", fill))(data)
    }

    /**
     * Creates a data series for highcharts based on GitHub raw api data
     * Filters top 10 languages
     * @param {Object} current - GitHub api data set
     * @returns {Object} Data series for top 10 languages
     */
    const createSeries = (top) => (data) => {
        return pipe(
            uniqBy("name"),
            reject((o) => !includes(o.name)(top)),
            map.convert({ cap: 0 })((d, i) => ({
                name: d.name,
                color: GitHubColors.get(d.name)
                    ? GitHubColors.get(d.name).color // or random color
                    : "#" + Math.floor(Math.random() * 16777215).toString(16),
                visible: visible ? visible.includes(d.name) : i < 7,
                data: map("count")(filter({ name: d.name })(data)),
            })),
            fillZeros
        )(data)
    }

    /*
     * Updates react state if state has changed
     */
    function updateState(newState) {
        if (!isEqual(state, newState)) {
            debounce(newState)
        }
    }

    /*
     * Creates a new percentage series of data
     */
    function createSeriesPercentage(data, top) {
        return pipe(
            map(update("count")(Math.floor)),
            createSeries(top),
            percentageData
        )(data)
    }

    /**
     * Creates a new chart if state has changed
     */
    function constructChart(data, title, top) {
        if (data.length === dataLength && size(top) === 0) {
            return
        }

        dataLength = data.length
        const newState = {
            ...state,
            yAxis: {
                ...state.yAxis,
                title: { text: title },
            },
            series: createSeriesPercentage(data, top),
            xAxis: { tickLength: 0, categories: categories() },
        }
        console.log
        updateState(newState)
    }

    /**
     * Native react function, called on component mount and
     * on every prop change event
     */
    useEffect(() => {
        const { lang } = props.match.params
        visible = lang ? lang.split(",") : undefined
        const [store, _] = props.store
        const data = store.data
        const title = store.name
        const top = pipe(
            take(50),
            sortBy("name"),
            map("name")
        )(props.table[0].data)
        constructChart(data, title, top)
    }, [props.hist, props.store, props.table])

    if (state && state.series && state.series.length === 0) return null
    return (

            <HighchartsReact highcharts={Highcharts} options={state} />

    )
}
<|endoftext|>


<commit_before>define(["Tone/core/Tone"], function (Tone) {

	//augment the built in functions
	return function(buffer){

		buffer.isSilent = function(channelNum){
			if (Tone.isUndef(channelNum)){
				return buffer.toMono().isSilent(0);
			} else {
				var array = buffer.toArray(channelNum);
				for (var i = 0; i < array.length; i++){
					if (array[i] !== 0){
						return false;
					}
				}
				return true;
			}
		};

		/**
		 *  Get the RMS levels for the buffer, returned as an array
		 *  @param  {blockSize}  [blockSize=512]
		 */
		buffer.getRMS = function(blockSize){
			blockSize = blockSize || 512;
			var rms = [];
			var array = buffer.toMono().toArray();
			for (var j = 0; j < array.length; j++){
				var sum = 0;
				if (j >= blockSize){
					for (var k = j - blockSize; k < j; k++){
						sum += array[k] * array[k];
					}
					rms.push(Math.sqrt(sum / blockSize));
				}
			}
			return rms;
		};

		//return the time when the buffer is no longer silent
		buffer.getFirstSoundTime = function(channelNum){
			if (Tone.isUndef(channelNum)){
				return buffer.toMono().getFirstSoundTime(0);
			} else {
				var array = buffer.toArray(channelNum);
				for (var i = 0; i < array.length; i++){
					if (array[i] !== 0){
						return i / buffer.context.sampleRate;
					}
				}
				return -1;
			}
		};

		//returns the value at the given time
		buffer.getValueAtTime = function(time){
			var ret = [];
			var sample = Math.round(time * buffer.context.sampleRate);
			for (var i = 0; i < buffer.numberOfChannels; i++){
				ret[i] = buffer.getChannelData(i)[sample];
			}
			if (ret.length === 1){
				return ret[0];
			} else {
				return ret;
			}
		};

		//return the time when the buffer is silent to the remainer of the buffer
		buffer.getLastSoundTime = function(channelNum){
			if (Tone.isUndef(channelNum)){
				return buffer.toMono().getLastSoundTime(0);
			} else {
				var array = buffer.toArray(channelNum);
				for (var i = array.length - 1; i >= 0; i--){
					if (array[i] !== 0){
						return i / buffer.context.sampleRate;
					}
				}
				return 0;
			}
		};

		//stops and returns value if callback does
		buffer.forEach = function(callback, start, end){
			var i, ret;
			start = start || 0;
			end = end || buffer.duration;
			start = Math.floor((start / buffer.duration) * buffer.length);
			end = Math.floor((end / buffer.duration) * buffer.length);
			if (buffer.numberOfChannels === 2){
				var arrayL = buffer.toArray(0);
				var arrayR = buffer.toArray(1);
				for (i = start; i < end; i++){
					ret = callback(arrayL[i], arrayR[i], (i/buffer.length) * buffer.duration);
					if (typeof ret !== "undefined"){
						return ret;
					}
				}

			} else {
				var array = buffer.toArray();
				for (i = start; i < end; i++){
					ret = callback(array[i], (i/array.length) * buffer.duration);
					if (typeof ret !== "undefined"){
						return ret;
					}
				}
			}
		};

		/**
		 *  Returns the max value in the buffer
		 *  @return  {Number}
		 */
		buffer.max = function(){
			var max = -Infinity;
			buffer.toMono().forEach(function(sample){
				max = Math.max(sample, max);
			});
			return max;
		};

		/**
		 *  Returns the min value in the buffer
		 *  @return  {Number}
		 */
		buffer.min = function(){
			var min = Infinity;
			buffer.toMono().forEach(function(sample){
				min = Math.min(sample, min);
			});
			return min;
		};

		/**
		 *  returns the value if there is a single value the entire buffer
		 */
		buffer.value = function(){
			var val;
			buffer.toMono().forEach(function(sample){
				if (typeof val === "undefined"){
					val = sample;
				} else if (Math.abs(val - sample) > 0.0001){
					throw new Error("multiple values in buffer");
				}
			});
			return val;
		};
	};
});
<commit_msg>adding get getRmsAtTime to BufferTests<commit_after>define(["Tone/core/Tone"], function(Tone) {

	//augment the built in functions
	return function(buffer){

		buffer.isSilent = function(channelNum){
			if (Tone.isUndef(channelNum)){
				return buffer.toMono().isSilent(0);
			} else {
				var array = buffer.toArray(channelNum);
				for (var i = 0; i < array.length; i++){
					if (array[i] !== 0){
						return false;
					}
				}
				return true;
			}
		};

		/**
		 *  Get the RMS levels for the buffer, returned as an array
		 *  @param  {blockSize}  [blockSize=512]
		 */
		buffer.getRMS = function(blockSize){
			blockSize = blockSize || 512;
			var rms = [];
			var array = buffer.toMono().toArray();
			for (var j = 0; j < array.length; j++){
				var sum = 0;
				if (j >= blockSize){
					for (var k = j - blockSize; k < j; k++){
						sum += array[k] * array[k];
					}
					rms.push(Math.sqrt(sum / blockSize));
				}
			}
			return rms;
		};

		//get the rms at the given time
		buffer.getRmsAtTime = function(time){
			var rms = this.getRMS();
			var sample = Math.floor(time * this.context.sampleRate);
			return rms[sample];
		};

		//return the time when the buffer is no longer silent
		buffer.getFirstSoundTime = function(channelNum){
			if (Tone.isUndef(channelNum)){
				return buffer.toMono().getFirstSoundTime(0);
			} else {
				var array = buffer.toArray(channelNum);
				for (var i = 0; i < array.length; i++){
					if (array[i] !== 0){
						return i / buffer.context.sampleRate;
					}
				}
				return -1;
			}
		};

		//returns the value at the given time
		buffer.getValueAtTime = function(time){
			var ret = [];
			var sample = Math.round(time * buffer.context.sampleRate);
			for (var i = 0; i < buffer.numberOfChannels; i++){
				ret[i] = buffer.getChannelData(i)[sample];
			}
			if (ret.length === 1){
				return ret[0];
			} else {
				return ret;
			}
		};

		//return the time when the buffer is silent to the remainer of the buffer
		buffer.getLastSoundTime = function(channelNum){
			if (Tone.isUndef(channelNum)){
				return buffer.toMono().getLastSoundTime(0);
			} else {
				var array = buffer.toArray(channelNum);
				for (var i = array.length - 1; i >= 0; i--){
					if (array[i] !== 0){
						return i / buffer.context.sampleRate;
					}
				}
				return 0;
			}
		};

		//stops and returns value if callback does
		buffer.forEach = function(callback, start, end){
			var i, ret;
			start = start || 0;
			end = end || buffer.duration;
			start = Math.floor((start / buffer.duration) * buffer.length);
			end = Math.floor((end / buffer.duration) * buffer.length);
			if (buffer.numberOfChannels === 2){
				var arrayL = buffer.toArray(0);
				var arrayR = buffer.toArray(1);
				for (i = start; i < end; i++){
					ret = callback(arrayL[i], arrayR[i], (i/buffer.length) * buffer.duration);
					if (typeof ret !== "undefined"){
						return ret;
					}
				}

			} else {
				var array = buffer.toArray();
				for (i = start; i < end; i++){
					ret = callback(array[i], (i/array.length) * buffer.duration);
					if (typeof ret !== "undefined"){
						return ret;
					}
				}
			}
		};

		/**
		 *  Returns the max value in the buffer
		 *  @return  {Number}
		 */
		buffer.max = function(){
			var max = -Infinity;
			buffer.toMono().forEach(function(sample){
				max = Math.max(sample, max);
			});
			return max;
		};

		/**
		 *  Returns the min value in the buffer
		 *  @return  {Number}
		 */
		buffer.min = function(){
			var min = Infinity;
			buffer.toMono().forEach(function(sample){
				min = Math.min(sample, min);
			});
			return min;
		};

		/**
		 *  returns the value if there is a single value the entire buffer
		 */
		buffer.value = function(){
			var val;
			buffer.toMono().forEach(function(sample){
				if (typeof val === "undefined"){
					val = sample;
				} else if (Math.abs(val - sample) > 0.0001){
					throw new Error("multiple values in buffer");
				}
			});
			return val;
		};
	};
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import AboutProfile from './AboutProfile.js';

var team = [{
  key: 1,
  name: "Mark Kim",
  bio: "Placeholder Bio",
  image: "../assets/mark-profile.jpg",
  git: "https://github.com/marksanghoonkim",
  linked: "https://www.linkedin.com/in/marksanghoonkim"
}, {
  key: 2,
  name: "Rick Yeh",
  bio: "Placeholder Bio",
  image: "../assets/rick-profile.jpg",
  git: "https://github.com/rickyeh",
  linked: "https://www.linkedin.com/in/rickyeh"
}, {
  key: 3,
  name: "Jordan Allen",
  bio: "Placeholder Bio",
  image: "../assets/jordan-profile.jpg",
  git: "https://github.com/jordanallen98",
  linked: "https://www.linkedin.com/in/jordandallen"
}, {
  key: 4,
  name: "Nicholas Der",
  bio: "Placeholder Bio",
  image: "../assets/nick-profile.jpg",
  git: "https://github.com/kiritsuzu",
  linked: "https://www.linkedin.com/in/kiritsuzu"
}];

class About extends Component {
  render() {
    var Profiles = team.map(function(profile){
      return ( <AboutProfile key={profile.key} name={profile.name} bio={profile.bio} image={profile.image} git={profile.git} linked={profile.linked}> </AboutProfile> );
    });

    return (

Meet The Team

        {Profiles}

    );
  }
}

export default About;
<commit_msg>[add] adds filler text for bio to work with styling area<commit_after>import React, { Component } from 'react';
import AboutProfile from './AboutProfile.js';

var team = [{
  key: 1,
  name: "Mark Kim",
  bio: "Completely synergize resource taxing relationships via premier niche markets. Professionally cultivate one-to-one customer service with robust ideas. Dynamically innovate resource-leveling customer service for state of the art customer service.",
  image: "../assets/mark-profile.jpg",
  git: "https://github.com/marksanghoonkim",
  linked: "https://www.linkedin.com/in/marksanghoonkim"
}, {
  key: 2,
  name: "Rick Yeh",
  bio: "Objectively innovate empowered manufactured products whereas parallel platforms. Holisticly predominate extensible testing procedures for reliable supply chains. Dramatically engage top-line web services vis-a-vis cutting-edge deliverables.",
  image: "../assets/rick-profile.jpg",
  git: "https://github.com/rickyeh",
  linked: "https://www.linkedin.com/in/rickyeh"
}, {
  key: 3,
  name: "Jordan Allen",
  bio: "Collaboratively administrate empowered markets via plug-and-play networks. Dynamically procrastinate B2C users after installed base benefits. Dramatically visualize customer directed convergence without revolutionary ROI.",
  image: "../assets/jordan-profile.jpg",
  git: "https://github.com/jordanallen98",
  linked: "https://www.linkedin.com/in/jordandallen"
}, {
  key: 4,
  name: "Nicholas Der",
  bio: "Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas. Dramatically maintain clicks-and-mortar solutions without functional solutions.",
  image: "../assets/nick-profile.jpg",
  git: "https://github.com/kiritsuzu",
  linked: "https://www.linkedin.com/in/kiritsuzu"
}];

class About extends Component {
  render() {
    var Profiles = team.map(function(profile){
      return ( <AboutProfile key={profile.key} name={profile.name} bio={profile.bio} image={profile.image} git={profile.git} linked={profile.linked}> </AboutProfile> );
    });

    return (

Meet The Team

        {Profiles}

    );
  }
}

export default About;
<|endoftext|>


<commit_before>'use strict';

angular.module('copayApp.controllers').controller('tabSendController', function($scope, $rootScope, $log, $timeout, $ionicScrollDelegate, addressbookService, profileService, lodash, $state, walletService, incomingData, popupService, platformInfo, bwcError, gettextCatalog, scannerService) {

  var originalList;
  var CONTACTS_SHOW_LIMIT;
  var currentContactsPage;
  $scope.isChromeApp = platformInfo.isChromeApp;

  var hasWallets = function() {
    $scope.wallets = profileService.getWallets({
      onlyComplete: true
    });
    $scope.hasWallets = lodash.isEmpty($scope.wallets) ? false : true;
  };

  // THIS is ONLY to show the 'buy bitcoins' message
  // does not has any other function.

  var updateHasFunds = function() {

    if ($rootScope.everHasFunds) {
      $scope.hasFunds = true;
      return;
    }

    $scope.hasFunds = false;
    var index = 0;
    lodash.each($scope.wallets, function(w) {
      walletService.getStatus(w, {}, function(err, status) {

        ++index;
        if (err && !status) {
          $log.error(err);
          // error updating the wallet. Probably a network error, do not show
          // the 'buy bitcoins' message.

          $scope.hasFunds = true;
        } else if (status.availableBalanceSat > 0) {
          $scope.hasFunds = true;
          $rootScope.everHasFunds = true;
        }

        if (index == $scope.wallets.length) {
          $scope.checkingBalance = false;
          $timeout(function() {
            $scope.$apply();
          });
        }
      });
    });
  };

  var updateWalletsList = function() {

    var networkResult = lodash.countBy($scope.wallets, 'network');

    $scope.showTransferCard = $scope.hasWallets && (networkResult.livenet > 1 || networkResult.testnet > 1);

    if ($scope.showTransferCard) {
      var walletsToTransfer = $scope.wallets;
      if (!(networkResult.livenet > 1)) {
        walletsToTransfer = lodash.filter(walletsToTransfer, function(item) {
          return item.network == 'testnet';
        });
      }
      if (!(networkResult.testnet > 1)) {
        walletsToTransfer = lodash.filter(walletsToTransfer, function(item) {
          return item.network == 'livenet';
        });
      }
      var walletList = [];
      lodash.each(walletsToTransfer, function(v) {
        walletList.push({
          color: v.color,
          name: v.name,
          recipientType: 'wallet',
          getAddress: function(cb) {
            walletService.getAddress(v, false, cb);
          },
        });
      });
      originalList = originalList.concat(walletList);
    }
  }

  var updateContactsList = function(cb) {
    addressbookService.list(function(err, ab) {
      if (err) $log.error(err);

      $scope.hasContacts = lodash.isEmpty(ab) ? false : true;
      if (!$scope.hasContacts) return cb();

      var completeContacts = [];
      lodash.each(ab, function(v, k) {
        completeContacts.push({
          name: lodash.isObject(v) ? v.name : v,
          address: k,
          email: lodash.isObject(v) ? v.email : null,
          recipientType: 'contact',
          getAddress: function(cb) {
            return cb(null, k);
          },
        });
      });
      var contacts = completeContacts.slice(0, (currentContactsPage + 1) * CONTACTS_SHOW_LIMIT);
      $scope.contactsShowMore = completeContacts.length > contacts.length;
      originalList = originalList.concat(contacts);
      return cb();
    });
  };

  var updateList = function() {
    $scope.list = lodash.clone(originalList);
    $timeout(function() {
      $ionicScrollDelegate.resize();
      $scope.$apply();
    }, 10);
  };

  $scope.openScanner = function() {
    var isWindowsPhoneApp = platformInfo.isCordova && platformInfo.isWP;

    if (!isWindowsPhoneApp) {
      $state.go('tabs.scan');
      return;
    }

    scannerService.useOldScanner(function(err, contents) {
      if (err) {
        popupService.showAlert(gettextCatalog.getString('Error'), err);
        return;
      }
      incomingData.redir(contents);
    });
  };

  $scope.showMore = function() {
    currentContactsPage++;
    updateWalletsList();
  };

  $scope.searchInFocus = function() {
    $scope.searchFocus = true;
  };

  $scope.searchBlurred = function() {
    if ($scope.formData.search == null || $scope.formData.search.length == 0) {
      $scope.searchFocus = false;
    }
  };

  $scope.findContact = function(search) {

    if (incomingData.redir(search)) {
      return;
    }

    if (!search || search.length < 2) {
      $scope.list = originalList;
      $timeout(function() {
        $scope.$apply();
      });
      return;
    }

    var result = lodash.filter(originalList, function(item) {
      var val = item.name;
      return lodash.includes(val.toLowerCase(), search.toLowerCase());
    });

    $scope.list = result;
  };

  $scope.goToAmount = function(item) {
    $timeout(function() {
      item.getAddress(function(err, addr) {
        if (err || !addr) {
          //Error is already formated
          return popupService.showAlert(err);
        }
        $log.debug('Got toAddress:' + addr + ' | ' + item.name);
        return $state.transitionTo('tabs.send.amount', {
          recipientType: item.recipientType,
          toAddress: addr,
          toName: item.name,
          toEmail: item.email,
          toColor: item.color
        })
      });
    });
  };

  // This could probably be enhanced refactoring the routes abstract states
  $scope.createWallet = function() {
    $state.go('tabs.home').then(function() {
      $state.go('tabs.add.create-personal');
    });
  };

  $scope.buyBitcoin = function() {
    $state.go('tabs.home').then(function() {
      $state.go('tabs.buyandsell');
    });
  };

  $scope.$on("$ionicView.beforeEnter", function(event, data) {
    $scope.checkingBalance = true;
    $scope.formData = {
      search: null
    };
    originalList = [];
    CONTACTS_SHOW_LIMIT = 10;
    currentContactsPage = 0;
    hasWallets();
  });

  $scope.$on("$ionicView.enter", function(event, data) {
    if (!$scope.hasWallets) {
      $scope.checkingBalance = false;
      return;
    }
    updateHasFunds();
    updateWalletsList();
    updateContactsList(function() {
      updateList();
    });
  });
});
<commit_msg>Fix transfer to another wallet<commit_after>'use strict';

angular.module('copayApp.controllers').controller('tabSendController', function($scope, $rootScope, $log, $timeout, $ionicScrollDelegate, addressbookService, profileService, lodash, $state, walletService, incomingData, popupService, platformInfo, bwcError, gettextCatalog, scannerService) {

  var originalList;
  var CONTACTS_SHOW_LIMIT;
  var currentContactsPage;
  $scope.isChromeApp = platformInfo.isChromeApp;

  var hasWallets = function() {
    $scope.wallets = profileService.getWallets({
      onlyComplete: true
    });
    $scope.hasWallets = lodash.isEmpty($scope.wallets) ? false : true;
  };

  // THIS is ONLY to show the 'buy bitcoins' message
  // does not has any other function.

  var updateHasFunds = function() {

    if ($rootScope.everHasFunds) {
      $scope.hasFunds = true;
      return;
    }

    $scope.hasFunds = false;
    var index = 0;
    lodash.each($scope.wallets, function(w) {
      walletService.getStatus(w, {}, function(err, status) {

        ++index;
        if (err && !status) {
          $log.error(err);
          // error updating the wallet. Probably a network error, do not show
          // the 'buy bitcoins' message.

          $scope.hasFunds = true;
        } else if (status.availableBalanceSat > 0) {
          $scope.hasFunds = true;
          $rootScope.everHasFunds = true;
        }

        if (index == $scope.wallets.length) {
          $scope.checkingBalance = false;
          $timeout(function() {
            $scope.$apply();
          });
        }
      });
    });
  };

  var updateWalletsList = function() {

    var networkResult = lodash.countBy($scope.wallets, 'network');

    $scope.showTransferCard = $scope.hasWallets && (networkResult.livenet > 1 || networkResult.testnet > 1);

    if ($scope.showTransferCard) {
      var walletsToTransfer = $scope.wallets;
      if (!(networkResult.livenet > 1)) {
        walletsToTransfer = lodash.filter(walletsToTransfer, function(item) {
          return item.network == 'testnet';
        });
      }
      if (!(networkResult.testnet > 1)) {
        walletsToTransfer = lodash.filter(walletsToTransfer, function(item) {
          return item.network == 'livenet';
        });
      }
      var walletList = [];
      lodash.each(walletsToTransfer, function(v) {
        walletList.push({
          color: v.color,
          name: v.name,
          recipientType: 'wallet',
          coin: v.coin,
          getAddress: function(cb) {
            walletService.getAddress(v, false, cb);
          },
        });
      });
      originalList = originalList.concat(walletList);
    }
  }

  var updateContactsList = function(cb) {
    addressbookService.list(function(err, ab) {
      if (err) $log.error(err);

      $scope.hasContacts = lodash.isEmpty(ab) ? false : true;
      if (!$scope.hasContacts) return cb();

      var completeContacts = [];
      lodash.each(ab, function(v, k) {
        completeContacts.push({
          name: lodash.isObject(v) ? v.name : v,
          address: k,
          email: lodash.isObject(v) ? v.email : null,
          recipientType: 'contact',
          getAddress: function(cb) {
            return cb(null, k);
          },
        });
      });
      var contacts = completeContacts.slice(0, (currentContactsPage + 1) * CONTACTS_SHOW_LIMIT);
      $scope.contactsShowMore = completeContacts.length > contacts.length;
      originalList = originalList.concat(contacts);
      return cb();
    });
  };

  var updateList = function() {
    $scope.list = lodash.clone(originalList);
    $timeout(function() {
      $ionicScrollDelegate.resize();
      $scope.$apply();
    }, 10);
  };

  $scope.openScanner = function() {
    var isWindowsPhoneApp = platformInfo.isCordova && platformInfo.isWP;

    if (!isWindowsPhoneApp) {
      $state.go('tabs.scan');
      return;
    }

    scannerService.useOldScanner(function(err, contents) {
      if (err) {
        popupService.showAlert(gettextCatalog.getString('Error'), err);
        return;
      }
      incomingData.redir(contents);
    });
  };

  $scope.showMore = function() {
    currentContactsPage++;
    updateWalletsList();
  };

  $scope.searchInFocus = function() {
    $scope.searchFocus = true;
  };

  $scope.searchBlurred = function() {
    if ($scope.formData.search == null || $scope.formData.search.length == 0) {
      $scope.searchFocus = false;
    }
  };

  $scope.findContact = function(search) {

    if (incomingData.redir(search)) {
      return;
    }

    if (!search || search.length < 2) {
      $scope.list = originalList;
      $timeout(function() {
        $scope.$apply();
      });
      return;
    }

    var result = lodash.filter(originalList, function(item) {
      var val = item.name;
      return lodash.includes(val.toLowerCase(), search.toLowerCase());
    });

    $scope.list = result;
  };

  $scope.goToAmount = function(item) {
    $timeout(function() {
      item.getAddress(function(err, addr) {
        if (err || !addr) {
          //Error is already formated
          return popupService.showAlert(err);
        }
        $log.debug('Got toAddress:' + addr + ' | ' + item.name);
        return $state.transitionTo('tabs.send.amount', {
          recipientType: item.recipientType,
          toAddress: addr,
          toName: item.name,
          toEmail: item.email,
          toColor: item.color,
          coin: item.coin
        })
      });
    });
  };

  // This could probably be enhanced refactoring the routes abstract states
  $scope.createWallet = function() {
    $state.go('tabs.home').then(function() {
      $state.go('tabs.add.create-personal');
    });
  };

  $scope.buyBitcoin = function() {
    $state.go('tabs.home').then(function() {
      $state.go('tabs.buyandsell');
    });
  };

  $scope.$on("$ionicView.beforeEnter", function(event, data) {
    $scope.checkingBalance = true;
    $scope.formData = {
      search: null
    };
    originalList = [];
    CONTACTS_SHOW_LIMIT = 10;
    currentContactsPage = 0;
    hasWallets();
  });

  $scope.$on("$ionicView.enter", function(event, data) {
    if (!$scope.hasWallets) {
      $scope.checkingBalance = false;
      return;
    }
    updateHasFunds();
    updateWalletsList();
    updateContactsList(function() {
      updateList();
    });
  });
});
<|endoftext|>


<commit_before>window.onload = function(){
  var christmasDay = new Date("January 5, 2017 00:00:00");
  startTimer("clock", christmasDay);
};

function startTimer(id, christmasDay){
  var timerInterval = setInterval(function(){
    var clock = document.getElementById(id);
    var timer = updateTimer(christmasDay);

    clock.innerHTML = '' + timer.days + ''
                    + '' + timer.hours + ''
                    + '' + timer.minutes + ''
                    + '' + timer.seconds + '';

    var spans = clock.getElementsByTagName("span");
    animateClock(spans[3]);
    if(timer.seconds == 59) animateClock(spans[2]);
    if(timer.minutes == 59 && timer.seconds == 59) animateClock(spans[1]);
    if(timer.hours == 23 && timer.minutes == 59 && timer.seconds == 59) animateClock(spans[0]);

    if(timer.total < 1){
      clearInterval(timerInterval);
      clock.innerHTML = '0000';
    }

  }, 1000);
}

function updateTimer(christmasDay){
  var time = christmasDay - new Date();
  return {
    'days': Math.floor( time/(1000*60*60*24) ),
    'hours': Math.floor( (time/(1000*60*60)) % 24 ),
    'minutes': Math.floor( (time/1000/60) % 60 ),
    'seconds': Math.floor( (time/1000) % 60 ),
    'total' : time
  };
}

function animateClock(span){
  span.className = "turn";
  setTimeout(function(){
    span.className = "";
  },700);
}

<commit_msg>Update FinalScript.js<commit_after>window.onload = function(){
  var christmasDay = new Date("March 16, 2017 00:00:00");
  startTimer("clock", christmasDay);
};

function startTimer(id, christmasDay){
  var timerInterval = setInterval(function(){
    var clock = document.getElementById(id);
    var timer = updateTimer(christmasDay);

    clock.innerHTML = '' + timer.days + ''
                    + '' + timer.hours + ''
                    + '' + timer.minutes + ''
                    + '' + timer.seconds + '';

    var spans = clock.getElementsByTagName("span");
    animateClock(spans[3]);
    if(timer.seconds == 59) animateClock(spans[2]);
    if(timer.minutes == 59 && timer.seconds == 59) animateClock(spans[1]);
    if(timer.hours == 23 && timer.minutes == 59 && timer.seconds == 59) animateClock(spans[0]);

    if(timer.total < 1){
      clearInterval(timerInterval);
      clock.innerHTML = '0000';
    }

  }, 1000);
}

function updateTimer(christmasDay){
  var time = christmasDay - new Date();
  return {
    'days': Math.floor( time/(1000*60*60*24) ),
    'hours': Math.floor( (time/(1000*60*60)) % 24 ),
    'minutes': Math.floor( (time/1000/60) % 60 ),
    'seconds': Math.floor( (time/1000) % 60 ),
    'total' : time
  };
}

function animateClock(span){
  span.className = "turn";
  setTimeout(function(){
    span.className = "";
  },700);
}

<|endoftext|>


<commit_before>'use strict';

angular.module('copayApp.controllers').controller('tabSendController', function($scope, $log, $timeout, $ionicScrollDelegate, addressbookService, profileService, lodash, $state, walletService, incomingData, popupService) {

  var originalList;
  var CONTACTS_SHOW_LIMIT;
  var currentContactsPage;

  var updateList = function() {
    CONTACTS_SHOW_LIMIT = 10;
    currentContactsPage = 0;
    originalList = [];

    var wallets = profileService.getWallets({
      onlyComplete: true
    });
    $scope.hasWallets = lodash.isEmpty(wallets) ? false : true;
    $scope.oneWallet = wallets.length == 1;

    if (!$scope.oneWallet) {
      lodash.each(wallets, function(v) {
        originalList.push({
          color: v.color,
          name: v.name,
          isWallet: true,
          getAddress: function(cb) {
            walletService.getAddress(v, false, cb);
          },
        });
      });
    }

    addressbookService.list(function(err, ab) {
      if (err) $log.error(err);

      $scope.hasContacts = lodash.isEmpty(ab) ? false : true;
      var completeContacts = [];
      lodash.each(ab, function(v, k) {
        completeContacts.push({
          name: lodash.isObject(v) ? v.name : v,
          address: k,
          email: lodash.isObject(v) ? v.email : null,
          getAddress: function(cb) {
            return cb(null, k);
          },
        });
      });

      var contacts = completeContacts.slice(0, (currentContactsPage + 1) * CONTACTS_SHOW_LIMIT);
      $scope.contactsShowMore = completeContacts.length > contacts.length;
      originalList = originalList.concat(contacts);
      $scope.list = lodash.clone(originalList);

      $timeout(function() {
        $ionicScrollDelegate.resize();
        $scope.$apply();
      });
    });
  };

  $scope.openScanner = function() {
    $state.go('tabs.scan');
  }

  $scope.showMore = function() {
    currentContactsPage++;
    updateList();
  };

  $scope.findContact = function(search) {

    if (incomingData.redir(search)) {
      return;
    }

    if (!search || search.length < 2) {
      $scope.list = originalList;
      $timeout(function() {
        $scope.$apply();
      });
      return;
    }

    var result = lodash.filter(originalList, function(item) {
      var val = item.name;
      return lodash.includes(val.toLowerCase(), search.toLowerCase());
    });

    $scope.list = result;
  };

  $scope.goToAmount = function(item) {
    $timeout(function() {
      item.getAddress(function(err, addr) {
        if (err || !addr) {
          $log.error(err);
          return;
        }
        $log.debug('Got toAddress:' + addr + ' | ' + item.name);
        return $state.transitionTo('tabs.send.amount', {
          isWallet: item.isWallet,
          toAddress: addr,
          toName: item.name,
          toEmail: item.email,
          toColor: item.color
        })
      });
    });
  };

  var updateHasFunds = function() {
    $scope.hasFunds = true;

    var wallets = profileService.getWallets({
      onlyComplete: true,
    });

    if (!wallets || !wallets.length) {
      $scope.hasFunds = false;
      $timeout(function() {
        $scope.$apply();
      });
    }

    var index = 0;
    var walletsTotalBalance = 0;
    lodash.each(wallets, function(w) {
      walletService.getStatus(w, {}, function(err, status) {
        ++index;
        if (err || !status) {
          $log.error(err);
          return;
        }
        walletsTotalBalance = walletsTotalBalance + status.availableBalanceSat;
        if (index == wallets.length && walletsTotalBalance == 0) {
          $scope.hasFunds = false;
          $timeout(function() {
            $scope.$apply();
          });
        }
      });
    });
  };

  $scope.$on("$ionicView.beforeEnter", function(event, data) {
    $scope.formData = {
      search: null
    };
    updateList();
    updateHasFunds();
  });

  // This could probably be enhanced refactoring the routes abstract states
  $scope.createWallet = function() {
    $state.go('tabs.home').then(function() {
      $state.go('tabs.add.create-personal');
    });
  };

  $scope.buyBitcoin = function() {
    $state.go('tabs.home').then(function() {
      $state.go('tabs.buyandsell.glidera');
    });
  };

});
<commit_msg>add "Cache" for hasFunds<commit_after>'use strict';

angular.module('copayApp.controllers').controller('tabSendController', function($scope, $log, $timeout, $ionicScrollDelegate, addressbookService, profileService, lodash, $state, walletService, incomingData, popupService, $rootScope) {

  var originalList;
  var CONTACTS_SHOW_LIMIT;
  var currentContactsPage;

  var updateList = function() {
    CONTACTS_SHOW_LIMIT = 10;
    currentContactsPage = 0;
    originalList = [];

    var wallets = profileService.getWallets({
      onlyComplete: true
    });
    $scope.hasWallets = lodash.isEmpty(wallets) ? false : true;
    $scope.oneWallet = wallets.length == 1;

    if (!$scope.oneWallet) {
      lodash.each(wallets, function(v) {
        originalList.push({
          color: v.color,
          name: v.name,
          isWallet: true,
          getAddress: function(cb) {
            walletService.getAddress(v, false, cb);
          },
        });
      });
    }

    addressbookService.list(function(err, ab) {
      if (err) $log.error(err);

      $scope.hasContacts = lodash.isEmpty(ab) ? false : true;
      var completeContacts = [];
      lodash.each(ab, function(v, k) {
        completeContacts.push({
          name: lodash.isObject(v) ? v.name : v,
          address: k,
          email: lodash.isObject(v) ? v.email : null,
          getAddress: function(cb) {
            return cb(null, k);
          },
        });
      });

      var contacts = completeContacts.slice(0, (currentContactsPage + 1) * CONTACTS_SHOW_LIMIT);
      $scope.contactsShowMore = completeContacts.length > contacts.length;
      originalList = originalList.concat(contacts);
      $scope.list = lodash.clone(originalList);

      $timeout(function() {
        $ionicScrollDelegate.resize();
        $scope.$apply();
      });
    });
  };

  $scope.openScanner = function() {
    $state.go('tabs.scan');
  }

  $scope.showMore = function() {
    currentContactsPage++;
    updateList();
  };

  $scope.findContact = function(search) {

    if (incomingData.redir(search)) {
      return;
    }

    if (!search || search.length < 2) {
      $scope.list = originalList;
      $timeout(function() {
        $scope.$apply();
      });
      return;
    }

    var result = lodash.filter(originalList, function(item) {
      var val = item.name;
      return lodash.includes(val.toLowerCase(), search.toLowerCase());
    });

    $scope.list = result;
  };

  $scope.goToAmount = function(item) {
    $timeout(function() {
      item.getAddress(function(err, addr) {
        if (err || !addr) {
          $log.error(err);
          return;
        }
        $log.debug('Got toAddress:' + addr + ' | ' + item.name);
        return $state.transitionTo('tabs.send.amount', {
          isWallet: item.isWallet,
          toAddress: addr,
          toName: item.name,
          toEmail: item.email,
          toColor: item.color
        })
      });
    });
  };

  var updateHasFunds = function() {
    $scope.hasFunds = true;

    if ($rootScope.everHasFunds)
      return;

    var wallets = profileService.getWallets({
      onlyComplete: true,
    });

    if (!wallets || !wallets.length) {
      $scope.hasFunds = false;
      $timeout(function() {
        $scope.$apply();
      });
    }

    var index = 0;
    var walletsTotalBalance = 0;
    lodash.each(wallets, function(w) {
      walletService.getStatus(w, {}, function(err, status) {
        ++index;
        if (err || !status) {
          $log.error(err);
          return;
        }
        walletsTotalBalance = walletsTotalBalance + status.availableBalanceSat;
        if (walletsTotalBalance>0) {
          $rootScope.everHasFunds = true;
        }
        if (index == wallets.length && walletsTotalBalance == 0) {
          $scope.hasFunds = false;
          $timeout(function() {
            $scope.$apply();
          });
        }
      });
    });
  };

  $scope.$on("$ionicView.beforeEnter", function(event, data) {
    $scope.formData = {
      search: null
    };
    updateList();
    updateHasFunds();
  });

  // This could probably be enhanced refactoring the routes abstract states
  $scope.createWallet = function() {
    $state.go('tabs.home').then(function() {
      $state.go('tabs.add.create-personal');
    });
  };

  $scope.buyBitcoin = function() {
    $state.go('tabs.home').then(function() {
      $state.go('tabs.buyandsell.glidera');
    });
  };

});
<|endoftext|>


<commit_before>const utils = require('./../../utils');
const HoverPreview = require('./utilities/image-map-hover.js');

const errorTemplate = require('./../../common/templates/_error.hbs');
const template = require("./../templates/index.hbs");

(($) => {
    $(document).ready(() => {
        utils.getCurrentPageHAL($)
            .then((result) => {
                let content;

                if (result.error) {
                    content = errorTemplate(result.data);
                } else {
                    console.log("initial load: data=", result.data);
                    content = template(result.data);
                }
                $('#i3c-portal-placeholder').html(content);

                const hoverPreview = new HoverPreview();

                $('.overview-image-container')
                .on('mouseenter', '.map-hover-area', hoverPreview.onFocus.bind(hoverPreview, $))
                .on('mouseleave', '.map-hover-area', hoverPreview.onBlur.bind(hoverPreview, $));
            });
    });
})(jQuery);
<commit_msg>Dynamically changing document title<commit_after>const utils = require('./../../utils');
const HoverPreview = require('./utilities/image-map-hover.js');

const errorTemplate = require('./../../common/templates/_error.hbs');
const template = require("./../templates/index.hbs");

(($) => {
    $(document).ready(() => {
        utils.getCurrentPageHAL($)
            .then((result) => {
                const content = (result.error) ? errorTemplate(result.data) : template(result.data);
                if (!result.error && result.data && result.data.Name) {
                    document.title = result.data.Name;
                }

                $('#i3c-portal-placeholder').html(content);

                const hoverPreview = new HoverPreview();

                $('.overview-image-container')
                .on('mouseenter', '.map-hover-area', hoverPreview.onFocus.bind(hoverPreview, $))
                .on('mouseleave', '.map-hover-area', hoverPreview.onBlur.bind(hoverPreview, $));
            });
    });
})(jQuery);
<|endoftext|>


<commit_before>/* eslint-env mocha */
/* eslint-disable no-multi-assign */

import Bluebird from 'bluebird';
import puppeteer from 'puppeteer';
import singletons from './integration/singletons';

// use bluebird instead of native promises for improved async stack traces
Bluebird.config({ longStackTraces: true });
global.Promise = Bluebird;

let browser;

const loadPage = () => new Promise((resolve, reject) => {
  let tryCount = 0;
  const innerLoadPage = async () => {
    try {
      await singletons.page.goto('http://local.lunch.pink:3000/');
      resolve();
    } catch (err) {
      if (err.message.indexOf('ERR_CONNECTION_REFUSED') > -1 && tryCount < 30) {
        // eslint-disable-next-line no-console
        console.log('No response from server. Trying again in 1 second...');
        setTimeout(innerLoadPage, 1000);
        tryCount += 1;
      } else {
        reject(err);
      }
    };
  };
  innerLoadPage();
});

const opts =
  {
    headless: !!process.env.CI,
    slowMo: 10,
  };

before(async () => {
  browser = singletons.browser = await puppeteer.launch(opts);
  singletons.page = await browser.newPage();
  singletons.page.setViewport({width: 1024, height: 768});
  await loadPage();
});

after(async () => {
  await browser.close();
});
<commit_msg>increase slo-mo delay to 30<commit_after>/* eslint-env mocha */
/* eslint-disable no-multi-assign */

import Bluebird from 'bluebird';
import puppeteer from 'puppeteer';
import singletons from './integration/singletons';

// use bluebird instead of native promises for improved async stack traces
Bluebird.config({ longStackTraces: true });
global.Promise = Bluebird;

let browser;

const loadPage = () => new Promise((resolve, reject) => {
  let tryCount = 0;
  const innerLoadPage = async () => {
    try {
      await singletons.page.goto('http://local.lunch.pink:3000/');
      resolve();
    } catch (err) {
      if (err.message.indexOf('ERR_CONNECTION_REFUSED') > -1 && tryCount < 30) {
        // eslint-disable-next-line no-console
        console.log('No response from server. Trying again in 1 second...');
        setTimeout(innerLoadPage, 1000);
        tryCount += 1;
      } else {
        reject(err);
      }
    };
  };
  innerLoadPage();
});

const opts =
  {
    headless: !!process.env.CI,
    slowMo: 30,
  };

before(async () => {
  browser = singletons.browser = await puppeteer.launch(opts);
  singletons.page = await browser.newPage();
  singletons.page.setViewport({width: 1024, height: 768});
  await loadPage();
});

after(async () => {
  await browser.close();
});
<|endoftext|>