<commit_before>// Copyright 2013-2019, University of Colorado Boulder

/**
 * Convenience type for creating a vertical group of AquaRadioButtons.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const AquaRadioButton = require( 'SUN/AquaRadioButton' );
  const HStrut = require( 'SCENERY/nodes/HStrut' );
  const merge = require( 'PHET_CORE/merge' );
  const Node = require( 'SCENERY/nodes/Node' );
  const radioButtonSoundPlayerFactory = require( 'TAMBO/radioButtonSoundPlayerFactory' );
  const sun = require( 'SUN/sun' );
  const Tandem = require( 'TANDEM/Tandem' );
  const VBox = require( 'SCENERY/nodes/VBox' );

  // a11y - An id for each instance of VerticalAquaRadioButtonGroup, passed to individual buttons in the group.
  // Each button in a radio button group must have the same "name" attribute to be considered in a group, otherwise
  // arrow keys will navigate all radio type inputs in the document.
  let instanceCount = 0;

  // constants
  // to prefix instanceCount in case there are different kinds of "groups"
  const CLASS_NAME = 'VerticalAquaRadioButtonGroup';

  class VerticalAquaRadioButtonGroup extends VBox {
    /**
     * @param {Property} property
     * @param {Object[]} items - Each item describes a radio button, and is an object with these properties:
     *    node: Node, // label for the button
     *    value: *, // value associated with the button
     *    [tandemName: Tandem], // optional tandem for PhET-iO
     *    [labelContent: string] // optional label for a11y
     * @param {Object} [options]
     * @constructor
     */
    constructor( property, items, options ) {

      instanceCount++;

      options = merge( {

        // {Object|null} options passed to constructor of the AquaRadioButtons
        radioButtonOptions: null,

        // dilation of pointer areas for each radio button, y dimension is computed
        touchAreaXDilation: 0,
        mouseAreaXDilation: 0,

        // supertype options
        spacing: 3, // vertical space between each button
        tandem: Tandem.required,

        // supertype a11y options
        tagName: 'ul',
        groupFocusHighlight: true

      }, options );

      // Determine the max item width
      let maxItemWidth = 0;
      for ( let i = 0; i < items.length; i++ ) {
        maxItemWidth = Math.max( maxItemWidth, items[ i ].node.width );
      }

      // Create a radio button for each item
      const radioButtons = [];
      for ( let i = 0; i < items.length; i++ ) {

        const item = items[ i ];

        // Content for the radio button. Add an invisible strut, so that buttons have uniform width.
        const content = new Node( {
          children: [ new HStrut( maxItemWidth ), item.node ]
        } );

        const radioButton = new AquaRadioButton( property, item.value, content,
          merge( {}, options.radioButtonOptions, {
            tandem: item.tandemName ? options.tandem.createTandem( item.tandemName ) : Tandem.required,
            labelContent: item.labelContent || null,
            soundPlayer: radioButtonSoundPlayerFactory.getRadioButtonSoundPlayer( i ),
            a11yNameAttribute: CLASS_NAME + instanceCount
          } ) );

        // set pointer areas, y dimensions are computed
        const yDilation = options.spacing / 2;
        radioButton.mouseArea = radioButton.localBounds.dilatedXY( options.mouseAreaXDilation, yDilation );
        radioButton.touchArea = radioButton.localBounds.dilatedXY( options.touchAreaXDilation, yDilation );

        radioButtons.push( radioButton );
      }

      // Verify that the client hasn't set options that we will be overwriting.
      assert && assert( !options.children, 'VerticalAquaRadioButtonGroup sets children' );
      options.children = radioButtons;

      super( options );

      // @private
      this.disposeVerticalAquaRadioButtonGroup = () => {
        for ( let i = 0; i < radioButtons.length; i++ ) {
          radioButtons[ i ].dispose();
        }
      };
    }

    /**
     * @public
     * @override
     */
    dispose() {
      this.disposeVerticalAquaRadioButtonGroup();
      super.dispose();
    }
  }

  return sun.register( 'VerticalAquaRadioButtonGroup', VerticalAquaRadioButtonGroup );
} );
<commit_msg>add // phet-io<commit_after>// Copyright 2013-2019, University of Colorado Boulder

/**
 * Convenience type for creating a vertical group of AquaRadioButtons.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const AquaRadioButton = require( 'SUN/AquaRadioButton' );
  const HStrut = require( 'SCENERY/nodes/HStrut' );
  const merge = require( 'PHET_CORE/merge' );
  const Node = require( 'SCENERY/nodes/Node' );
  const radioButtonSoundPlayerFactory = require( 'TAMBO/radioButtonSoundPlayerFactory' );
  const sun = require( 'SUN/sun' );
  const Tandem = require( 'TANDEM/Tandem' );
  const VBox = require( 'SCENERY/nodes/VBox' );

  // a11y - An id for each instance of VerticalAquaRadioButtonGroup, passed to individual buttons in the group.
  // Each button in a radio button group must have the same "name" attribute to be considered in a group, otherwise
  // arrow keys will navigate all radio type inputs in the document.
  let instanceCount = 0;

  // constants
  // to prefix instanceCount in case there are different kinds of "groups"
  const CLASS_NAME = 'VerticalAquaRadioButtonGroup';

  class VerticalAquaRadioButtonGroup extends VBox {
    /**
     * @param {Property} property
     * @param {Object[]} items - Each item describes a radio button, and is an object with these properties:
     *    node: Node, // label for the button
     *    value: *, // value associated with the button
     *    [tandemName: Tandem], // optional tandem for PhET-iO
     *    [labelContent: string] // optional label for a11y
     * @param {Object} [options]
     * @constructor
     */
    constructor( property, items, options ) {

      instanceCount++;

      options = merge( {

        // {Object|null} options passed to constructor of the AquaRadioButtons
        radioButtonOptions: null,

        // dilation of pointer areas for each radio button, y dimension is computed
        touchAreaXDilation: 0,
        mouseAreaXDilation: 0,

        // supertype options
        spacing: 3, // vertical space between each button

        // phet-io
        tandem: Tandem.required,

        // supertype a11y options
        tagName: 'ul',
        groupFocusHighlight: true

      }, options );

      // Determine the max item width
      let maxItemWidth = 0;
      for ( let i = 0; i < items.length; i++ ) {
        maxItemWidth = Math.max( maxItemWidth, items[ i ].node.width );
      }

      // Create a radio button for each item
      const radioButtons = [];
      for ( let i = 0; i < items.length; i++ ) {

        const item = items[ i ];

        // Content for the radio button. Add an invisible strut, so that buttons have uniform width.
        const content = new Node( {
          children: [ new HStrut( maxItemWidth ), item.node ]
        } );

        const radioButton = new AquaRadioButton( property, item.value, content,
          merge( {}, options.radioButtonOptions, {
            tandem: item.tandemName ? options.tandem.createTandem( item.tandemName ) : Tandem.required,
            labelContent: item.labelContent || null,
            soundPlayer: radioButtonSoundPlayerFactory.getRadioButtonSoundPlayer( i ),
            a11yNameAttribute: CLASS_NAME + instanceCount
          } ) );

        // set pointer areas, y dimensions are computed
        const yDilation = options.spacing / 2;
        radioButton.mouseArea = radioButton.localBounds.dilatedXY( options.mouseAreaXDilation, yDilation );
        radioButton.touchArea = radioButton.localBounds.dilatedXY( options.touchAreaXDilation, yDilation );

        radioButtons.push( radioButton );
      }

      // Verify that the client hasn't set options that we will be overwriting.
      assert && assert( !options.children, 'VerticalAquaRadioButtonGroup sets children' );
      options.children = radioButtons;

      super( options );

      // @private
      this.disposeVerticalAquaRadioButtonGroup = () => {
        for ( let i = 0; i < radioButtons.length; i++ ) {
          radioButtons[ i ].dispose();
        }
      };
    }

    /**
     * @public
     * @override
     */
    dispose() {
      this.disposeVerticalAquaRadioButtonGroup();
      super.dispose();
    }
  }

  return sun.register( 'VerticalAquaRadioButtonGroup', VerticalAquaRadioButtonGroup );
} );
<|endoftext|>


<commit_before>import React from "react";
import {
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  Button,
  StatusBar,
  Platform,
  Alert
} from "react-native";
import { Permissions } from "expo";
//import { MapView } from "expo";
import { NavigationActions } from "react-navigation";
import { lightpurple, darkpurple, pink } from "./colors.js";
import { Feather } from '@expo/vector-icons';
import MapViewDirections from 'react-native-maps-directions';

import  MapView, {Polyline} from 'react-native-maps';

// This triggers asking the user for location permissions.
// This won't do anything if the permission is already granted.
Permissions.askAsync(Permissions.LOCATION);

// Note: For all intents and purposes, "mural key" is the same as "mural id".
// But "mural index" does not refer to either of those things, it only refers
// to a mural's order in the tour.
export default class ExplorePage extends React.Component {
    constructor(props) {
        super(props);
        self = this;

        // Where we will store the refs to all the markers
        // This is necessary because showing and hiding a callout must be done imperatively.
        this.markers = {}

      this.tourNext = this.tourNext.bind(this);
 }

  static navigationOptions = ({ navigation}) => {
    return Platform.OS === "ios"
      ? {
          headerLeft: (
            <TouchableOpacity
              style={{ top: 30, left: -25, padding: 40 }}
              onPress={() => {navigation.dispatch(NavigationActions.back())}}
            >
              <View
                style={{
                  position: "relative",
                  flexDirection: "row",
                  backgroundColor: 'white',
                  zIndex: 100,
                  marginTop: -15,
                  width: 120,
                  height: 40,
                  borderRadius: 100,
                  alignItems: 'center',
                  justifyContent: 'center',
                  paddingRight: 6,
                  shadowOffset: { width: 1, height: 1 },
                  shadowRadius: 2,
                  shadowOpacity: 0.6,
                }}
              >
                <Feather name="chevron-left" size={25} color={pink} style={{marginBottom: 1}}/>
                <Text style={{fontWeight: 'bold', fontSize: 17, color: pink}}>  Back </Text>
              </View>
            </TouchableOpacity>
          ),
          headerStyle: {
            position: "absolute",
            backgroundColor: "transparent",
            zIndex: 100,
            top: 0,
            left: 0,
            right: 0,
            borderBottomColor: "transparent"
          }
        }
      : {
          title: "Punto Urban Art",
          headerTintColor: "white",
          headerStyle: { backgroundColor: pink }
        };
  }

  // Returns true if we came from the gallery's mural info page ("see mural on map" button)
  didComeFromGallery() {
    return (this.props.navigation.state.params && this.props.navigation.state.params.muralID);
  }

  // Logic for determining which mural should currently be shown to the user.
  // If we came from the gallery -> mural info page, show that mural.
  // If we're on a tour, show the mural of the index we're currently at
  // Otherwise return undefined.
  currentMuralID() {
    if (this.didComeFromGallery()) {
      return this.props.navigation.state.params.muralID;
    }
    else if (this.props.screenProps.tourStarted) {
      currMarkerIndex = this.props.screenProps.currMarker
      murals = this.props.screenProps.murals || {};

      for (muralKey in murals) {
        if (murals[muralKey]["Index"] == currMarkerIndex) {
          return muralKey;
        }
      }
    }

    return undefined;

  }

  renderMarkers() {
    const { navigate } = this.props.navigation;

    murals = this.props.screenProps.murals || {};
    artists = this.props.screenProps.artists || {};

    defaultMuralID = '';
    if (this.props.navigation.state.params && this.props.navigation.state.params.muralID) {
      defaultMuralID = this.props.navigation.state.params.muralID;
    }

    return Object.keys(murals).map((key, i) => {
      lat = parseFloat(murals[key]["Lat"]);
      long = parseFloat(murals[key]["Long"]);
      title = murals[key]["Title"];
      artistName = artists[murals[key]["Artist"]]["name"];

      return (
        <MapView.Marker
          key={i}
          title={title}
          description={artistName}
          coordinate={{ latitude: lat, longitude: long }}
          pinColor={pink}
          ref = {(ref) => this.markers[key] = ref}
          onCalloutPress={() => {
            navigate("MuralInfoPage", {
              mural: murals[key],
              artist: artists[murals[key]["Artist"]]
            });
          }}
        />
      );
    });

  }

  goToMural() {
    murals = this.props.screenProps.murals || {};

      if (this.markers && this.currentMuralID()) {

        // Note: we must delay showing the callout because it should only happen
        // AFTER we animate to the region for that callout.
        // This prevents an animation bug in which we showed the callout while
        // the map was still animating to the region.

        // TODO: use constants to determine the delay amount. Here we use 1500
        // because it is the sum of the map's animation delays (500ms before
        // animating, animate moving to new region for 1000ms).

        setTimeout(function () {
          this.markers[this.currentMuralID()].showCallout();
        }.bind(this), 1500);

      }
  }

    toggleTour() {

      console.log("start button pressed");

      // If we're ending a tour, hide any callouts that may be still visible.
      murals = this.props.screenProps.murals || {};
      if (this.props.screenProps.tourStarted){
        Object.keys(murals).map((key,i) =>{
          this.markers[key].hideCallout();
        });
      }

      this.props.screenProps.tourState()

    }

    tourNext () {

        this.props.screenProps.changeMarker();
        if( this.props.screenProps.currMarker == Object.keys(this.props.screenProps.murals).length - 1){
            this.toggleTour();
        }

    }

    tourPrev() {
      if(this.props.screenProps.currMarker == 1){
        return;
      }
      else{
        this.props.screenProps.changeMarkerPrev();
      }
    }

    render() {
        const { navigate } = this.props.navigation;
        initialLat = 42.518217;
        initialLong = -70.891919;
        initialDelta = 0.005;

        initialRegion = {
            longitude: initialLong,
            latitude: initialLat,
            latitudeDelta: initialDelta,
            longitudeDelta: initialDelta
        };

        region = undefined;
        murals = this.props.screenProps.murals || {};

        if (this.currentMuralID()) {
          mural = murals[this.currentMuralID()];
          region = {
            longitude: mural["Long"],
            latitude: mural["Lat"],
            longitudeDelta: .001,
            latitudeDelta: .001
          };
        }
        else {
          region = initialRegion
        }

        console.log("326", region)

        return (
            <View style = {{flex: 1}}>
            <StatusBar barStyle = { Platform.OS === 'ios' ? "dark-content" : "light-content"}/>
            <AnimatedMapView
              style = {{flex: 1 }}
              showsPointsOfInterest={false}
              showsUserLocation={true}
              initialRegion = {initialRegion}
              region =  {region}
              onLayout = {this.goToMural.bind(this)}
               >
              {this.renderMarkers()}

            </AnimatedMapView>
            {console.log(this.props.screenProps.tourStarted)}
          {this.props.screenProps.tourStarted ?
            <View>
             <Button
            title="prev"
            onPress={()=>this.tourPrev()}
            >  </Button>
             <Button
            title="next"
            onPress = {()=>this.tourNext()} >
            </Button>
            <Button
            title="end tour"
            onPress={()=>this.toggleTour()}
            >  </Button>
            </View>
            : this.didComeFromGallery() ?
            <View></View> :
            <Button
            title="start tour"
            onPress={()=>this.toggleTour()}>
            </Button>  }
          </View>
        );
    }

}

/*****************************************************************************/

// Just a MapView but it animates to region if the region prop changes!
class AnimatedMapView extends React.Component {

    shouldComponentUpdate(nextProps, nextState) {
        console.log("408")

        // Only animate to the region if the region is different
        if (this.props.region !== nextProps.region) {
          this.goToRegion(nextProps.region, nextProps.onLayout);
        }

        return false;
    }

    // Note: onLayout (which gets passed in as a prop) is called afterwards so
    // that the parent component has a way to hook into onLayout.
    // But TBH im not sure if this is the right way to do this lol.
    goToRegion(region, onLayout) {
        if (region) {
            console.log("415")
            setTimeout(function () {
                this.map.animateToRegion(region, 1000);
            }.bind(this), 500);
        }

        if (onLayout) {
            onLayout();
        }
    }

    render() {
        var {initialRegion, region, children, onLayout, ...otherProps} = this.props;

        // Avoid a weird animation from initialRegion to region if theyre the same
        if (region === initialRegion) {
          region = undefined;
        }

        return (
            <MapView
                onLayout={this.goToRegion.bind(this, region, onLayout)}
                initialRegion =  {initialRegion}
                ref =  {r => {this.map = r}}
                {...otherProps}>
                {children}
            </MapView>
        )
    }

}

<commit_msg>prettier buttons for tour<commit_after>import React from "react";
import {
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  Button,
  StatusBar,
  Platform,
  Alert
} from "react-native";
import { Permissions } from "expo";
//import { MapView } from "expo";
import { NavigationActions } from "react-navigation";
import { lightpurple, darkpurple, pink } from "./colors.js";
import { Feather } from '@expo/vector-icons';
import MapViewDirections from 'react-native-maps-directions';

import  MapView, {Polyline} from 'react-native-maps';

// This triggers asking the user for location permissions.
// This won't do anything if the permission is already granted.
Permissions.askAsync(Permissions.LOCATION);

// Note: For all intents and purposes, "mural key" is the same as "mural id".
// But "mural index" does not refer to either of those things, it only refers
// to a mural's order in the tour.
export default class ExplorePage extends React.Component {
    constructor(props) {
        super(props);
        self = this;

        // Where we will store the refs to all the markers
        // This is necessary because showing and hiding a callout must be done imperatively.
        this.markers = {}

      this.tourNext = this.tourNext.bind(this);
 }

  static navigationOptions = ({ navigation}) => {
    return Platform.OS === "ios"
      ? {
          headerLeft: (
            <TouchableOpacity
              style={{ top: 30, left: -25, padding: 40 }}
              onPress={() => {navigation.dispatch(NavigationActions.back())}}
            >
              <View
                style={{
                  position: "relative",
                  flexDirection: "row",
                  backgroundColor: 'white',
                  zIndex: 100,
                  marginTop: -15,
                  width: 120,
                  height: 40,
                  borderRadius: 100,
                  alignItems: 'center',
                  justifyContent: 'center',
                  paddingRight: 6,
                  shadowOffset: { width: 1, height: 1 },
                  shadowRadius: 2,
                  shadowOpacity: 0.6,
                }}
              >
                <Feather name="chevron-left" size={25} color={pink} style={{marginBottom: 1}}/>
                <Text style={{fontWeight: 'bold', fontSize: 17, color: pink}}>  Back </Text>
              </View>
            </TouchableOpacity>
          ),
          headerStyle: {
            position: "absolute",
            backgroundColor: "transparent",
            zIndex: 100,
            top: 0,
            left: 0,
            right: 0,
            borderBottomColor: "transparent"
          }
        }
      : {
          title: "Punto Urban Art",
          headerTintColor: "white",
          headerStyle: { backgroundColor: pink }
        };
  }

  // Returns true if we came from the gallery's mural info page ("see mural on map" button)
  didComeFromGallery() {
    return (this.props.navigation.state.params && this.props.navigation.state.params.muralID);
  }

  // Logic for determining which mural should currently be shown to the user.
  // If we came from the gallery -> mural info page, show that mural.
  // If we're on a tour, show the mural of the index we're currently at
  // Otherwise return undefined.
  currentMuralID() {
    if (this.didComeFromGallery()) {
      return this.props.navigation.state.params.muralID;
    }
    else if (this.props.screenProps.tourStarted) {
      currMarkerIndex = this.props.screenProps.currMarker
      murals = this.props.screenProps.murals || {};

      for (muralKey in murals) {
        if (murals[muralKey]["Index"] == currMarkerIndex) {
          return muralKey;
        }
      }
    }

    return undefined;

  }

  renderMarkers() {
    const { navigate } = this.props.navigation;

    murals = this.props.screenProps.murals || {};
    artists = this.props.screenProps.artists || {};

    defaultMuralID = '';
    if (this.props.navigation.state.params && this.props.navigation.state.params.muralID) {
      defaultMuralID = this.props.navigation.state.params.muralID;
    }

    return Object.keys(murals).map((key, i) => {
      lat = parseFloat(murals[key]["Lat"]);
      long = parseFloat(murals[key]["Long"]);
      title = murals[key]["Title"];
      artistName = artists[murals[key]["Artist"]]["name"];

      return (
        <MapView.Marker
          key={i}
          title={title}
          description={artistName}
          coordinate={{ latitude: lat, longitude: long }}
          pinColor={pink}
          ref = {(ref) => this.markers[key] = ref}
          onCalloutPress={() => {
            navigate("MuralInfoPage", {
              mural: murals[key],
              artist: artists[murals[key]["Artist"]]
            });
          }}
        />
      );
    });

  }

  goToMural() {
    murals = this.props.screenProps.murals || {};

      if (this.markers && this.currentMuralID()) {

        // Note: we must delay showing the callout because it should only happen
        // AFTER we animate to the region for that callout.
        // This prevents an animation bug in which we showed the callout while
        // the map was still animating to the region.

        // TODO: use constants to determine the delay amount. Here we use 1500
        // because it is the sum of the map's animation delays (500ms before
        // animating, animate moving to new region for 1000ms).

        setTimeout(function () {
          this.markers[this.currentMuralID()].showCallout();
        }.bind(this), 1500);

      }
  }

    toggleTour() {

      console.log("start button pressed");

      // If we're ending a tour, hide any callouts that may be still visible.
      murals = this.props.screenProps.murals || {};
      if (this.props.screenProps.tourStarted){
        Object.keys(murals).map((key,i) =>{
          this.markers[key].hideCallout();
        });
      }

      this.props.screenProps.tourState()

    }

    tourNext () {

        this.props.screenProps.changeMarker();
        if( this.props.screenProps.currMarker == Object.keys(this.props.screenProps.murals).length - 1){
            this.toggleTour();
        }

    }

    tourPrev() {
      if(this.props.screenProps.currMarker == 1){
        return;
      }
      else{
        this.props.screenProps.changeMarkerPrev();
      }
    }

    render() {
        const { navigate } = this.props.navigation;
        initialLat = 42.518217;
        initialLong = -70.891919;
        initialDelta = 0.005;

        initialRegion = {
            longitude: initialLong,
            latitude: initialLat,
            latitudeDelta: initialDelta,
            longitudeDelta: initialDelta
        };

        region = undefined;
        murals = this.props.screenProps.murals || {};

        if (this.currentMuralID()) {
          mural = murals[this.currentMuralID()];
          region = {
            longitude: mural["Long"],
            latitude: mural["Lat"],
            longitudeDelta: .001,
            latitudeDelta: .001
          };
        }
        else {
          region = initialRegion
        }

        console.log("326", region)

        return (
            <View style = {{flex: 1}}>
            <StatusBar barStyle = { Platform.OS === 'ios' ? "dark-content" : "light-content"}/>
            <AnimatedMapView
              style = {{flex: 1 }}
              showsPointsOfInterest={false}
              showsUserLocation={true}
              initialRegion = {initialRegion}
              region =  {region}
              onLayout = {this.goToMural.bind(this)}
               >
              {this.renderMarkers()}

            </AnimatedMapView>
            {console.log(this.props.screenProps.tourStarted)}
          {this.props.screenProps.tourStarted ?
            <View style = {style.buttonContainer}>
              <View style = {style.previousNextContainer}>
                <TouchableOpacity style= {style.button} onPress={() => this.tourPrev()}>
                  <Text style = {style.text}>Previous</Text>
                </TouchableOpacity>
                <TouchableOpacity style= {style.button} onPress={() => this.tourNext()}>
                  <Text style = {style.text}>Next</Text>
                </TouchableOpacity>
              </View>
              <TouchableOpacity style= {style.button} onPress={() => this.toggleTour()}>
                <Text style = {style.text}>End Tour</Text>
              </TouchableOpacity>
            </View>
            :
                this.didComeFromGallery() ? null :
                <View style = {style.buttonContainer}>
                  <TouchableOpacity style= {style.button} onPress={() => this.toggleTour()}>
                    <Text style = {style.text}>Start Tour</Text>
                  </TouchableOpacity>
                </View>

            }
          </View>
        );
    }
}

style = StyleSheet.create({
    text: {
      fontSize: 16,
      fontWeight: 'bold',
      color: pink,
    },
    buttonContainer: {
      flex: 1,
      flexDirection: "column",
      justifyContent: "flex-end",
      alignItems: "center",
      position: "absolute",
      width: "100%",
      height: "100%%"
    },
    previousNextContainer: {
      flexDirection: "row",
      justifyContent: "space-around",
    },
    button: {
      flexDirection: "row",
      backgroundColor: 'white',
      zIndex: 100,
      margin: 15,
      width: 120,
      height: 40,
      borderRadius: 100,
      alignItems: 'center',
      justifyContent: 'center',
      paddingRight: 6,
      shadowOffset: { width: 1, height: 1 },
      shadowRadius: 2,
      shadowOpacity: 0.6,
    }
});

/*****************************************************************************/

// Just a MapView but it animates to region if the region prop changes!
class AnimatedMapView extends React.Component {

    shouldComponentUpdate(nextProps, nextState) {
        console.log("408")

        // Only animate to the region if the region is different
        if (this.props.region !== nextProps.region) {
          this.goToRegion(nextProps.region, nextProps.onLayout);
        }

        return false;
    }

    // Note: onLayout (which gets passed in as a prop) is called afterwards so
    // that the parent component has a way to hook into onLayout.
    // But TBH im not sure if this is the right way to do this lol.
    goToRegion(region, onLayout) {
        if (region) {
            console.log("415")
            setTimeout(function () {
                this.map.animateToRegion(region, 1000);
            }.bind(this), 500);
        }

        if (onLayout) {
            onLayout();
        }
    }

    render() {
        var {initialRegion, region, children, onLayout, ...otherProps} = this.props;

        // Avoid a weird animation from initialRegion to region if theyre the same
        if (region === initialRegion) {
          region = undefined;
        }

        return (
            <MapView
                onLayout={this.goToRegion.bind(this, region, onLayout)}
                initialRegion =  {initialRegion}
                ref =  {r => {this.map = r}}
                {...otherProps}>
                {children}
            </MapView>
        )
    }

}

<|endoftext|>


<commit_before>frappe.provide("frappe.ui");

frappe.ui.Scanner = class Scanner {
	constructor(options) {
		this.dialog = null;
		this.handler = null;
		this.options = options;
		this.is_alive = false;

		if (!("multiple" in this.options)) {
			this.options.multiple = false;
		}
		if (options.container) {
			this.$scan_area = $(options.container);
			this.scan_area_id = frappe.dom.set_unique_id(this.$scan_area);
		}
		if (options.dialog) {
			this.dialog = this.make_dialog();
			this.dialog.show();
		}
	}

	scan() {
		this.load_lib().then(() => this.start_scan());
	}

	start_scan() {
		if (!this.handler) {
			this.handler = new Html5Qrcode(this.scan_area_id);
		}
		this.handler
			.start(
				{ facingMode: "environment" },
				{ fps: 10, qrbox: 250 },
				(decodedText, decodedResult) => {
					if (this.options.on_scan) {
						this.options.on_scan(decodedResult);
					}
					if (!this.options.multiple) {
						this.stop_scan();
						this.hide_dialog();
					}
				},
				errorMessage => {
					// parse error, ignore it.
				}
			)
			.catch(err => {
				this.is_alive = false;
				console.error(err);
			});
		this.is_alive = true;
	}

	stop_scan() {
		if (this.handler && this.is_alive) {
			this.handler.stop().then(() => {
				this.is_alive = false;
				this.$scan_area.empty();
				this.hide_dialog();
			});
		}
	}

	make_dialog() {
		let dialog = new frappe.ui.Dialog({
			title: __("Scan QRCode"),
			fields: [
				{
					fieldtype: "HTML",
					fieldname: "scan_area"
				}
			],
			on_page_show: () => {
				this.$scan_area = dialog.get_field("scan_area").$wrapper;
				this.$scan_area.addClass("barcode-scanner");
				this.scan_area_id = frappe.dom.set_unique_id(this.$scan_area);
				this.scan();
			},
			on_hide: () => {
				this.stop_scan();
			}
		});
		return dialog;
	}

	hide_dialog() {
		this.dialog && this.dialog.hide();
	}

	load_lib() {
		return frappe.require(
			"/assets/frappe/node_modules/html5-qrcode/dist/html5-qrcode.min.js"
		);
	}
};
<commit_msg>feat: handle exceptions on scan<commit_after>frappe.provide("frappe.ui");

frappe.ui.Scanner = class Scanner {
	constructor(options) {
		this.dialog = null;
		this.handler = null;
		this.options = options;
		this.is_alive = false;

		if (!("multiple" in this.options)) {
			this.options.multiple = false;
		}
		if (options.container) {
			this.$scan_area = $(options.container);
			this.scan_area_id = frappe.dom.set_unique_id(this.$scan_area);
		}
		if (options.dialog) {
			this.dialog = this.make_dialog();
			this.dialog.show();
		}
	}

	scan() {
		this.load_lib().then(() => this.start_scan());
	}

	start_scan() {
		if (!this.handler) {
			this.handler = new Html5Qrcode(this.scan_area_id);
		}
		this.handler
			.start(
				{ facingMode: "environment" },
				{ fps: 10, qrbox: 250 },
				(decodedText, decodedResult) => {
					if (this.options.on_scan) {
						try {
							this.options.on_scan(decodedResult);
						} catch (error) {
							console.error(error);
						}
					}
					if (!this.options.multiple) {
						this.stop_scan();
						this.hide_dialog();
					}
				},
				errorMessage => {
					// parse error, ignore it.
				}
			)
			.catch(err => {
				this.is_alive = false;
				console.error(err);
			});
		this.is_alive = true;
	}

	stop_scan() {
		if (this.handler && this.is_alive) {
			this.handler.stop().then(() => {
				this.is_alive = false;
				this.$scan_area.empty();
				this.hide_dialog();
			});
		}
	}

	make_dialog() {
		let dialog = new frappe.ui.Dialog({
			title: __("Scan QRCode"),
			fields: [
				{
					fieldtype: "HTML",
					fieldname: "scan_area"
				}
			],
			on_page_show: () => {
				this.$scan_area = dialog.get_field("scan_area").$wrapper;
				this.$scan_area.addClass("barcode-scanner");
				this.scan_area_id = frappe.dom.set_unique_id(this.$scan_area);
				this.scan();
			},
			on_hide: () => {
				this.stop_scan();
			}
		});
		return dialog;
	}

	hide_dialog() {
		this.dialog && this.dialog.hide();
	}

	load_lib() {
		return frappe.require(
			"/assets/frappe/node_modules/html5-qrcode/dist/html5-qrcode.min.js"
		);
	}
};
<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch';

export function deleteItem(data) {
    return fetch('/producto', {
        method: 'DELETE',
        mode: 'CORS',
        body: JSON.stringify(data),
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(res => {
        return res;
    }).catch(err => err);
}<commit_msg>Delete<commit_after>import fetch from 'isomorphic-fetch';

export function deleteItem(data) {
    return fetch('/producto/' + data.id, {
        method: 'DELETE',
        mode: 'CORS',
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(res => {
        return res;
    }).catch(err => err);
}<|endoftext|>


<commit_before>/*   RSence
 *   Copyright 2009 Riassence Inc.
 *   http://riassence.com/
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this software package. If not, contact licensing@riassence.com
 */

/*** = Description
  ** Implements the client-server interface.
  **
  ** COMM.Transporter manages the client side of the server-client-server
  ** data synchronization and the server-client command channel.
  **
  ** It uses COMM.Session for session key handling, COMM.Queue for command
  ** queuing and COMM.Values for data value management.
  **
  ** COMM.Transporter operates in a fully automatic mode and starts when
  ** the document has been loaded.
  **
  ** Don't call any of its methods from your code.
***/
//var//RSence.COMM
COMM.Transporter = HApplication.extend({

/** Sets up the default settings upon construction.
  **/
  constructor: function(){
    var _this = this;
    this.serverLostMessage = 'Server Connection Lost: Reconnecting...';
    _this.label = 'Transporter';
    _this.url = false;
    _this.busy = false;
    _this.stop = true;
    _this._serverInterruptView = false;
    _this._clientEvalError = false;
    _this._busyFlushTimeout = false;
    _this.base(1);
  },

/** Tries to (re)connect to the server as often as possible,
  * mandated essentially by the priority of its
  * HApplication instance.
  **/
  onIdle: function(){
    this.sync();
  },

/** (Re)sets the priority of itself, effects how
  * frequently +onIdle+ is called.
  * Usually set by the server.
  **/
  poll: function(_pri){
    HSystem.reniceApp(this.appId,_pri);
  },

/** Returns the last transaction error of itself. Used by +sync+
  * to report js errors to the server.
  * If no error, returns an empty string.
  **/
  getClientEvalError: function(){
    var _this = COMM.Transporter;
    return _this._clientEvalError?'&err_msg=' +
           COMM.Values._encodeString(_this._clientEvalError):'';
  },

/** = Description
  * Handles synchronization responses.
  *
  * Upon a successful request, this method is called by
  * the onSuccess event of the XMLHttpRequest.
  *
  * It splits up the response string and passes the response
  * messages to COMM.Queue for execution.
  *
  * Parameters:
  * +resp+:: The response object.
  *
  **/
  success: function(resp){
    var _this = COMM.Transporter;
    if(!resp.X.responseText){
      _this.failure(resp);
      return;
    }
    var _responseArray = eval(resp.X.responseText),
        i = 1,
        _responseArrayLen = _responseArray.length,
        _sesKey = _responseArray[0],
        _session = COMM.Session,
        _queue = COMM.Queue;
    if(_sesKey === ''){
      console.log('Invalid session, error message should follow...');
    }
    else {
      _session.newKey(_sesKey);
    }
    for(;i<_responseArrayLen;i++){
      try {
        _queue.pushEval( _responseArray[i] );
      }
      catch(e) {
        console.log( 'clientError:'+e+" - "+e.description+' - '+_responseArray[i]);
        _this._clientEvalError = e+" - "+e.description+' - '+_responseArray[i];
      }
    }
    if(_this._serverInterruptView){
      _this._serverInterruptView.die();
      _this._serverInterruptView = false;
    }
    _queue.push( function(){COMM.Transporter.flushBusy();} );
    _queue.flush();
  },

/** Sets the +busy+ flag to false and resynchronizes immediately,
  * if COMM.Values contain any unsynchronized values.
  **/
  flushBusy: function(){
    var _this = COMM.Transporter;
    _this.busy = false;
    COMM.Values.tosync.length !== 0 && _this.sync();
  },
  failMessage: function(_title,_message){
    var _this = COMM.Transporter,
        _queue = COMM.Queue;
    console.log('failMessage?');
    _this.stop = true;
    _queue.push(function(){jsLoader.load('default_theme');});
    _queue.push(function(){jsLoader.load('controls');});
    _queue.push(function(){jsLoader.load('servermessage');});
    _queue.push(function(){ReloadApp.nu(_title,_message);});
  },

/** Called by the XMLHttpRequest, when there was a failure in communication.
  **/
  failure: function(_resp){
    var _this = COMM.Transporter;
    // server didn't respond, likely network issue.. retry.
    if(_resp.X.status===0){
      console.log(_this.serverLostMessage);
      if(!_this._serverInterruptView){
        _this._serverInterruptView = HView.extend({
          _setFailedResp: function(_resp){
            if(_resp!==undefined){
              this._failedResp = _resp;
            }
            this._errorIndex++;
            return this;
          },
          _retry: function(){
            this._retryIndex++;
            var _resp = this._failedResp;
            COMM.request(
              _resp.url,
              _resp.options
            );
          },
          onIdle: function(){
            var _currentDate = new Date().getTime();
            this.bringToFront();
            if( this._errorIndex > 0 &&
                (this._retryIndex !== this._errorIndex) &&
                (this._lastError + 2000 < _currentDate) &&
                this._failedResp ){
              this._lastError = _currentDate;
              this._retry();
            }
            this.base();
          },
          _errorIndex: 0,
          _retryIndex: 0,
          _lastError: new Date().getTime(),
          die: function(){
            var _app = this.app;
            HSystem.reniceApp(_app.appId,this._origPriority);
            this.base();
            _app.sync();
          },
          drawSubviews: function(){
            var _style = [
              ['padding-left', '8px'],
              ['background-color', '#600'],
              ['text-align','center'],
              ['color', '#fff'],
              ['font-size', '16px'],
              ['opacity', 0.85]
            ], i = 0;
            for( ; i<_style.length; i++ ){
              this.setStyle( _style[i][0], _style[i][1] );
            }
            this.setHTML(this.app.serverLostMessage);
            this._origPriority = HSystem.appPriorities[this.appId];
            if(HSystem.appPriorities[this.appId]<10){
              HSystem.reniceApp(this.appId,10);
            }
            this._anim = HView.extend({
              _animIndex: 0,
              _anim: function(){
                var _targetRect,
                    _width = ELEM.getSize(this.parent.elemId)[0];
                this._animIndex++;
                if(this._animIndex%2===0){
                  _targetRect = HRect.nu(0,0,80,20);
                }
                else {
                  _targetRect = HRect.nu(_width-80,0,_width,20);
                }
                this.animateTo(_targetRect,2000);
              },
              onAnimationEnd: function(){
                if(this.drawn){
                  this._anim();
                }
              }
            }
          ).nu( [0,0,80,20], this ).setStyle('background-color','#fff').setStyle('opacity',0.8)._anim();
          }
        }).nu([0,0,200,20,0,null],_this)._setFailedResp(_resp);
      }
      else {
        _this._serverInterruptView._setFailedResp();
      }
    }
    else {
      _this.failMessage('Transporter Error','Transporter was unable to complete the synchronization request.');
    }
  },

/** Starts requests.
  **/
  sync: function(){
    if(this.stop){
      // console.log('sync stop');
      return;
    }
    if(this.busy){
      // console.log('sync busy');
      return;
    }
    // console.log('sync.');
    this.busy = true;
    if(window['sesWatcher'] && window.sesWatcher['sesTimeoutValue']){
      sesWatcher.sesTimeoutValue.set( new Date().getTime() );
    }
    var _this = this,
        _values = COMM.Values.sync(),
        _sesKey = 'ses_key='+COMM.Session.ses_key,
        _errorMessage = _this.getClientEvalError(),
        _body = [_sesKey,_errorMessage,_values?'&values='+_values:''].join('');
    COMM.request(
      _this.url, {
        _this: _this,
        onSuccess: COMM.Transporter.success,
        onFailure: COMM.Transporter.failure,
        method: 'POST',
        async: true,
        body: _body
      }
    );
  }
}).nu();
<commit_msg>Added comment for sesWatcher presence in transporter.<commit_after>/*   RSence
 *   Copyright 2009 Riassence Inc.
 *   http://riassence.com/
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this software package. If not, contact licensing@riassence.com
 */

/*** = Description
  ** Implements the client-server interface.
  **
  ** COMM.Transporter manages the client side of the server-client-server
  ** data synchronization and the server-client command channel.
  **
  ** It uses COMM.Session for session key handling, COMM.Queue for command
  ** queuing and COMM.Values for data value management.
  **
  ** COMM.Transporter operates in a fully automatic mode and starts when
  ** the document has been loaded.
  **
  ** Don't call any of its methods from your code.
***/
//var//RSence.COMM
COMM.Transporter = HApplication.extend({

/** Sets up the default settings upon construction.
  **/
  constructor: function(){
    var _this = this;
    this.serverLostMessage = 'Server Connection Lost: Reconnecting...';
    _this.label = 'Transporter';
    _this.url = false;
    _this.busy = false;
    _this.stop = true;
    _this._serverInterruptView = false;
    _this._clientEvalError = false;
    _this._busyFlushTimeout = false;
    _this.base(1);
  },

/** Tries to (re)connect to the server as often as possible,
  * mandated essentially by the priority of its
  * HApplication instance.
  **/
  onIdle: function(){
    this.sync();
  },

/** (Re)sets the priority of itself, effects how
  * frequently +onIdle+ is called.
  * Usually set by the server.
  **/
  poll: function(_pri){
    HSystem.reniceApp(this.appId,_pri);
  },

/** Returns the last transaction error of itself. Used by +sync+
  * to report js errors to the server.
  * If no error, returns an empty string.
  **/
  getClientEvalError: function(){
    var _this = COMM.Transporter;
    return _this._clientEvalError?'&err_msg=' +
           COMM.Values._encodeString(_this._clientEvalError):'';
  },

/** = Description
  * Handles synchronization responses.
  *
  * Upon a successful request, this method is called by
  * the onSuccess event of the XMLHttpRequest.
  *
  * It splits up the response string and passes the response
  * messages to COMM.Queue for execution.
  *
  * Parameters:
  * +resp+:: The response object.
  *
  **/
  success: function(resp){
    var _this = COMM.Transporter;
    if(!resp.X.responseText){
      _this.failure(resp);
      return;
    }
    var _responseArray = eval(resp.X.responseText),
        i = 1,
        _responseArrayLen = _responseArray.length,
        _sesKey = _responseArray[0],
        _session = COMM.Session,
        _queue = COMM.Queue;
    if(_sesKey === ''){
      console.log('Invalid session, error message should follow...');
    }
    else {
      _session.newKey(_sesKey);
    }
    for(;i<_responseArrayLen;i++){
      try {
        _queue.pushEval( _responseArray[i] );
      }
      catch(e) {
        console.log( 'clientError:'+e+" - "+e.description+' - '+_responseArray[i]);
        _this._clientEvalError = e+" - "+e.description+' - '+_responseArray[i];
      }
    }
    if(_this._serverInterruptView){
      _this._serverInterruptView.die();
      _this._serverInterruptView = false;
    }
    _queue.push( function(){COMM.Transporter.flushBusy();} );
    _queue.flush();
  },

/** Sets the +busy+ flag to false and resynchronizes immediately,
  * if COMM.Values contain any unsynchronized values.
  **/
  flushBusy: function(){
    var _this = COMM.Transporter;
    _this.busy = false;
    COMM.Values.tosync.length !== 0 && _this.sync();
  },
  failMessage: function(_title,_message){
    var _this = COMM.Transporter,
        _queue = COMM.Queue;
    console.log('failMessage?');
    _this.stop = true;
    _queue.push(function(){jsLoader.load('default_theme');});
    _queue.push(function(){jsLoader.load('controls');});
    _queue.push(function(){jsLoader.load('servermessage');});
    _queue.push(function(){ReloadApp.nu(_title,_message);});
  },

/** Called by the XMLHttpRequest, when there was a failure in communication.
  **/
  failure: function(_resp){
    var _this = COMM.Transporter;
    // server didn't respond, likely network issue.. retry.
    if(_resp.X.status===0){
      console.log(_this.serverLostMessage);
      if(!_this._serverInterruptView){
        _this._serverInterruptView = HView.extend({
          _setFailedResp: function(_resp){
            if(_resp!==undefined){
              this._failedResp = _resp;
            }
            this._errorIndex++;
            return this;
          },
          _retry: function(){
            this._retryIndex++;
            var _resp = this._failedResp;
            COMM.request(
              _resp.url,
              _resp.options
            );
          },
          onIdle: function(){
            var _currentDate = new Date().getTime();
            this.bringToFront();
            if( this._errorIndex > 0 &&
                (this._retryIndex !== this._errorIndex) &&
                (this._lastError + 2000 < _currentDate) &&
                this._failedResp ){
              this._lastError = _currentDate;
              this._retry();
            }
            this.base();
          },
          _errorIndex: 0,
          _retryIndex: 0,
          _lastError: new Date().getTime(),
          die: function(){
            var _app = this.app;
            HSystem.reniceApp(_app.appId,this._origPriority);
            this.base();
            _app.sync();
          },
          drawSubviews: function(){
            var _style = [
              ['padding-left', '8px'],
              ['background-color', '#600'],
              ['text-align','center'],
              ['color', '#fff'],
              ['font-size', '16px'],
              ['opacity', 0.85]
            ], i = 0;
            for( ; i<_style.length; i++ ){
              this.setStyle( _style[i][0], _style[i][1] );
            }
            this.setHTML(this.app.serverLostMessage);
            this._origPriority = HSystem.appPriorities[this.appId];
            if(HSystem.appPriorities[this.appId]<10){
              HSystem.reniceApp(this.appId,10);
            }
            this._anim = HView.extend({
              _animIndex: 0,
              _anim: function(){
                var _targetRect,
                    _width = ELEM.getSize(this.parent.elemId)[0];
                this._animIndex++;
                if(this._animIndex%2===0){
                  _targetRect = HRect.nu(0,0,80,20);
                }
                else {
                  _targetRect = HRect.nu(_width-80,0,_width,20);
                }
                this.animateTo(_targetRect,2000);
              },
              onAnimationEnd: function(){
                if(this.drawn){
                  this._anim();
                }
              }
            }
          ).nu( [0,0,80,20], this ).setStyle('background-color','#fff').setStyle('opacity',0.8)._anim();
          }
        }).nu([0,0,200,20,0,null],_this)._setFailedResp(_resp);
      }
      else {
        _this._serverInterruptView._setFailedResp();
      }
    }
    else {
      _this.failMessage('Transporter Error','Transporter was unable to complete the synchronization request.');
    }
  },

/** Starts requests.
  **/
  sync: function(){
    if(this.stop){
      // console.log('sync stop');
      return;
    }
    if(this.busy){
      // console.log('sync busy');
      return;
    }
    // console.log('sync.');
    this.busy = true;
    if(window['sesWatcher'] && window.sesWatcher['sesTimeoutValue']){
      // Sets the value of the session watcher to the current time. It could cause an unnecessary re-sync poll immediately after this sync otherwise.
      sesWatcher.sesTimeoutValue.set( new Date().getTime() );
    }
    var _this = this,
        _values = COMM.Values.sync(),
        _sesKey = 'ses_key='+COMM.Session.ses_key,
        _errorMessage = _this.getClientEvalError(),
        _body = [_sesKey,_errorMessage,_values?'&values='+_values:''].join('');
    COMM.request(
      _this.url, {
        _this: _this,
        onSuccess: COMM.Transporter.success,
        onFailure: COMM.Transporter.failure,
        method: 'POST',
        async: true,
        body: _body
      }
    );
  }
}).nu();
<|endoftext|>


<commit_before>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

SDK.PerformanceMetricsModel = class extends SDK.SDKModel {
  /**
   * @param {!SDK.Target} target
   */
  constructor(target) {
    super(target);
    this._agent = target.performanceAgent();

    const mode = SDK.PerformanceMetricsModel.MetricMode;
    /** @type {!Map<string, !SDK.PerformanceMetricsModel.MetricMode>} */
    this._metricModes = new Map([
      ['TaskDuration', mode.CumulativeTime], ['ScriptDuration', mode.CumulativeTime],
      ['LayoutDuration', mode.CumulativeTime], ['RecalcStyleDuration', mode.CumulativeTime],
      ['LayoutCount', mode.CumulativeCount], ['RecalcStyleCount', mode.CumulativeCount]
    ]);

    /** @type {!Map<string, !{lastValue: (number|undefined), lastTimestamp: (number|undefined)}>} */
    this._metricData = new Map();
  }

  /**
   * @return {!Promise}
   */
  enable() {
    return this._agent.enable();
  }

  /**
   * @return {!Promise}
   */
  disable() {
    return this._agent.disable();
  }

  /**
   * @return {!Promise<!{metrics: !Map<string, number>, timestamp: number}>}
   */
  async requestMetrics() {
    const rawMetrics = await this._agent.getMetrics() || [];
    const metrics = new Map();
    const timestamp = performance.now();
    for (const metric of rawMetrics) {
      let data = this._metricData.get(metric.name);
      if (!data) {
        data = {};
        this._metricData.set(metric.name, data);
      }
      let value;
      switch (this._metricModes.get(metric.name)) {
        case SDK.PerformanceMetricsModel.MetricMode.CumulativeTime:
          value = data.lastTimestamp ?
              Number.constrain((metric.value - data.lastValue) * 1000 / (timestamp - data.lastTimestamp), 0, 1) :
              0;
          data.lastValue = metric.value;
          data.lastTimestamp = timestamp;
          break;
        case SDK.PerformanceMetricsModel.MetricMode.CumulativeCount:
          value = data.lastTimestamp ?
              Math.max(0, (metric.value - data.lastValue) * 1000 / (timestamp - data.lastTimestamp)) :
              0;
          data.lastValue = metric.value;
          data.lastTimestamp = timestamp;
          break;
        default:
          value = metric.value;
          break;
      }
      metrics.set(metric.name, value);
    }
    const totalMemoryUsage = await this._requestTotalMemory();
    metrics.set('JSHeapUsedSize', totalMemoryUsage.usedSize);
    metrics.set('JSHeapTotalSize', totalMemoryUsage.totalSize);
    return {metrics: metrics, timestamp: timestamp};
  }

  /**
   * @return {!Promise<!{usedSize: number, totalSize: number}>}
   */
  async _requestTotalMemory() {
    const models = SDK.targetManager.models(SDK.RuntimeModel);
    const isolates = await Promise.all(models.map(model => model.isolateId()));
    /** @type {!Map<string, !SDK.RuntimeModel>} */
    const modelsByIsolate = new Map();
    for (let i = 0; i < isolates.length; ++i)
      modelsByIsolate.set(isolates[i], models[i]);
    const usages = await Promise.all(modelsByIsolate.valuesArray().map(model => model.heapUsage()));
    let totalSize = 0;
    let usedSize = 0;
    for (const usage of usages) {
      totalSize += usage ? usage.totalSize : 0;
      usedSize += usage ? usage.usedSize : 0;
    }
    return {totalSize, usedSize};
  }
};

/** @enum {symbol} */
SDK.PerformanceMetricsModel.MetricMode = {
  CumulativeTime: Symbol('CumulativeTime'),
  CumulativeCount: Symbol('CumulativeCount'),
};

SDK.SDKModel.register(SDK.PerformanceMetricsModel, SDK.Target.Capability.Browser, false);
<commit_msg>DevTools: Make performance monitor report a single process memory again.<commit_after>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

SDK.PerformanceMetricsModel = class extends SDK.SDKModel {
  /**
   * @param {!SDK.Target} target
   */
  constructor(target) {
    super(target);
    this._agent = target.performanceAgent();

    const mode = SDK.PerformanceMetricsModel.MetricMode;
    /** @type {!Map<string, !SDK.PerformanceMetricsModel.MetricMode>} */
    this._metricModes = new Map([
      ['TaskDuration', mode.CumulativeTime], ['ScriptDuration', mode.CumulativeTime],
      ['LayoutDuration', mode.CumulativeTime], ['RecalcStyleDuration', mode.CumulativeTime],
      ['LayoutCount', mode.CumulativeCount], ['RecalcStyleCount', mode.CumulativeCount]
    ]);

    /** @type {!Map<string, !{lastValue: (number|undefined), lastTimestamp: (number|undefined)}>} */
    this._metricData = new Map();
  }

  /**
   * @return {!Promise}
   */
  enable() {
    return this._agent.enable();
  }

  /**
   * @return {!Promise}
   */
  disable() {
    return this._agent.disable();
  }

  /**
   * @return {!Promise<!{metrics: !Map<string, number>, timestamp: number}>}
   */
  async requestMetrics() {
    const rawMetrics = await this._agent.getMetrics() || [];
    const metrics = new Map();
    const timestamp = performance.now();
    for (const metric of rawMetrics) {
      let data = this._metricData.get(metric.name);
      if (!data) {
        data = {};
        this._metricData.set(metric.name, data);
      }
      let value;
      switch (this._metricModes.get(metric.name)) {
        case SDK.PerformanceMetricsModel.MetricMode.CumulativeTime:
          value = data.lastTimestamp ?
              Number.constrain((metric.value - data.lastValue) * 1000 / (timestamp - data.lastTimestamp), 0, 1) :
              0;
          data.lastValue = metric.value;
          data.lastTimestamp = timestamp;
          break;
        case SDK.PerformanceMetricsModel.MetricMode.CumulativeCount:
          value = data.lastTimestamp ?
              Math.max(0, (metric.value - data.lastValue) * 1000 / (timestamp - data.lastTimestamp)) :
              0;
          data.lastValue = metric.value;
          data.lastTimestamp = timestamp;
          break;
        default:
          value = metric.value;
          break;
      }
      metrics.set(metric.name, value);
    }
    return {metrics: metrics, timestamp: timestamp};
  }
};

/** @enum {symbol} */
SDK.PerformanceMetricsModel.MetricMode = {
  CumulativeTime: Symbol('CumulativeTime'),
  CumulativeCount: Symbol('CumulativeCount'),
};

SDK.SDKModel.register(SDK.PerformanceMetricsModel, SDK.Target.Capability.Browser, false);
<|endoftext|>


<commit_before>set_global('$', global.make_zjquery());

add_dependencies({
    people: 'js/people.js',
});

var people = global.people;

var user_events = require("js/user_events.js");

set_global('activity', {
    redraw: function () {},
});
set_global('settings_users', {
    update_user_data: function () {},
});
set_global('admin', {
    show_or_hide_menu_item: function () {},
});
set_global('page_params', {
    is_admin: true,
});

set_global('pm_list', {
    update_private_messages: function () {},
});

set_global('narrow_state', {
    update_email: function () {},
});

set_global('compose', {
    update_email: function () {},
});

set_global('settings_account', {
    update_email: function () {},
});

set_global('message_live_update', {
});

set_global('blueslip', {});

var me = {
    email: 'me@example.com',
    user_id: 30,
    full_name: 'Me Myself',
    is_admin: true,
};

function initialize() {
    people.init();
    people.add(me);
    people.initialize_current_user(me.user_id);
}

initialize();

(function test_updates() {
    var person;

    var isaac = {
        email: 'isaac@example.com',
        user_id: 32,
        full_name: 'Isaac Newton',
    };
    people.add(isaac);

    user_events.update_person({user_id: isaac.user_id, is_admin: true});
    person = people.get_by_email(isaac.email);
    assert.equal(person.full_name, 'Isaac Newton');
    assert.equal(person.is_admin, true);

    var user_id;
    var full_name;
    global.message_live_update.update_user_full_name = function (user_id_arg, full_name_arg) {
        user_id = user_id_arg;
        full_name = full_name_arg;
    };

    user_events.update_person({user_id: isaac.user_id, full_name: 'Sir Isaac'});
    person = people.get_by_email(isaac.email);
    assert.equal(person.full_name, 'Sir Isaac');
    assert.equal(person.is_admin, true);
    assert.equal(user_id, isaac.user_id);
    assert.equal(full_name, 'Sir Isaac');

    user_events.update_person({user_id: me.user_id, is_admin: false});
    assert(!global.page_params.is_admin);

    user_events.update_person({user_id: me.user_id, full_name: 'Me V2'});
    assert.equal(people.my_full_name(), 'Me V2');
    assert.equal(user_id, me.user_id);
    assert.equal(full_name, 'Me V2');

    user_events.update_person({user_id: isaac.user_id, new_email: 'newton@example.com'});
    person = people.get_person_from_user_id(isaac.user_id);
    assert.equal(person.email, 'newton@example.com');
    assert.equal(person.full_name, 'Sir Isaac');

    user_events.update_person({user_id: me.user_id, new_email: 'meforu@example.com'});
    person = people.get_person_from_user_id(me.user_id);
    assert.equal(person.email, 'meforu@example.com');
    assert.equal(person.full_name, 'Me V2');

    var avatar_url;
    global.message_live_update.update_avatar = function (user_id_arg, avatar_url_arg) {
        user_id = user_id_arg;
        avatar_url = avatar_url_arg;
    };

    user_events.update_person({user_id: isaac.user_id, full_name: 'Sir Isaac'});
    person = people.get_by_email(isaac.email);
    assert.equal(person.full_name, 'Sir Isaac');
    assert.equal(person.is_admin, true);
    assert.equal(user_id, isaac.user_id);
    assert.equal(full_name, 'Sir Isaac');

    user_events.update_person({user_id: isaac.user_id, avatar_url: 'http://gravatar.com/123456'});
    person = people.get_by_email(isaac.email);
    assert.equal(person.full_name, 'Sir Isaac');
    assert.equal(user_id, isaac.user_id);
    assert.equal(person.avatar_url, avatar_url);

    user_events.update_person({user_id: me.user_id, avatar_url: 'http://gravatar.com/789456'});
    person = people.get_by_email(me.email);
    assert.equal(person.full_name, 'Me V2');
    assert.equal(user_id, me.user_id);
    assert.equal(person.avatar_url, avatar_url);

    user_events.update_person({user_id: me.user_id, timezone: 'UTC'});
    person = people.get_by_email(me.email);
    assert(person.timezone);

    var error_msg;
    var error_details;
    global.blueslip.error = function (error_message_arg, error_details_arg) {
        error_msg = error_message_arg;
        error_details = error_details_arg;
    };

    assert(!user_events.update_person({user_id: 29, full_name: 'Sir Isaac Newton'}));
    assert.equal(error_msg, "Got update_person event for unexpected user");
    assert.equal(error_details.email, 29);

}());
<commit_msg>node: Fix node test for user_events.<commit_after>set_global('$', global.make_zjquery());

add_dependencies({
    people: 'js/people.js',
});

var people = global.people;

var user_events = require("js/user_events.js");

set_global('activity', {
    redraw: function () {},
});
set_global('settings_users', {
    update_user_data: function () {},
});
set_global('admin', {
    show_or_hide_menu_item: function () {},
});
set_global('page_params', {
    is_admin: true,
});

set_global('pm_list', {
    update_private_messages: function () {},
});

set_global('narrow_state', {
    update_email: function () {},
});

set_global('compose', {
    update_email: function () {},
});

set_global('settings_account', {
    update_email: function () {},
});

set_global('message_live_update', {
});

set_global('blueslip', {});

var me = {
    email: 'me@example.com',
    user_id: 30,
    full_name: 'Me Myself',
    is_admin: true,
};

function initialize() {
    people.init();
    people.add(me);
    people.initialize_current_user(me.user_id);
}

initialize();

(function test_updates() {
    var person;

    var isaac = {
        email: 'isaac@example.com',
        user_id: 32,
        full_name: 'Isaac Newton',
    };
    people.add(isaac);

    user_events.update_person({user_id: isaac.user_id, is_admin: true});
    person = people.get_by_email(isaac.email);
    assert.equal(person.full_name, 'Isaac Newton');
    assert.equal(person.is_admin, true);

    var user_id;
    var full_name;
    global.message_live_update.update_user_full_name = function (user_id_arg, full_name_arg) {
        user_id = user_id_arg;
        full_name = full_name_arg;
    };

    user_events.update_person({user_id: isaac.user_id, full_name: 'Sir Isaac'});
    person = people.get_by_email(isaac.email);
    assert.equal(person.full_name, 'Sir Isaac');
    assert.equal(person.is_admin, true);
    assert.equal(user_id, isaac.user_id);
    assert.equal(full_name, 'Sir Isaac');

    user_events.update_person({user_id: me.user_id, is_admin: false});
    assert(!global.page_params.is_admin);

    user_events.update_person({user_id: me.user_id, full_name: 'Me V2'});
    assert.equal(people.my_full_name(), 'Me V2');
    assert.equal(user_id, me.user_id);
    assert.equal(full_name, 'Me V2');

    user_events.update_person({user_id: isaac.user_id, new_email: 'newton@example.com'});
    person = people.get_person_from_user_id(isaac.user_id);
    assert.equal(person.email, 'newton@example.com');
    assert.equal(person.full_name, 'Sir Isaac');

    user_events.update_person({user_id: me.user_id, new_email: 'meforu@example.com'});
    person = people.get_person_from_user_id(me.user_id);
    assert.equal(person.email, 'meforu@example.com');
    assert.equal(person.full_name, 'Me V2');

    var avatar_url;
    global.message_live_update.update_avatar = function (user_id_arg, avatar_url_arg) {
        user_id = user_id_arg;
        avatar_url = avatar_url_arg;
    };

    user_events.update_person({user_id: isaac.user_id, full_name: 'Sir Isaac'});
    person = people.get_by_email(isaac.email);
    assert.equal(person.full_name, 'Sir Isaac');
    assert.equal(person.is_admin, true);
    assert.equal(user_id, isaac.user_id);
    assert.equal(full_name, 'Sir Isaac');

    user_events.update_person({user_id: isaac.user_id, avatar_url: 'http://gravatar.com/123456'});
    person = people.get_by_email(isaac.email);
    assert.equal(person.full_name, 'Sir Isaac');
    assert.equal(user_id, isaac.user_id);
    assert.equal(person.avatar_url, avatar_url);

    user_events.update_person({user_id: me.user_id, avatar_url: 'http://gravatar.com/789456'});
    person = people.get_by_email(me.email);
    assert.equal(person.full_name, 'Me V2');
    assert.equal(user_id, me.user_id);
    assert.equal(person.avatar_url, avatar_url);

    user_events.update_person({user_id: me.user_id, timezone: 'UTC'});
    person = people.get_by_email(me.email);
    assert(person.timezone);

    var error_msg;
    global.blueslip.error = function (error_message_arg) {
        error_msg = error_message_arg;
    };

    assert(!user_events.update_person({user_id: 29, full_name: 'Sir Isaac Newton'}));
    assert.equal(error_msg, "Got update_person event for unexpected user 29");

}());
<|endoftext|>


<commit_before>var util = require('util'),
  os = require('os'),
  PythonShell = require('python-shell'),
  exec = require('child_process').exec,
  bleno = require('bleno'),
  gpio = require("pi-gpio"),
  Descriptor = bleno.Descriptor,
  Characteristic = bleno.Characteristic,
  ShinySettings = require('./shiny');

var BatteryLevelCharacteristic = function() {
  BatteryLevelCharacteristic.super_.call(this, {
      uuid: '2A19',
      properties: ['read', 'write', 'notify'],
      descriptors: [
        new Descriptor({
            uuid: '2901',
            value: 'Battery level between 0 and 100 percent'
        }),
        new Descriptor({
            uuid: '2904',
            value: new Buffer([0x04, 0x01, 0x27, 0xAD, 0x01, 0x00, 0x00 ]) // maybe 12 0xC unsigned 8 bit
        })
      ]
  });
};

util.inherits(BatteryLevelCharacteristic, Characteristic);

BatteryLevelCharacteristic.prototype.onReadRequest = function(offset, callback) {

  console.log("in read");
  if (os.platform() === 'darwin') {
    exec('pmset -g batt', function (error, stdout, stderr) {

      var data = stdout.toString();
      // data - 'Now drawing from \'Battery Power\'\n -InternalBattery-0\t95%; discharging; 4:11 remaining\n'
      var percent = data.split('\t')[1].split(';')[0];
      console.log(percent);
      percent = parseInt(percent, 10);
      callback(this.RESULT_SUCCESS, new Buffer([percent]));

    });
  } else {
    // return hardcoded value
    console.log("reading...")
    callback(this.RESULT_SUCCESS, new Buffer([98]));

  }
};

BatteryLevelCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) {
  //console.log("in write");
  if (offset) {
    //console.log("in write - offset");
    callback(this.RESULT_ATTR_NOT_LONG);
  }
  //else if (data.length !== 1) {
   // console.log("data length !== 1");
    //console.log(JSON.stringify(data));
    //callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH);
  //}
  else {
    // console.log(JSON.stringify(data));
    // console.log('processing write request');
    // var receivedData = data.readUInt8(0);
    // console.log(typeof data);
    // console.log(data.toString('ascii'));

    // console.log(receivedData);
    // console.log(typeof receivedData);
        var command = data.toString('ascii');
    //console.log('command');
    console.log(command);

    if(command === "0"){
      console.log("stop");
      // print "Now stop"
      // GPIO.output(Motor1E,GPIO.LOW)

           gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }
    else if(command === "1"){
      console.log("command left");

           gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 1, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 1, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }else if(command === "2"){
      console.log("command right");

            gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 1, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 1, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });
    }
    else if(command === "3"){
      console.log("forward");

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 1, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 1, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }
    else if(command === "4"){
      console.log("back");

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 low");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 1, function() {
                    console.log("set pin 18 high");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 low");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 1, function() {
                                      console.log("set pin 15 high");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          }

  }
}
  callback(this.RESULT_SUCCESS);
};

function setMotorDirection(direction) {
    console.log('Setting: ' + direction);

          var pin16 = 0;
          var pin18 = 0;
          var pin22 = 0;

          if(direction === 'forward'){
            pin16 = 1;
            pin18 = 0;
            pin22 = 1;
          }else if (direction == 'reverse'){
            pin16 = 1;
            pin18 = 0;
            pin22 = 1;
          }

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, pin16, function() {            // Set pin 16 high (1)
                console.log("set pin 16 " + pin16);
              //gpio.close(16);                        // Close pin 16
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, pin18, function() {            // Set pin 18 low (0)
                    console.log("set pin 18 " + pin18);
                  //gpio.close(18);                        // Close pin 18
                    gpio.open(22, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(22, pin22, function() {            // Set pin 22 high (1)
                              console.log("set pin 22 " + pin22);
                            //gpio.close(22);                        // Close pin 22
                          });
                        });
                });
              });
            });
          });
}

BatteryLevelCharacteristic.prototype.onNotify = function() {
  console.log('NotifyOnlyCharacteristic on notify');
};

module.exports = BatteryLevelCharacteristic;
<commit_msg>fix parens<commit_after>var util = require('util'),
  os = require('os'),
  PythonShell = require('python-shell'),
  exec = require('child_process').exec,
  bleno = require('bleno'),
  gpio = require("pi-gpio"),
  Descriptor = bleno.Descriptor,
  Characteristic = bleno.Characteristic,
  ShinySettings = require('./shiny');

var BatteryLevelCharacteristic = function() {
  BatteryLevelCharacteristic.super_.call(this, {
      uuid: '2A19',
      properties: ['read', 'write', 'notify'],
      descriptors: [
        new Descriptor({
            uuid: '2901',
            value: 'Battery level between 0 and 100 percent'
        }),
        new Descriptor({
            uuid: '2904',
            value: new Buffer([0x04, 0x01, 0x27, 0xAD, 0x01, 0x00, 0x00 ]) // maybe 12 0xC unsigned 8 bit
        })
      ]
  });
};

util.inherits(BatteryLevelCharacteristic, Characteristic);

BatteryLevelCharacteristic.prototype.onReadRequest = function(offset, callback) {

  console.log("in read");
  if (os.platform() === 'darwin') {
    exec('pmset -g batt', function (error, stdout, stderr) {

      var data = stdout.toString();
      // data - 'Now drawing from \'Battery Power\'\n -InternalBattery-0\t95%; discharging; 4:11 remaining\n'
      var percent = data.split('\t')[1].split(';')[0];
      console.log(percent);
      percent = parseInt(percent, 10);
      callback(this.RESULT_SUCCESS, new Buffer([percent]));

    });
  } else {
    // return hardcoded value
    console.log("reading...")
    callback(this.RESULT_SUCCESS, new Buffer([98]));

  }
};

BatteryLevelCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) {
  //console.log("in write");
  if (offset) {
    //console.log("in write - offset");
    callback(this.RESULT_ATTR_NOT_LONG);
  }
  //else if (data.length !== 1) {
   // console.log("data length !== 1");
    //console.log(JSON.stringify(data));
    //callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH);
  //}
  else {
    // console.log(JSON.stringify(data));
    // console.log('processing write request');
    // var receivedData = data.readUInt8(0);
    // console.log(typeof data);
    // console.log(data.toString('ascii'));

    // console.log(receivedData);
    // console.log(typeof receivedData);
        var command = data.toString('ascii');
    //console.log('command');
    console.log(command);

    if(command === "0"){
      console.log("stop");
      // print "Now stop"
      // GPIO.output(Motor1E,GPIO.LOW)

           gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }
    else if(command === "1"){
      console.log("command left");

           gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 1, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 1, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }else if(command === "2"){
      console.log("command right");

            gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 1, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 1, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });
    }
    else if(command === "3"){
      console.log("forward");

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 1, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 1, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }
    else if(command === "4"){
      console.log("back");

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 low");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 1, function() {
                    console.log("set pin 18 high");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 low");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 1, function() {
                                      console.log("set pin 15 high");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });

      });
    }
  }
  callback(this.RESULT_SUCCESS);
};

function setMotorDirection(direction) {
    console.log('Setting: ' + direction);

          var pin16 = 0;
          var pin18 = 0;
          var pin22 = 0;

          if(direction === 'forward'){
            pin16 = 1;
            pin18 = 0;
            pin22 = 1;
          }else if (direction == 'reverse'){
            pin16 = 1;
            pin18 = 0;
            pin22 = 1;
          }

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, pin16, function() {            // Set pin 16 high (1)
                console.log("set pin 16 " + pin16);
              //gpio.close(16);                        // Close pin 16
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, pin18, function() {            // Set pin 18 low (0)
                    console.log("set pin 18 " + pin18);
                  //gpio.close(18);                        // Close pin 18
                    gpio.open(22, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(22, pin22, function() {            // Set pin 22 high (1)
                              console.log("set pin 22 " + pin22);
                            //gpio.close(22);                        // Close pin 22
                          });
                        });
                });
              });
            });
          });
}

BatteryLevelCharacteristic.prototype.onNotify = function() {
  console.log('NotifyOnlyCharacteristic on notify');
};

module.exports = BatteryLevelCharacteristic;
<|endoftext|>


<commit_before>//
// Example : collect 100 parallel async calls
//

var sequencer = require('sequencer');

//
// Get a pseudo random number to simulate async variability
//

var randomNumber = function() {
  return Math.floor(Math.random() * 100);
}

//
// Build an array with 100 sequencable async calls
//

var asyncCalls = [];

for (var i=0;i<100;i++) {
  (function(no) {
      asyncCalls.push(
        function(callback) {
          console.log("Call #" + no);
          setTimeout(callback, randomNumber()); // Simulate async
        }
      );
    })(i);
}

//
// Add a finishing function at the end
//

asyncCalls.push(function(callback) {
    console.log("Finished all tasks");
  });

sequencer.sequence(asyncCalls);

<commit_msg>Updated example<commit_after>//
// Example : collect 100 parallel async calls
//

var collect = require('sequencer').collect;

//
// Get a pseudo random number to simulate async variability
//

var randomNumber = function() {
  return Math.floor(Math.random() * 100);
}

//
// Build an array with 100 sequencable async calls
//

var asyncCalls = [];

for (var i=0;i<100;i++) {
  (function(no) {
      asyncCalls.push(
        function(callback) {
          console.log("Call #" + no);
          setTimeout(callback, randomNumber()); // Simulate async
        }
      );
    })(i);
}

//
// Add a finishing function at the end
//

asyncCalls.push(function(callback) {
    console.log("Finished all tasks");
  });

collect(asyncCalls);

<|endoftext|>


<commit_before>const React = require('react');
import { Link } from 'react-router';
const chatWindow = require('../chat/chatWindow');
const axios = require('axios');
const cookie = require('react-cookie');

const MatchList = React.createClass({

  getInitialState: function() {
    return ({
      chatWindows: [],
      matches: []
    })
  },

componentWillMount: function() {
  let user = cookie.load('user');

  if (user !== undefined){
    let url='http://localhost:3000/api/matches';
    let token = cookie.load('token');
    axios.post(url,
      { id: user._id },
      { headers: { Authorization: token }
    }).then((res)=>{
        console.log(res)
        this.setState({
          matches: res
        });
    }).catch((err)=> {
      console.log(err)
    });
  } else {
    return false;
  }
},

  renderList: function() {
    let user = cookie.load('user');
    if (user !==undefined) {
      return (

            {this.state.matches.map((item)=>{
              return
              (

                 {item}

)
            })}

);
    } else {
      return (
)
    }
  },

  openChat: function(e) {
    let user = cookie.load('user');
    if (user !== undefined) {
      this.state.chatWindows.concat(
        {
          user1: "what de fuck"
        }
      )
    } else {
      console.log("WOOWOOOOO!!!")
      return false;
    }
  },

  mapChats: function () {
    let user = cookie.load('user');
    console.log(user);
    if (user !== undefined) {
      this.state.chatWindows.map((item) => {
        return
        (<chatWindow user1={item.user1} />)
        //set IDs as props here as well.
      })
    } else {
      return false;
    }
  },

  render: function() {
    return (

        {this.renderList()}
        {this.mapChats()}

    );
  }
})

module.exports = MatchList;<commit_msg>match list/chat updates<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router';
import chatWindow from '../chat/chatWindow';
const axios = require('axios');
const cookie = require('react-cookie');

const MatchList = React.createClass({

getInitialState: function() {
  return {
    chatWindows: [],
    matches: []
  }
},

componentWillMount: function() {
    let url='http://localhost:3000/api/matches';
    let token = cookie.load('token');
    let user = cookie.load('user');
    if (user !== undefined) {
    axios.post(url,
      { id: user._id },
      { headers: { Authorization: token }
    }).then((res)=>{
        console.log(res.data)
        this.setState({
          matches: res.data
        });
    }).catch((err)=> {
      console.log(err)
    });
    }
  },

  renderList: function() {
    let user = cookie.load('user');
    if (user !==undefined) {
      return (

            {this.state.matches.map(item=>(

                  <Link onClick={this.handleClick.bind(this)} firstName={item.firstName}> {item.firstName} </Link>

            ))}

);
    } else {
      return (
)
    }
  },

  handleClick: function(e) {
    e.preventDefault();
      this.setState({chatWindows: this.state.chatWindows.concat(
        [{
          user1: "what de fuck"
        }]
      )});
      console.log(this.state.chatWindows);
      this.mapChats();
  },

  mapChats: function() {
    let user = cookie.load('user');
    if (user !== undefined) {
      this.state.chatWindows.map(item=>{
       return (<chatWindow user1={item.user1} />)
        //set IDs as props here as well.
      })
    } else {
      return false;
    }
  },

  render: function() {
    return (

        {this.renderList()}
        {this.mapChats()}

    );
  }
})

module.exports = MatchList;<|endoftext|>