<commit_before>import React, { PureComponent, Fragment } from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import { Card, Button, H3, H4, FormGroup, InputGroup, Intent } from "@blueprintjs/core";
import uuid from "uuid/v4";
import { Input as ButtercupInput, Button as ButtercupButton } from "@buttercup/ui";
import LayoutMain from "./LayoutMain.js";
import ArchiveTypeChooser from "../containers/ArchiveTypeChooser.js";
import { ARCHIVE_TYPES } from "./ArchiveTypeChooser.js";
import RemoteExplorer from "../containers/RemoteExplorer.js";
import { FormButtonContainer, FormContainer, FormLegendItem, FormRow, FormInputItem } from "./forms.js";

const Spacer = styled.div`
    width: 100%;
    height: 2rem;
`;
const SplitView = styled.div`
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 1rem;
`;

class AddArchivePage extends PureComponent {
    static propTypes = {
        dropboxAuthID: PropTypes.string,
        dropboxAuthToken: PropTypes.string,
        isConnected: PropTypes.bool.isRequired,
        isConnecting: PropTypes.bool.isRequired,
        onAuthenticateDropbox: PropTypes.func.isRequired,
        onChooseDropboxBasedArchive: PropTypes.func.isRequired,
        onChooseWebDAVBasedArchive: PropTypes.func.isRequired,
        onConnectWebDAVBasedSource: PropTypes.func.isRequired,
        onCreateRemotePath: PropTypes.func.isRequired,
        onSelectRemotePath: PropTypes.func.isRequired,
        selectedArchiveType: PropTypes.string,
        selectedFilename: PropTypes.string,
        selectedFilenameNeedsCreation: PropTypes.bool.isRequired
    };

    // We store some details in the state, because they're sensitive. No point
    // storing them globally..
    state = {
        archiveName: "",
        dropboxAuthenticationID: "",
        masterPassword: "",
        remoteURL: "",
        remoteUsername: "",
        remotePassword: ""
    };

    componentDidMount() {
        this.setState({
            dropboxAuthenticationID: uuid()
        });
    }

    handleDropboxAuth(event) {
        event.preventDefault();
        this.props.onAuthenticateDropbox(this.state.dropboxAuthenticationID);
    }

    handleChooseDropboxBasedFile(event) {
        event.preventDefault();
        // We send the remote credentials as these should never touch Redux
        this.props.onChooseDropboxBasedArchive(this.state.archiveName, this.state.masterPassword);
    }

    handleChooseWebDAVBasedFile(event) {
        event.preventDefault();
        // We send the remote credentials as these should never touch Redux
        this.props.onChooseWebDAVBasedArchive(
            this.props.selectedArchiveType,
            this.state.archiveName,
            this.state.masterPassword,
            this.state.remoteURL,
            this.state.remoteUsername,
            this.state.remotePassword
        );
    }

    handleConnectWebDAV(event) {
        event.preventDefault();
        this.props.onConnectWebDAVBasedSource(
            this.props.selectedArchiveType,
            this.state.remoteURL,
            this.state.remoteUsername,
            this.state.remotePassword
        );
    }

    handleUpdateForm(property, event) {
        this.setState({
            [property]: event.target.value
        });
    }

    render() {
        const isTargetingWebDAV = ["webdav", "owncloud", "nextcloud"].includes(this.props.selectedArchiveType);
        const isTargetingDropbox = this.props.selectedArchiveType === "dropbox";
        const hasAuthenticatedDropbox = typeof this.props.dropboxAuthToken === "string";
        const hasAuthenticated =
            (isTargetingWebDAV && this.props.isConnected) || (isTargetingDropbox && hasAuthenticatedDropbox);
        return (
            <LayoutMain title="Add Archive">

Choose Vault Type

                <ArchiveTypeChooser disabled={hasAuthenticated} />
                <Spacer />
                <If condition={this.props.selectedArchiveType}>
                    <Choose>
                        <When condition={hasAuthenticated}>

Choose or Create Vault

                            <SplitView>
                                <Card>
                                    <RemoteExplorer
                                        onCreateRemotePath={path => this.props.onCreateRemotePath(path)}
                                        onSelectRemotePath={path => this.props.onSelectRemotePath(path)}
                                        selectedFilename={this.props.selectedFilename}
                                        selectedFilenameNeedsCreation={this.props.selectedFilenameNeedsCreation}
                                        fetchType={isTargetingWebDAV ? "webdav" : "dropbox"}
                                    />
                                </Card>
                                <Card>{this.renderArchiveNameInput()}</Card>
                            </SplitView>
                        </When>
                        <Otherwise>{this.renderConnectionInfo()}</Otherwise>
                    </Choose>
                </If>
            </LayoutMain>
        );
    }

    renderArchiveNameInput() {
        const { selectedFilename } = this.props;
        const disabled = !selectedFilename;
        return (
            <Fragment>
                <FormGroup full label="Name" labelInfo="(required)" disabled={disabled}>
                    <InputGroup
                        leftIcon="tag"
                        disabled={disabled}
                        placeholder="Enter vault name..."
                        onChange={event => this.handleUpdateForm("archiveName", event)}
                        value={this.state.archiveName}
                    />
                </FormGroup>
                <FormGroup full label="Master Password" labelInfo="(required)" disabled={disabled}>
                    <InputGroup
                        leftIcon="lock"
                        disabled={disabled}
                        placeholder="Enter vault password..."
                        type="password"
                        onChange={event => this.handleUpdateForm("masterPassword", event)}
                        value={this.state.masterPassword}
                    />
                </FormGroup>
                <Button
                    fill
                    disabled={disabled}
                    onClick={event =>
                        this.props.selectedArchiveType === "dropbox"
                            ? this.handleChooseDropboxBasedFile(event)
                            : this.handleChooseWebDAVBasedFile(event)
                    }
                >
                    Save Vault
                </Button>
            </Fragment>
        );
    }

    renderConnectionInfo() {
        const connectionOptionsDisabled = this.props.isConnecting || this.props.isConnected;
        const sectionTitle =
            this.props.selectedArchiveType === "dropbox" ? "Authenticate Cloud Source" : "Enter Connection Details";
        const isAuthenticatingDropbox = this.props.dropboxAuthID === this.state.dropboxAuthenticationID;
        const hasAuthenticatedDropbox = isAuthenticatingDropbox && this.props.dropboxAuthToken;
        const isWebDAV = ["webdav", "owncloud", "nextcloud"].includes(this.props.selectedArchiveType);
        const title = ARCHIVE_TYPES.find(archiveType => archiveType.type === this.props.selectedArchiveType).title;
        return (
            <Fragment>

{sectionTitle}

                <Choose>
                    <When condition={isWebDAV}>
                        <Card>
                            <FormGroup full label={`${title} URL`} labelInfo="(required)">
                                <InputGroup
                                    leftIcon="globe"
                                    placeholder="Enter remote URL..."
                                    disabled={connectionOptionsDisabled}
                                    onChange={event => this.handleUpdateForm("remoteURL", event)}
                                    value={this.state.remoteURL}
                                />
                            </FormGroup>
                            <FormGroup full label={`${title} Username`} labelInfo="(required)">
                                <InputGroup
                                    leftIcon="user"
                                    placeholder={`Enter ${title} username...`}
                                    disabled={connectionOptionsDisabled}
                                    onChange={event => this.handleUpdateForm("remoteUsername", event)}
                                    value={this.state.remoteUsername}
                                />
                            </FormGroup>
                            <FormGroup full label={`${title} Password`} labelInfo="(required)">
                                <InputGroup
                                    leftIcon="key"
                                    placeholder={`Enter ${title} password...`}
                                    type="password"
                                    disabled={connectionOptionsDisabled}
                                    onChange={event => this.handleUpdateForm("remotePassword", event)}
                                    value={this.state.remotePassword}
                                />
                            </FormGroup>
                            <Button
                                intent={Intent.SUCCESS}
                                onClick={::this.handleConnectWebDAV}
                                loading={this.props.isConnecting}
                                disabled={this.props.isConnected}
                            >
                                Connect
                            </Button>
                        </Card>
                    </When>
                    <When condition={this.props.selectedArchiveType === "dropbox"}>
                        <Card>

Dropbox

                                To start, please grant Buttercup access to your Dropbox account. This access will be
                                only used to store and read a Buttercup Vault that you choose or create.

                            <Button
                                icon="key"
                                onClick={::this.handleDropboxAuth}
                                disabled={hasAuthenticatedDropbox}
                                loading={isAuthenticatingDropbox && !hasAuthenticatedDropbox}
                            >
                                Grant Dropbox Access
                            </Button>
                        </Card>
                    </When>
                    <Otherwise>
                        Unsupported vault type.
                    </Otherwise>
                </Choose>
            </Fragment>
        );
    }
}

export default AddArchivePage;
<commit_msg>Better columns for file tree<commit_after>import React, { PureComponent, Fragment } from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import { Card, Button, H3, H4, FormGroup, InputGroup, Intent } from "@blueprintjs/core";
import uuid from "uuid/v4";
import { Input as ButtercupInput, Button as ButtercupButton } from "@buttercup/ui";
import LayoutMain from "./LayoutMain.js";
import ArchiveTypeChooser from "../containers/ArchiveTypeChooser.js";
import { ARCHIVE_TYPES } from "./ArchiveTypeChooser.js";
import RemoteExplorer from "../containers/RemoteExplorer.js";
import { FormButtonContainer, FormContainer, FormLegendItem, FormRow, FormInputItem } from "./forms.js";

const Spacer = styled.div`
    width: 100%;
    height: 2rem;
`;
const SplitView = styled.div`
    display: grid;
    grid-template-columns: repeat(2, calc(50% - 0.5rem));
    grid-gap: 1rem;
`;

class AddArchivePage extends PureComponent {
    static propTypes = {
        dropboxAuthID: PropTypes.string,
        dropboxAuthToken: PropTypes.string,
        isConnected: PropTypes.bool.isRequired,
        isConnecting: PropTypes.bool.isRequired,
        onAuthenticateDropbox: PropTypes.func.isRequired,
        onChooseDropboxBasedArchive: PropTypes.func.isRequired,
        onChooseWebDAVBasedArchive: PropTypes.func.isRequired,
        onConnectWebDAVBasedSource: PropTypes.func.isRequired,
        onCreateRemotePath: PropTypes.func.isRequired,
        onSelectRemotePath: PropTypes.func.isRequired,
        selectedArchiveType: PropTypes.string,
        selectedFilename: PropTypes.string,
        selectedFilenameNeedsCreation: PropTypes.bool.isRequired
    };

    // We store some details in the state, because they're sensitive. No point
    // storing them globally..
    state = {
        archiveName: "",
        dropboxAuthenticationID: "",
        masterPassword: "",
        remoteURL: "",
        remoteUsername: "",
        remotePassword: ""
    };

    componentDidMount() {
        this.setState({
            dropboxAuthenticationID: uuid()
        });
    }

    handleDropboxAuth(event) {
        event.preventDefault();
        this.props.onAuthenticateDropbox(this.state.dropboxAuthenticationID);
    }

    handleChooseDropboxBasedFile(event) {
        event.preventDefault();
        // We send the remote credentials as these should never touch Redux
        this.props.onChooseDropboxBasedArchive(this.state.archiveName, this.state.masterPassword);
    }

    handleChooseWebDAVBasedFile(event) {
        event.preventDefault();
        // We send the remote credentials as these should never touch Redux
        this.props.onChooseWebDAVBasedArchive(
            this.props.selectedArchiveType,
            this.state.archiveName,
            this.state.masterPassword,
            this.state.remoteURL,
            this.state.remoteUsername,
            this.state.remotePassword
        );
    }

    handleConnectWebDAV(event) {
        event.preventDefault();
        this.props.onConnectWebDAVBasedSource(
            this.props.selectedArchiveType,
            this.state.remoteURL,
            this.state.remoteUsername,
            this.state.remotePassword
        );
    }

    handleUpdateForm(property, event) {
        this.setState({
            [property]: event.target.value
        });
    }

    render() {
        const isTargetingWebDAV = ["webdav", "owncloud", "nextcloud"].includes(this.props.selectedArchiveType);
        const isTargetingDropbox = this.props.selectedArchiveType === "dropbox";
        const hasAuthenticatedDropbox = typeof this.props.dropboxAuthToken === "string";
        const hasAuthenticated =
            (isTargetingWebDAV && this.props.isConnected) || (isTargetingDropbox && hasAuthenticatedDropbox);
        return (
            <LayoutMain title="Add Archive">

Choose Vault Type

                <ArchiveTypeChooser disabled={hasAuthenticated} />
                <Spacer />
                <If condition={this.props.selectedArchiveType}>
                    <Choose>
                        <When condition={hasAuthenticated}>

Choose or Create Vault

                            <SplitView>
                                <Card>
                                    <RemoteExplorer
                                        onCreateRemotePath={path => this.props.onCreateRemotePath(path)}
                                        onSelectRemotePath={path => this.props.onSelectRemotePath(path)}
                                        selectedFilename={this.props.selectedFilename}
                                        selectedFilenameNeedsCreation={this.props.selectedFilenameNeedsCreation}
                                        fetchType={isTargetingWebDAV ? "webdav" : "dropbox"}
                                    />
                                </Card>
                                <Card>{this.renderArchiveNameInput()}</Card>
                            </SplitView>
                        </When>
                        <Otherwise>{this.renderConnectionInfo()}</Otherwise>
                    </Choose>
                </If>
            </LayoutMain>
        );
    }

    renderArchiveNameInput() {
        const { selectedFilename } = this.props;
        const disabled = !selectedFilename;
        return (
            <Fragment>
                <FormGroup full label="Name" labelInfo="(required)" disabled={disabled}>
                    <InputGroup
                        leftIcon="tag"
                        disabled={disabled}
                        placeholder="Enter vault name..."
                        onChange={event => this.handleUpdateForm("archiveName", event)}
                        value={this.state.archiveName}
                    />
                </FormGroup>
                <FormGroup full label="Master Password" labelInfo="(required)" disabled={disabled}>
                    <InputGroup
                        leftIcon="lock"
                        disabled={disabled}
                        placeholder="Enter vault password..."
                        type="password"
                        onChange={event => this.handleUpdateForm("masterPassword", event)}
                        value={this.state.masterPassword}
                    />
                </FormGroup>
                <Button
                    fill
                    disabled={disabled}
                    onClick={event =>
                        this.props.selectedArchiveType === "dropbox"
                            ? this.handleChooseDropboxBasedFile(event)
                            : this.handleChooseWebDAVBasedFile(event)
                    }
                >
                    Save Vault
                </Button>
            </Fragment>
        );
    }

    renderConnectionInfo() {
        const connectionOptionsDisabled = this.props.isConnecting || this.props.isConnected;
        const sectionTitle =
            this.props.selectedArchiveType === "dropbox" ? "Authenticate Cloud Source" : "Enter Connection Details";
        const isAuthenticatingDropbox = this.props.dropboxAuthID === this.state.dropboxAuthenticationID;
        const hasAuthenticatedDropbox = isAuthenticatingDropbox && this.props.dropboxAuthToken;
        const isWebDAV = ["webdav", "owncloud", "nextcloud"].includes(this.props.selectedArchiveType);
        const title = ARCHIVE_TYPES.find(archiveType => archiveType.type === this.props.selectedArchiveType).title;
        return (
            <Fragment>

{sectionTitle}

                <Choose>
                    <When condition={isWebDAV}>
                        <Card>
                            <FormGroup full label={`${title} URL`} labelInfo="(required)">
                                <InputGroup
                                    leftIcon="globe"
                                    placeholder="Enter remote URL..."
                                    disabled={connectionOptionsDisabled}
                                    onChange={event => this.handleUpdateForm("remoteURL", event)}
                                    value={this.state.remoteURL}
                                />
                            </FormGroup>
                            <FormGroup full label={`${title} Username`} labelInfo="(required)">
                                <InputGroup
                                    leftIcon="user"
                                    placeholder={`Enter ${title} username...`}
                                    disabled={connectionOptionsDisabled}
                                    onChange={event => this.handleUpdateForm("remoteUsername", event)}
                                    value={this.state.remoteUsername}
                                />
                            </FormGroup>
                            <FormGroup full label={`${title} Password`} labelInfo="(required)">
                                <InputGroup
                                    leftIcon="key"
                                    placeholder={`Enter ${title} password...`}
                                    type="password"
                                    disabled={connectionOptionsDisabled}
                                    onChange={event => this.handleUpdateForm("remotePassword", event)}
                                    value={this.state.remotePassword}
                                />
                            </FormGroup>
                            <Button
                                intent={Intent.SUCCESS}
                                onClick={::this.handleConnectWebDAV}
                                loading={this.props.isConnecting}
                                disabled={this.props.isConnected}
                            >
                                Connect
                            </Button>
                        </Card>
                    </When>
                    <When condition={this.props.selectedArchiveType === "dropbox"}>
                        <Card>

Dropbox

                                To start, please grant Buttercup access to your Dropbox account. This access will be
                                only used to store and read a Buttercup Vault that you choose or create.

                            <Button
                                icon="key"
                                onClick={::this.handleDropboxAuth}
                                disabled={hasAuthenticatedDropbox}
                                loading={isAuthenticatingDropbox && !hasAuthenticatedDropbox}
                            >
                                Grant Dropbox Access
                            </Button>
                        </Card>
                    </When>
                    <Otherwise>
                        Unsupported vault type.
                    </Otherwise>
                </Choose>
            </Fragment>
        );
    }
}

export default AddArchivePage;
<|endoftext|>


<commit_before>(function(c,a){window.mixpanel=a;var b,d,h,e;b=c.createElement("script");
    b.type="text/javascript";b.async=!0;b.src=("https:"===c.location.protocol?"https:":"http:")+
    '//cdn.mxpnl.com/libs/mixpanel-2.2.min.js';d=c.getElementsByTagName("script")[0];
    d.parentNode.insertBefore(b,d);a._i=[];a.init=function(b,c,f){function d(a,b){
    var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(
    Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:
    f="mixpanel";g.people=g.people||[];h=['disable','track','track_pageview','track_links',
    'track_forms','register','register_once','unregister','identify','alias','name_tag',
    'set_config','people.set','people.increment','people.track_charge','people.append'];
    for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2;})(document,window.mixpanel||[]);
    	<commit_msg>updated mix panel library<commit_after>(function(c,a){window.mixpanel=a;var b,d,h,e;b=c.createElement("script");
    b.type="text/javascript";b.async=!0;b.src=("https:"===c.location.protocol?"https:":"http:")+
    '//cdn.mxpnl.com/libs/mixpanel-2.2.min.js';d=c.getElementsByTagName("script")[0];
    d.parentNode.insertBefore(b,d);a._i=[];a.init=function(b,c,f){function d(a,b){
    var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(
    Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:
    f="mixpanel";g.people=g.people||[];h=['disable','track','track_pageview','track_links',
    'track_forms','register','register_once','unregister','identify','alias','name_tag','set_config',
    'people.set','people.set_once','people.increment','people.track_charge','people.append'];
    for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2;})(document,window.mixpanel||[]);<|endoftext|>


<commit_before>import { StyleSheet, Dimensions } from 'react-native';

export default StyleSheet.create({
  mainContainer: {
    // flex: 3,
    width: Dimensions.get('window').width * .97,
    height: Dimensions.get('window').height * .95,
    marginLeft: Dimensions.get('window').width / 60,
    marginTop: Dimensions.get('window').width / 20,
  },
  startingActorView: {
    flex: 1.6,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    // borderWidth: 1,
  },
  endingActorView: {
    flex: 1.6,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    // borderWidth: 1,
  },
  pathsView: {
    flex: 3,
    justifyContent: 'center',
    // borderWidth: 1,
    // left: 0,
  },
  path: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    padding: 5,
    // alignItems: 'flex-start',
  },
  buttonView: {
    flex: .11,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
})
<commit_msg>Add styles for loading text view/text<commit_after>import { StyleSheet, Dimensions } from 'react-native';

export default StyleSheet.create({
  mainContainer: {
    // flex: 3,
    width: Dimensions.get('window').width * .97,
    height: Dimensions.get('window').height * .95,
    marginLeft: Dimensions.get('window').width / 60,
    marginTop: Dimensions.get('window').width / 20,
  },
  startingActorView: {
    flex: 1.6,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    // borderWidth: 1,
  },
  endingActorView: {
    flex: 1.6,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    // borderWidth: 1,
  },
  pathsView: {
    flex: 3,
    justifyContent: 'center',
    // borderWidth: 1,
    // left: 0,
  },
  path: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    padding: 5,
    // alignItems: 'flex-start',
  },
  buttonView: {
    flex: .11,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  loadingView: {
    marginTop: Dimensions.get('window').height / 1.03
  },
  loadingText: {
    fontFamily: 'Faster One'
  }
})
<|endoftext|>


<commit_before>var lingcod = (function(){

    var options = {};
    var that = {};

    that.init = function(opts){
        options = opts;
        that.options = opts;

        $('#sidebar').tabs();
        resize();
        google.earth.createInstance(
            "map",
            function(i){
                geInit(i);
            },
            function(code){
                geFailure(code);
            });
        setupListeners();
        lingcod.menu_items.init($('.menu_items'));
        // makes button clicking a lot more reliable!!
        $(document).find('a.button').live('dragstart', function(){
            return false;
        });
    };

    var geInit = function(pluginInstance){
        ge = pluginInstance;
        ge.getWindow().setVisibility(true); // required
        gex = new GEarthExtensions(ge);

        that.googleLayers = new lingcod.map.googleLayers(ge,
            $('#ge_options'), $('#ge_layers'));
        that.geocoder = new lingcod.map.geocoder(gex, $('#flyToLocation'));
        that.measureTool = new lingcod.measureTool();

        $('#measure_distance').click(function(){
            that.measureTool.clear();
            that.measureTool.measureDistance(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_area').click(function(){
            that.measureTool.clear();
            that.measureTool.measureArea(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_clear').click(function(){
            that.measureTool.clear();
            $(this).addClass('disabled');
            $('#measureAmountHolder').hide();
        });
        $('#measure_units').change(function(){
            that.measureTool.setUnits($(this).val());
        });

        $('#datalayerstree').append('

');

        var studyRegion = lingcod.kmlTree({
            url: window.studyregion,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#study_region'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true
        });
        $(studyRegion).bind('kmlLoaded', function(){
            $('#study_region').find('li').dblclick();
        });
        studyRegion.load();

        var publicData = lingcod.kmlTree({
            url: window.public_data_layers,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#public_data'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true
        });
        publicData.load(true);

        // var forest = lingcod.kmlForest({
        //     element: $('#datalayerstree'),
        //     ge: ge,
        //     gex: gex,
        //     div: $('#map')
        // });
        //
        // forest.add(window.studyregion, {
        //     cachebust: true,
        //     callback: function(kmlObject, topNode){
        //         topNode.find('> ul > li > a').trigger('dblclick');
        //     }
        // });
        //
        // forest.add(window.public_data_layers, {
        //     cachebust: true
        // });

        var panel = lingcod.panel({appendTo: $('#panel-holder'),
            showCloseButton: false});

        that.client = lingcod.rest.client(gex, panel);

        if(typeof options.form_shown === 'function'){
            $(that.client).bind('form_shown', options.form_shown);
        }

        if(options.ecotrust){
            var ecotrustData = lingcod.kmlTree({
                url: options.ecotrust,
                ge: ge,
                gex: gex,
                animate: false,
                map_div: $('#map'),
                element: $('#ecotrust_data'),
                trans: options.media_url + 'common/images/transparent.gif',
                title: true
            });
            ecotrustData.load(true);
        }

        var editors = [];

        if(options.myshapes){
            for(var i=0;i<options.myshapes.length; i++){
                editors.push(lingcod.rest.kmlEditor({
                    ge: ge,
                    gex: gex,
                    appendTo: '#myshapestree',
                    div: '#map',
                    url: options.myshapes[i],
                    client: that.client
                }));
            }
        }

        $('#sidebar, #meta-navigation').click(function(e){
            if(e.target === this || e.target === $('#MyShapes')[0]){
                for(var i=0;i<editors.length;i++){
                    editors[0].clearSelection();
                }
            }
        });

        var url = that.options.media_url + 'common/kml/shadow.kmz';
        google.earth.fetchKml(ge, url, function(k){
            ge.getFeatures().appendChild(k);
        });
    };

    var studyRegionLoaded = function(kmlObject, node){
        // Reorder so studyRegion is on top of the list
        $('#datalayerstree').prepend(node);
        if (kmlObject.getAbstractView()){
            ge.getView().setAbstractView(kmlObject.getAbstractView());
        }
    };

    var geFailure = function(errorCode){
        alert("Failure loading the Google Earth Plugin: " + errorCode);
    }

    var setupListeners = function(){
        $(window).smartresize(function(){
            resize();
        });
        $('#meta-navigation').click(function(){
            lingcod.menu_items.closeAll();
        });
        $('#sidebar').bind('mouseup', function(e){
            lingcod.menu_items.closeAll();
            return false;
        });
        $('#sidebar-mask').click(function(){
            lingcod.menu_items.closeAll();
        });
    };

    var resize = function(){
        var mh = $('#meta-navigation').outerHeight();
        var h = $(document.body).height() - mh;
        $('#sidebar').css({top: mh, height: h});
        $('#panel-holder').css({top: mh, height: h});

        var w = $(document.body).width() - $('#sidebar').width();
        $('#map_container').height(h).width(w);
    };

    that.maskSidebar = function(){
        $('#panel-holder').show();
        $('#sidebar').addClass('masked');
    };

    that.unmaskSidebar = function(){
        $('#panel-holder').hide();
        $('#sidebar').removeClass('masked');
    };

    var panels = [];

    that.addPanel = function(panel){
        panels.push(panel);
        $(panel).bind('panelshow', onPanelShown);
        $(panel).bind('panelhide', onPanelHide);
        $(panel).bind('panelclose', onPanelHide);
    },

    that.removePanel = function(panel){
        panels.remove(panel);
        $(panel).unbind('panelshow', onPanelShown);
        $(panel).unbind('panelhide', onPanelHide);
        $(panel).unbind('panelclose', onPanelHide);
    };

    var onPanelShown = function(e, panel){
        that.maskSidebar();
    };

    var onPanelHide = function(e, panel){
        var count = 0;
        for(var i=0; i<panels.length; i++){
            var p = panels[i];
            if(p.shown){
                count++;
            }
        }
        if(count > 0){
            // console.log('another panel still shown');
        }else{
            that.unmaskSidebar();
        }
    };

    return that;
})();<commit_msg>turned on status bar and navigation controls by default<commit_after>var lingcod = (function(){

    var options = {};
    var that = {};

    that.init = function(opts){
        options = opts;
        that.options = opts;

        $('#sidebar').tabs();
        resize();
        google.earth.createInstance(
            "map",
            function(i){
                geInit(i);
            },
            function(code){
                geFailure(code);
            });
        setupListeners();
        lingcod.menu_items.init($('.menu_items'));
        // makes button clicking a lot more reliable!!
        $(document).find('a.button').live('dragstart', function(){
            return false;
        });
    };

    var geInit = function(pluginInstance){
        ge = pluginInstance;
        ge.getWindow().setVisibility(true); // required
        ge.getOptions().setStatusBarVisibility(true);
        ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
        gex = new GEarthExtensions(ge);

        // that.googleLayers = new lingcod.map.googleLayers(ge,
        //     $('#ge_options'), $('#ge_layers'));
        that.geocoder = new lingcod.map.geocoder(gex, $('#flyToLocation'));
        that.measureTool = new lingcod.measureTool();

        $('#measure_distance').click(function(){
            that.measureTool.clear();
            that.measureTool.measureDistance(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_area').click(function(){
            that.measureTool.clear();
            that.measureTool.measureArea(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_clear').click(function(){
            that.measureTool.clear();
            $(this).addClass('disabled');
            $('#measureAmountHolder').hide();
        });
        $('#measure_units').change(function(){
            that.measureTool.setUnits($(this).val());
        });

        $('#datalayerstree').append('

');

        var studyRegion = lingcod.kmlTree({
            url: window.studyregion,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#study_region'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true
        });
        $(studyRegion).bind('kmlLoaded', function(){
            $('#study_region').find('li').dblclick();
        });
        studyRegion.load();

        var publicData = lingcod.kmlTree({
            url: window.public_data_layers,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#public_data'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true
        });
        publicData.load(true);

        // var forest = lingcod.kmlForest({
        //     element: $('#datalayerstree'),
        //     ge: ge,
        //     gex: gex,
        //     div: $('#map')
        // });
        //
        // forest.add(window.studyregion, {
        //     cachebust: true,
        //     callback: function(kmlObject, topNode){
        //         topNode.find('> ul > li > a').trigger('dblclick');
        //     }
        // });
        //
        // forest.add(window.public_data_layers, {
        //     cachebust: true
        // });

        var panel = lingcod.panel({appendTo: $('#panel-holder'),
            showCloseButton: false});

        that.client = lingcod.rest.client(gex, panel);

        if(typeof options.form_shown === 'function'){
            $(that.client).bind('form_shown', options.form_shown);
        }

        if(options.ecotrust){
            var ecotrustData = lingcod.kmlTree({
                url: options.ecotrust,
                ge: ge,
                gex: gex,
                animate: false,
                map_div: $('#map'),
                element: $('#ecotrust_data'),
                trans: options.media_url + 'common/images/transparent.gif',
                title: true
            });
            ecotrustData.load(true);
        }

        var editors = [];

        if(options.myshapes){
            for(var i=0;i<options.myshapes.length; i++){
                editors.push(lingcod.rest.kmlEditor({
                    ge: ge,
                    gex: gex,
                    appendTo: '#myshapestree',
                    div: '#map',
                    url: options.myshapes[i],
                    client: that.client
                }));
            }
        }

        $('#sidebar, #meta-navigation').click(function(e){
            if(e.target === this || e.target === $('#MyShapes')[0]){
                for(var i=0;i<editors.length;i++){
                    editors[0].clearSelection();
                }
            }
        });

        var url = that.options.media_url + 'common/kml/shadow.kmz';
        google.earth.fetchKml(ge, url, function(k){
            ge.getFeatures().appendChild(k);
        });
    };

    var studyRegionLoaded = function(kmlObject, node){
        // Reorder so studyRegion is on top of the list
        $('#datalayerstree').prepend(node);
        if (kmlObject.getAbstractView()){
            ge.getView().setAbstractView(kmlObject.getAbstractView());
        }
    };

    var geFailure = function(errorCode){
        alert("Failure loading the Google Earth Plugin: " + errorCode);
    }

    var setupListeners = function(){
        $(window).smartresize(function(){
            resize();
        });
        $('#meta-navigation').click(function(){
            lingcod.menu_items.closeAll();
        });
        $('#sidebar').bind('mouseup', function(e){
            lingcod.menu_items.closeAll();
            return false;
        });
        $('#sidebar-mask').click(function(){
            lingcod.menu_items.closeAll();
        });
    };

    var resize = function(){
        var mh = $('#meta-navigation').outerHeight();
        var h = $(document.body).height() - mh;
        $('#sidebar').css({top: mh, height: h});
        $('#panel-holder').css({top: mh, height: h});

        var w = $(document.body).width() - $('#sidebar').width();
        $('#map_container').height(h).width(w);
    };

    that.maskSidebar = function(){
        $('#panel-holder').show();
        $('#sidebar').addClass('masked');
    };

    that.unmaskSidebar = function(){
        $('#panel-holder').hide();
        $('#sidebar').removeClass('masked');
    };

    var panels = [];

    that.addPanel = function(panel){
        panels.push(panel);
        $(panel).bind('panelshow', onPanelShown);
        $(panel).bind('panelhide', onPanelHide);
        $(panel).bind('panelclose', onPanelHide);
    },

    that.removePanel = function(panel){
        panels.remove(panel);
        $(panel).unbind('panelshow', onPanelShown);
        $(panel).unbind('panelhide', onPanelHide);
        $(panel).unbind('panelclose', onPanelHide);
    };

    var onPanelShown = function(e, panel){
        that.maskSidebar();
    };

    var onPanelHide = function(e, panel){
        var count = 0;
        for(var i=0; i<panels.length; i++){
            var p = panels[i];
            if(p.shown){
                count++;
            }
        }
        if(count > 0){
            // console.log('another panel still shown');
        }else{
            that.unmaskSidebar();
        }
    };

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


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

'use strict';

let yargs = require('yargs'),
  browsertime = require('browsertime'),
  merge = require('lodash.merge'),
  getURLs = require('../lib/cli/util').getURLs,
  browsertimeConfig = require('../lib/plugins/browsertime/index').config;

async function testURL(engine, url) {
  try {
    await engine.start();
    await engine.run(url);
  } finally {
    engine.stop();
  }
}

async function runBrowsertime() {
  let parsed = yargs
    .env('SITESPEED_IO')
    .require(1, 'urlOrFile')
    .option('browsertime.browser', {
      alias: ['b', 'browser'],
      default: browsertimeConfig.browser,
      describe: 'Choose which Browser to use when you test.',
      choices: ['chrome', 'firefox'],
      group: 'Browser'
    })
    .option('browsertime.viewPort', {
      default: browsertimeConfig.viewPort,
      describe: 'The browser view port size WidthxHeight like 400x300',
      group: 'Browser'
    });

  const defaultConfig = {
    iterations: 1,
    connectivity: {
      profile: 'native',
      downstreamKbps: undefined,
      upstreamKbps: undefined,
      latency: undefined,
      engine: 'external'
    },
    viewPort: '1366x708',
    delay: 0,
    video: false,
    speedIndex: false,
    resultDir: '/tmp/browsertime'
  };

  const btOptions = merge({}, parsed.argv.browsertime, defaultConfig);
  browsertime.logging.configure(parsed.argv);

  const engine = new browsertime.Engine(btOptions);
  const urls = getURLs(parsed.argv._);

  for (let url of urls) {
    await testURL(engine, url);
  }
}

runBrowsertime();
<commit_msg>cleanup for wpr<commit_after>#!/usr/bin/env node

'use strict';

const yargs = require('yargs');
const browsertime = require('browsertime');
const merge = require('lodash.merge');
const getURLs = require('../lib/cli/util').getURLs;
const browsertimeConfig = require('../lib/plugins/browsertime/index').config;

async function testURL(engine, url) {
  try {
    await engine.start();
    await engine.run(url);
  } finally {
    engine.stop();
  }
}

async function runBrowsertime() {
  let parsed = yargs
    .env('SITESPEED_IO')
    .require(1, 'urlOrFile')
    .option('browsertime.browser', {
      alias: ['b', 'browser'],
      default: browsertimeConfig.browser,
      describe: 'Choose which Browser to use when you test.',
      choices: ['chrome', 'firefox'],
      group: 'Browser'
    })
    .option('browsertime.viewPort', {
      default: browsertimeConfig.viewPort,
      describe: 'The browser view port size WidthxHeight like 400x300',
      group: 'Browser'
    });

  const defaultConfig = {
    iterations: 1,
    connectivity: {
      profile: 'native',
      downstreamKbps: undefined,
      upstreamKbps: undefined,
      latency: undefined,
      engine: 'external'
    },
    viewPort: '1366x708',
    delay: 0,
    video: false,
    visualMetrics: false,
    resultDir: '/tmp/browsertime'
  };

  const btOptions = merge({}, parsed.argv.browsertime, defaultConfig);
  browsertime.logging.configure(parsed.argv);

  const engine = new browsertime.Engine(btOptions);
  const urls = getURLs(parsed.argv._);

  for (let url of urls) {
    await testURL(engine, url);
  }
}

runBrowsertime();
<|endoftext|>


<commit_before>var READ_SIZE          = 100;

var config;
var fs      = require( 'fs' );
var path    = require( 'path' );
var express = require( 'express' );
var app     = express();
var eventbrite = require( 'eventbrite' );

var configFile = fs.readFileSync(path.join(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE, '.serenedirc'), 'utf-8');
if(!configFile) throw new Error('Missing .serenedirc');
else {
    config = JSON.parse(configFile);
}

var io        = require( 'socket.io' ).listen( app.listen( config.port ) );
var eb_client = eventbrite( {'app_key' : config.eventbriteAPIkey} );

app.use( express.static( __dirname + '/public' ));
app.get( '/', function ( req, res ) { res.redirect( '/index.html' ); } );

io.sockets.on('connection', function( socket ) {
	socket.on('getEventsCall', function( data ) {
    	var params = {'longitude': data.message.lng,
            			'latitude' : data.message.lat,
            			'within_unit' : 'K',
            			'max' : READ_SIZE,
            			'page' : 1,
            			'within' : Math.ceil(data.message.radius),
            			'date' : getEventbriteDateRange(data.message.dateFrom, data.message.dateTo),
            			'category' : getTypeString(data.message.type),
            			'sort_by' : 'id'};

		eb_client.event_search(params, function(err, data){
			socket.emit('getEventsResult', {message : data});
		});
	});

	socket.on('getEventsByIDCall', function( data ) {
		var params = {'id' : data.message.id};
		var radius = Math.ceil(data.message.radius);

		eb_client.event_get(params, function(err, data){

			var lat = data.event.venue.latitude;
			var lng = data.event.venue.longitude;

			var startDate = data.event.start_date.split(' ')[0].split('-');
			var endDate = new Date(startDate);

			startDate = startDate[1] + "/" + startDate[2] + "/" + startDate[0];
			endDate.setDate(endDate.getDate() + 7);

			var endDateMonth = endDate.getMonth() + 1;
			if (endDateMonth < 10) {
				endDateMonth = '0' + endDateMonth;
			}

			var endDateDay = endDate.getDate();
			if (endDateDay < 10) {
				endDateDay = '0' + endDateDay;
			}

			endDate = endDateMonth + "/" + endDateDay + "/" + endDate.getFullYear();

			var params = {'longitude': lng,
				'latitude' : lat,
				'within_unit' : 'K',
				'date' : '',
				'max' : READ_SIZE,
				'page' : 1,
				'sort_by' : 'id',
				'data' : getEventbriteDateRange(startDate, endDate),
				'within' : radius};

			eb_client.event_search(params, function(err, data){

				socket.emit('getEventsResult', {message: data, center:{lat: lat, lng: lng}, date:{startDate : startDate, endDate : endDate}});
			});
		});
	});

});

function getPrettyDate(date) {
	var month = date.getMonth() + 1;
	var day = date.getDate();

	if (month < 10) {
		month = month + "0";
	}
	if (day < 10) {
		day = day + "0";
	}

	return month + '/' + day + '/' + date.getFullYear();
}

function getEventbriteDateRange(from, to) {
    var fromArray = from.split('/');
    var toArray = to.split('/');

    return fromArray[2] + '-' + fromArray[0] + '-' + fromArray[1] + ' ' + toArray[2] + '-' + toArray[0] + '-' + toArray[1];
}

//TODO There is a better way of handling this...
function getTypeString(type) {
    var typeStr = '';

    if(type.charAt(0) == '1') {
        typeStr += 'conference, ';
    }

    if(type.charAt(1) == '1') {
        typeStr += 'conventions, ';
    }

    if(type.charAt(2) == '1') {
        typeStr += 'entertainment, ';
    }

    if(type.charAt(3) == '1') {
        typeStr += 'fairs, ';
    }

    if(type.charAt(4) == '1') {
        typeStr += 'food, ';
    }

    if(type.charAt(5) == '1') {
        typeStr += 'fundraisers, ';
    }

    if(type.charAt(6) == '1') {
        typeStr += 'meetings, ';
    }

    if(type.charAt(7) == '1') {
        typeStr += 'music, ';
    }

    if(type.charAt(8) == '1') {
        typeStr += 'performances, ';
    }

    if(type.charAt(9) == '1') {
        typeStr += 'recreation, ';
    }

    if(type.charAt(10) == '1') {
        typeStr += 'religion, ';
    }

    if(type.charAt(11) == '1') {
        typeStr += 'reunions, ';
    }

    if(type.charAt(12) == '1') {
        typeStr += 'sales, ';
    }

    if(type.charAt(13) == '1') {
        typeStr += 'social, ';
    }

    if(type.charAt(14) == '1') {
        typeStr += 'sports, ';
    }

    if(type.charAt(15) == '1') {
        typeStr += 'tradeshows, ';
    }

    if(type.charAt(16) == '1') {
        typeStr += 'travel, ';
    }

    if(type.charAt(17) == '1') {
        typeStr += 'other';
    }

    return typeStr;
}

<commit_msg>Refractoring serenedi.js based on JS Hint<commit_after>var READ_SIZE = 100;

var config;
var fs = require('fs');
var path = require('path');
var express = require('express');
var app = express();
var eventbrite = require('eventbrite');

var configFile = fs.readFileSync(path.join(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE, '.serenedirc'), 'utf-8');
if (!configFile) {
  throw new Error('Missing .serenedirc');
}
else {
  config = JSON.parse(configFile);
}

var io = require('socket.io').listen(app.listen(config.port));
var eb_client = eventbrite({'app_key' : config.eventbriteAPIkey});

app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) { res.redirect('/index.html'); });

io.sockets.on('connection', function(socket) {
  socket.on('getEventsCall', function(data) {
    var params = {'longitude': data.message.lng,
      'latitude' : data.message.lat,
      'within_unit' : 'K',
      'max' : READ_SIZE,
      'page' : 1,
      'within' : Math.ceil(data.message.radius),
      'date' : getEventbriteDateRange(data.message.dateFrom, data.message.dateTo),
      'category' : getTypeString(data.message.type),
      'sort_by' : 'id'};

    eb_client.event_search(params, function(err, data){
      socket.emit('getEventsResult', {message : data});
    });
  });

  socket.on('getEventsByIDCall', function(data) {
    var params = {'id' : data.message.id};
    var radius = Math.ceil(data.message.radius);

    eb_client.event_get(params, function(err, data){
      if (data === null || data === "") {
        return;
      }
      var lat = data.event.venue.latitude;
      var lng = data.event.venue.longitude;

      var startDate = data.event.start_date.split(' ')[0].split('-');
      var endDate = new Date(startDate);

      startDate = startDate[1] + "/" + startDate[2] + "/" + startDate[0];
      endDate.setDate(endDate.getDate() + 7);

      var endDateMonth = endDate.getMonth() + 1;
      if (endDateMonth < 10) {
        endDateMonth = '0' + endDateMonth;
      }

      var endDateDay = endDate.getDate();
      if (endDateDay < 10) {
        endDateDay = '0' + endDateDay;
      }

      endDate = endDateMonth + "/" + endDateDay + "/" + endDate.getFullYear();

      var params = {'longitude': lng,
      'latitude' : lat,
      'within_unit' : 'K',
      'date' : '',
      'max' : READ_SIZE,
      'page' : 1,
      'sort_by' : 'id',
      'data' : getEventbriteDateRange(startDate, endDate),
      'within' : radius};

      eb_client.event_search(params, function(err, data){

        socket.emit('getEventsResult', {message: data, center:{lat: lat, lng: lng}, date:{startDate : startDate, endDate : endDate}});
      });
    });
  });
});

function getPrettyDate(date) {
  var month = date.getMonth() + 1;
  var day = date.getDate();

  if (month < 10) {
    month = month + "0";
  }
  if (day < 10) {
    day = day + "0";
  }

  return month + '/' + day + '/' + date.getFullYear();
}

function getEventbriteDateRange(from, to) {
  var fromArray = from.split('/');
  var toArray = to.split('/');

  return fromArray[2] + '-' + fromArray[0] + '-' + fromArray[1] + ' ' + toArray[2] + '-' + toArray[0] + '-' + toArray[1];
}

//TODO There is a better way of handling this...
function getTypeString(type) {
  var typeStr = '';

  if(type.charAt(0) == '1') {
    typeStr += 'conference, ';
  }

  if(type.charAt(1) == '1') {
    typeStr += 'conventions, ';
  }

  if(type.charAt(2) == '1') {
    typeStr += 'entertainment, ';
  }

  if(type.charAt(3) == '1') {
    typeStr += 'fairs, ';
  }

  if(type.charAt(4) == '1') {
    typeStr += 'food, ';
  }

  if(type.charAt(5) == '1') {
    typeStr += 'fundraisers, ';
  }

  if(type.charAt(6) == '1') {
    typeStr += 'meetings, ';
  }

  if(type.charAt(7) == '1') {
    typeStr += 'music, ';
  }

  if(type.charAt(8) == '1') {
    typeStr += 'performances, ';
  }

  if(type.charAt(9) == '1') {
    typeStr += 'recreation, ';
  }

  if(type.charAt(10) == '1') {
    typeStr += 'religion, ';
  }

  if(type.charAt(11) == '1') {
    typeStr += 'reunions, ';
  }

  if(type.charAt(12) == '1') {
    typeStr += 'sales, ';
  }

  if(type.charAt(13) == '1') {
    typeStr += 'social, ';
  }

  if(type.charAt(14) == '1') {
    typeStr += 'sports, ';
  }

  if(type.charAt(15) == '1') {
    typeStr += 'tradeshows, ';
  }

  if(type.charAt(16) == '1') {
    typeStr += 'travel, ';
  }

  if(type.charAt(17) == '1') {
    typeStr += 'other';
  }

  return typeStr;
}

<|endoftext|>


<commit_before>"use strict";

var ManifestParser = (function() {

  var _json_input = {};
  var _manifest = {};
  var _logs = [];
  var _success = true;

  var ALLOWED_DISPLAY_VALUES = [ 'fullscreen',
                                 'standalone',
                                 'minimal-ui',
                                 'browser' ];

  var ALLOWED_ORIENTATION_VALUES = [ 'any',
                                     'natural',
                                     'landscape',
                                     'portrait',
                                     'portrait-primary',
                                     'portrait-secondary',
                                     'landscape-primary',
                                     'landscape-secondary' ];

  function _parseString(args) {
    var object = args.object;
    var property = args.property;
    if (!(property in object))
      return undefined;

    if (typeof object[property] != 'string') {
      _logs.push('ERROR: "' + property + '" expected to be a string but is not.');
      return undefined;
    }

    if (args.trim)
      return object[property].trim();
    return object[property];
  }

  function _parseBoolean(args) {
    var object = args.object;
    var property = args.property;
    var defaultValue = args.defaultValue;
    if (!(property in object))
      return defaultValue;

    if (typeof object[property] != 'boolean') {
      _logs.push('ERROR: "' + property + '" expected to be a boolean but is not.');
      return defaultValue;
    }

    return object[property];
  }

  function _parseURL(args) {
    var object = args.object;
    var property = args.property;
    var baseURL = args.baseURL;

    var str = _parseString({ object: object, property: property, trim: false });
    if (str === undefined)
      return undefined;

    // TODO: resolve url using baseURL
    // new URL(object[property], baseURL);
    return object[property];
  }

  function _parseColor(args) {
    var object = args.object;
    var property = args.property;
    if (!(property in object))
      return undefined;

    if (typeof object[property] != 'string') {
      _logs.push('ERROR: "' + property + '" expected to be a string but is not.');
      return undefined;
    }

    // If style.color changes when set to the given color, it is valid. Testing
    // against 'white' and 'black' in case of the given color is one of them.
    var dummy = document.createElement('div');
    dummy.style.color = 'white';
    dummy.style.color = object[property];
    if (dummy.style.color != 'white')
      return object[property];
    dummy.style.color = 'black';
    dummy.style.color = object[property];
    if (dummy.style.color != 'black')
      return object[property];
    return undefined;
  }

  function _parseName() {
    return _parseString({ object: _json_input, property: 'name', trim: true });
  }

  function _parseShortName() {
    return _parseString({ object: _json_input,
                          property: 'short_name',
                          trim: true });
  }

  function _parseStartUrl() {
    // TODO: parse url using manifest_url as a base (missing).
    return _parseURL({ object: _json_input, property: 'start_url' });
  }

  function _parseDisplay() {
    var display = _parseString({ object: _json_input,
                                 property: 'display',
                                 trim: true });
    if (display === undefined)
      return display;

    if (ALLOWED_DISPLAY_VALUES.indexOf(display.toLowerCase()) == -1) {
      _logs.push('ERROR: "display" has an invalid value, will be ignored.');
      return undefined;
    }

    return display;
  }

  function _parseOrientation() {
    var orientation = _parseString({ object: _json_input,
                                     property: 'orientation',
                                     trim: true });
    if (orientation === undefined)
      return orientation;

    if (ALLOWED_ORIENTATION_VALUES.indexOf(orientation.toLowerCase()) == -1) {
      _logs.push('ERROR: "orientation" has an invalid value, will be ignored.');
      return undefined;
    }

    return orientation;
  }

  function _parseIcons() {
    var property = 'icons';
    var icons = [];

    if (!(property in _json_input))
      return icons;

    if (!Array.isArray(_json_input[property])) {
      _logs.push('ERROR: "' + property + '" expected to be an array but is not.');
      return icons;
    }

    _json_input[property].forEach(function(object) {
      var icon = {};
      if (!('src' in object))
        return;
      // TODO: pass manifest url as base.
      icon.src = _parseURL({ object: object, property: 'src' });
      icon.type = _parseString({ object: object,
                                 property: 'type',
                                 trim: true });

      icon.density = parseFloat(object['density']);
      if (isNaN(icon.density) || !isFinite(icon.density) || icon.density <= 0)
        icon.density = 1.0;

      if ('sizes' in object) {
        var set = new Set();
        var link = document.createElement('link');
        link.sizes = object['sizes'];

        for (var i = 0; i < link.sizes.length; ++i)
          set.add(link.sizes.item(i).toLowerCase());

        if (set.size != 0)
          icon.sizes = set;
      }

      icons.push(icon);
    });

    return icons;
  }

  function _parseRelatedApplications() {
    var property = 'related_applications';
    var applications = [];

    if (!(property in _json_input))
      return applications;

    if (!Array.isArray(_json_input[property])) {
      _logs.push('ERROR: "' + property + '" expected to be an array but is not.');
      return applications;
    }

    _json_input[property].forEach(function(object) {
      var application = {};
      application.platform = _parseString({ object: object,
                                            property: 'platform',
                                            trim: true });
      application.id = _parseString({ object: object,
                                      property: 'id',
                                      trim: true });
      // TODO: pass manfiest url as base.
      application.url = _parseURL({ object: object, property: 'url' });
      applications.push(application);
    });

    return applications;
  }

  function _parsePreferRelatedApplications() {
    return _parseBoolean({ object: _json_input,
                           property: 'prefer_related_applications',
                           defaultValue: false });
  }

  function _parseThemeColor() {
    return _parseColor({ object: _json_input, property: 'theme_color' });
  }

  function _parseBackgroundColor() {
    return _parseColor({ object: _json_input, property: 'background_color' });
  }

  function _parse(string) {
    // TODO: temporary while ManifestParser is a collection of static methods.
    _logs = [];

    try {
      _json_input = JSON.parse(string);
    } catch (e) {
      _logs.push("File isn't valid JSON: " + e);
      _success = false;
      return;
    }

    _logs.push("JSON parsed successfuly.");

    _manifest.name = _parseName();
    _manifest.short_name = _parseShortName();
    _manifest.start_url= _parseStartUrl();
    _manifest.display = _parseDisplay();
    _manifest.orientation = _parseOrientation();
    _manifest.icons = _parseIcons();
    _manifest.related_applications = _parseRelatedApplications();
    _manifest.prefer_related_applications = _parsePreferRelatedApplications();
    _manifest.theme_color = _parseThemeColor();
    _manifest.background_color = _parseBackgroundColor();

    _logs.push('Parsed `name` property is: ' + _manifest.name);
    _logs.push('Parsed `short_name` property is: ' + _manifest.short_name);
    _logs.push('Parsed `start_url` property is: ' + _manifest.start_url);
    _logs.push('Parsed `display` property is: ' + _manifest.display);
    _logs.push('Parsed `orientation` property is: ' + _manifest.orientation);
    _logs.push('Parsed `icons` property is: ' + _manifest.icons);
    _logs.push('Parsed `related_applications` property is: ' + _manifest.related_applications);
    _logs.push('Parsed `prefer_related_applications` property is: ' + _manifest.prefer_related_applications);
    _logs.push('Parsed `theme_color` property is: ' + _manifest.theme_color);
    _logs.push('Parsed `background_color` property is: ' + _manifest.background_color);
  }

  return {
    parse: _parse,
    manifest: function() { return _manifest; },
    logs: function() { return _logs; },
    success: function() { return _success; }
  };
})();
<commit_msg>Reset success value before each run.<commit_after>"use strict";

var ManifestParser = (function() {

  var _json_input = {};
  var _manifest = {};
  var _logs = [];
  var _success = true;

  var ALLOWED_DISPLAY_VALUES = [ 'fullscreen',
                                 'standalone',
                                 'minimal-ui',
                                 'browser' ];

  var ALLOWED_ORIENTATION_VALUES = [ 'any',
                                     'natural',
                                     'landscape',
                                     'portrait',
                                     'portrait-primary',
                                     'portrait-secondary',
                                     'landscape-primary',
                                     'landscape-secondary' ];

  function _parseString(args) {
    var object = args.object;
    var property = args.property;
    if (!(property in object))
      return undefined;

    if (typeof object[property] != 'string') {
      _logs.push('ERROR: "' + property + '" expected to be a string but is not.');
      return undefined;
    }

    if (args.trim)
      return object[property].trim();
    return object[property];
  }

  function _parseBoolean(args) {
    var object = args.object;
    var property = args.property;
    var defaultValue = args.defaultValue;
    if (!(property in object))
      return defaultValue;

    if (typeof object[property] != 'boolean') {
      _logs.push('ERROR: "' + property + '" expected to be a boolean but is not.');
      return defaultValue;
    }

    return object[property];
  }

  function _parseURL(args) {
    var object = args.object;
    var property = args.property;
    var baseURL = args.baseURL;

    var str = _parseString({ object: object, property: property, trim: false });
    if (str === undefined)
      return undefined;

    // TODO: resolve url using baseURL
    // new URL(object[property], baseURL);
    return object[property];
  }

  function _parseColor(args) {
    var object = args.object;
    var property = args.property;
    if (!(property in object))
      return undefined;

    if (typeof object[property] != 'string') {
      _logs.push('ERROR: "' + property + '" expected to be a string but is not.');
      return undefined;
    }

    // If style.color changes when set to the given color, it is valid. Testing
    // against 'white' and 'black' in case of the given color is one of them.
    var dummy = document.createElement('div');
    dummy.style.color = 'white';
    dummy.style.color = object[property];
    if (dummy.style.color != 'white')
      return object[property];
    dummy.style.color = 'black';
    dummy.style.color = object[property];
    if (dummy.style.color != 'black')
      return object[property];
    return undefined;
  }

  function _parseName() {
    return _parseString({ object: _json_input, property: 'name', trim: true });
  }

  function _parseShortName() {
    return _parseString({ object: _json_input,
                          property: 'short_name',
                          trim: true });
  }

  function _parseStartUrl() {
    // TODO: parse url using manifest_url as a base (missing).
    return _parseURL({ object: _json_input, property: 'start_url' });
  }

  function _parseDisplay() {
    var display = _parseString({ object: _json_input,
                                 property: 'display',
                                 trim: true });
    if (display === undefined)
      return display;

    if (ALLOWED_DISPLAY_VALUES.indexOf(display.toLowerCase()) == -1) {
      _logs.push('ERROR: "display" has an invalid value, will be ignored.');
      return undefined;
    }

    return display;
  }

  function _parseOrientation() {
    var orientation = _parseString({ object: _json_input,
                                     property: 'orientation',
                                     trim: true });
    if (orientation === undefined)
      return orientation;

    if (ALLOWED_ORIENTATION_VALUES.indexOf(orientation.toLowerCase()) == -1) {
      _logs.push('ERROR: "orientation" has an invalid value, will be ignored.');
      return undefined;
    }

    return orientation;
  }

  function _parseIcons() {
    var property = 'icons';
    var icons = [];

    if (!(property in _json_input))
      return icons;

    if (!Array.isArray(_json_input[property])) {
      _logs.push('ERROR: "' + property + '" expected to be an array but is not.');
      return icons;
    }

    _json_input[property].forEach(function(object) {
      var icon = {};
      if (!('src' in object))
        return;
      // TODO: pass manifest url as base.
      icon.src = _parseURL({ object: object, property: 'src' });
      icon.type = _parseString({ object: object,
                                 property: 'type',
                                 trim: true });

      icon.density = parseFloat(object['density']);
      if (isNaN(icon.density) || !isFinite(icon.density) || icon.density <= 0)
        icon.density = 1.0;

      if ('sizes' in object) {
        var set = new Set();
        var link = document.createElement('link');
        link.sizes = object['sizes'];

        for (var i = 0; i < link.sizes.length; ++i)
          set.add(link.sizes.item(i).toLowerCase());

        if (set.size != 0)
          icon.sizes = set;
      }

      icons.push(icon);
    });

    return icons;
  }

  function _parseRelatedApplications() {
    var property = 'related_applications';
    var applications = [];

    if (!(property in _json_input))
      return applications;

    if (!Array.isArray(_json_input[property])) {
      _logs.push('ERROR: "' + property + '" expected to be an array but is not.');
      return applications;
    }

    _json_input[property].forEach(function(object) {
      var application = {};
      application.platform = _parseString({ object: object,
                                            property: 'platform',
                                            trim: true });
      application.id = _parseString({ object: object,
                                      property: 'id',
                                      trim: true });
      // TODO: pass manfiest url as base.
      application.url = _parseURL({ object: object, property: 'url' });
      applications.push(application);
    });

    return applications;
  }

  function _parsePreferRelatedApplications() {
    return _parseBoolean({ object: _json_input,
                           property: 'prefer_related_applications',
                           defaultValue: false });
  }

  function _parseThemeColor() {
    return _parseColor({ object: _json_input, property: 'theme_color' });
  }

  function _parseBackgroundColor() {
    return _parseColor({ object: _json_input, property: 'background_color' });
  }

  function _parse(string) {
    // TODO: temporary while ManifestParser is a collection of static methods.
    _logs = [];
    _success = true;

    try {
      _json_input = JSON.parse(string);
    } catch (e) {
      _logs.push("File isn't valid JSON: " + e);
      _success = false;
      return;
    }

    _logs.push("JSON parsed successfuly.");

    _manifest.name = _parseName();
    _manifest.short_name = _parseShortName();
    _manifest.start_url= _parseStartUrl();
    _manifest.display = _parseDisplay();
    _manifest.orientation = _parseOrientation();
    _manifest.icons = _parseIcons();
    _manifest.related_applications = _parseRelatedApplications();
    _manifest.prefer_related_applications = _parsePreferRelatedApplications();
    _manifest.theme_color = _parseThemeColor();
    _manifest.background_color = _parseBackgroundColor();

    _logs.push('Parsed `name` property is: ' + _manifest.name);
    _logs.push('Parsed `short_name` property is: ' + _manifest.short_name);
    _logs.push('Parsed `start_url` property is: ' + _manifest.start_url);
    _logs.push('Parsed `display` property is: ' + _manifest.display);
    _logs.push('Parsed `orientation` property is: ' + _manifest.orientation);
    _logs.push('Parsed `icons` property is: ' + _manifest.icons);
    _logs.push('Parsed `related_applications` property is: ' + _manifest.related_applications);
    _logs.push('Parsed `prefer_related_applications` property is: ' + _manifest.prefer_related_applications);
    _logs.push('Parsed `theme_color` property is: ' + _manifest.theme_color);
    _logs.push('Parsed `background_color` property is: ' + _manifest.background_color);
  }

  return {
    parse: _parse,
    manifest: function() { return _manifest; },
    logs: function() { return _logs; },
    success: function() { return _success; }
  };
})();
<|endoftext|>


<commit_before>// Atm this is too complex to warrant this style

var Roller = function() {

}

Roller.protoype.roll = function(dNum, dSides) {
	var total = 0,
	i = 0;
	while(total < 12) {
		for(i; i < dNum; i += 1) {
			total = total + Math.floor(Math.random()*dSides) + 1;
			console.log('current roll ' + total);
		}

		return total;
	}
}

module.exports.roller = new Roller();
<commit_msg>Useless file, missed it when prepping for the push<commit_after><|endoftext|>