<commit_before>import React, { Component } from 'react';
import { View, StyleSheet, TouchableOpacity, Image, Text } from 'react-native';
import PropTypes from 'prop-types';

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
  },
  button: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  valueContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

class UIStepper extends Component {
  static propTypes = {
    initialValue: PropTypes.number,
    minimumValue: PropTypes.number,
    maximumValue: PropTypes.number,
    steps: PropTypes.number,
    tintColor: PropTypes.string,
    backgroundColor: PropTypes.string,
    decrementImage: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    incrementImage: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    imageWidth: PropTypes.number,
    imageHeight: PropTypes.number,
    width: PropTypes.number,
    height: PropTypes.number,
    borderColor: PropTypes.string,
    borderWidth: PropTypes.number,
    borderRadius: PropTypes.number,
    onValueChange: PropTypes.func,
    onDecrement: PropTypes.func,
    onIncrement: PropTypes.func,
    onMinimumReached: PropTypes.func,
    onMaximumReached: PropTypes.func,
    wraps: PropTypes.bool,
    displayValue: PropTypes.bool,
    textColor: PropTypes.string,
    fontSize: PropTypes.number,
    overrideTintColor: PropTypes.bool,
    vertical: PropTypes.bool,
    displayDecrementFirst: PropTypes.bool,
  };
  static defaultProps = {
    initialValue: 0,
    minimumValue: 0,
    maximumValue: 100,
    steps: 1,
    tintColor: '#0076FF',
    backgroundColor: 'transparent',
    decrementImage: require('./assets/decrement.png'),
    incrementImage: require('./assets/increment.png'),
    imageWidth: 20,
    imageHeight: 15,
    width: 94,
    height: 29,
    borderColor: '#0076FF',
    borderWidth: 1,
    borderRadius: 4,
    onValueChange: null,
    onDecrement: null,
    onIncrement: null,
    onMinimumReached: null,
    onMaximumReached: null,
    wraps: false,
    displayValue: false,
    textColor: '#0076FF',
    fontSize: 15,
    overrideTintColor: false,
    vertical: false,
    displayDecrementFirst: false,
  };
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.initialValue,
    };
    console.log(this.props);
  }
  decrement = () => {
    const { steps, onDecrement } = this.props;
    let value = this.state.value;
    value -= steps;
    this.validate(value, onDecrement);
  };
  increment = () => {
    const { steps, onIncrement } = this.props;
    let value = this.state.value;
    value += steps;
    this.validate(value, onIncrement);
  };
  isExternalImage = image => typeof image === 'string';
  resolveImage = image => {
    if (this.isExternalImage(image)) {
      return { uri: image };
    }
    return image;
  };
  resolveStyles = image => {
    const {
      tintColor,
      height,
      width,
      overrideTintColor,
      imageHeight,
      imageWidth,
      buttonPadding,
    } = this.props;
    const containerHeight = height / 3;
    const containerWidth = width / 3;

    if (this.isExternalImage(image)) {
      const styles = {
        flex: 1,
        alignSelf: 'stretch',
        width: this.getImageWidth(),
        height: this.getImageHeight(),
      };
      if (overrideTintColor) {
        styles.tintColor = tintColor;
      }
      return styles;
    }
    return {
      tintColor,
      width: this.getImageWidth(),
      height: this.getImageHeight(),
    };
  };
  getImageHeight = () => {
    const { imageHeight, height } = this.props;
    const containerHeight = height;

    if (imageHeight > containerHeight) {
      return height;
    }
    return imageHeight;
  };
  getImageWidth = () => {
    const { imageWidth, width } = this.props;
    const containerWidth = width / 3;

    if (imageWidth > containerWidth) {
      return containerWidth;
    }
    return imageWidth;
  };
  validate = (value, callback) => {
    const {
      minimumValue: min,
      maximumValue: max,
      onValueChange,
      onMinimumReached,
      onMaximumReached,
      wraps,
    } = this.props;
    if (min <= value && max >= value) {
      this.setState({
        value,
      });
      if (onValueChange) {
        onValueChange(value);
      }
      if (callback) {
        callback(value);
      }
      return;
    }
    if (value < min) {
      if (wraps) {
        this.setState({
          value: max,
        });
        if (onValueChange) {
          onValueChange(max);
        }
        if (callback) {
          callback(max);
        }
        return;
      }
      onMinimumReached && onMinimumReached(value);
    }
    if (value > max) {
      if (wraps) {
        this.setState({
          value: min,
        });
        if (onValueChange) {
          onValueChange(min);
        }
        if (callback) {
          callback(min);
        }
        return;
      }
      onMaximumReached && onMaximumReached(value);
    }
  };
  setValue = (value, callback) => {
    const { onValueChange } = this.props;
    this.setState({
      value: value,
    });
    if (onValueChange) {
      onValueChange(value);
    }
    if (callback) {
      callback(value);
    }
  };
  render() {
    const {
      tintColor,
      backgroundColor,
      decrementImage,
      dividerImage,
      incrementImage,
      imageWidth,
      imageHeight,
      width,
      height,
      borderColor,
      borderWidth,
      borderRadius,
      displayValue,
      textColor,
      fontSize,
      vertical,
      displayDecrementFirst,
    } = this.props;
    return (
      <View
        style={[
          styles.container,
          {
            backgroundColor,
            width: vertical ? width / 2 : width,
            height: vertical ? 'auto' : height,
            borderColor,
            borderWidth,
            borderRadius,
            flexDirection: vertical
              ? displayDecrementFirst ? 'column' : 'column-reverse'
              : 'row',
          },
        ]}
      >
        <TouchableOpacity
          onPress={this.decrement}
          style={[
            styles.button,
            {
              borderRightWidth: vertical ? 0 : borderWidth,
              borderRightColor: borderColor,
              height: vertical ? 30 : 'auto',
            },
          ]}
        >
          <Image
            source={this.resolveImage(decrementImage)}
            style={this.resolveStyles(decrementImage)}
            resizeMode={'contain'}
          />
        </TouchableOpacity>
        {displayValue && (
          <View style={styles.valueContainer}>
            <Text style={{ color: textColor, fontSize }}>
              {this.state.value}
            </Text>
          </View>
        )}
        <TouchableOpacity
          onPress={this.increment}
          style={[
            styles.button,
            {
              borderLeftWidth: vertical ? 0 : displayValue ? 1 : 0,
              borderColor,
              height: vertical ? 30 : 'auto',
            },
          ]}
        >
          <Image
            source={this.resolveImage(incrementImage)}
            style={this.resolveStyles(incrementImage)}
            resizeMode={'contain'}
          />
        </TouchableOpacity>
      </View>
    );
  }
}

export default UIStepper;
<commit_msg>Remove console log (#9)<commit_after>import React, { Component } from 'react';
import { View, StyleSheet, TouchableOpacity, Image, Text } from 'react-native';
import PropTypes from 'prop-types';

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
  },
  button: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  valueContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

class UIStepper extends Component {
  static propTypes = {
    initialValue: PropTypes.number,
    minimumValue: PropTypes.number,
    maximumValue: PropTypes.number,
    steps: PropTypes.number,
    tintColor: PropTypes.string,
    backgroundColor: PropTypes.string,
    decrementImage: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    incrementImage: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    imageWidth: PropTypes.number,
    imageHeight: PropTypes.number,
    width: PropTypes.number,
    height: PropTypes.number,
    borderColor: PropTypes.string,
    borderWidth: PropTypes.number,
    borderRadius: PropTypes.number,
    onValueChange: PropTypes.func,
    onDecrement: PropTypes.func,
    onIncrement: PropTypes.func,
    onMinimumReached: PropTypes.func,
    onMaximumReached: PropTypes.func,
    wraps: PropTypes.bool,
    displayValue: PropTypes.bool,
    textColor: PropTypes.string,
    fontSize: PropTypes.number,
    overrideTintColor: PropTypes.bool,
    vertical: PropTypes.bool,
    displayDecrementFirst: PropTypes.bool,
  };
  static defaultProps = {
    initialValue: 0,
    minimumValue: 0,
    maximumValue: 100,
    steps: 1,
    tintColor: '#0076FF',
    backgroundColor: 'transparent',
    decrementImage: require('./assets/decrement.png'),
    incrementImage: require('./assets/increment.png'),
    imageWidth: 20,
    imageHeight: 15,
    width: 94,
    height: 29,
    borderColor: '#0076FF',
    borderWidth: 1,
    borderRadius: 4,
    onValueChange: null,
    onDecrement: null,
    onIncrement: null,
    onMinimumReached: null,
    onMaximumReached: null,
    wraps: false,
    displayValue: false,
    textColor: '#0076FF',
    fontSize: 15,
    overrideTintColor: false,
    vertical: false,
    displayDecrementFirst: false,
  };
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.initialValue,
    };
  }
  decrement = () => {
    const { steps, onDecrement } = this.props;
    let value = this.state.value;
    value -= steps;
    this.validate(value, onDecrement);
  };
  increment = () => {
    const { steps, onIncrement } = this.props;
    let value = this.state.value;
    value += steps;
    this.validate(value, onIncrement);
  };
  isExternalImage = image => typeof image === 'string';
  resolveImage = image => {
    if (this.isExternalImage(image)) {
      return { uri: image };
    }
    return image;
  };
  resolveStyles = image => {
    const {
      tintColor,
      height,
      width,
      overrideTintColor,
      imageHeight,
      imageWidth,
      buttonPadding,
    } = this.props;
    const containerHeight = height / 3;
    const containerWidth = width / 3;

    if (this.isExternalImage(image)) {
      const styles = {
        flex: 1,
        alignSelf: 'stretch',
        width: this.getImageWidth(),
        height: this.getImageHeight(),
      };
      if (overrideTintColor) {
        styles.tintColor = tintColor;
      }
      return styles;
    }
    return {
      tintColor,
      width: this.getImageWidth(),
      height: this.getImageHeight(),
    };
  };
  getImageHeight = () => {
    const { imageHeight, height } = this.props;
    const containerHeight = height;

    if (imageHeight > containerHeight) {
      return height;
    }
    return imageHeight;
  };
  getImageWidth = () => {
    const { imageWidth, width } = this.props;
    const containerWidth = width / 3;

    if (imageWidth > containerWidth) {
      return containerWidth;
    }
    return imageWidth;
  };
  validate = (value, callback) => {
    const {
      minimumValue: min,
      maximumValue: max,
      onValueChange,
      onMinimumReached,
      onMaximumReached,
      wraps,
    } = this.props;
    if (min <= value && max >= value) {
      this.setState({
        value,
      });
      if (onValueChange) {
        onValueChange(value);
      }
      if (callback) {
        callback(value);
      }
      return;
    }
    if (value < min) {
      if (wraps) {
        this.setState({
          value: max,
        });
        if (onValueChange) {
          onValueChange(max);
        }
        if (callback) {
          callback(max);
        }
        return;
      }
      onMinimumReached && onMinimumReached(value);
    }
    if (value > max) {
      if (wraps) {
        this.setState({
          value: min,
        });
        if (onValueChange) {
          onValueChange(min);
        }
        if (callback) {
          callback(min);
        }
        return;
      }
      onMaximumReached && onMaximumReached(value);
    }
  };
  setValue = (value, callback) => {
    const { onValueChange } = this.props;
    this.setState({
      value: value,
    });
    if (onValueChange) {
      onValueChange(value);
    }
    if (callback) {
      callback(value);
    }
  };
  render() {
    const {
      tintColor,
      backgroundColor,
      decrementImage,
      dividerImage,
      incrementImage,
      imageWidth,
      imageHeight,
      width,
      height,
      borderColor,
      borderWidth,
      borderRadius,
      displayValue,
      textColor,
      fontSize,
      vertical,
      displayDecrementFirst,
    } = this.props;
    return (
      <View
        style={[
          styles.container,
          {
            backgroundColor,
            width: vertical ? width / 2 : width,
            height: vertical ? 'auto' : height,
            borderColor,
            borderWidth,
            borderRadius,
            flexDirection: vertical
              ? displayDecrementFirst ? 'column' : 'column-reverse'
              : 'row',
          },
        ]}
      >
        <TouchableOpacity
          onPress={this.decrement}
          style={[
            styles.button,
            {
              borderRightWidth: vertical ? 0 : borderWidth,
              borderRightColor: borderColor,
              height: vertical ? 30 : 'auto',
            },
          ]}
        >
          <Image
            source={this.resolveImage(decrementImage)}
            style={this.resolveStyles(decrementImage)}
            resizeMode={'contain'}
          />
        </TouchableOpacity>
        {displayValue && (
          <View style={styles.valueContainer}>
            <Text style={{ color: textColor, fontSize }}>
              {this.state.value}
            </Text>
          </View>
        )}
        <TouchableOpacity
          onPress={this.increment}
          style={[
            styles.button,
            {
              borderLeftWidth: vertical ? 0 : displayValue ? 1 : 0,
              borderColor,
              height: vertical ? 30 : 'auto',
            },
          ]}
        >
          <Image
            source={this.resolveImage(incrementImage)}
            style={this.resolveStyles(incrementImage)}
            resizeMode={'contain'}
          />
        </TouchableOpacity>
      </View>
    );
  }
}

export default UIStepper;
<|endoftext|>


<commit_before>// from
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/105074#105074
// not a true guid but good enough for now
function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
             .toString(16)
             .substring(1);
};

function guid() {
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
         s4() + '-' + s4() + s4() + s4();
};

var clientId = guid();
var es = new EventSource('/contributions?id='+clientId);
es.addEventListener('results', function(e) {
  $("#results").append(e.data + "\n");
});
es.addEventListener('end-message', function(e) {
  window.history.pushState({"message": $("#message").html(),
                            "title": document.title,
                            "results": $("#results").html()},
                           null, e.data);
});
es.onmessage = function(e) {
  $('#message').html(e.data + "\n");
};
es.onerror = function(e) {
  $('.alert-box').show();
  $('#error').html(e.data);
};

$(function() {
  window.addEventListener("popstate", function(e) {
    // guard against initial page load
    if (e.state) {
      $("#message").html(e.state.message);
      $("#results").html(e.state.results);
      $("h1").html(e.state.title);
      document.title = e.state.title;
    }
  });

  var fetchUserContributions = function(user) {
    $.post('/contributions', {id: clientId, user: user});
    $('#results').show();
    $('#message').show();
    $('#message').html('Fetching repositories...');
    $('#user').val('');
    $('tbody').html('');
    document.title = user + "'s Github Contributions"
    $('h1').html(document.title);
  };

  $("form").on('submit', function(e) {
    fetchUserContributions($("#user").val());
    e.preventDefault();
  });

  // close alert box
  $('a.close').on('click', function(e) { $(e.target).parent().hide() });

  $('a.user').on('click', function(e) {
    fetchUserContributions(e.target.text);
    e.preventDefault;
  });

  var match;
  if (match = location.pathname.match(/^\/(.+)/)) {
    // Allow time for sse to register
    setTimeout(function() {fetchUserContributions(match[1])},
               500);
  } else {
    window.history.pushState({"message": '', "results": '', "title": $("h1").html()},
                             null,
                             '');
  }
});
<commit_msg>comment tweak<commit_after>// from
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/105074#105074
// not a true guid but good enough for now
function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
             .toString(16)
             .substring(1);
};

function guid() {
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
         s4() + '-' + s4() + s4() + s4();
};

var clientId = guid();
var es = new EventSource('/contributions?id='+clientId);
es.addEventListener('results', function(e) {
  $("#results").append(e.data + "\n");
});
es.addEventListener('end-message', function(e) {
  window.history.pushState({"message": $("#message").html(),
                            "title": document.title,
                            "results": $("#results").html()},
                           null, e.data);
});
es.onmessage = function(e) {
  $('#message').html(e.data + "\n");
};
es.onerror = function(e) {
  $('.alert-box').show();
  $('#error').html(e.data);
};

$(function() {
  window.addEventListener("popstate", function(e) {
    // guard against initial page load in chrome
    if (e.state) {
      $("#message").html(e.state.message);
      $("#results").html(e.state.results);
      $("h1").html(e.state.title);
      document.title = e.state.title;
    }
  });

  var fetchUserContributions = function(user) {
    $.post('/contributions', {id: clientId, user: user});
    $('#results').show();
    $('#message').show();
    $('#message').html('Fetching repositories...');
    $('#user').val('');
    $('tbody').html('');
    document.title = user + "'s Github Contributions"
    $('h1').html(document.title);
  };

  $("form").on('submit', function(e) {
    fetchUserContributions($("#user").val());
    e.preventDefault();
  });

  // close alert box
  $('a.close').on('click', function(e) { $(e.target).parent().hide() });

  $('a.user').on('click', function(e) {
    fetchUserContributions(e.target.text);
    e.preventDefault;
  });

  var match;
  if (match = location.pathname.match(/^\/(.+)/)) {
    // Allow time for sse to register
    setTimeout(function() {fetchUserContributions(match[1])},
               500);
  } else {
    window.history.pushState({"message": '', "results": '', "title": $("h1").html()},
                             null,
                             '');
  }
});
<|endoftext|>


<commit_before><commit_msg>level2 change velocity of acid rain<commit_after><|endoftext|>


<commit_before>$env_name = 'unknown'; // this should be replaced with actual environment name during installation
$actas_cookie_name = "aaadactas"; // this should be replaced if the cookie name is different
$aaadselectorClicked = false;
$username = ''
$aaad_update_timer_id = 0
$(document).ready(function(){
  $('head').append('<link rel="stylesheet" type="text/css" href="/static/aaad-ui.css">');
  var $elm = '

	Welcome to RogerOS! This is the ' + $env_name + ' environment.
Hello! Please [log in]

' +
             '

	-: ' + $env_name + ' :-

'
  $('body').append($elm)
  updateUserDetails()
  $(aaadselector).click(function () {
    $aaadselectorClicked = true;
    $(aaaddropdown).slideToggle(300);
    if($('#aaaddropdown').css('display') != 'none') {
      updateUserDetails()
      $aaad_update_timer_id = setInterval(updateUserDetails, 10000);
    } else {
      if ($aaad_update_timer_id != 0) {
        clearInterval($aaad_update_timer_id);
      }
    }
  });
  if (getCookieValue($actas_cookie_name)) {
    // If the user is (or was) already logged in let's check in a few seconds...
    setTimeout(function(){
      // ... and if dropdown is still visible, let's slideToggle to hide it
      if(!$aaadselectorClicked && $('#aaaddropdown').css('display') != 'none') {
        $(aaaddropdown).slideToggle(300);
        if ($aaad_update_timer_id != 0) {
          clearInterval($aaad_update_timer_id);
        }
      }
    }, 5000);
  }
});
function updateUserDetails() {
  $.getJSON( "/login/user" )
    .done(function (responseData) {
      $username = responseData["username"];
      if(isEmpty($username)) {
        $('#welcomeuser').html('Hello! Please [log in]');
        $('#actasdetails').html('');
      } else {
        $('#welcomeuser').html('Hello ' + $username + '!');
        var $actas = getCookieValue($actas_cookie_name);
        if (isEmpty($actas) || $actas == $username) {
          $actas = 'yourself';
        }
        $('#actasdetails').html(' You\'re acting as ' + $actas + ' [change] | [log out]');
      }
    });
}
function getCookieValue(a) {
  b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
  return b ? b.pop() : '';
}
function onActAsChangeClick() {
  window.location.href = '/login?resetactas=true&next=' + encodeURIComponent(window.location.href);
}
function isEmpty(str) {
    return (!str || 0 === str.length);
}
<commit_msg>Toggling the aaadui in 1s instead of 5s.<commit_after>$env_name = 'unknown'; // this should be replaced with actual environment name during installation
$actas_cookie_name = "aaadactas"; // this should be replaced if the cookie name is different
$aaadselectorClicked = false;
$username = ''
$aaad_update_timer_id = 0
$(document).ready(function(){
  $('head').append('<link rel="stylesheet" type="text/css" href="/static/aaad-ui.css">');
  var $elm = '

	Welcome to RogerOS! This is the ' + $env_name + ' environment.
Hello! Please [log in]

' +
             '

	-: ' + $env_name + ' :-

'
  $('body').append($elm)
  updateUserDetails()
  $(aaadselector).click(function () {
    $aaadselectorClicked = true;
    $(aaaddropdown).slideToggle(300);
    if($('#aaaddropdown').css('display') != 'none') {
      updateUserDetails()
      $aaad_update_timer_id = setInterval(updateUserDetails, 10000);
    } else {
      if ($aaad_update_timer_id != 0) {
        clearInterval($aaad_update_timer_id);
      }
    }
  });
  if (getCookieValue($actas_cookie_name)) {
    // If the user is (or was) already logged in let's check in a few seconds...
    setTimeout(function(){
      // ... and if dropdown is still visible, let's slideToggle to hide it
      if(!$aaadselectorClicked && $('#aaaddropdown').css('display') != 'none') {
        $(aaaddropdown).slideToggle(300);
        if ($aaad_update_timer_id != 0) {
          clearInterval($aaad_update_timer_id);
        }
      }
    }, 1000);
  }
});
function updateUserDetails() {
  $.getJSON( "/login/user" )
    .done(function (responseData) {
      $username = responseData["username"];
      if(isEmpty($username)) {
        $('#welcomeuser').html('Hello! Please [log in]');
        $('#actasdetails').html('');
      } else {
        $('#welcomeuser').html('Hello ' + $username + '!');
        var $actas = getCookieValue($actas_cookie_name);
        if (isEmpty($actas) || $actas == $username) {
          $actas = 'yourself';
        }
        $('#actasdetails').html(' You\'re acting as ' + $actas + ' [change] | [log out]');
      }
    });
}
function getCookieValue(a) {
  b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
  return b ? b.pop() : '';
}
function onActAsChangeClick() {
  window.location.href = '/login?resetactas=true&next=' + encodeURIComponent(window.location.href);
}
function isEmpty(str) {
    return (!str || 0 === str.length);
}
<|endoftext|>


<commit_before>import SimpleStepper from 'react-native-simple-stepper'
import React, { Component, Proptypes } from 'react'
import { StyleSheet, Text, ListView, View } from 'react-native'
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})

export default class Main extends Component {
  constructor(props) {
    super(props)
    this.state = {
      dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
      data: []
    }
  }
  componentWillMount() {
    const data = [
      { tintColor: '#32A54A', value: .99, minimumValue: 0, maximumValue: 15, initialValue: .99, stepValue: .99, tintOnIncrementImage: true, tintOnDecrementImage: true, incrementImage: '', decrementImage: '' },
      { tintColor: '#cc3232', value: 50, minimumValue: -100, maximumValue: 100, initialValue: 50, stepValue: 25, tintOnIncrementImage: true, tintOnDecrementImage: true, incrementImage: '', decrementImage: '' },
      { tintColor: '#4F3D9E', value: 0, minimumValue: -70, maximumValue: 70, initialValue: 30, stepValue: 10, tintOnIncrementImage: false, tintOnDecrementImage: false, incrementImage: 'https://facebook.github.io/react/img/logo_og.png', decrementImage: 'https://facebook.github.io/react/img/logo_og.png' },
    ]
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(data),
      data: data
    })
  }
  valueChanged(value, rowID) {
    var data = this.state.data
    data[rowID].value = value.toFixed(2)
    this.setState({
      dataSource: ds.cloneWithRows(data),
      data: data
    })
  }
  renderRow(rowData, sectionID, rowID) {
    return (
      <View style={styles.row}>
        <SimpleStepper
          tintColor={rowData.tintColor}
          valueChanged={(value) => this.valueChanged(value, rowID)}
          tintOnIncrementImage={rowData.tintOnIncrementImage}
          tintOnDecrementImage={rowData.tintOnDecrementImage}
          incrementImage={rowData.incrementImage}
          decrementImage={rowData.decrementImage}
          minimumValue={rowData.minimumValue}
          maximumValue={rowData.maximumValue}
          initialValue={rowData.initialValue}
          stepValue={rowData.stepValue} />
          <View style={styles.column}>
            <Text style={styles.text}>{'min: '}{rowData.minimumValue}</Text>
            <Text style={styles.text}>{'max: '}{rowData.maximumValue}</Text>
            <Text style={styles.text}>{'initial: '}{rowData.initialValue}</Text>
            <Text style={styles.text}>{'step: '}{rowData.stepValue}</Text>
          </View>
          <Text style={[styles.text, {color: rowData.tintColor, fontSize: 30, padding: 4, position: 'absolute', right: 8}]}>{rowData.value}</Text>
      </View>
    )
  }
  render() {
    return (
      <ListView
        contentContainerStyle={styles.container}
        initialListSize={this.state.data.length}
        dataSource={this.state.dataSource}
        renderRow={(rowData, sectionID, rowID) => this.renderRow(rowData, sectionID, rowID)}
        renderSeparator={(sectionID, rowID) => <View key={`${sectionID}-${rowID}`} style={styles.separator} />} />
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#E9EEEF'
  },
  row: {
    flexDirection: 'row',
    padding: 8,
    alignItems: 'center'
  },
  column: {
    flexDirection: 'column',
    paddingLeft: 8
  },
  text: {
    fontSize: 16,
    color: '#222222'
  },
  separator: {
    height: 1,
    backgroundColor: '#8B9B9C'
  }
});
<commit_msg>Update example minor data fix<commit_after>import SimpleStepper from 'react-native-simple-stepper'
import React, { Component, Proptypes } from 'react'
import { StyleSheet, Text, ListView, View } from 'react-native'
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})

export default class Main extends Component {
  constructor(props) {
    super(props)
    this.state = {
      dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
      data: []
    }
  }
  componentWillMount() {
    const data = [
      { tintColor: '#358CDC', value: 0, minimumValue: -100, maximumValue: 1000, initialValue: .05, stepValue: 1, tintOnIncrementImage: true, tintOnDecrementImage: true, incrementImage: '', decrementImage: ''},
      { tintColor: '#32A54A', value: .99, minimumValue: 0, maximumValue: 15, initialValue: .99, stepValue: .99, tintOnIncrementImage: true, tintOnDecrementImage: true, incrementImage: '', decrementImage: '' },
      { tintColor: '#cc3232', value: 50, minimumValue: -100, maximumValue: 100, initialValue: 50, stepValue: 25, tintOnIncrementImage: true, tintOnDecrementImage: true, incrementImage: '', decrementImage: '' },
      { tintColor: '#4F3D9E', value: 0, minimumValue: -70, maximumValue: 70, initialValue: 30, stepValue: 10, tintOnIncrementImage: false, tintOnDecrementImage: false, incrementImage: 'https://facebook.github.io/react/img/logo_og.png', decrementImage: 'https://facebook.github.io/react/img/logo_og.png' },
    ]
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(data),
      data: data
    })
  }
  valueChanged(value, rowID) {
    var data = this.state.data
    data[rowID].value = value.toFixed(2)
    this.setState({
      dataSource: ds.cloneWithRows(data),
      data: data
    })
  }
  renderRow(rowData, sectionID, rowID) {
    return (
      <View style={styles.row}>
        <SimpleStepper
          tintColor={rowData.tintColor}
          valueChanged={(value) => this.valueChanged(value, rowID)}
          tintOnIncrementImage={rowData.tintOnIncrementImage}
          tintOnDecrementImage={rowData.tintOnDecrementImage}
          incrementImage={rowData.incrementImage}
          decrementImage={rowData.decrementImage}
          minimumValue={rowData.minimumValue}
          maximumValue={rowData.maximumValue}
          initialValue={rowData.initialValue}
          stepValue={rowData.stepValue} />
          <View style={styles.column}>
            <Text style={styles.text}>{'min: '}{rowData.minimumValue}</Text>
            <Text style={styles.text}>{'max: '}{rowData.maximumValue}</Text>
            <Text style={styles.text}>{'initial: '}{rowData.initialValue}</Text>
            <Text style={styles.text}>{'step: '}{rowData.stepValue}</Text>
          </View>
          <Text style={[styles.text, {color: rowData.tintColor, fontSize: 30, padding: 4, position: 'absolute', right: 8}]}>{rowData.value}</Text>
      </View>
    )
  }
  render() {
    return (
      <ListView
        contentContainerStyle={styles.container}
        initialListSize={this.state.data.length}
        dataSource={this.state.dataSource}
        renderRow={(rowData, sectionID, rowID) => this.renderRow(rowData, sectionID, rowID)}
        renderSeparator={(sectionID, rowID) => <View key={`${sectionID}-${rowID}`} style={styles.separator} />} />
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#E9EEEF'
  },
  row: {
    flexDirection: 'row',
    padding: 8,
    alignItems: 'center'
  },
  column: {
    flexDirection: 'column',
    paddingLeft: 8
  },
  text: {
    fontSize: 16,
    color: '#222222'
  },
  separator: {
    height: 1,
    backgroundColor: '#8B9B9C'
  }
});
<|endoftext|>


<commit_before>'use strict';

define(['ol',
        'sidebar',
        //'toolbar',
        'layermanager',
        'query',
        'search',
        'print',
        'permalink',
        'measure',
        'bootstrap',
        'geolocation',
        'api',
        'drag',
        'compositions'
    ],
    function(ol, toolbar) {
        var module = angular.module('hs', [
            //'hs.toolbar',
            'hs.layermanager',
            'hs.query',
            'hs.print',
            'hs.permalink',
            'hs.geolocation',
            'hs.api',
            'hs.sidebar',
            'hs.drag',
            'hs.compositions'
        ]);

        module.directive(
            'hs', [
                'hs.map.service', 'Core',
                function(OlMap, Core) {
                    return {
                        templateUrl: hsl_path + 'hslayers.html',
                        link: function(scope, element) {
                            Core.fullScreenMap(element);
                        }
                    };
                }
            ]);

        module.value('config', {
            default_layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM(),
                    title: "Base layer",
                    base: true
                })
            ],
            default_view: new ol.View({
                center: ol.proj.transform([6.1319, 49.6116], 'EPSG:4326', 'EPSG:3857'), //Latitude longitude    to Spherical Mercator
                zoom: 13,
                units: "m"
            })
        });

        module.controller('Main', ['$scope', 'Core', '$compile', 'hs.map.service', 'hs.compositions.service_parser', '$timeout',
            function($scope, Core, $compile, hsmap, composition_parser, $timeout) {
                $scope.hsl_path = hsl_path; //Get this from hslayers.js file
                $scope.Core = Core;

                $scope.split_moved = function(x, y) {
                    $scope.split_x = x;
                    $scope.split_y = y;
                    hsmap.map.render();
                }
                $scope.$on("scope_loaded", function(event, args) {
                    if (args == 'Map') {

                        $scope.split_x = hsmap.map.getSize()[0] / 2;
                        $scope.split_y = hsmap.map.getSize()[1] / 2;

                        var slider_button = angular.element('');

                        angular.element('#map').append(slider_button);
                        $compile(slider_button)($scope);
                    }
                });
                $scope.$on('layermanager.updated', function(data, layer) {
                    if (layer.get('base') != true && layer.get('always_visible') != true) {
                        if (layer.get('title') == 'Intenzita dopravy v Plzni - normální stav - podzim') {
                            layer.set('split_group', 2);
                            layer.setVisible(true);
                        } else if (layer.get('title').indexOf('Intenzita') > -1) {
                            layer.set('split_group', 1);
                            layer.set('exclusive', true);
                        }
                        layer.on('precompose', function(evt) {
                            var ctx = evt.context;
                            ctx.save();
                            if (evt.currentTarget.get('split_group') == 1) {
                                ctx.save();
                                ctx.beginPath();
                                ctx.rect(0, 0, $scope.split_x, 20);
                                ctx.fillStyle = 'rgba(255, 255, 255, 0.6)';
                                ctx.fill();
                                ctx.restore();
                                ctx.save();
                                ctx.beginPath();
                                ctx.moveTo($scope.split_x, 0);
                                ctx.lineTo($scope.split_x, 20);
                                ctx.strokeStyle = 'red';
                                ctx.stroke();
                                ctx.restore();
                            }
                            if (evt.currentTarget.get('split_group') == 2) {
                                ctx.save();
                                ctx.beginPath();
                                ctx.rect($scope.split_x, 0, ctx.canvas.width-$scope.split_x, 20);
                                ctx.fillStyle = 'rgba(255, 255, 255, 0.6)';
                                ctx.fill();
                                ctx.restore();
                                ctx.save();
                                ctx.beginPath();
                                ctx.moveTo($scope.split_x, 0);
                                ctx.lineTo($scope.split_x, 20);
                                ctx.strokeStyle = 'red';
                                ctx.stroke();
                                ctx.restore();
                            }
                            ctx.beginPath();
                            var title = evt.currentTarget.get('title');
                            //Set clip rectangle and draw red outline for splitter
                            if (evt.currentTarget.get('split_group') == 1) {
                                ctx.rect(0, 20, $scope.split_x, $scope.split_y-20);
                                ctx.font = '14pt Calibri';
                                ctx.fillText(title, $scope.split_x - ctx.measureText(title).width-5, 15);
                            } else  if(evt.currentTarget.get('split_group') == 2){
                                ctx.moveTo($scope.split_x, 20);
                                ctx.lineTo(ctx.canvas.width, 20);
                                ctx.lineTo(ctx.canvas.width, ctx.canvas.height);
                                ctx.lineTo(0, ctx.canvas.height);
                                ctx.lineTo(0, $scope.split_y);
                                ctx.lineTo($scope.split_x, $scope.split_y);
                                ctx.closePath();
                                ctx.font = '14pt Calibri';
                                ctx.fillText(title, $scope.split_x+5, 15);
                            } else {
                                ctx.rect(0, 0, ctx.canvas.width, ctx.canvas.height);
                            }
                            ctx.strokeStyle = 'red';
                            ctx.stroke();
                            ctx.clip();
                        });
                        layer.on('postcompose', function(evt) {
                            evt.context.restore();
                        })
                    }
                    if (layer.get('base') == true) {
                        //Grayscale map
                        layer.on('postcompose', function(event) {
                            var context = event.context;
                            var canvas = context.canvas;
                            var image = context.getImageData(0, 0, canvas.width, canvas.height);
                            var data = image.data;
                            for (var i = 0, ii = data.length; i < ii; i += 4) {
                                data[i] = data[i + 1] = data[i + 2] = (3 * data[i] + 4 * data[i + 1] + data[i + 2]) / 8;
                            }
                            context.putImageData(image, 0, 0);
                        });
                    }
                });
                $scope.$on('layermanager.layer_time_changed', function(evt, layer, d) {
                    angular.forEach(hsmap.map.getLayers(), function(other_layer) {
                        if (other_layer.getSource().updateParams)
                            other_layer.getSource().updateParams({
                                'TIME': d
                            });
                    })
                })

                composition_parser.load('http://opentransportnet.eu/wwwlibs/statusmanager2/index.php?request=load&id=b8b5a347-4637-44d0-ae67-da17c5b047d3', undefined, undefined, function(response) {
                    angular.forEach(response.data.layers, function(layer) {
                        if (layer.title == 'Intenzita dopravy v Plzni - normální stav - podzim') {
                            layer.path = 'Bez dopravních omezení (base)';
                        } else if (layer.title.indexOf('Intenzita') > -1) {
                            layer.path = 'S dopravním omezením (other)';
                        }
                    })
                    return response;
                });
                Core.panelEnabled('compositions', false);

                $scope.$on('infopanel.updated', function(event) {});
            }
        ]);

        return module;
    });
<commit_msg>dpi aware drawing in pslit_map example<commit_after>'use strict';

define(['ol',
        'sidebar',
        //'toolbar',
        'layermanager',
        'query',
        'search',
        'print',
        'permalink',
        'measure',
        'bootstrap',
        'geolocation',
        'api',
        'drag',
        'compositions'
    ],
    function(ol, toolbar) {
        var module = angular.module('hs', [
            //'hs.toolbar',
            'hs.layermanager',
            'hs.query',
            'hs.print',
            'hs.permalink',
            'hs.geolocation',
            'hs.api',
            'hs.sidebar',
            'hs.drag',
            'hs.compositions'
        ]);

        module.directive(
            'hs', [
                'hs.map.service', 'Core',
                function(OlMap, Core) {
                    return {
                        templateUrl: hsl_path + 'hslayers.html',
                        link: function(scope, element) {
                            Core.fullScreenMap(element);
                        }
                    };
                }
            ]);

        module.value('config', {
            default_layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM(),
                    title: "Base layer",
                    base: true
                })
            ],
            default_view: new ol.View({
                center: ol.proj.transform([6.1319, 49.6116], 'EPSG:4326', 'EPSG:3857'), //Latitude longitude    to Spherical Mercator
                zoom: 13,
                units: "m"
            })
        });

        module.controller('Main', ['$scope', 'Core', '$compile', 'hs.map.service', 'hs.compositions.service_parser', '$timeout',
            function($scope, Core, $compile, hsmap, composition_parser, $timeout) {
                $scope.hsl_path = hsl_path; //Get this from hslayers.js file
                $scope.Core = Core;

                $scope.split_moved = function(x, y) {
                    $scope.split_x = x;
                    $scope.split_y = y;
                    hsmap.map.render();
                }
                $scope.$on("scope_loaded", function(event, args) {
                    if (args == 'Map') {

                        $scope.split_x = hsmap.map.getSize()[0] / 2;
                        $scope.split_y = hsmap.map.getSize()[1] / 2;

                        var slider_button = angular.element('');

                        angular.element('#map').append(slider_button);
                        $compile(slider_button)($scope);
                    }
                });
                $scope.$on('layermanager.updated', function(data, layer) {
                    if (layer.get('base') != true && layer.get('always_visible') != true) {
                        if (layer.get('title') == 'Intenzita dopravy v Plzni - normální stav - podzim') {
                            layer.set('split_group', 2);
                            layer.setVisible(true);
                        } else if (layer.get('title').indexOf('Intenzita') > -1) {
                            layer.set('split_group', 1);
                            layer.set('exclusive', true);
                        }
                        layer.on('precompose', function(evt) {
                            var ctx = evt.context;
                            ctx.save();
                            var dpi = window.devicePixelRatio;
                            if (evt.currentTarget.get('split_group') == 1) {
                                ctx.save();
                                ctx.beginPath();
                                ctx.rect(0, 0, $scope.split_x * dpi, 20 * dpi);
                                ctx.fillStyle = 'rgba(255, 255, 255, 0.6)';
                                ctx.fill();
                                ctx.restore();
                                ctx.save();
                                ctx.beginPath();
                                ctx.moveTo($scope.split_x * dpi, 0 * dpi);
                                ctx.lineTo($scope.split_x * dpi, 20 * dpi);
                                ctx.strokeStyle = 'red';
                                ctx.stroke();
                                ctx.restore();
                            }
                            if (evt.currentTarget.get('split_group') == 2) {
                                ctx.save();
                                ctx.beginPath();
                                ctx.rect($scope.split_x * dpi, 0 * dpi, ctx.canvas.width * dpi - $scope.split_x * dpi, 20 * dpi);
                                ctx.fillStyle = 'rgba(255, 255, 255, 0.6)';
                                ctx.fill();
                                ctx.restore();
                                ctx.save();
                                ctx.beginPath();
                                ctx.moveTo($scope.split_x * dpi, 0 * dpi);
                                ctx.lineTo($scope.split_x * dpi, 20 * dpi);
                                ctx.strokeStyle = 'red';
                                ctx.stroke();
                                ctx.restore();
                            }
                            ctx.beginPath();
                            var title = evt.currentTarget.get('title');
                            //Set clip rectangle and draw red outline for splitter
                            if (evt.currentTarget.get('split_group') == 1) {
                                ctx.rect(0 * dpi, 20 * dpi, $scope.split_x * dpi, $scope.split_y * dpi - 20 * dpi);
                                ctx.font = '14pt Calibri';
                                ctx.fillText(title, ($scope.split_x - ctx.measureText(title).width - 5) * dpi, 15 * dpi);
                            } else if (evt.currentTarget.get('split_group') == 2) {
                                ctx.moveTo($scope.split_x * dpi, 20 * dpi);
                                ctx.lineTo(ctx.canvas.width * dpi, 20 * dpi);
                                ctx.lineTo(ctx.canvas.width * dpi, ctx.canvas.height * dpi);
                                ctx.lineTo(0 * dpi, ctx.canvas.height * dpi);
                                ctx.lineTo(0 * dpi, $scope.split_y * dpi);
                                ctx.lineTo($scope.split_x * dpi, $scope.split_y * dpi);
                                ctx.closePath();
                                ctx.font = '14pt Calibri';
                                ctx.fillText(title, ($scope.split_x + 5) * dpi, 15 * dpi);
                            } else {
                                ctx.rect(0, 0, ctx.canvas.width * dpi, ctx.canvas.height * dpi);
                            }
                            ctx.strokeStyle = 'red';
                            ctx.stroke();
                            ctx.clip();
                        });
                        layer.on('postcompose', function(evt) {
                            evt.context.restore();
                        })
                    }
                    if (layer.get('base') == true) {
                        //Grayscale map
                        layer.on('postcompose', function(event) {
                            var context = event.context;
                            var canvas = context.canvas;
                            var image = context.getImageData(0, 0, canvas.width, canvas.height);
                            var data = image.data;
                            for (var i = 0, ii = data.length; i < ii; i += 4) {
                                data[i] = data[i + 1] = data[i + 2] = (3 * data[i] + 4 * data[i + 1] + data[i + 2]) / 8;
                            }
                            context.putImageData(image, 0, 0);
                        });
                    }
                });
                $scope.$on('layermanager.layer_time_changed', function(evt, layer, d) {
                    angular.forEach(hsmap.map.getLayers(), function(other_layer) {
                        if (other_layer.getSource().updateParams)
                            other_layer.getSource().updateParams({
                                'TIME': d
                            });
                    })
                })

                composition_parser.load('http://opentransportnet.eu/wwwlibs/statusmanager2/index.php?request=load&id=b8b5a347-4637-44d0-ae67-da17c5b047d3', undefined, undefined, function(response) {
                    angular.forEach(response.data.layers, function(layer) {
                        if (layer.title == 'Intenzita dopravy v Plzni - normální stav - podzim') {
                            layer.path = 'Bez dopravních omezení (base)';
                        } else if (layer.title.indexOf('Intenzita') > -1) {
                            layer.path = 'S dopravním omezením (other)';
                        }
                    })
                    return response;
                });
                Core.panelEnabled('compositions', false);

                $scope.$on('infopanel.updated', function(event) {});
            }
        ]);

        return module;
    });
<|endoftext|>


<commit_before>'use strict';

var w = window.innerWidth;
var h = window.innerHeight;

//var mapUrl = 'https://gist.githubusercontent.com/thepeted/60242378d8c825281ea695c572ab4d51/raw/00685152c5cb34093aabc22b2c06e3df052cc981/world110m.json';
//var dataUrl = 'https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json';

var mapUrl = 'map.json';
var dataUrl = 'tripz.json';

var svg = d3.select('body').append('svg').attr('width', w).attr('height', h);

window.addEventListener('resize', function () {
	d3.select('svg').attr('width', window.innerWidth).attr('height', window.innerHeight);
});

//define the projection settings
var projection = d3.geo.mercator().scale(w / 6).translate([w / 2, h / 2]).center([0, 40]);

//load topology data
d3.json(mapUrl, function (topo) {
	// append topo data to svg as a group, path positions are calculated by projection function
	console.log(topo);
	var worldMap = svg.append('g');

	worldMap.append("path").datum(topojson.feature(topo, topo.objects.countries)).attr('class', 'land').attr("d", d3.geo.path().projection(projection));

	//define and activate zoom behaviour
	var zoom = d3.behavior.zoom().size([h, w]).scaleExtent([0.9, 5]).on('zoom', function () {
		worldMap.attr('transform', 'translate(' + d3.event.translate.join(',') + ') scale(' + d3.event.scale + ')');
	});
	svg.call(zoom);

	// load meteorite and create strike data
	d3.json(dataUrl, function (response) {
		//remove records without any geometry data
		var dataset = response.features.filter(function (e) {
			return e.geometry;
		});
		//scale for sizing the radius of strike circles
		var massScale = d3.scale.pow().exponent(0.5).domain([1, d3.max(dataset.map(function (e) {
			return +e.properties.mass;
		}))]).rangeRound([2, 40]);

		var strikes = worldMap.selectAll('circle').data(dataset).enter().append('circle').attr('class', 'strike').attr('cx', function (d) {
			return projection(d.geometry.coordinates)[0];
		}).attr('cy', function (d) {
			return projection(d.geometry.coordinates)[1];
		})
		// set intial radius to 0 (transition to mass radius defined below)
		.attr('r', 0)
		// reorder shapes with highest mass first so that we access
		// all overlapping circles on hover
		.sort(function (a, b) {
			return b.properties.mass - a.properties.mass;
		});

		//set up a scale to delay the start of the strike animation
		var strikeDates = dataset.map(function (d) {
			return new Date(d.properties.year);
		});
		var animateStrikeDelay = d3.time.scale()
		// manual tweak of min date to avoid data outliers
		.domain([new Date(1980, 0), d3.max(strikeDates)]).range([0, 2000]).clamp(true);

		//dyncamically delay the creation of the strike animation
		strikes.transition().delay(function (d) {
			return animateStrikeDelay(new Date(d.properties.year));
		})
		// duration of the animation
		.duration(1000).attr('r', function (d) {
			return massScale(d.properties.mass);
		});

		//tooltip behaviour
		worldMap.selectAll('circle').on('mouseover', function (d) {
			var _d3$mouse = d3.mouse(document.body);

			var x = _d3$mouse[0];
			var y = _d3$mouse[1];

			//populate tootip with data

			d3.select('#name').text(d.properties.name);
			d3.select('#class').text(d.properties.recclass);
			d3.select('#mass').text(d.properties.mass);
			d3.select('#lat').text(d.properties.reclat);
			d3.select('#lon').text(d.properties.reclong);
			d3.select('#year').text(d.properties.year.split('-', 1));

			//show tooltip
			d3.select('.tooltip').classed('hidden', false).style('left', x + 10 + 'px').style('top', y + 10 + 'px');
		});
		//hide tooltip
		worldMap.selectAll('circle').on('mouseout', function (d) {
			d3.select('.tooltip').classed('hidden', true);
		});
	});
});
<commit_msg>Update map.js<commit_after>'use strict';

var w = window.innerWidth;
var h = window.innerHeight;

//var mapUrl = 'https://gist.githubusercontent.com/thepeted/60242378d8c825281ea695c572ab4d51/raw/00685152c5cb34093aabc22b2c06e3df052cc981/world110m.json';
//var dataUrl = 'https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json';

var mapUrl = 'map.json';
var dataUrl = 'tripz.json';

var svg = d3.select('body').append('svg').attr('width', w).attr('height', h);

window.addEventListener('resize', function () {
	d3.select('svg').attr('width', window.innerWidth).attr('height', window.innerHeight);
});

//define the projection settings
var projection = d3.geo.mercator().scale(w / 6).translate([w / 2, h / 2]).center([0, 40]);

//load topology data
d3.json(mapUrl, function (topo) {
	// append topo data to svg as a group, path positions are calculated by projection function
	console.log(topo);
	var worldMap = svg.append('g');

	worldMap.append("path").datum(topojson.feature(topo, topo.objects.countries)).attr('class', 'land').attr("d", d3.geo.path().projection(projection));

	//define and activate zoom behaviour
	var zoom = d3.behavior.zoom().size([h, w]).scaleExtent([0.9, 5]).on('zoom', function () {
		worldMap.attr('transform', 'translate(' + d3.event.translate.join(',') + ') scale(' + d3.event.scale + ')');
	});
	svg.call(zoom);

	// load meteorite and create strike data
	d3.json(dataUrl, function (response) {
		//remove records without any geometry data
		var dataset = response.features.filter(function (e) {
			return e.geometry;
		});
		//scale for sizing the radius of strike circles
		var massScale = d3.scale.pow().exponent(0.5).domain([1, d3.max(dataset.map(function (e) {
			return +e.properties.mass;
		}))]).rangeRound([2, 40]);

		var strikes = worldMap.selectAll('circle').data(dataset).enter().append('circle').attr('class', 'strike').attr('cx', function (d) {
			return projection(d.geometry.coordinates)[0];
		}).attr('cy', function (d) {
			return projection(d.geometry.coordinates)[1];
		})
		// set intial radius to 0 (transition to mass radius defined below)
		.attr('r', 0)
		// reorder shapes with highest mass first so that we access
		// all overlapping circles on hover
		.sort(function (a, b) {
			return b.properties.mass - a.properties.mass;
		});

		//set up a scale to delay the start of the strike animation
		var strikeDates = dataset.map(function (d) {
			return new Date(d.properties.year);
		});
		var animateStrikeDelay = d3.time.scale()
		// manual tweak of min date to avoid data outliers
		.domain([new Date(1980, 0), d3.max(strikeDates)]).range([0, 2000]).clamp(true);

		//dyncamically delay the creation of the strike animation
		strikes.transition().delay(function (d) {
			return animateStrikeDelay(new Date(d.properties.year));
		})
		// duration of the animation
		.duration(1000).attr('r', function (d) {
			return massScale(d.properties.mass);
		});

		//tooltip behaviour
		worldMap.selectAll('circle').on('mouseover', function (d) {
			var _d3$mouse = d3.mouse(document.body);

			var x = _d3$mouse[0];
			var y = _d3$mouse[1];

			//populate tootip with data

			d3.select('#name').text(d.properties.name);
			d3.select('#class').text(d.properties.recclass);
			d3.select('#mass').text(d.properties.mass);
			d3.select('#lat').text(d.properties.reclat);
			d3.select('#lon').text(d.properties.reclong);
			d3.select('#years').text(d.properties.years);
			d3.select('#year').text(d.properties.year.split('-', 1));

			//show tooltip
			d3.select('.tooltip').classed('hidden', false).style('left', x + 10 + 'px').style('top', y + 10 + 'px');
		});
		//hide tooltip
		worldMap.selectAll('circle').on('mouseout', function (d) {
			d3.select('.tooltip').classed('hidden', true);
		});
	});
});
<|endoftext|>


<commit_before>import React, { Component } from "react";
import PropTypes from "prop-types";
import cx from "classnames";
import IconButton from "@hig/icon-button";
import Input from "./presenters/Input";

import "./text-field.scss";

function generatedId() {
  return `text-field-${Math.floor(Math.random() * 100000, 5)}`;
}

export default class TextFieldPresenter extends Component {
  static propTypes = {
    /**
     * Prevents user actions on the field
     */
    disabled: PropTypes.bool,
    /**
     * Error text for the field. Setting this value applies error styling to the entire component.
     */
    errors: PropTypes.string,
    /**
     * When true, displays passed error text. When false, displays instructions with error styling.
     */
    hideInstructionsOnErrors: PropTypes.bool,
    /**
     * HTML ID attribute
     */
    id: PropTypes.string,
    /**
     * Icon element that precedes the input.
     */
    icon: PropTypes.node,
    /**
     * Instructional text for the field
     */
    instructions: PropTypes.string,
    /**
     * Text describing what the field represents
     */
    label: PropTypes.string,
    /**
     * Name of the field when submitted with a form
     */
    name: PropTypes.string,
    /**
     * Called when user moves focus from the field
     */
    onBlur: PropTypes.func,
    /**
     * Called after user changes the value of the field
     */
    onChange: PropTypes.func,
    /**
     * Called when user clicks the clear button
     */
    onClearButtonClick: PropTypes.func,
    /**
     * Called when user puts focus onto the field
     */
    onFocus: PropTypes.func,
    /**
     * Called as user changes the value of the field
     */
    onInput: PropTypes.func,
    /**
     * Example of what the user should type into the field
     */
    placeholder: PropTypes.string,
    /**
     * Marks input as read-only
     */
    readOnly: PropTypes.bool,
    /**
     * Text describing why the field is required
     */
    required: PropTypes.string,
    /**
     * When true, causes the clear button to appear
     */
    showClearButton: PropTypes.bool,
    /**
     * Corresponds to the type attribute of an <input>. Relevant for designating a password field, for example.
     */
    type: PropTypes.string,
    /**
     * Value of the field
     */
    value: PropTypes.string
  };

  static defaultProps = {
    id: generatedId(),
    type: "text"
  };

  hasClearableInput() {
    return (
      this.props.showClearButton &&
      this.props.value &&
      this.props.value.length > 0
    );
  }

  shouldShowInstructions() {
    if (this.props.instructions) {
      if (this.props.errors) {
        return !this.props.hideInstructionsOnErrors;
      }
      return true;
    }

    return false;
  }

  render() {
    const hasClearableInput = this.hasClearableInput();

    return (

            {this.props.icon && (

                {this.props.icon}

            )}

            <Input
              id={this.props.id}
              value={this.props.value}
              onChange={this.props.onChange}
              name={this.props.name}
              type={this.props.type}
              disabled={this.props.disabled}
              readOnly={this.props.readOnly}
              placeholder={this.props.placeholder}
              onBlur={this.props.onBlur}
              onFocus={this.props.onFocus}
              onInput={this.props.onInput}
            />

            {this.props.label && (

                {this.props.label}

            )}

            {hasClearableInput && (

                <IconButton
                  type="transparent"
                  icon="clear-small"
                  title="Clear field"
                  onClick={this.props.onClearButtonClick}
                />

            )}

          {this.shouldShowInstructions() && (

              {this.props.instructions}

          )}

          {this.props.errors && (

{this.props.errors}

          )}

          {this.props.required && (

              {this.props.required}

          )}

    );
  }
}
<commit_msg>feat(text-field): Pass through all other props to input presenter<commit_after>import React, { Component } from "react";
import PropTypes from "prop-types";
import cx from "classnames";
import IconButton from "@hig/icon-button";
import Input from "./presenters/Input";

import "./text-field.scss";

function generatedId() {
  return `text-field-${Math.floor(Math.random() * 100000, 5)}`;
}

export default class TextFieldPresenter extends Component {
  static propTypes = {
    /**
     * Prevents user actions on the field
     */
    disabled: PropTypes.bool,
    /**
     * Error text for the field. Setting this value applies error styling to the entire component.
     */
    errors: PropTypes.string,
    /**
     * When true, displays passed error text. When false, displays instructions with error styling.
     */
    hideInstructionsOnErrors: PropTypes.bool,
    /**
     * HTML ID attribute
     */
    id: PropTypes.string,
    /**
     * Icon element that precedes the input.
     */
    icon: PropTypes.node,
    /**
     * Instructional text for the field
     */
    instructions: PropTypes.string,
    /**
     * Text describing what the field represents
     */
    label: PropTypes.string,
    /**
     * Name of the field when submitted with a form
     */
    name: PropTypes.string,
    /**
     * Called when user moves focus from the field
     */
    onBlur: PropTypes.func,
    /**
     * Called after user changes the value of the field
     */
    onChange: PropTypes.func,
    /**
     * Called when user clicks the clear button
     */
    onClearButtonClick: PropTypes.func,
    /**
     * Called when user puts focus onto the field
     */
    onFocus: PropTypes.func,
    /**
     * Called as user changes the value of the field
     */
    onInput: PropTypes.func,
    /**
     * Example of what the user should type into the field
     */
    placeholder: PropTypes.string,
    /**
     * Marks input as read-only
     */
    readOnly: PropTypes.bool,
    /**
     * Text describing why the field is required
     */
    required: PropTypes.string,
    /**
     * When true, causes the clear button to appear
     */
    showClearButton: PropTypes.bool,
    /**
     * Corresponds to the type attribute of an <input>. Relevant for designating a password field, for example.
     */
    type: PropTypes.string,
    /**
     * Value of the field
     */
    value: PropTypes.string
  };

  static defaultProps = {
    id: generatedId(),
    type: "text"
  };

  hasClearableInput() {
    return (
      this.props.showClearButton &&
      this.props.value &&
      this.props.value.length > 0
    );
  }

  shouldShowInstructions() {
    if (this.props.instructions) {
      if (this.props.errors) {
        return !this.props.hideInstructionsOnErrors;
      }
      return true;
    }

    return false;
  }

  render() {
    const hasClearableInput = this.hasClearableInput();

    const {
      errors,
      hideInstructionsOnErrors,
      icon,
      instructions,
      label,
      onClearButtonClick,
      required,
      showClearButton,
      ...inputProps
    } = this.props;

    return (

            {icon && (

                {icon}

            )}

            <Input {...inputProps} />

            {label && (

                {label}

            )}

            {hasClearableInput && (

                <IconButton
                  type="transparent"
                  icon="clear-small"
                  title="Clear field"
                  onClick={onClearButtonClick}
                />

            )}

          {this.shouldShowInstructions() && (

{instructions}

          )}

          {errors &&
{errors}
}

          {required && (

{required}

          )}

    );
  }
}
<|endoftext|>


<commit_before>var React = require('react');
var UI = require('../../index');
var StyleKeys = require('../StyleKeys');
var Invariant = require('react/lib/invariant');
var AnimateStore = require('../../stores/Animate');

var defined = variable => (typeof variable !== 'undefined');

module.exports = {
  contextTypes: {
    animateProps: React.PropTypes.object
  },

  componentWillMount() {
    this.setAnimations(this.props, this.state);
  },

  componentWillUpdate(nextProps) {
    if (!this.props.animations && !nextProps.animations)
      return;

    if (this.hasNewAnimations(nextProps))
      this.setAnimations(nextProps);
    else
      this.updateAnimations();
  },

  componentWillUnmount() {
    if (this._headStyleTag)
      document.head.removeChild(this._headStyleTag);
  },

  isAnimating(source) {
    return this.getAnimationProps(source).step % 1 !== 0;
  },

  getAnimation(name, animations) {
    animations = animations || this.props.animations;
    return animations.filter(a => a && a.name === name);
  },

  hasAnimation(name, animations) {
    animations = animations || this.props.animations;
    return animations && !!this.getAnimation(name, animations).length;
  },

  getAnimator(name) {
    return UI.getAnimations(name);
  },

  hasNewAnimations(nextProps) {
    var animations = nextProps.animations;

    if (!animations)
      return false;

    for (var i = 0, len = animations.length; i < len; i++)
      if (!this.isSameAnimation(animations[i], this.props.animations[i]))
        return true;

    return false;
  },

  setAnimations(props) {
    if (props.animations) {
      this._animations = {};

      props.animations.forEach(animation => {
        this._animations[animation.source] = Object.assign({},
          AnimateStore(animation.source, this._mountDepth) || {},
          props && props.animateProps && props.animateProps[animation.source] || {}
        );
      });
    }
  },

  // a slightly quicker version of setAnimations (ignores props)
  updateAnimations() {
    var newProps;

    this.props.animations.forEach(animation => {
      newProps = AnimateStore(animation.source, this._mountDepth);
      Object.assign(this._animations[animation.source], newProps);
    });
  },

  getAnimationProps(source) {
    return this._animations[source];
  },

  getAnimationStep(source) {
    return this.getAnimationProps(source).step;
  },

  setAnimationStyles(part) {
    var styles = this.getAnimationStyles();

    var node = part ?
      this.refs[part].getDOMNode() :
      this.getDOMNode();

    var id, selector;

    if (node.id) {
      id = node.id;
      selector = `#${node.id}`;
    }
    else {
      id = node.getAttribute('data-reactid');
      selector = `[data-reactid="${id}"]`;
    }

    var hasHeadStyleTag = !!this._headStyleTag;

    if (!hasHeadStyleTag)
      this._headStyleTag = document.createElement('style');

    this._headStyleTag.innerHTML =
      `${selector} {
        ${this.stylesToString(styles)}
      }`;

    if (!hasHeadStyleTag)
      document.head.appendChild(this._headStyleTag);
  },

  stylesToString(obj) {
    return Object.keys(obj).reduce((acc, key) => `${key}: ${obj[key]} !important; ${acc}`, '');
  },

  getAnimationStyles() {
    var styles = {};

    if (!this.props.animations)
      return styles;

    var animation;
    var firstTransform = true;
    var i, len = this.props.animations.length;

    for (i = 0; i < len; i++) {
      animation = this.props.animations[i];

      if (!animation)
        continue;

      var { index, step, ...props } = this.getAnimationProps(animation.source);
      index = defined(index) ? index : 1;

      if (!animation.source && this.getTweeningValue && this.getTweeningValue('step'))
        step = this.getTweeningValue('step');

      if (!defined(step))
        continue; // throw new Error(`No step defined for animation ${source}`);

      var animator = this.getAnimator(animation.name);
      var { scale, rotate, rotate3d, translate, ...other } = animator(index, step, props);

      if (firstTransform && (defined(scale) || defined(rotate) || defined(rotate3d) || defined(translate))) {
        firstTransform = false;
        styles.transforms = { scale, rotate, rotate3d, translate };
      }
      else
        this.mergeTransforms(styles.transforms, scale, rotate, rotate3d, translate);

      if (other)
        Object.assign(styles, other);
    }

    return this.animationTransformsToString(styles);
  },

  animationTransformsToString(styles) {
    if (!styles.transforms)
      return styles;

    var transformsString = '';
    var t = styles.transforms;

    if (t) {
      if (defined(t.scale))
        transformsString += `scale(${t.scale}) `;

      if (defined(t.rotate3d))
        transformsString += (
          rotate.x ? `rotateX(${t.rotate3d.x || 0}deg)` : '' +
          rotate.y ? `rotateY(${t.rotate3d.y || 0}deg)` : '' +
          rotate.z ? `rotateZ(${t.rotate3d.z || 0}deg)` : ''
        );

      if (defined(t.rotate))
        transformsString += `rotate(${t.rotate}deg)`;

      if (defined(t.translate))
        transformsString += `translate3d(${t.translate.x || 0}px, ${t.translate.y || 0}px, ${t.translate.z || 0}px)`;
    }

    delete styles.transforms;
    styles['transform'] = transformsString || 'translateZ(0px)';
    return styles;
  },

  mergeTransforms(transforms, scale, rotate, rotate3d, translate) {
    if (defined(scale)) {
      if (!defined(transforms.scale))
        transforms.scale = 1;

      transforms.scale += 1 - scale;
    }

    if (defined(rotate3d)) {
      if (!defined(transforms.rotate3d))
        transforms.rotate3d = { x: 0, y: 0, z: 0 };

      transforms.rotate3d.x += (rotate3d.x || 0);
      transforms.rotate3d.y += (rotate3d.y || 0);
      transforms.rotate3d.z += (rotate3d.z || 0);
    }

    if (defined(rotate)) {
      transforms.rotate = (transforms.rotate || 0) + rotate;
    }

    if (defined(translate)) {
      if (!defined(transforms.translate))
        transforms.translate = { x: 0, y: 0, z: 0 };

      transforms.translate.x += (translate.x || 0);
      transforms.translate.y += (translate.y || 0);
      transforms.translate.z += (translate.z || 0);
    }
  },

  isSameAnimation(a, b) {
    return a.name === b.name && a.source === b.source;
  }
};<commit_msg>cleanup figuring out selector for animation<commit_after>var React = require('react');
var UI = require('../../index');
var StyleKeys = require('../StyleKeys');
var Invariant = require('react/lib/invariant');
var AnimateStore = require('../../stores/Animate');

var defined = variable => (typeof variable !== 'undefined');

module.exports = {
  contextTypes: {
    animateProps: React.PropTypes.object
  },

  componentWillMount() {
    this.setAnimations(this.props, this.state);
  },

  componentWillUpdate(nextProps) {
    if (!this.props.animations && !nextProps.animations)
      return;

    if (this.hasNewAnimations(nextProps))
      this.setAnimations(nextProps);
    else
      this.updateAnimations();
  },

  componentWillUnmount() {
    if (this._headStyleTag)
      document.head.removeChild(this._headStyleTag);
  },

  isAnimating(source) {
    return this.getAnimationProps(source).step % 1 !== 0;
  },

  getAnimation(name, animations) {
    animations = animations || this.props.animations;
    return animations.filter(a => a && a.name === name);
  },

  hasAnimation(name, animations) {
    animations = animations || this.props.animations;
    return animations && !!this.getAnimation(name, animations).length;
  },

  getAnimator(name) {
    return UI.getAnimations(name);
  },

  hasNewAnimations(nextProps) {
    var animations = nextProps.animations;

    if (!animations)
      return false;

    for (var i = 0, len = animations.length; i < len; i++)
      if (!this.isSameAnimation(animations[i], this.props.animations[i]))
        return true;

    return false;
  },

  setAnimations(props) {
    if (props.animations) {
      this._animations = {};

      props.animations.forEach(animation => {
        this._animations[animation.source] = Object.assign({},
          AnimateStore(animation.source, this._mountDepth) || {},
          props && props.animateProps && props.animateProps[animation.source] || {}
        );
      });
    }
  },

  // a slightly quicker version of setAnimations (ignores props)
  updateAnimations() {
    var newProps;

    this.props.animations.forEach(animation => {
      newProps = AnimateStore(animation.source, this._mountDepth);
      Object.assign(this._animations[animation.source], newProps);
    });
  },

  getAnimationProps(source) {
    return this._animations[source];
  },

  getAnimationStep(source) {
    return this.getAnimationProps(source).step;
  },

  setAnimationStyles(ref) {
    var node = ref ?
      this.refs[ref].getDOMNode() :
      this.getDOMNode();

    var selector = node.id ?
      `#${node.id}` :
      `[data-reactid="${node.getAttribute('data-reactid')}"]`;

    var hasHeadStyleTag = !!this._headStyleTag;

    if (!hasHeadStyleTag)
      this._headStyleTag = document.createElement('style');

    // get styles
    var styles = this.getAnimationStyles();

    // set tag styles
    this._headStyleTag.innerHTML =
      `${selector} {
        ${this.stylesToString(styles)}
      }`;

    if (!hasHeadStyleTag)
      document.head.appendChild(this._headStyleTag);
  },

  stylesToString(obj) {
    return Object.keys(obj).reduce(
      (acc, key) =>
        `${key}: ${obj[key]} !important;
         ${acc}`,
      '');
  },

  getAnimationStyles() {
    var styles = {};

    if (!this.props.animations)
      return styles;

    var animation;
    var firstTransform = true;
    var i, len = this.props.animations.length;

    for (i = 0; i < len; i++) {
      animation = this.props.animations[i];

      if (!animation)
        continue;

      var { index, step, ...props } = this.getAnimationProps(animation.source);
      index = defined(index) ? index : 1;

      if (!animation.source && this.getTweeningValue && this.getTweeningValue('step'))
        step = this.getTweeningValue('step');

      if (!defined(step))
        continue; // throw new Error(`No step defined for animation ${source}`);

      var animator = this.getAnimator(animation.name);
      var { scale, rotate, rotate3d, translate, ...other } = animator(index, step, props);

      if (firstTransform && (defined(scale) || defined(rotate) || defined(rotate3d) || defined(translate))) {
        firstTransform = false;
        styles.transforms = { scale, rotate, rotate3d, translate };
      }
      else
        this.mergeTransforms(styles.transforms, scale, rotate, rotate3d, translate);

      if (other)
        Object.assign(styles, other);
    }

    return this.animationTransformsToString(styles);
  },

  animationTransformsToString(styles) {
    if (!styles.transforms)
      return styles;

    var transformsString = '';
    var t = styles.transforms;

    if (t) {
      if (defined(t.scale))
        transformsString += `scale(${t.scale}) `;

      if (defined(t.rotate3d))
        transformsString += (
          rotate.x ? `rotateX(${t.rotate3d.x || 0}deg)` : '' +
          rotate.y ? `rotateY(${t.rotate3d.y || 0}deg)` : '' +
          rotate.z ? `rotateZ(${t.rotate3d.z || 0}deg)` : ''
        );

      if (defined(t.rotate))
        transformsString += `rotate(${t.rotate}deg)`;

      if (defined(t.translate))
        transformsString += `translate3d(${t.translate.x || 0}px, ${t.translate.y || 0}px, ${t.translate.z || 0}px)`;
    }

    delete styles.transforms;
    styles.transform = transformsString || 'translateZ(0px)';
    return styles;
  },

  mergeTransforms(transforms, scale, rotate, rotate3d, translate) {
    if (defined(scale)) {
      if (!defined(transforms.scale))
        transforms.scale = 1;

      transforms.scale += 1 - scale;
    }

    if (defined(rotate3d)) {
      if (!defined(transforms.rotate3d))
        transforms.rotate3d = { x: 0, y: 0, z: 0 };

      transforms.rotate3d.x += (rotate3d.x || 0);
      transforms.rotate3d.y += (rotate3d.y || 0);
      transforms.rotate3d.z += (rotate3d.z || 0);
    }

    if (defined(rotate)) {
      transforms.rotate = (transforms.rotate || 0) + rotate;
    }

    if (defined(translate)) {
      if (!defined(transforms.translate))
        transforms.translate = { x: 0, y: 0, z: 0 };

      transforms.translate.x += (translate.x || 0);
      transforms.translate.y += (translate.y || 0);
      transforms.translate.z += (translate.z || 0);
    }
  },

  isSameAnimation(a, b) {
    return a.name === b.name && a.source === b.source;
  }
};<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'dva';
import ScaffoldItem from '../components/ScaffoldItem';
import styles from './IndexPage.css';

function IndexPage({ list }) {
  return (

        {list.map(item => <ScaffoldItem key={item.name} data={item} styles={styles} />)}

  );
}

IndexPage.propTypes = {
  list: PropTypes.array,
};

IndexPage.defaultProps = {
  list: [],
};

export default connect(props => ({
  list: props.list,
}))(IndexPage);
<commit_msg>refactor IndexPage<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'dva';
import ScaffoldItem from '../components/ScaffoldItem';
import styles from './IndexPage.css';

const IndexPage = ({ list }) => (

      {list.map(item => <ScaffoldItem key={item.name} data={item} styles={styles} />)}

);

IndexPage.propTypes = {
  list: PropTypes.array,
};

IndexPage.defaultProps = {
  list: [],
};

export default connect(props => ({
  list: props.list,
}))(IndexPage);
<|endoftext|>


<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */
// http://www.material-ui.com/#/components/select-field
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
// import AutoComplete from 'material-ui/AutoComplete';
import DatePicker from 'material-ui/DatePicker';
import TimePicker from 'material-ui/TimePicker';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import Slider from 'material-ui/Slider';
import FontIcon from 'material-ui/FontIcon';
import RaisedButton from 'material-ui/RaisedButton';
import AutoComplete from 'material-ui/AutoComplete';
import Snackbar from 'material-ui/Snackbar';
import s from './Home.css';

const listOfServices = [
  'Full Set',
  'Touch Up',
  'Facial',
  'Full Leg Waxing',
  'Half Leg Waxing',
  'Full Arm Waxing',
  'Half Arm Waxing',
  'Under Arm Waxing',
  'Full Face Waxing',
];

const iconStyles = {
  marginRight: 24,
};

class Home extends React.Component {
  static propTypes = {
    contact: PropTypes.arrayOf(
      PropTypes.shape({
        name: PropTypes.string.isRequired,
        mobile: PropTypes.string.isRequired,
        resourceName: PropTypes.string.isRequired,
      }),
    ).isRequired,
    post: PropTypes.func.isRequired,
  };

  state = {
    open: false,
    slider: 75,
  };

  handleNewRequest = (inputString, index) => {
    this.setState({ index, ...inputString });
  };

  handleServiceChange = (event, index, services) => this.setState({ services });

  handleSliderChange = (event, value) => {
    this.setState({ slider: value });
  };

  handleDateChange = (something, dateChosen) => this.setState({ dateChosen });
  handleTimeChange = (something, timeChosen) => this.setState({ timeChosen });

  render() {
    const { services } = this.state;
    return (
      <MuiThemeProvider>

            <AutoComplete
              hintText="Type anything"
              dataSource={this.props.contact}
              dataSourceConfig={{ text: 'name', value: 'name' }}
              onUpdateInput={this.handleNameChange}
              onNewRequest={this.handleNewRequest}
              floatingLabelText="Name"
              filter={AutoComplete.fuzzyFilter}
              fullWidth
            />
            <DatePicker
              hintText="Date"
              autoOk
              fullWidth
              onChange={this.handleDateChange}
              value={this.state.dateChosen}
            />
            <TimePicker
              autoOk
              hintText="Time"
              minutesStep={5}
              onChange={this.handleTimeChange}
              fullWidth
              value={this.state.timeChosen}
            />
            <FontIcon className="material-icons" style={iconStyles}>
              schedule
            </FontIcon>
            <Slider
              defaultValue={75}
              step={5}
              value={this.state.slider}
              min={5}
              max={500}
              onChange={this.handleSliderChange}
            />

                {'Duration: '}

                {this.state.slider}

            <SelectField
              multiple
              hintText="Services"
              value={services}
              onChange={this.handleServiceChange}
              fullWidth
            >
              {listOfServices.map(name =>
                <MenuItem
                  key={name}
                  insetChildren
                  checked={
                    this.state.services &&
                    this.state.services.indexOf(name) > -1
                  }
                  value={name}
                  primaryText={name}
                />,
              )}
            </SelectField>
            <RaisedButton
              label="Create Appointment"
              primary
              fullWidth
              onClick={() => {
                this.props.post(this.state);
                this.setState({ open: true });
              }}
            />
            <Snackbar
              open={this.state.open}
              message="Appointment added to your calendar"
              autoHideDuration={4000}
              onRequestClose={this.handleRequestClose}
              bodyStyle={{ backgroundColor: '#373277' }}
            />

      </MuiThemeProvider>
    );
  }
}

export default withStyles(s)(Home);
<commit_msg>with mobile now<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */
// http://www.material-ui.com/#/components/select-field
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
// import AutoComplete from 'material-ui/AutoComplete';
import DatePicker from 'material-ui/DatePicker';
import TimePicker from 'material-ui/TimePicker';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import Slider from 'material-ui/Slider';
import FontIcon from 'material-ui/FontIcon';
import RaisedButton from 'material-ui/RaisedButton';
import AutoComplete from 'material-ui/AutoComplete';
import Snackbar from 'material-ui/Snackbar';
import s from './Home.css';

const listOfServices = [
  'Full Set',
  'Touch Up',
  'Facial',
  'Full Leg Waxing',
  'Half Leg Waxing',
  'Full Arm Waxing',
  'Half Arm Waxing',
  'Under Arm Waxing',
  'Full Face Waxing',
];

const iconStyles = {
  marginRight: 24,
};

class Home extends React.Component {
  static propTypes = {
    contact: PropTypes.arrayOf(
      PropTypes.shape({
        name: PropTypes.string.isRequired,
        mobile: PropTypes.string.isRequired,
        resourceName: PropTypes.string.isRequired,
      }),
    ).isRequired,
    post: PropTypes.func.isRequired,
  };

  state = {
    open: false,
    slider: 75,
  };

  handleNewRequest = (inputString, index) => {
    this.setState({ index, ...inputString });
  };

  handleServiceChange = (event, index, services) => this.setState({ services });

  handleSliderChange = (event, value) => {
    this.setState({ slider: value });
  };

  handleDateChange = (something, dateChosen) => this.setState({ dateChosen });
  handleTimeChange = (something, timeChosen) => this.setState({ timeChosen });

  render() {
    const { services } = this.state;
    return (
      <MuiThemeProvider>

            <AutoComplete
              hintText="Type anything"
              dataSource={this.props.contact}
              dataSourceConfig={{ text: 'name', value: 'name' }}
              onNewRequest={this.handleNewRequest}
              floatingLabelText="Name"
              filter={AutoComplete.fuzzyFilter}
              fullWidth
            />
            <AutoComplete
              hintText="Type anything"
              dataSource={this.props.contact}
              dataSourceConfig={{ text: 'mobile', value: 'mobile' }}
              onNewRequest={this.handleNewRequest}
              floatingLabelText="Mobile"
              filter={AutoComplete.fuzzyFilter}
              fullWidth
              searchText={this.state.mobile}
            />
            <DatePicker
              hintText="Date"
              autoOk
              fullWidth
              onChange={this.handleDateChange}
              value={this.state.dateChosen}
            />
            <TimePicker
              autoOk
              hintText="Time"
              minutesStep={5}
              onChange={this.handleTimeChange}
              fullWidth
              value={this.state.timeChosen}
            />
            <FontIcon className="material-icons" style={iconStyles}>
              schedule
            </FontIcon>
            <Slider
              defaultValue={75}
              step={5}
              value={this.state.slider}
              min={5}
              max={500}
              onChange={this.handleSliderChange}
            />

                {'Duration: '}

                {this.state.slider}

            <SelectField
              multiple
              hintText="Services"
              value={services}
              onChange={this.handleServiceChange}
              fullWidth
            >
              {listOfServices.map(name =>
                <MenuItem
                  key={name}
                  insetChildren
                  checked={
                    this.state.services &&
                    this.state.services.indexOf(name) > -1
                  }
                  value={name}
                  primaryText={name}
                />,
              )}
            </SelectField>
            <RaisedButton
              label="Create Appointment"
              primary
              fullWidth
              onClick={() => {
                this.props.post(this.state);
                this.setState({ open: true });
              }}
            />
            <Snackbar
              open={this.state.open}
              message="Appointment added to your calendar"
              autoHideDuration={4000}
              onRequestClose={this.handleRequestClose}
              bodyStyle={{ backgroundColor: '#373277' }}
            />

      </MuiThemeProvider>
    );
  }
}

export default withStyles(s)(Home);
<|endoftext|>


<commit_before>
import CONSTANTS from '../../constants'
import log from '../../log'

export default function *( next ) {
    log.info( this.request.method, this.request.url, 'OK', this.request.ip )

    this.onSuccess({
        status: 200,
        body: {
            ping: 'pong'
        }
    })
}
<commit_msg>#update ping route logging<commit_after>
export default function *( next ) {
    this.onSuccess({
        status: 200,
        body: {
            ping: 'pong'
        }
    })
}
<|endoftext|>


<commit_before>import config from '../config'

export const feedback: (feedback) => any =
  (feedback) => {
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': "application/json",
        "Voter-ID": feedback.uuid
      },
      body: JSON.stringify(feedback.feedback)
    }
    return fetch(`${config.urls.devnull}/events/${feedback.eventId}/sessions/${feedback.sessionId}/feedbacks`, options)
      .then(res => {
        if (res.status === 202) {
          return { message: 'Feedback submitted' }
        } else if(res.status === 403) {
          return { message : 'Please try again. Feedback opens 10 min before session ends.' }
        } else {
          return res.status
        }
      }
      )
  } <commit_msg>Add feedback for unidentified errors<commit_after>import config from '../config'

export const feedback: (feedback) => any =
  (feedback) => {
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': "application/json",
        "Voter-ID": feedback.uuid
      },
      body: JSON.stringify(feedback.feedback)
    }
    return fetch(`${config.urls.devnull}/events/${feedback.eventId}/sessions/${feedback.sessionId}/feedbacks`, options)
      .then(res => {
        if (res.status === 202) {
          return { message: 'Feedback submitted' }
        } else if(res.status === 403) {
          return { message : 'Please try again. Feedback opens 10 min before session ends.' }
        } else {
          return { message: 'Ops somthing went wrong.' }
        }
      }
      )
  } <|endoftext|>


<commit_before>var library = require('./library');

function test (obj, testFn) {
    // set logger to console, now output will be displayed
    obj.logger = console;

    // call obj to see some log messages
    testFn();

    // reset the logger to the default, obj and all children will be silent
    obj.logger = null;
    testFn();

    // set the logger to a custom logger, obj and all children will use this logger
    obj.logger = {
        log: function () { console.log("REPLACEMENT LOGGER: LOG"); },
        debug: function () { console.log("REPLACEMENT LOGGER: DEBUG"); },
        info: function () { console.log("REPLACEMENT LOGGER: INFO"); },
        warn: function () { console.log("REPLACEMENT LOGGER: WARN"); },
        error: function () { console.log("REPLACEMENT LOGGER: ERROR"); },
        fatal: function () { console.log("REPLACEMENT LOGGER: FATAL"); }
    };
    testFn();

    // set the logger to undefined, will cause obj to revert to parent (which in this case is nothing, thus the default
    // will be used)
    obj.logger = undefined;
    testFn();
}

test(library, library);

library.logger = console;
test(library.child, library);<commit_msg>Updated examples for linter<commit_after>var library = require('./library');

function test (obj, testFn) {
    // set logger to console, now output will be displayed
    obj.logger = console;

    // call obj to see some log messages
    testFn();

    // reset the logger to the default, obj and all children will be silent
    obj.logger = null;
    testFn();

    // set the logger to a custom logger, obj and all children will use this logger
    obj.logger = {
        log: function () { console.log('REPLACEMENT LOGGER: LOG'); },
        debug: function () { console.log('REPLACEMENT LOGGER: DEBUG'); },
        info: function () { console.log('REPLACEMENT LOGGER: INFO'); },
        warn: function () { console.log('REPLACEMENT LOGGER: WARN'); },
        error: function () { console.log('REPLACEMENT LOGGER: ERROR'); },
        fatal: function () { console.log('REPLACEMENT LOGGER: FATAL'); }
    };
    testFn();

    // set the logger to undefined, will cause obj to revert to parent (which in this case is nothing, thus the default
    // will be used)
    obj.logger = undefined;
    testFn();
}

test(library, library);

library.logger = console;
test(library.child, library);<|endoftext|>


<commit_before><commit_msg>Use -1 cid as indication of no cid<commit_after><|endoftext|>


<commit_before>import HapoalimScraper from './hapoalim';
import OtsarHahayalScraper from './otsar-hahayal';
import LeumiScraper from './leumi';
import DiscountScraper from './discount';
import MaxScraper from './max';
import VisaCalScraper from './visa-cal';
import IsracardScraper from './isracard';
import AmexScraper from './amex';
import MizrahiScraper from './mizrahi';

export default function createScraper(options) {
  switch (options.companyId) {
    case 'hapoalim':
      return new HapoalimScraper(options);
    case 'hapoalimBeOnline':
      console.warn("hapoalimBeOnline is deprecated, use 'hapoalim' instead");
      return new HapoalimScraper(options);
    case 'leumi':
      return new LeumiScraper(options);
    case 'mizrahi':
      return new MizrahiScraper(options);
    case 'discount':
      return new DiscountScraper(options);
    case 'otsarHahayal':
      return new OtsarHahayalScraper(options);
    case 'visaCal':
      return new VisaCalScraper(options);
    case 'leumiCard':
      console.warn("leumiCard is deprecated, use 'max' instead");
      return new MaxScraper(options);
    case 'max':
      return new MaxScraper(options);
    case 'isracard':
      return new IsracardScraper(options);
    case 'amex':
      return new AmexScraper(options);
    default:
      throw new Error(`unknown company id ${options.companyId}`);
  }
}
<commit_msg>Importing UnionBankScraper<commit_after>import HapoalimScraper from './hapoalim';
import OtsarHahayalScraper from './otsar-hahayal';
import LeumiScraper from './leumi';
import DiscountScraper from './discount';
import MaxScraper from './max';
import VisaCalScraper from './visa-cal';
import IsracardScraper from './isracard';
import AmexScraper from './amex';
import MizrahiScraper from './mizrahi';

export default function createScraper(options) {
  switch (options.companyId) {
    case 'hapoalim':
      return new HapoalimScraper(options);
    case 'hapoalimBeOnline':
      console.warn("hapoalimBeOnline is deprecated, use 'hapoalim' instead");
      return new HapoalimScraper(options);
    case 'leumi':
      return new LeumiScraper(options);
    case 'mizrahi':
      return new MizrahiScraper(options);
    case 'discount':
      return new DiscountScraper(options);
    case 'otsarHahayal':
      return new OtsarHahayalScraper(options);
    case 'visaCal':
      return new VisaCalScraper(options);
    case 'leumiCard':
      console.warn("leumiCard is deprecated, use 'max' instead");
      return new MaxScraper(options);
    case 'max':
      return new MaxScraper(options);
    case 'isracard':
      return new IsracardScraper(options);
    case 'amex':
      return new AmexScraper(options);
    case 'union':
      return new UnionBankScraper(options);
    default:
      throw new Error(`unknown company id ${options.companyId}`);
  }
}
<|endoftext|>