<commit_before>import React from 'react'
import Paper from '@material-ui/core/Paper'
import Grid from '@material-ui/core/Grid'
import Button from '@material-ui/core/Button'
import Divider from '@material-ui/core/Divider'
import Typography from '@material-ui/core/Typography'
import CircularProgress from '@material-ui/core/CircularProgress'
import { connect } from 'react-redux'
import { withTheme } from '@material-ui/core/styles'
import { Form } from 'informed'

import MaterialFormText from '../MaterialFormText'
import { Model } from '../../store'
import LoginButtons from '../chrome/LoginButtons'
import { getActivityCount } from '../../selectors'

const Signups = new Model('signups')

const Thanks = _props => (
    <React.Fragment>
        <Grid item><Typography variant="headline">Thanks!</Typography></Grid>
        <Grid item>An organizer will get in touch.</Grid>
    </React.Fragment>
)

class SavedState extends React.Component {
    constructor(props) {
        super(props)
        this.state = {value: undefined}
        this.setValue = this.setValue.bind(this)
    }

    setValue(v) { this.setState({value: v}) }

    render() {
        return this.props.children(this.state.value, this.setValue)
    }
}

const IntroText = props => {
    const orgName = (window.ORG_METADATA || {}).name
    if (props.event) {
        if (props.event.checkIn.isInPast) {
            return (
                <React.Fragment>

<Typography variant="headline">You just missed this event.</Typography>

Sign up to join {orgName} and learn about future events like this!

                </React.Fragment>
            )
        } else if (props.event.checkIn.hasNotStarted) {
            return (
                <React.Fragment>

<Typography variant="headline">This hasn't started yet.</Typography>

Sign up to join {orgName} and learn about future events like this, or come back later!

                </React.Fragment>
            )
        } else if (props.event.checkIn.isNearby) {
            return (
                <React.Fragment>

<Typography variant="headline">Is this what you're for?</Typography>

Sign up now to join {orgName} and collect an event point for this!

                </React.Fragment>
            )
        } else {
            return null
        }
    } else {
        return null
    }
}

export const SigninBox = props => (
    <SavedState>
        {(hasSaved, setHasSaved) => (
            <Form onSubmit={values => props.createSignup(values).then(() => setHasSaved(true))}>
                <Paper style={{padding: '1rem', backgroundColor: props.theme.palette.secondary.light}} >
                    <Grid container direction="column" justify="center" alignItems="stretch" spacing={8}>
                        {props.isSaving ? (
                            <Grid style={{textAlign: 'center'}} item>
                                <CircularProgress size={100} color="primary" />
                            </Grid>
                        ) : (
                            !hasSaved ? (
                                <React.Fragment>
                                    <Grid item><IntroText event={props.event} /></Grid>
                                    <Grid item><MaterialFormText fullWidth label="E-Mail" field="email" validate={v => (v.indexOf('@') != -1) ? null : "Please enter your e-mail address."}/></Grid>
                                    <Grid item><Button fullWidth variant="contained" color="primary" type="submit">Request to join</Button></Grid>
                                    <Grid item style={{marginTop: '1rem'}} container alignItems="center">
                                        <Grid item xs><Divider /></Grid>
                                        <Grid item xs={4} style={{textAlign: 'center'}}>Or login</Grid>
                                        <Grid item xs><Divider /></Grid>
                                    </Grid>
                                    <Grid item container spacing={8} justify="center">
                                        <LoginButtons label={false} />
                                    </Grid>
                                </React.Fragment>
                            ) : (
                                <Thanks />
                            )
                        )}
                    </Grid>
                </Paper>
            </Form>
        )}
    </SavedState>
)

const mapStateToProps = state => {
    return {
        isSaving: getActivityCount(state) > 0
    }
}

function eventID(evt) {
    if (evt && evt.isNearby && !evt.checkIn.isInPast && !evt.checkIn.hasNotStarted) {
        return evt.id
    }
    return undefined
}

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        createSignup: (values) => {
            return dispatch(Signups.create({
                ...values,
                event: eventID(ownProps.nearbyEvent)
            }))
        }
    }
}

export default withTheme()(connect(mapStateToProps, mapDispatchToProps)(SigninBox))
<commit_msg>components: chrome: signinbox: fix lint<commit_after>import React from 'react'
import Paper from '@material-ui/core/Paper'
import Grid from '@material-ui/core/Grid'
import Button from '@material-ui/core/Button'
import Divider from '@material-ui/core/Divider'
import Typography from '@material-ui/core/Typography'
import CircularProgress from '@material-ui/core/CircularProgress'
import { connect } from 'react-redux'
import { withTheme } from '@material-ui/core/styles'
import { Form } from 'informed'

import MaterialFormText from '../MaterialFormText'
import { Model } from '../../store'
import LoginButtons from '../chrome/LoginButtons'
import { getActivityCount } from '../../selectors'

const Signups = new Model('signups')

const Thanks = _props => (
    <React.Fragment>
        <Grid item><Typography variant="headline">Thanks!</Typography></Grid>
        <Grid item>An organizer will get in touch.</Grid>
    </React.Fragment>
)

class SavedState extends React.Component {
    constructor(props) {
        super(props)
        this.state = {value: undefined}
        this.setValue = this.setValue.bind(this)
    }

    setValue(v) { this.setState({value: v}) }

    render() {
        return this.props.children(this.state.value, this.setValue)
    }
}

const IntroText = props => {
    const orgName = (window.ORG_METADATA || {}).name
    if (props.event) {
        if (props.event.checkIn.isInPast) {
            return (
                <React.Fragment>

<Typography variant="headline">You just missed this event.</Typography>

Sign up to join {orgName} and learn about future events like this!

                </React.Fragment>
            )
        } else if (props.event.checkIn.hasNotStarted) {
            return (
                <React.Fragment>

<Typography variant="headline">This hasn't started yet.</Typography>

Sign up to join {orgName} and learn about future events like this, or come back later!

                </React.Fragment>
            )
        } else if (props.event.checkIn.isNearby) {
            return (
                <React.Fragment>

<Typography variant="headline">Is this what you're for?</Typography>

Sign up now to join {orgName} and collect an event point for this!

                </React.Fragment>
            )
        } else {
            return null
        }
    } else {
        return null
    }
}

export const SigninBox = props => (
    <SavedState>
        {(hasSaved, setHasSaved) => (
            <Form onSubmit={values => props.createSignup(values).then(() => setHasSaved(true))}>
                <Paper style={{padding: '1rem', backgroundColor: props.theme.palette.secondary.light}} >
                    <Grid container direction="column" justify="center" alignItems="stretch" spacing={8}>
                        {props.isSaving ? (
                            <Grid style={{textAlign: 'center'}} item>
                                <CircularProgress size={100} color="primary" />
                            </Grid>
                        ) : (
                            !hasSaved ? (
                                <React.Fragment>
                                    <Grid item><IntroText event={props.event} /></Grid>
                                    <Grid item><MaterialFormText fullWidth label="E-Mail" field="email" validate={v => (v.indexOf('@') != -1) ? null : 'Please enter your e-mail address.'}/></Grid>
                                    <Grid item><Button fullWidth variant="contained" color="primary" type="submit">Request to join</Button></Grid>
                                    <Grid item style={{marginTop: '1rem'}} container alignItems="center">
                                        <Grid item xs><Divider /></Grid>
                                        <Grid item xs={4} style={{textAlign: 'center'}}>Or login</Grid>
                                        <Grid item xs><Divider /></Grid>
                                    </Grid>
                                    <Grid item container spacing={8} justify="center">
                                        <LoginButtons label={false} />
                                    </Grid>
                                </React.Fragment>
                            ) : (
                                <Thanks />
                            )
                        )}
                    </Grid>
                </Paper>
            </Form>
        )}
    </SavedState>
)

const mapStateToProps = state => {
    return {
        isSaving: getActivityCount(state) > 0
    }
}

function eventID(evt) {
    if (evt && evt.isNearby && !evt.checkIn.isInPast && !evt.checkIn.hasNotStarted) {
        return evt.id
    }
    return undefined
}

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        createSignup: (values) => {
            return dispatch(Signups.create({
                ...values,
                event: eventID(ownProps.nearbyEvent)
            }))
        }
    }
}

export default withTheme()(connect(mapStateToProps, mapDispatchToProps)(SigninBox))
<|endoftext|>


<commit_before>"use strict";
//This JS file simply bootstraps the app from the root component when the window loads

var AppRoot = require('./components/AppRoot.jsx');
var Home = require('./components/Home.jsx');
var IndexRedirect = require('react-router').IndexRedirect;
var React = require('react');
var ReactDOM = require('react-dom');
var Redirect = require('react-router').Redirect;
var Router = require('react-router').Router;
var Route = require('react-router').Route;
var useRouterHistory = require('react-router').useRouterHistory;
var createHistory = require('history').createHistory;

const history = useRouterHistory(createHistory)({
  basename: '/'
});

//Keep references to these outside of the function
var appRootComponent;

//This function executes immediately
(function() {
    //This function is attached to execute when the window loads
    document.addEventListener('DOMContentLoaded', function() {

        ReactDOM.render(
            /* jshint ignore:start */
            <Router history={history}>
                <Route path="/" component={AppRoot}>
                    <IndexRedirect to="/home" />
                    <Route path="/home" component={Home}/>
                    <Redirect from="*" to="/home"/>
                </Route>
            </Router>, document.getElementById('app')
            /* jshint ignore:end */
        );

    });
})();
<commit_msg>more history problems<commit_after>"use strict";
//This JS file simply bootstraps the app from the root component when the window loads

var AppRoot = require('./components/AppRoot.jsx');
var Home = require('./components/Home.jsx');
var IndexRedirect = require('react-router').IndexRedirect;
var React = require('react');
var ReactDOM = require('react-dom');
var Redirect = require('react-router').Redirect;
var Router = require('react-router').Router;
var Route = require('react-router').Route;
var history = require('react-router').hashHistory;

//Keep references to these outside of the function
var appRootComponent;

//This function executes immediately
(function() {
    //This function is attached to execute when the window loads
    document.addEventListener('DOMContentLoaded', function() {

        ReactDOM.render(
            /* jshint ignore:start */
            <Router history={history}>
                <Route path="/" component={AppRoot}>
                    <IndexRedirect to="/home" />
                    <Route path="/home" component={Home}/>
                    <Redirect from="*" to="/home"/>
                </Route>
            </Router>, document.getElementById('app')
            /* jshint ignore:end */
        );

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


<commit_before>#!/usr/bin/env node

/**
 */

var opts = require('commander');
var fasta = require('bionode-fasta');
var fs = require('fs');
var through = require('through2')

function increaseVerbosity(v, total) {
  return total + 1;
}

opts
  .version('1.0.0')
  .usage('[options] contigs.fasta [contigs2.fasta ...]')
  .description('Print fasta stats')
  .option('-m, --minlen <n>', 'Minimum length sequence to include in stats (default=0)', parseInt, 0)
  .option('-v, --verbose', "Print more stuff about what's happening", increaseVerbosity, 0)
  .parse(process.argv);

if (opts.args == 0)
    opts.args = ["/dev/stdin"];

// Stream to process a fasta file for stats
function process_fasta(file) {
    var bp=0;
    var n=0;
    var min,max;
    var stream = through.obj(next_seq, done)
    return stream

    function next_seq(data, enc, next) {
        var l = data.seq.length
        if (l>=opts.minlen) {
            if (opts.verbose>=2)
                console.error([file, data.id, l].join("\t"))
            min = n==0 ? l : Math.min(l,min)
            max = n==0 ? l : Math.max(l,max)
            n += 1
            bp += l
        }
        next()
    }

    function done() {
        this.push([n, bp, min, Math.floor(bp/n), max]);
        this.push(null);
    }
}

function process_files(files) {
    if (files.length==0)
        return
    var file = files.shift()
    if (opts.verbose>=1)
        console.error("Processing: "+file);
    fs.createReadStream(file)
      .pipe(fasta({objectMode:true}))
      .pipe(process_fasta(file))
      .on('data', function(stats) {
           console.log([file].concat(stats).join("\t"))
           process_files(files)
       });
}

process_files(opts.args)

<commit_msg>Add table header to js output<commit_after>#!/usr/bin/env node

/**
 */

var opts = require('commander');
var fasta = require('bionode-fasta');
var fs = require('fs');
var through = require('through2')

function increaseVerbosity(v, total) {
  return total + 1;
}

opts
  .version('1.0.0')
  .usage('[options] contigs.fasta [contigs2.fasta ...]')
  .description('Print fasta stats')
  .option('-m, --minlen <n>', 'Minimum length sequence to include in stats (default=0)', parseInt, 0)
  .option('-v, --verbose', "Print more stuff about what's happening", increaseVerbosity, 0)
  .parse(process.argv);

if (opts.args == 0)
    opts.args = ["/dev/stdin"];

// Stream to process a fasta file for stats
function process_fasta(file) {
    var bp=0;
    var n=0;
    var min,max;
    var stream = through.obj(next_seq, done)
    return stream

    function next_seq(data, enc, next) {
        var l = data.seq.length
        if (l>=opts.minlen) {
            if (opts.verbose>=2)
                console.error([file, data.id, l].join("\t"))
            min = n==0 ? l : Math.min(l,min)
            max = n==0 ? l : Math.max(l,max)
            n += 1
            bp += l
        }
        next()
    }

    function done() {
        this.push([n, bp, min, Math.floor(bp/n), max]);
        this.push(null);
    }
}

function process_files(files) {
    if (files.length==0)
        return
    var file = files.shift()
    if (opts.verbose>=1)
        console.error("Processing: "+file);
    fs.createReadStream(file)
      .pipe(fasta({objectMode:true}))
      .pipe(process_fasta(file))
      .on('data', function(stats) {
           console.log([file].concat(stats).join("\t"))
           process_files(files)
       });
}

console.log("FILENAME\tNUMSEQ\tTOTAL\tMIN\tAVG\tMAX");
process_files(opts.args)

<|endoftext|>


<commit_before>function demoSetup(apis) {

  var apiOptions = $('#demo-api');
  apiOptions.empty();
  $.each(apis, function() {
    apiOptions.append($("<option />").val(this.id).text(this.id));
  });

  $('#demo').show();
}

function demoTeardown() {
  $('#demo-results').empty();
  $('#demo').hide();
}

function doDemo(demoMethod) {
  var fullUrl = '';
  var demoRoute = $('#demo-route').val();
  var demoApi = $('#demo-api').val();
  var demoUrl = $('#demo-url').val().trim();

  if(demoUrl.length===0) {
    demoUrl = '/';
  }

  switch(demoRoute) {
    case '/api':
    case '/data':
      break;
    default:
      console.log(demoRoute + ' route not supported');
      return; // not supported
  }

  if(demoMethod) {
    demoMethod = demoMethod.toUpperCase();
  }

  switch(demoMethod) {
    case 'GET':
      if(demoUrl === '/data') {
        fullUrl = demoRoute + demoUrl;
      }
      else {
        fullUrl = demoRoute + '/' + demoApi + demoUrl;
      }
      break;
    case 'POST':
      if(demoUrl !== '/data') {
        return; // not supported
      }
      fullUrl = demoRoute + '/' + demoApi + demoUrl;
      break;
    default:
      console.log(demoMethod + ' method not supported');
      return; // not supported
  }

  console.log(demoMethod + ' submitted for ' + fullUrl);
  $('#demo-results').empty();

  if(demoMethod === 'GET') {
    $('#demo-results').location.href = fullUrl;
  }
  else {
    var demoForm = document.createElement('form');
    demoForm.method = demoMethod;
    demoForm.action = fullUrl;
    demoForm.target = 'demo-results';
    demoForm.submit();
  }
}
<commit_msg>using iframe src for get request to prevent question mark<commit_after>function demoSetup(apis) {

  var apiOptions = $('#demo-api');
  apiOptions.empty();
  $.each(apis, function() {
    apiOptions.append($("<option />").val(this.id).text(this.id));
  });

  $('#demo').show();
}

function demoTeardown() {
  $('#demo-results').empty();
  $('#demo').hide();
}

function doDemo(demoMethod) {
  var fullUrl = '';
  var demoRoute = $('#demo-route').val();
  var demoApi = $('#demo-api').val();
  var demoUrl = $('#demo-url').val().trim();

  if(demoUrl.length===0) {
    demoUrl = '/';
  }

  switch(demoRoute) {
    case '/api':
    case '/data':
      break;
    default:
      console.log(demoRoute + ' route not supported');
      return; // not supported
  }

  if(demoMethod) {
    demoMethod = demoMethod.toUpperCase();
  }

  switch(demoMethod) {
    case 'GET':
      if(demoUrl === '/data') {
        fullUrl = demoRoute + demoUrl;
      }
      else {
        fullUrl = demoRoute + '/' + demoApi + demoUrl;
      }
      break;
    case 'POST':
      if(demoUrl !== '/data') {
        return; // not supported
      }
      fullUrl = demoRoute + '/' + demoApi + demoUrl;
      break;
    default:
      console.log(demoMethod + ' method not supported');
      return; // not supported
  }

  console.log(demoMethod + ' submitted for ' + fullUrl);
  $('#demo-results').empty();

  if(demoMethod === 'GET') {
    $('#demo-results').location = fullUrl;
  }
  else {
    var demoForm = document.createElement('form');
    demoForm.method = demoMethod;
    demoForm.action = fullUrl;
    demoForm.target = 'demo-results';
    demoForm.submit();
  }
}
<|endoftext|>


<commit_before>const request = require("request");

const BOTLYTICS_API_KEY = process.env.BOTLYTICS_API_KEY;

function logUserRequest(message, conversationId) {
    request({
        url: 'http://www.botlytics.co/api/v1/messages',
        qs: {
            token : BOTLYTICS_API_KEY
        },
        method: 'POST',
        json : {
            message: {
                text: message,
                kind: "incoming",
                conversation_identifier: conversationId
            }
        }
    }, (err, response, body) => {
        if (err) {
            console.log("Sending User Req to Botylitcs");
        } else {
            if (response.statusCode == 201) {
                console.log("Sent User Req to Botylitcs OK");
            } else {
                console.log("Sent User Req to Botylitcs Failed with " + response.statusCode);
            }
        }
    });
};

function logServerResponse(message, conversationId) {
    request({
        url: 'http://www.botlytics.co/api/v1/messages',
        qs: {
            token : BOTLYTICS_API_KEY
        },
        method: 'POST',
        json : {
            message: {
                text: message,
                kind: "outgoing",
                conversation_identifier: conversationId
            }
        }
    }, (err, response, body) => {
        if (err) {
            console.log("Sending Server Resp to Botylitcs");
        } else {
            if (response.statusCode == 201) {
                console.log("Sent Server Resp to Botylitcs OK");
            } else {
                console.log("Sent Server Resp to Botylitcs Failed with " + response.statusCode);
            }
        }
    });
};

exports.logUserRequest = logUserRequest;
exports.logServerResponse = logServerResponse;
<commit_msg>Remove Botlytics<commit_after><|endoftext|>


<commit_before>/* eslint-disable  func-names */
/* eslint quote-props: ["error", "consistent"]*/

'use strict';

const rp = require('request-promise-native');
const Alexa = require('alexa-sdk');
const beaufort = require('beaufort-scale');
const format = require('string-format');
const APP_ID = undefined;  // TODO replace with your app ID (OPTIONAL).

const languageStrings = {
    'en-GB': {
        translation: {
            SKILL_NAME: 'British Weer',
            // current temp options
            GET_CURRENT_MESSAGE_FEELS_LIKE: "In {city} it is currently {currentTemp} degrees, but it feels like {currentFeelsLikeTemp}.",
            GET_CURRENT_MESSAGE_FEELS_LIKE_IS_CURRENT: "In {city} it is currently {currentTemp} degrees.",

            GET_MAX_MIN_TEMP_MESSAGE: "The low for the rest of the day will be {dailyMinTemp} degrees with a high of {dailyMaxTemp} degrees.",
            GET_WIND_MESSAGE: "Wind is currently a {windType}.",
            GET_RAIN_MESSAGE_NOW: "There is a {rain.chanceOfRain} percent chance of rain this hour.",
            GET_RAIN_MESSAGE_FUTURE: "There is a {rain.chanceOfRain} percent chance of rain in around {rain.hoursUntilRain} hours.",
            GET_NO_RAIN_FOR_REST_OF_DAY: "There is no chance of rain for the rest of the day.",
            HELP_MESSAGE: 'You can say tell me a space fact, or, you can say exit... What can I help you with?',
            HELP_REPROMPT: 'What can I help you with?',
            STOP_MESSAGE: 'Goodbye!',
        },
    },
    'en-US': {
        translation: {
            SKILL_NAME: 'American Weer',
            // current temp options
            GET_CURRENT_MESSAGE_FEELS_LIKE: "In {city} it is currently {currentTemp} degrees, but it feels like {currentFeelsLikeTemp}.",
            GET_CURRENT_MESSAGE_FEELS_LIKE_IS_CURRENT: "In {city} it is currently {currentTemp} degrees.",

            GET_MAX_MIN_TEMP_MESSAGE: "The low for the rest of the day will be {dailyMinTemp} degrees with a high of {dailyMaxTemp} degrees.",
            GET_WIND_MESSAGE: "Wind is currently a {windType}.",
            GET_RAIN_MESSAGE_NOW: "There is a {rain.chanceOfRain} percent chance of rain this hour.",
            GET_RAIN_MESSAGE_FUTURE: "There is a {rain.chanceOfRain} percent chance of rain in around {rain.hoursUntilRain} hours.",
            GET_NO_RAIN_FOR_REST_OF_DAY: "There is no chance of rain for the rest of the day.",
            HELP_MESSAGE: 'You can say tell me a space fact, or, you can say exit... What can I help you with?',
            HELP_REPROMPT: 'What can I help you with?',
            STOP_MESSAGE: 'Goodbye!',
        },
    }
    // 'de-DE': {
    //     translation: {
    //         FACTS: [
    //             'Ein Jahr dauert auf dem Merkur nur 88 Tage.',
    //             'Die Venus ist zwar weiter von der Sonne entfernt, hat aber höhere Temperaturen als Merkur.',
    //             'Venus dreht sich entgegen dem Uhrzeigersinn, möglicherweise aufgrund eines früheren Zusammenstoßes mit einem Asteroiden.',
    //             'Auf dem Mars erscheint die Sonne nur halb so groß wie auf der Erde.',
    //             'Die Erde ist der einzige Planet, der nicht nach einem Gott benannt ist.',
    //             'Jupiter hat den kürzesten Tag aller Planeten.',
    //             'Die Milchstraßengalaxis wird in etwa 5 Milliarden Jahren mit der Andromeda-Galaxis zusammenstoßen.',
    //             'Die Sonne macht rund 99,86 % der Masse im Sonnensystem aus.',
    //             'Die Sonne ist eine fast perfekte Kugel.',
    //             'Eine Sonnenfinsternis kann alle ein bis zwei Jahre eintreten. Sie ist daher ein seltenes Ereignis.',
    //             'Der Saturn strahlt zweieinhalb mal mehr Energie in den Weltraum aus als er von der Sonne erhält.',
    //             'Die Temperatur in der Sonne kann 15 Millionen Grad Celsius erreichen.',
    //             'Der Mond entfernt sich von unserem Planeten etwa 3,8 cm pro Jahr.',
    //         ],
    //         SKILL_NAME: 'Weltraumwissen auf Deutsch',
    //         GET_WEATHER_MESSAGE: 'Hier sind deine Fakten: ',
    //         HELP_MESSAGE: 'Du kannst sagen, „Nenne mir einen Fakt über den Weltraum“, oder du kannst „Beenden“ sagen... Wie kann ich dir helfen?',
    //         HELP_REPROMPT: 'Wie kann ich dir helfen?',
    //         STOP_MESSAGE: 'Auf Wiedersehen!',
    //     },
    // },
};

const buienRaderForecast = function (forecast, hours_ahead_to_check_rain, rain_percent_threshold = 9) {
    const rain = (forecast, hours_ahead_to_check_rain) => {
        // the site only returns an hours array containing the amount of hours left depending on request time
        let hoursLeftInDay = Object.keys(forecast['days'][0]['hours']).length;

        let hoursToCheck;

        // only go through the rest of the hours in the day, even if user asks for more
        if (hoursLeftInDay < hours_ahead_to_check_rain) {
            hoursToCheck = hoursLeftInDay;
        } else {
            hoursToCheck = hours_ahead_to_check_rain;
        }

        // loop through each of the hours in the day, and find the hour when there is a chance of rain
        for (let i = 0, len = hoursToCheck; i < len; i++) {
            let chanceOfRain = forecast['days'][0]['hours'][i]['precipation'];

            if (chanceOfRain > rain_percent_threshold) {
                return {
                    chanceOfRain: chanceOfRain,
                    hoursUntilRain: i
                }
            }
        }

        return null; // there is no rain up coming
    };

    let currentTemp = roundFloat(forecast['days'][0]['hours'][0]['temperature']);
    let currentFeelsLikeTemp = roundFloat(forecast['days'][0]['hours'][0]['feeltemperature']);

    return {
        dailyMaxTemp: roundFloat(forecast['days'][0]['maxtemp']),
        dailyMinTemp: roundFloat(forecast['days'][0]['mintemp']),
        currentTemp: currentTemp,
        currentFeelsLikeTemp: currentFeelsLikeTemp,
        feelsLikeEqualCurrentTemp: currentTemp === currentFeelsLikeTemp,
        windType: beaufort(forecast['days'][0]['hours'][0]['windspeed']).desc.toLowerCase(),
        rain: rain(forecast, hours_ahead_to_check_rain)
    }
};

// round temperatures which come in as floats
const roundFloat = (float) => {
    return Math.round(float);
};

const handlers = {
    'LaunchRequest': function () {
        this.emit('GetWeer');
    },
    'GetWeerRainIntent': function () {
        let options = {
            uri: 'https://api.buienradar.nl/data/forecast/1.1/all/2747596',
            json: true
        };

        rp(options)
            .then((weather) => {
                let forecast = buienRaderForecast(weather, 24, 0);

                forecast['city'] = 'Schiedam';

                let speechOut = [];

                // rain message
                if (forecast.rain) {
                    speechOut.push(
                        format(
                            (forecast.rain.hoursUntilRain > 0) ? this.t('GET_RAIN_MESSAGE_FUTURE') : this.t('GET_RAIN_MESSAGE_NOW'),
                            forecast
                        )
                    );
                } else {
                    speechOut.push(
                        this.t('GET_NO_RAIN_FOR_REST_OF_DAY')
                    );
                }

                this.emit(':tellWithCard', speechOut.join(' '), this.t('SKILL_NAME'), speechOut.join(' '))
            })
            .catch((err) => {
                const speechOutput = 'Failed to query for Weather information: ' + err;
                this.emit(':tellWithCard', speechOutput, this.t('SKILL_NAME'), speechOutput);
            });
    },
    'GetWeerIntent': function () {
        this.emit('GetWeer');
    },
    'GetWeer': function () {
        let options = {
            uri: 'https://api.buienradar.nl/data/forecast/1.1/all/2747596',
            json: true
        };

        rp(options)
            .then((weather) => {
                let forecast = buienRaderForecast(weather, 5);

                forecast['city'] = 'Schiedam';

                let speechOut = [];

                // get current temp
                speechOut.push(
                    format(
                        forecast.feelsLikeEqualCurrentTemp ? this.t('GET_CURRENT_MESSAGE_FEELS_LIKE_IS_CURRENT') : this.t('GET_CURRENT_MESSAGE_FEELS_LIKE'),
                        forecast
                    )
                );

                // min max temp message
                speechOut.push(
                    format(
                        this.t('GET_MAX_MIN_TEMP_MESSAGE'),
                        forecast
                    )
                );

                // wind message
                speechOut.push(
                    format(
                        this.t('GET_WIND_MESSAGE'),
                        forecast
                    )
                );

                // rain message
                if (forecast.rain) {
                    speechOut.push(
                        format(
                            (forecast.rain.hoursUntilRain > 0) ? this.t('GET_RAIN_MESSAGE_FUTURE') : this.t('GET_RAIN_MESSAGE_NOW'),
                            forecast
                        )
                    );
                }

                this.emit(':tellWithCard', speechOut.join(' '), this.t('SKILL_NAME'), speechOut.join(' '))
            })
            .catch((err) => {
                const speechOutput = 'Failed to query for Weather information: ' + err;
                this.emit(':tellWithCard', speechOutput, this.t('SKILL_NAME'), speechOutput);
            });
    },
    'AMAZON.HelpIntent': function () {
        const speechOutput = this.t('HELP_MESSAGE');
        const reprompt = this.t('HELP_MESSAGE');
        this.emit(':ask', speechOutput, reprompt);
    },
    'AMAZON.CancelIntent': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
    'AMAZON.StopIntent': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
    'SessionEndedRequest': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
};

exports.handler = (event, context) => {
    const alexa = Alexa.handler(event, context);
    alexa.APP_ID = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    alexa.resources = languageStrings;
    alexa.registerHandlers(handlers);
    alexa.execute();
};
<commit_msg>fix help<commit_after>/* eslint-disable  func-names */
/* eslint quote-props: ["error", "consistent"]*/

'use strict';

const rp = require('request-promise-native');
const Alexa = require('alexa-sdk');
const beaufort = require('beaufort-scale');
const format = require('string-format');
const APP_ID = undefined;  // TODO replace with your app ID (OPTIONAL).

const languageStrings = {
    'en-GB': {
        translation: {
            SKILL_NAME: 'British Weer',
            // current temp options
            GET_CURRENT_MESSAGE_FEELS_LIKE: "In {city} it is currently {currentTemp} degrees, but it feels like {currentFeelsLikeTemp}.",
            GET_CURRENT_MESSAGE_FEELS_LIKE_IS_CURRENT: "In {city} it is currently {currentTemp} degrees.",

            GET_MAX_MIN_TEMP_MESSAGE: "The low for the rest of the day will be {dailyMinTemp} degrees with a high of {dailyMaxTemp} degrees.",
            GET_WIND_MESSAGE: "Wind is currently a {windType}.",
            GET_RAIN_MESSAGE_NOW: "There is a {rain.chanceOfRain} percent chance of rain this hour.",
            GET_RAIN_MESSAGE_FUTURE: "There is a {rain.chanceOfRain} percent chance of rain in around {rain.hoursUntilRain} hours.",
            GET_NO_RAIN_FOR_REST_OF_DAY: "There is no chance of rain for the rest of the day.",
            HELP_MESSAGE: 'You can say tell me the weather, or, when is it going to rain. You can also just say quit. What can I help you with?',
            HELP_REPROMPT: 'What can I help you with?',
            STOP_MESSAGE: 'Goodbye!',
        },
    },
    'en-US': {
        translation: {
            SKILL_NAME: 'American Weer',
            // current temp options
            GET_CURRENT_MESSAGE_FEELS_LIKE: "In {city} it is currently {currentTemp} degrees, but it feels like {currentFeelsLikeTemp}.",
            GET_CURRENT_MESSAGE_FEELS_LIKE_IS_CURRENT: "In {city} it is currently {currentTemp} degrees.",

            GET_MAX_MIN_TEMP_MESSAGE: "The low for the rest of the day will be {dailyMinTemp} degrees with a high of {dailyMaxTemp} degrees.",
            GET_WIND_MESSAGE: "Wind is currently a {windType}.",
            GET_RAIN_MESSAGE_NOW: "There is a {rain.chanceOfRain} percent chance of rain this hour.",
            GET_RAIN_MESSAGE_FUTURE: "There is a {rain.chanceOfRain} percent chance of rain in around {rain.hoursUntilRain} hours.",
            GET_NO_RAIN_FOR_REST_OF_DAY: "There is no chance of rain for the rest of the day.",
            HELP_MESSAGE: 'You can say tell me the weather, or, when is it going to rain. You can also just say quit. What can I help you with?',
            HELP_REPROMPT: 'What can I help you with?',
            STOP_MESSAGE: 'Goodbye!',
        },
    }
    // 'de-DE': {
    //     translation: {
    //         FACTS: [
    //             'Ein Jahr dauert auf dem Merkur nur 88 Tage.',
    //             'Die Venus ist zwar weiter von der Sonne entfernt, hat aber höhere Temperaturen als Merkur.',
    //             'Venus dreht sich entgegen dem Uhrzeigersinn, möglicherweise aufgrund eines früheren Zusammenstoßes mit einem Asteroiden.',
    //             'Auf dem Mars erscheint die Sonne nur halb so groß wie auf der Erde.',
    //             'Die Erde ist der einzige Planet, der nicht nach einem Gott benannt ist.',
    //             'Jupiter hat den kürzesten Tag aller Planeten.',
    //             'Die Milchstraßengalaxis wird in etwa 5 Milliarden Jahren mit der Andromeda-Galaxis zusammenstoßen.',
    //             'Die Sonne macht rund 99,86 % der Masse im Sonnensystem aus.',
    //             'Die Sonne ist eine fast perfekte Kugel.',
    //             'Eine Sonnenfinsternis kann alle ein bis zwei Jahre eintreten. Sie ist daher ein seltenes Ereignis.',
    //             'Der Saturn strahlt zweieinhalb mal mehr Energie in den Weltraum aus als er von der Sonne erhält.',
    //             'Die Temperatur in der Sonne kann 15 Millionen Grad Celsius erreichen.',
    //             'Der Mond entfernt sich von unserem Planeten etwa 3,8 cm pro Jahr.',
    //         ],
    //         SKILL_NAME: 'Weltraumwissen auf Deutsch',
    //         GET_WEATHER_MESSAGE: 'Hier sind deine Fakten: ',
    //         HELP_MESSAGE: 'Du kannst sagen, „Nenne mir einen Fakt über den Weltraum“, oder du kannst „Beenden“ sagen... Wie kann ich dir helfen?',
    //         HELP_REPROMPT: 'Wie kann ich dir helfen?',
    //         STOP_MESSAGE: 'Auf Wiedersehen!',
    //     },
    // },
};

const buienRaderForecast = function (forecast, hours_ahead_to_check_rain, rain_percent_threshold = 9) {
    const rain = (forecast, hours_ahead_to_check_rain) => {
        // the site only returns an hours array containing the amount of hours left depending on request time
        let hoursLeftInDay = Object.keys(forecast['days'][0]['hours']).length;

        let hoursToCheck;

        // only go through the rest of the hours in the day, even if user asks for more
        if (hoursLeftInDay < hours_ahead_to_check_rain) {
            hoursToCheck = hoursLeftInDay;
        } else {
            hoursToCheck = hours_ahead_to_check_rain;
        }

        // loop through each of the hours in the day, and find the hour when there is a chance of rain
        for (let i = 0, len = hoursToCheck; i < len; i++) {
            let chanceOfRain = forecast['days'][0]['hours'][i]['precipation'];

            if (chanceOfRain > rain_percent_threshold) {
                return {
                    chanceOfRain: chanceOfRain,
                    hoursUntilRain: i
                }
            }
        }

        return null; // there is no rain up coming
    };

    let currentTemp = roundFloat(forecast['days'][0]['hours'][0]['temperature']);
    let currentFeelsLikeTemp = roundFloat(forecast['days'][0]['hours'][0]['feeltemperature']);

    return {
        dailyMaxTemp: roundFloat(forecast['days'][0]['maxtemp']),
        dailyMinTemp: roundFloat(forecast['days'][0]['mintemp']),
        currentTemp: currentTemp,
        currentFeelsLikeTemp: currentFeelsLikeTemp,
        feelsLikeEqualCurrentTemp: currentTemp === currentFeelsLikeTemp,
        windType: beaufort(forecast['days'][0]['hours'][0]['windspeed']).desc.toLowerCase(),
        rain: rain(forecast, hours_ahead_to_check_rain)
    }
};

// round temperatures which come in as floats
const roundFloat = (float) => {
    return Math.round(float);
};

const handlers = {
    'LaunchRequest': function () {
        this.emit('GetWeer');
    },
    'GetWeerRainIntent': function () {
        let options = {
            uri: 'https://api.buienradar.nl/data/forecast/1.1/all/2747596',
            json: true
        };

        rp(options)
            .then((weather) => {
                let forecast = buienRaderForecast(weather, 24, 0);

                forecast['city'] = 'Schiedam';

                let speechOut = [];

                // rain message
                if (forecast.rain) {
                    speechOut.push(
                        format(
                            (forecast.rain.hoursUntilRain > 0) ? this.t('GET_RAIN_MESSAGE_FUTURE') : this.t('GET_RAIN_MESSAGE_NOW'),
                            forecast
                        )
                    );
                } else {
                    speechOut.push(
                        this.t('GET_NO_RAIN_FOR_REST_OF_DAY')
                    );
                }

                this.emit(':tellWithCard', speechOut.join(' '), this.t('SKILL_NAME'), speechOut.join(' '))
            })
            .catch((err) => {
                const speechOutput = 'Failed to query for Weather information: ' + err;
                this.emit(':tellWithCard', speechOutput, this.t('SKILL_NAME'), speechOutput);
            });
    },
    'GetWeerIntent': function () {
        this.emit('GetWeer');
    },
    'GetWeer': function () {
        let options = {
            uri: 'https://api.buienradar.nl/data/forecast/1.1/all/2747596',
            json: true
        };

        rp(options)
            .then((weather) => {
                let forecast = buienRaderForecast(weather, 5);

                forecast['city'] = 'Schiedam';

                let speechOut = [];

                // get current temp
                speechOut.push(
                    format(
                        forecast.feelsLikeEqualCurrentTemp ? this.t('GET_CURRENT_MESSAGE_FEELS_LIKE_IS_CURRENT') : this.t('GET_CURRENT_MESSAGE_FEELS_LIKE'),
                        forecast
                    )
                );

                // min max temp message
                speechOut.push(
                    format(
                        this.t('GET_MAX_MIN_TEMP_MESSAGE'),
                        forecast
                    )
                );

                // wind message
                speechOut.push(
                    format(
                        this.t('GET_WIND_MESSAGE'),
                        forecast
                    )
                );

                // rain message
                if (forecast.rain) {
                    speechOut.push(
                        format(
                            (forecast.rain.hoursUntilRain > 0) ? this.t('GET_RAIN_MESSAGE_FUTURE') : this.t('GET_RAIN_MESSAGE_NOW'),
                            forecast
                        )
                    );
                }

                this.emit(':tellWithCard', speechOut.join(' '), this.t('SKILL_NAME'), speechOut.join(' '))
            })
            .catch((err) => {
                const speechOutput = 'Failed to query for Weather information: ' + err;
                this.emit(':tellWithCard', speechOutput, this.t('SKILL_NAME'), speechOutput);
            });
    },
    'AMAZON.HelpIntent': function () {
        const speechOutput = this.t('HELP_MESSAGE');
        const reprompt = this.t('HELP_MESSAGE');
        this.emit(':ask', speechOutput, reprompt);
    },
    'AMAZON.CancelIntent': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
    'AMAZON.StopIntent': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
    'SessionEndedRequest': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
};

exports.handler = (event, context) => {
    const alexa = Alexa.handler(event, context);
    alexa.APP_ID = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    alexa.resources = languageStrings;
    alexa.registerHandlers(handlers);
    alexa.execute();
};
<|endoftext|>


<commit_before>/*!
 * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
    if ($(".navbar").offset().top > 50) {
        $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
});

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

// Google Maps Scripts
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);

function init() {
    // Basic options for a simple Google Map
    // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
    var mapOptions = {
        // How zoomed in you want the map to start at (always required)
        zoom: 15,

        // The latitude and longitude to center the map (always required)
        center: new google.maps.LatLng(40.6700, -73.9400), // New York

        // Disables the default Google Maps UI components
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: false,

        // How you would like to style the map.
        // This is where you would paste any style found on Snazzy Maps.
        styles: [{
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "landscape",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 29
            }, {
                "weight": 0.2
            }]
        }, {
            "featureType": "road.arterial",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 18
            }]
        }, {
            "featureType": "road.local",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "featureType": "poi",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 21
            }]
        }, {
            "elementType": "labels.text.stroke",
            "stylers": [{
                "visibility": "on"
            }, {
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "elementType": "labels.text.fill",
            "stylers": [{
                "saturation": 36
            }, {
                "color": "#000000"
            }, {
                "lightness": 40
            }]
        }, {
            "elementType": "labels.icon",
            "stylers": [{
                "visibility": "off"
            }]
        }, {
            "featureType": "transit",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 19
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }, {
                "weight": 1.2
            }]
        }]
    };

    // Get the HTML DOM element that will contain your map
    // We are using a div with id="map" seen below in the <body>
    var mapElement = document.getElementById('map');

    // Create the Google Map using out element and options defined above
    var map = new google.maps.Map(mapElement, mapOptions);

    // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon
    var image = 'img/map-marker.png';
    var myLatLng = new google.maps.LatLng(40.6700, -73.9400);
    var beachMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image
    });
}
<commit_msg>Mixing the maps up<commit_after>/*!
 * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
    if ($(".navbar").offset().top > 50) {
        $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
});

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

// Google Maps Scripts
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);

function init() {
    // Basic options for a simple Google Map
    // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
    var mapOptions = {
        // How zoomed in you want the map to start at (always required)
        zoom: 13,

        // The latitude and longitude to center the map (always required)
        center: new google.maps.LatLng(43.2341813,-86.2483921),

        // Disables the default Google Maps UI components
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: true,

        // How you would like to style the map.
        // This is where you would paste any style found on Snazzy Maps.
        styles: [{"featureType":"water","elementType":"geometry","stylers":[{"color":"#a2daf2"}]},{"featureType":"landscape.man_made","elementType":"geometry","stylers":[{"color":"#f7f1df"}]},{"featureType":"landscape.natural","elementType":"geometry","stylers":[{"color":"#d0e3b4"}]},{"featureType":"landscape.natural.terrain","elementType":"geometry","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#bde6ab"}]},{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi.medical","elementType":"geometry","stylers":[{"color":"#fbd3da"}]},{"featureType":"poi.business","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffe15f"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#efd151"}]},{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"road.local","elementType":"geometry.fill","stylers":[{"color":"black"}]},{"featureType":"transit.station.airport","elementType":"geometry.fill","stylers":[{"color":"#cfb2db"}]}]
    };

    // Get the HTML DOM element that will contain your map
    // We are using a div with id="map" seen below in the <body>
    var mapElement = document.getElementById('map');

    // Create the Google Map using out element and options defined above
    var map = new google.maps.Map(mapElement, mapOptions);

    // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon
    var myLatLng = new google.maps.LatLng(43.2341813,-86.2483921);
    var beachMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
    });
}
<|endoftext|>


<commit_before>$(document).ready(function() {
  $('#master').val(localStorage.hp_master).trigger('focus_empty')
  if ($('#master').val() != '') {
    $('#master').next('.clearinput').fadeIn(50)
  }

  // Set settings
  $('#settings input, #settings select').each(function(index) {
    var id = $(this).attr('id')
    switch (typeof settings[id]) {
      case "boolean":
        $('#'+id).attr('checked', settings[id])
        break
      case "number":
        $('#'+id).val(settings[id])
        break
      case "string":
        $('#'+id).val(settings[id])
        break
      default:
        console.log(id)
        break
    }
  })
  $('#save_key').trigger('save_key')

  $('#hatch').keyup(function(e){
    if (e.keyCode == 13 || e.keyCode == 9) {
      var master = $('#master').val()
      var domain = $('#domain').val()
      if (master != '' && domain != '') {
        $.post('/'+settings.key, {
         master: master,
         domain: domain,
         settings: settings
         }, function(data){
            $('#secret').val(data).select()
        })
      }
    }
  })

  // Remember master
  $('#master').change(function(){
    if ($("#r_master").is(':checked') && $('#master').val() != "") {
      localStorage.hp_master = $('#master').val()
    }
	})
	$('#master, #domain').keyup(function(){
    if ($(this).val() == "") {
      $('#secret').val('')
      $(this).next('.clearinput').fadeOut(50)
    } else {
      $(this).next('.clearinput').fadeIn(50)
    }
  })
  $('.clearinput').click(function() {
    $(this).prev('input').val('').focus();
    $(this).fadeOut(50);
    $('#secure').val('');
    return false;
  })

  $('#save_key').click(function() {
    $('#save_key').trigger('save_key')
    return false
  })

})
<commit_msg>fixed annoying shift tab bug<commit_after>$(document).ready(function() {
  $('#master').val(localStorage.hp_master).trigger('focus_empty')
  if ($('#master').val() != '') {
    $('#master').next('.clearinput').fadeIn(50)
  }

  // Set settings
  $('#settings input, #settings select').each(function(index) {
    var id = $(this).attr('id')
    switch (typeof settings[id]) {
      case "boolean":
        $('#'+id).attr('checked', settings[id])
        break
      case "number":
        $('#'+id).val(settings[id])
        break
      case "string":
        $('#'+id).val(settings[id])
        break
      default:
        console.log(id)
        break
    }
  })
  $('#save_key').trigger('save_key')

  $('#hatch').change(function(e){
      var master = $('#master').val()
      var domain = $('#domain').val()
      if (master != '' && domain != '') {
        $.post('/'+settings.key, {
         master: master,
         domain: domain,
         settings: settings
         }, function(data){
            $('#secret').val(data).select()
        })
      }
  })

  // Remember master
  $('#master').change(function(){
    if ($("#r_master").is(':checked') && $('#master').val() != "") {
      localStorage.hp_master = $('#master').val()
    }
	})
	$('#master, #domain').keyup(function(){
    if ($(this).val() == "") {
      $('#secret').val('')
      $(this).next('.clearinput').fadeOut(50)
    } else {
      $(this).next('.clearinput').fadeIn(50)
    }
  })
  $('.clearinput').click(function() {
    $(this).prev('input').val('').focus();
    $(this).fadeOut(50);
    $('#secure').val('');
    return false;
  })

  $('#save_key').click(function() {
    $('#save_key').trigger('save_key')
    return false
  })

})
<|endoftext|>


<commit_before>/**
 * CH. 04 - Core JavaScript Object Creation & Design Patterns
 * ES6 Array Methods
 *
 * JavaScript Patterns - modern JS patterns with ES5 & ES6 examples
 * @copyright 2016 - 2017, Ahad Bokhari
 * license: MIT
 */

/* (i). ES6 brings with different methods that help your workflow. Over the years libraries like Underscore and then Lodash have polyfilled the features
 * lacking in the language, but now we have many more tools for the functional array.
 */

// a. Array.from: long overdue method - Creates a new Array instance from an array-like or iterable object

Array.from('string');
// => ["s", "t", "r", "i", "n", "g"]

Array.from('')

// b. entries()

// c. fill()

// d. find()

// e. findIndex()

// f. keys()

// g. values()<commit_msg>Update es6-array-methods.js<commit_after>/**
 * CH. 04 - Core JavaScript Object Creation & Design Patterns
 * ES6 Array Methods
 *
 * JavaScript Patterns - modern JS patterns with ES5 & ES6 examples
 * @copyright 2016 - 2017, Ahad Bokhari
 * license: MIT
 */

/* (i). ES6 brings with different methods that help your workflow. Over the years libraries like Underscore and then Lodash have polyfilled the features
 * lacking in the language, but now we have many more tools for the functional array.
 */

/* Array.from: long overdue method - Creates a new Array instance from an array-like or iterable object */

// a. array from stromg
Array.from('string');
// => ["s", "t", "r", "i", "n", "g"]

// b. array from Map
const arrayFromMap = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(arrayFromMap);
// => [[1, 2], [2, 4], [4, 8]]

// b. entries()

// c. fill()

// d. find()

// e. findIndex()

// f. keys()

// g. values()
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2012 Bruno Jouhier <bruno.jouhier@sage.com>
 * MIT License
 */
/// !doc
///
/// # Streamline built-ins
///
(function (exports) {
	"use strict";
	var VERSION = 3;

	var future = function (fn, args, i) {
		var err, result, done, q = [],
			self = this;
		args = Array.prototype.slice.call(args);
		args[i] = function (e, r) {
			err = e;
			result = r;
			done = true;
			q && q.forEach(function (f) {
				f.call(self, e, r);
			});
			q = null;
		};
		fn.apply(this, args);
		return function F(cb) {
			if (!cb) return F;
			if (done) cb.call(self, err, result);
			else q.push(cb);
		};
	};

	var funnel = function (max) {
		max = max == null ? -1 : max;
		if (max === 0) max = exports.funnel.defaultSize;
		if (typeof max !== "number") throw new Error("bad max number: " + max);
		var queue = [],
			active = 0,
			closed = false;

		function _doOne() {
			var current = queue.shift();
			if (!current.cb) return current.fn();
			active++;
			current.fn(function (err, result) {
				active--;
				if (!closed) {
					current.cb(err, result);
					while (active < max && queue.length > 0) _doOne();
				}
			});
		}

		function overflow(callback, fn) {
			queue.push({
				fn: fn,
				cb: callback
			});
		}

		var fun = function (_, fn) {
			//console.log("FUNNEL: active=" + active + ", queued=" + queue.length);
			if (max < 0 || max === Infinity) return fn(_);
			// optimization to avoid _ -> callback transition in fibers mode when the funnel is available.
			if (active < max) {
				active++;
				try {
					return fn(_);
				} finally {
					active--;
					while (active < max && queue.length > 0) _doOne();
				}
			} else {
				return overflow(_, fn);
			}
		}

		fun.close = function () {
			queue = [];
			closed = true;
		};
		return fun;
	};
	funnel.defaultSize = 4;

	exports.funnel = funnel;

	function _parallel(options) {
		if (typeof options === "number") return options;
		if (typeof options.parallel === "number") return options.parallel;
		return options.parallel ? -1 : 1;
	}

	if (Array.prototype.forEach_ && Array.prototype.forEach_.version_ >= VERSION) return;

	// bail out (silently) if JS does not support defineProperty (IE 8).
	try {
		Object.defineProperty({}, 'x', {});
	} catch (e) {
		return;
	}

	var has = Object.prototype.hasOwnProperty;

	/* eslint-disable no-extend-native */

	/// ## Array functions
	///
	/// These functions are asynchronous variants of the EcmaScript 5 Array functions.
	///
	/// Common Rules:
	///
	/// These variants are postfixed by an underscore.
	/// They take the `_` callback as first parameter.
	/// They pass the `_` callback as first argument to their `fn` callback.
	/// Most of them have an optional `options` second parameter which controls the level of
	/// parallelism. This `options` parameter may be specified either as `{ parallel: par }`
	/// where `par` is an integer, or directly as a `par` integer value.
	/// The `par` values are interpreted as follows:
	///
	/// * If absent or equal to 1, execution is sequential.
	/// * If > 1, at most `par` operations are parallelized.
	/// * if 0, a default number of operations are parallelized.
	///   This default is defined by `flows.funnel.defaultSize` (4 by default - see `flows` module).
	/// * If < 0 or Infinity, operations are fully parallelized (no limit).
	///
	/// Functions:
	///
	/// * `array.forEach_(_[, options], fn[, thisObj])`
	///   `fn` is called as `fn(_, elt, i, array)`.
	delete Array.prototype.forEach_;
	Object.defineProperty(Array.prototype, 'forEach_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, options, fn, thisObj) {
			if (typeof options === "function") {
				thisObj = fn;
				fn = options;
				options = 1;
			}
			var par = _parallel(options);
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length;
			if (par === 1 || len <= 1) {
				for (var i = 0; i < len; i++) {
					if (has.call(this, i)) fn.call(thisObj, _, this[i], i, this);
				}
			} else {
				this.map_(_, par, fn, thisObj);
			}
			return this;
		}
	});
	Array.prototype.forEach_.version_ = VERSION;
	/// * `result = array.map_(_[, options], fn[, thisObj])`
	///   `fn` is called as `fn(_, elt, i, array)`.
	delete Array.prototype.map_;
	Object.defineProperty(Array.prototype, 'map_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, options, fn, thisObj) {
			if (typeof options === "function") {
				thisObj = fn;
				fn = options;
				options = 1;
			}
			var par = _parallel(options);
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length;
			var result, i;
			if (par === 1 || len <= 1) {
				result = new Array(len);
				for (i = 0; i < len; i++) {
					if (has.call(this, i)) result[i] = fn.call(thisObj, _, this[i], i, this);
				}
			} else {
				var futures = [];
				i = 0;
				result = new Array(len);
				for (var j = 0; j < par; j++) futures[j] = (_ => {
					while (i < this.length) {
						var k = i++;
						result[k] = fn.call(thisObj, _, this[k], this);
					}
				})(!_);
				for (var j = 0; j < par; j++) futures[j](_);
			}
			return result;
		}
	});
	/// * `result = array.filter_(_[, options], fn[, thisObj])`
	///   `fn` is called as `fn(_, elt, i, array)`.
	delete Array.prototype.filter_;
	Object.defineProperty(Array.prototype, 'filter_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, options, fn, thisObj) {
			if (typeof options === "function") {
				thisObj = fn;
				fn = options;
				options = 1;
			}
			var par = _parallel(options);
			thisObj = thisObj !== undefined ? thisObj : this;
			var result = [];
			var len = this.length;
			if (par === 1 || len <= 1) {
				for (var i = 0; i < len; i++) {
					if (has.call(this, i)) {
						var elt = this[i];
						if (fn.call(thisObj, _, elt, i, this)) result.push(elt);
					}
				}
			} else {
				this.map_(_, par, function (_, elt, i, arr) {
					if (fn.call(thisObj, _, elt, i, arr)) result.push(elt);
				}, thisObj);
			}
			return result;
		}
	});
	/// * `bool = array.every_(_[, options], fn[, thisObj])`
	///   `fn` is called as `fn(_, elt, i, array)`.
	delete Array.prototype.every_;
	Object.defineProperty(Array.prototype, 'every_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, options, fn, thisObj) {
			if (typeof options === "function") {
				thisObj = fn;
				fn = options;
				options = 1;
			}
			var par = _parallel(options);
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length, i;
			if (par === 1 || len <= 1) {
				for (i = 0; i < len; i++) {

					if (has.call(this, i) && !fn.call(thisObj, _, this[i], i, this)) return false;
				}
			} else {
				var fun = funnel(par);
				var futures = this.map(function (elt, i, arr) {
					return fun(!_, function (_) {
						return fn.call(thisObj, _, elt, i, arr);
					});
				});
				for (i = 0; i < len; i++) {
					if (has.call(this, i) && !futures[i](_)) {
						fun.close();
						return false;
					}
				}
			}
			return true;
		}
	});
	/// * `bool = array.some_(_[, options], fn[, thisObj])`
	///   `fn` is called as `fn(_, elt, i, array)`.
	delete Array.prototype.some_;
	Object.defineProperty(Array.prototype, 'some_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, options, fn, thisObj) {
			if (typeof options === "function") {
				thisObj = fn;
				fn = options;
				options = 1;
			}
			var par = _parallel(options);
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length, i;
			if (par === 1 || len <= 1) {
				for (i = 0; i < len; i++) {
					if (has.call(this, i) && fn.call(thisObj, _, this[i], i, this)) return true;
				}
			} else {
				var fun = funnel(par);
				var futures = this.map(function (elt, i, arr) {
					return fun(!_, function (_) {
						return fn.call(thisObj, _, elt, i, arr);
					});
				});
				for (i = 0; i < len; i++) {
					if (has.call(this, i) && futures[i](_)) {
						fun.close();
						return true;
					}
				}
			}
			return false;
		}
	});
	/// * `result = array.reduce_(_, fn, val[, thisObj])`
	///   `fn` is called as `val = fn(_, val, elt, i, array)`.
	delete Array.prototype.reduce_;
	Object.defineProperty(Array.prototype, 'reduce_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, fn, v, thisObj) {
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length;
			for (var i = 0; i < len; i++) {
				if (has.call(this, i)) v = fn.call(thisObj, _, v, this[i], i, this);
			}
			return v;
		}
	});
	/// * `result = array.reduceRight_(_, fn, val[, thisObj])`
	///   `fn` is called as `val = fn(_, val, elt, i, array)`.
	delete Array.prototype.reduceRight_;
	Object.defineProperty(Array.prototype, 'reduceRight_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, fn, v, thisObj) {
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length;
			for (var i = len - 1; i >= 0; i--) {
				if (has.call(this, i)) v = fn.call(thisObj, _, v, this[i], i, this);
			}
			return v;
		}
	});

	/// * `array = array.sort_(_, compare [, beg [, end]])`
	///   `compare` is called as `cmp = compare(_, elt1, elt2)`.
	///   Note: this function _changes_ the original array (and returns it).
	delete Array.prototype.sort_;
	Object.defineProperty(Array.prototype, 'sort_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, compare, beg, end) {
			var array = this;
			beg = beg || 0;
			end = end == null ? array.length - 1 : end;

			function _qsort(_, beg, end) {
				if (beg >= end) return;

				var tmp;
				if (end === beg + 1) {
					if (compare(_, array[beg], array[end]) > 0) {
						tmp = array[beg];
						array[beg] = array[end];
						array[end] = tmp;
					}
					return;
				}

				var mid = Math.floor((beg + end) / 2);
				var o = array[mid];
				var nbeg = beg;
				var nend = end;

				while (nbeg <= nend) {
					while (nbeg < end && compare(_, array[nbeg], o) < 0) nbeg++;
					while (beg < nend && compare(_, o, array[nend]) < 0) nend--;

					if (nbeg <= nend) {
						tmp = array[nbeg];
						array[nbeg] = array[nend];
						array[nend] = tmp;
						nbeg++;
						nend--;
					}
				}

				if (nbeg < end) _qsort(_, nbeg, end);
				if (beg < nend) _qsort(_, beg, nend);
			}
			_qsort(_, beg, end);
			return array;
		}
	});

	///
	/// ## Function functions
	///
	/// * `result = fn.apply_(_, thisObj, args[, index])`
	///   Helper to use `Function.prototype.apply` inside streamlined functions.
	///   Equivalent to `result = fn.apply(thisObj, argsWith_)` where `argsWith_` is
	///   a modified `args` in which the callback has been inserted at `index`
	///   (at the end of the argument list if `index` is omitted or negative).
	delete Function.prototype.apply_;
	Object.defineProperty(Function.prototype, 'apply_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (callback, thisObj, args, index) {
			args = Array.prototype.slice.call(args, 0);
			args.splice(index != null && index >= 0 ? index : args.length, 0, callback);
			return this.apply(thisObj, args);
		}
	});
})(typeof exports !== 'undefined' ? exports : (Streamline.builtins = Streamline.builtins || {}));<commit_msg>fixed Sage/streamlinejs#365<commit_after>/**
 * Copyright (c) 2012 Bruno Jouhier <bruno.jouhier@sage.com>
 * MIT License
 */
/// !doc
///
/// # Streamline built-ins
///
(function (exports) {
	"use strict";
	var VERSION = 3;

	var future = function (fn, args, i) {
		var err, result, done, q = [],
			self = this;
		args = Array.prototype.slice.call(args);
		args[i] = function (e, r) {
			err = e;
			result = r;
			done = true;
			q && q.forEach(function (f) {
				f.call(self, e, r);
			});
			q = null;
		};
		fn.apply(this, args);
		return function F(cb) {
			if (!cb) return F;
			if (done) cb.call(self, err, result);
			else q.push(cb);
		};
	};

	var funnel = function (max) {
		max = max == null ? -1 : max;
		if (max === 0) max = exports.funnel.defaultSize;
		if (typeof max !== "number") throw new Error("bad max number: " + max);
		var queue = [],
			active = 0,
			closed = false;

		function _doOne() {
			var current = queue.shift();
			if (!current.cb) return current.fn();
			active++;
			current.fn(function (err, result) {
				active--;
				if (!closed) {
					current.cb(err, result);
					while (active < max && queue.length > 0) _doOne();
				}
			});
		}

		function overflow(callback, fn) {
			queue.push({
				fn: fn,
				cb: callback
			});
		}

		var fun = function (_, fn) {
			//console.log("FUNNEL: active=" + active + ", queued=" + queue.length);
			if (max < 0 || max === Infinity) return fn(_);
			// optimization to avoid _ -> callback transition in fibers mode when the funnel is available.
			if (active < max) {
				active++;
				try {
					return fn(_);
				} finally {
					active--;
					while (active < max && queue.length > 0) _doOne();
				}
			} else {
				return overflow(_, fn);
			}
		}

		fun.close = function () {
			queue = [];
			closed = true;
		};
		return fun;
	};
	funnel.defaultSize = 4;

	exports.funnel = funnel;

	function _parallel(options) {
		if (typeof options === "number") return options;
		if (typeof options.parallel === "number") return options.parallel;
		return options.parallel ? -1 : 1;
	}

	if (Array.prototype.forEach_ && Array.prototype.forEach_.version_ >= VERSION) return;

	// bail out (silently) if JS does not support defineProperty (IE 8).
	try {
		Object.defineProperty({}, 'x', {});
	} catch (e) {
		return;
	}

	var has = Object.prototype.hasOwnProperty;

	/* eslint-disable no-extend-native */

	/// ## Array functions
	///
	/// These functions are asynchronous variants of the EcmaScript 5 Array functions.
	///
	/// Common Rules:
	///
	/// These variants are postfixed by an underscore.
	/// They take the `_` callback as first parameter.
	/// They pass the `_` callback as first argument to their `fn` callback.
	/// Most of them have an optional `options` second parameter which controls the level of
	/// parallelism. This `options` parameter may be specified either as `{ parallel: par }`
	/// where `par` is an integer, or directly as a `par` integer value.
	/// The `par` values are interpreted as follows:
	///
	/// * If absent or equal to 1, execution is sequential.
	/// * If > 1, at most `par` operations are parallelized.
	/// * if 0, a default number of operations are parallelized.
	///   This default is defined by `flows.funnel.defaultSize` (4 by default - see `flows` module).
	/// * If < 0 or Infinity, operations are fully parallelized (no limit).
	///
	/// Functions:
	///
	/// * `array.forEach_(_[, options], fn[, thisObj])`
	///   `fn` is called as `fn(_, elt, i, array)`.
	delete Array.prototype.forEach_;
	Object.defineProperty(Array.prototype, 'forEach_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, options, fn, thisObj) {
			if (typeof options === "function") {
				thisObj = fn;
				fn = options;
				options = 1;
			}
			var par = _parallel(options);
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length;
			if (par === 1 || len <= 1) {
				for (var i = 0; i < len; i++) {
					if (has.call(this, i)) fn.call(thisObj, _, this[i], i, this);
				}
			} else {
				this.map_(_, par, fn, thisObj);
			}
			return this;
		}
	});
	Array.prototype.forEach_.version_ = VERSION;
	/// * `result = array.map_(_[, options], fn[, thisObj])`
	///   `fn` is called as `fn(_, elt, i, array)`.
	delete Array.prototype.map_;
	Object.defineProperty(Array.prototype, 'map_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, options, fn, thisObj) {
			if (typeof options === "function") {
				thisObj = fn;
				fn = options;
				options = 1;
			}
			var par = _parallel(options);
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length;
			var result, i;
			if (par === 1 || len <= 1) {
				result = new Array(len);
				for (i = 0; i < len; i++) {
					if (has.call(this, i)) result[i] = fn.call(thisObj, _, this[i], i, this);
				}
			} else {
				var futures = [];
				i = 0;
				result = new Array(len);
				for (var j = 0; j < par; j++) futures[j] = (_ => {
					while (i < this.length) {
						var k = i++;
						result[k] = fn.call(thisObj, _, this[k], k, this);
					}
				})(!_);
				for (var j = 0; j < par; j++) futures[j](_);
			}
			return result;
		}
	});
	/// * `result = array.filter_(_[, options], fn[, thisObj])`
	///   `fn` is called as `fn(_, elt, i, array)`.
	delete Array.prototype.filter_;
	Object.defineProperty(Array.prototype, 'filter_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, options, fn, thisObj) {
			if (typeof options === "function") {
				thisObj = fn;
				fn = options;
				options = 1;
			}
			var par = _parallel(options);
			thisObj = thisObj !== undefined ? thisObj : this;
			var result = [];
			var len = this.length;
			if (par === 1 || len <= 1) {
				for (var i = 0; i < len; i++) {
					if (has.call(this, i)) {
						var elt = this[i];
						if (fn.call(thisObj, _, elt, i, this)) result.push(elt);
					}
				}
			} else {
				this.map_(_, par, function (_, elt, i, arr) {
					if (fn.call(thisObj, _, elt, i, arr)) result.push(elt);
				}, thisObj);
			}
			return result;
		}
	});
	/// * `bool = array.every_(_[, options], fn[, thisObj])`
	///   `fn` is called as `fn(_, elt, i, array)`.
	delete Array.prototype.every_;
	Object.defineProperty(Array.prototype, 'every_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, options, fn, thisObj) {
			if (typeof options === "function") {
				thisObj = fn;
				fn = options;
				options = 1;
			}
			var par = _parallel(options);
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length, i;
			if (par === 1 || len <= 1) {
				for (i = 0; i < len; i++) {

					if (has.call(this, i) && !fn.call(thisObj, _, this[i], i, this)) return false;
				}
			} else {
				var fun = funnel(par);
				var futures = this.map(function (elt, i, arr) {
					return fun(!_, function (_) {
						return fn.call(thisObj, _, elt, i, arr);
					});
				});
				for (i = 0; i < len; i++) {
					if (has.call(this, i) && !futures[i](_)) {
						fun.close();
						return false;
					}
				}
			}
			return true;
		}
	});
	/// * `bool = array.some_(_[, options], fn[, thisObj])`
	///   `fn` is called as `fn(_, elt, i, array)`.
	delete Array.prototype.some_;
	Object.defineProperty(Array.prototype, 'some_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, options, fn, thisObj) {
			if (typeof options === "function") {
				thisObj = fn;
				fn = options;
				options = 1;
			}
			var par = _parallel(options);
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length, i;
			if (par === 1 || len <= 1) {
				for (i = 0; i < len; i++) {
					if (has.call(this, i) && fn.call(thisObj, _, this[i], i, this)) return true;
				}
			} else {
				var fun = funnel(par);
				var futures = this.map(function (elt, i, arr) {
					return fun(!_, function (_) {
						return fn.call(thisObj, _, elt, i, arr);
					});
				});
				for (i = 0; i < len; i++) {
					if (has.call(this, i) && futures[i](_)) {
						fun.close();
						return true;
					}
				}
			}
			return false;
		}
	});
	/// * `result = array.reduce_(_, fn, val[, thisObj])`
	///   `fn` is called as `val = fn(_, val, elt, i, array)`.
	delete Array.prototype.reduce_;
	Object.defineProperty(Array.prototype, 'reduce_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, fn, v, thisObj) {
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length;
			for (var i = 0; i < len; i++) {
				if (has.call(this, i)) v = fn.call(thisObj, _, v, this[i], i, this);
			}
			return v;
		}
	});
	/// * `result = array.reduceRight_(_, fn, val[, thisObj])`
	///   `fn` is called as `val = fn(_, val, elt, i, array)`.
	delete Array.prototype.reduceRight_;
	Object.defineProperty(Array.prototype, 'reduceRight_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, fn, v, thisObj) {
			thisObj = thisObj !== undefined ? thisObj : this;
			var len = this.length;
			for (var i = len - 1; i >= 0; i--) {
				if (has.call(this, i)) v = fn.call(thisObj, _, v, this[i], i, this);
			}
			return v;
		}
	});

	/// * `array = array.sort_(_, compare [, beg [, end]])`
	///   `compare` is called as `cmp = compare(_, elt1, elt2)`.
	///   Note: this function _changes_ the original array (and returns it).
	delete Array.prototype.sort_;
	Object.defineProperty(Array.prototype, 'sort_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (_, compare, beg, end) {
			var array = this;
			beg = beg || 0;
			end = end == null ? array.length - 1 : end;

			function _qsort(_, beg, end) {
				if (beg >= end) return;

				var tmp;
				if (end === beg + 1) {
					if (compare(_, array[beg], array[end]) > 0) {
						tmp = array[beg];
						array[beg] = array[end];
						array[end] = tmp;
					}
					return;
				}

				var mid = Math.floor((beg + end) / 2);
				var o = array[mid];
				var nbeg = beg;
				var nend = end;

				while (nbeg <= nend) {
					while (nbeg < end && compare(_, array[nbeg], o) < 0) nbeg++;
					while (beg < nend && compare(_, o, array[nend]) < 0) nend--;

					if (nbeg <= nend) {
						tmp = array[nbeg];
						array[nbeg] = array[nend];
						array[nend] = tmp;
						nbeg++;
						nend--;
					}
				}

				if (nbeg < end) _qsort(_, nbeg, end);
				if (beg < nend) _qsort(_, beg, nend);
			}
			_qsort(_, beg, end);
			return array;
		}
	});

	///
	/// ## Function functions
	///
	/// * `result = fn.apply_(_, thisObj, args[, index])`
	///   Helper to use `Function.prototype.apply` inside streamlined functions.
	///   Equivalent to `result = fn.apply(thisObj, argsWith_)` where `argsWith_` is
	///   a modified `args` in which the callback has been inserted at `index`
	///   (at the end of the argument list if `index` is omitted or negative).
	delete Function.prototype.apply_;
	Object.defineProperty(Function.prototype, 'apply_', {
		configurable: true,
		writable: true,
		enumerable: false,
		value: function (callback, thisObj, args, index) {
			args = Array.prototype.slice.call(args, 0);
			args.splice(index != null && index >= 0 ? index : args.length, 0, callback);
			return this.apply(thisObj, args);
		}
	});
})(typeof exports !== 'undefined' ? exports : (Streamline.builtins = Streamline.builtins || {}));<|endoftext|>