<commit_before>function initialize() {
  var styles = [
    {
      "featureType": "administrative",
      "stylers": [
        { "visibility": "off" }
      ]
    },
    {
      "featureType": "landscape",
      "stylers": [
        { "visibility": "off" }
      ]
    },
    {
      "featureType": "poi",
      "stylers": [
        { "visibility": "off" }
      ]
    },
    {
      "featureType": "road",
      "stylers": [
        { "visibility": "off" }
      ]
    },
    {
      "featureType": "transit",
      "stylers": [
        { "visibility": "off" }
      ]
    },
    {
      "featureType": "water",
      "stylers": [
        { "visibility": "simplified" },
        { "color": "#a8a8a2" }
      ]
    },
    {
      "featureType": "administrative.province",
      "stylers": [
        { "visibility": "on" }
      ]
    },
    {
      "featureType": "administrative.province",
      "elementType": "labels",
      "stylers": [
        { "weight": 0.1 }
      ]
    },
    {
      "featureType": "administrative.province",
      "stylers": [
        { "weight": 1.2 }
      ]
    }
  ];

  var mapOptions = {
    center: new google.maps.LatLng(39.50, -98.35),
    zoom: 5,
    styles: styles
  };

  var map = new google.maps.Map(document.getElementById("map-canvas"),
    mapOptions);

  var DURATION = 10
    , INTERVAL = 1
    , MAGNITUDE_SCALE = 20000
    , START_RADIUS_RATIO = 0.8
    , START_OPACITY = 0.35
    , END_OPACITY = 0
    , FADE_TIME_RATIO = 4;

  var last_count = 0
    , data = new Array(2)
    , rotation = 0
    , data_ready_count = 0;

  function convert_event_to_circle_options(event) {
    return {
      strokeColor: '#FF0000',
      strokeOpacity: START_OPACITY,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: START_OPACITY,
      map: map,
      center: new google.maps.LatLng(event.lat, event.lng),
      radius: 0,
      time: event.time,
      magnitude: event.magnitude,
      type: event.type
    };
  }

  function continue_if_ready() {
    data_ready_count++;
    if(data_ready_count === 2) {
      data_ready_count = 0;
      yo_momma(data[1-rotation]);
    }
  }

  function animateCircle(circle, magnitude, duration, interval, delay) {
    window.setTimeout(function() {
      var startSize = magnitude*START_RADIUS_RATIO*MAGNITUDE_SCALE
        , endSize = magnitude*MAGNITUDE_SCALE
        , growthCycle = duration/FADE_TIME_RATIO
        , deltaRadius = (endSize-startSize)/growthCycle
        , deltaOpacity = (END_OPACITY-START_OPACITY)/(duration-growthCycle)
        , count = 0;

      circle.setRadius(startSize);

      var intervalHandle = window.setInterval(function() {
        if(count < growthCycle) {
          circle.setRadius(circle.radius + deltaRadius);
        } else {
          circle.setValues( {
            fillOpacity: circle.fillOpacity + deltaOpacity,
            strokeOpacity: circle.strokeOpacity + deltaOpacity
          });
          if(count === duration) {
            window.clearInterval(intervalHandle);
            circle.setMap(null);
            last_count--;
            if(last_count === 0) continue_if_ready();
          }
        }
        count++;
      }, interval);
    }, delay);
  };

  function batchAnimateCircles(circles, magnitudes, duration, interval, delay) {
    window.setTimeout(function() {
      var startSizes = []
        , endSizes = []
        , growthCycle = duration/FADE_TIME_RATIO
        , deltaRadii = []
        , deltaOpacity = (END_OPACITY-START_OPACITY)/(duration-growthCycle)
        , count = 0
        , len = circles.length
        , startScale = START_RADIUS_RATIO*MAGNITUDE_SCALE
        , i, circle;

      for(i = 0; i < len; i++) {
        startSizes.push(magnitudes[i]*startScale);
        endSizes.push(magnitudes[i]*MAGNITUDE_SCALE);
        deltaRadii.push((endSizes[i]-startSizes[i])/growthCycle);
        circles[i].setRadius(startSizes[i]);
      }

      var intervalHandle = window.setInterval(function() {
        if(count < growthCycle) {
          for(i = 0; i < len; i++) circles[i].setRadius(circles[i].radius + deltaRadii[i]);
        } else {
          for(i = 0; i < len; i++) {
            circle = circles[i];
            circle.setValues({
              fillOpacity: circle.fillOpacity + deltaOpacity,
              strokeOpacity: circle.strokeOpacity + deltaOpacity
            });
          }
          if(count === duration) {
            window.clearInterval(intervalHandle);
            for(i = 0; i < len; i++) circles[i].setMap(null);
            last_count -= len;
            if(last_count === 0) continue_if_ready();
          }
        }
        count++;
      }, interval);
    }, delay);
  }

  function yo_momma(input) {
    $.ajax({
      url: "/balls"
    }).done(function(response) {
      data[rotation] = response;
      rotation = 1-rotation;
      continue_if_ready()
    });

    var len = input.length
      , circleOptions = []
      , start_time = input[0].time;

    last_count = len;

    for(var i = 0; i < len; i++) {
      circleOptions.push(convert_event_to_circle_options(input[i]));
    }

    var circles = []
      , magnitudes = []
      , currentTime
      , options;

    for(var i = 0; i < len; i++) {
      options = circleOptions[i];
      currentTime = options.time;
      while(currentTime === options.time) {
        circles.push(new google.maps.Circle(options));
        magnitudes.push(options.magnitude);
        i++;
        if(i === len) break;
        options = circleOptions[i];
      }
      i--;
      batchAnimateCircles(circles.slice(0), magnitudes.slice(0), DURATION, INTERVAL, (options.time-start_time));
      circles.length = 0;
      magnitudes.length = 0;
    }
  }

  $.ajax({
    url: "/balls"
  }).done(function(response) {
    yo_momma(response);
  });

}

google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>animation framerate drop to cope with the buttloads of data we're swallowing (giggity)<commit_after>function initialize() {
  var styles = [
    {
      "featureType": "administrative",
      "stylers": [
        { "visibility": "off" }
      ]
    },
    {
      "featureType": "landscape",
      "stylers": [
        { "visibility": "off" }
      ]
    },
    {
      "featureType": "poi",
      "stylers": [
        { "visibility": "off" }
      ]
    },
    {
      "featureType": "road",
      "stylers": [
        { "visibility": "off" }
      ]
    },
    {
      "featureType": "transit",
      "stylers": [
        { "visibility": "off" }
      ]
    },
    {
      "featureType": "water",
      "stylers": [
        { "visibility": "simplified" },
        { "color": "#a8a8a2" }
      ]
    },
    {
      "featureType": "administrative.province",
      "stylers": [
        { "visibility": "on" }
      ]
    },
    {
      "featureType": "administrative.province",
      "elementType": "labels",
      "stylers": [
        { "weight": 0.1 }
      ]
    },
    {
      "featureType": "administrative.province",
      "stylers": [
        { "weight": 1.2 }
      ]
    }
  ];

  var mapOptions = {
    center: new google.maps.LatLng(39.50, -98.35),
    zoom: 5,
    styles: styles
  };

  var map = new google.maps.Map(document.getElementById("map-canvas"),
    mapOptions);

  var DURATION = 100
    , INTERVAL = 10
    , MAGNITUDE_SCALE = 20000
    , START_RADIUS_RATIO = 0.8
    , START_OPACITY = 0.35
    , END_OPACITY = 0
    , FADE_TIME_RATIO = 4;

  var last_count = 0
    , data = new Array(2)
    , rotation = 0
    , data_ready_count = 0;

  function convert_event_to_circle_options(event) {
    return {
      strokeColor: '#FF0000',
      strokeOpacity: START_OPACITY,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: START_OPACITY,
      map: map,
      center: new google.maps.LatLng(event.lat, event.lng),
      radius: 0,
      time: event.time,
      magnitude: event.magnitude,
      type: event.type
    };
  }

  function continue_if_ready() {
    data_ready_count++;
    if(data_ready_count === 2) {
      data_ready_count = 0;
      yo_momma(data[1-rotation]);
    }
  }

  function animateCircle(circle, magnitude, duration, interval, delay) {
    window.setTimeout(function() {
      duration = Math.floor(duration/interval);
      var startSize = magnitude*START_RADIUS_RATIO*MAGNITUDE_SCALE
        , endSize = magnitude*MAGNITUDE_SCALE
        , growthCycle = duration/FADE_TIME_RATIO
        , deltaRadius = (endSize-startSize)/growthCycle
        , deltaOpacity = (END_OPACITY-START_OPACITY)/(duration-growthCycle)
        , count = 0;

      circle.setRadius(startSize);

      var intervalHandle = window.setInterval(function() {
        if(count < growthCycle) {
          circle.setRadius(circle.radius + deltaRadius);
        } else {
          circle.setValues( {
            fillOpacity: circle.fillOpacity + deltaOpacity,
            strokeOpacity: circle.strokeOpacity + deltaOpacity
          });
          if(count === duration) {
            window.clearInterval(intervalHandle);
            circle.setMap(null);
            last_count--;
            if(last_count === 0) continue_if_ready();
          }
        }
        count++;
      }, interval);
    }, delay);
  };

  function batchAnimateCircles(circles, magnitudes, duration, interval, delay) {
    window.setTimeout(function() {
      duration = Math.floor(duration/interval);
      var startSizes = []
        , endSizes = []
        , growthCycle = duration/FADE_TIME_RATIO
        , deltaRadii = []
        , deltaOpacity = (END_OPACITY-START_OPACITY)/(duration-growthCycle)
        , count = 0
        , len = circles.length
        , startScale = START_RADIUS_RATIO*MAGNITUDE_SCALE
        , i, circle;

      for(i = 0; i < len; i++) {
        startSizes.push(magnitudes[i]*startScale);
        endSizes.push(magnitudes[i]*MAGNITUDE_SCALE);
        deltaRadii.push((endSizes[i]-startSizes[i])/growthCycle);
        circles[i].setRadius(startSizes[i]);
      }

      var intervalHandle = window.setInterval(function() {
        if(count < growthCycle) {
          for(i = 0; i < len; i++) circles[i].setRadius(circles[i].radius + deltaRadii[i]);
        } else {
          for(i = 0; i < len; i++) {
            circle = circles[i];
            circle.setValues({
              fillOpacity: circle.fillOpacity + deltaOpacity,
              strokeOpacity: circle.strokeOpacity + deltaOpacity
            });
          }
          if(count === duration) {
            window.clearInterval(intervalHandle);
            for(i = 0; i < len; i++) circles[i].setMap(null);
            last_count -= len;
            if(last_count === 0) continue_if_ready();
          }
        }
        count++;
      }, interval);
    }, delay);
  }

  function yo_momma(input) {
    $.ajax({
      url: "/balls"
    }).done(function(response) {
      data[rotation] = response;
      rotation = 1-rotation;
      continue_if_ready()
    });

    var len = input.length
      , circleOptions = []
      , start_time = input[0].time;

    last_count = len;

    for(var i = 0; i < len; i++) {
      circleOptions.push(convert_event_to_circle_options(input[i]));
    }

    var circles = []
      , magnitudes = []
      , currentTime
      , options;

    for(var i = 0; i < len; i++) {
      options = circleOptions[i];
      currentTime = options.time;
      while(currentTime === options.time) {
        circles.push(new google.maps.Circle(options));
        magnitudes.push(options.magnitude);
        i++;
        if(i === len) break;
        options = circleOptions[i];
      }
      i--;
      batchAnimateCircles(circles.slice(0), magnitudes.slice(0), DURATION, INTERVAL, (options.time-start_time));
      circles.length = 0;
      magnitudes.length = 0;
    }
  }

  $.ajax({
    url: "/balls"
  }).done(function(response) {
    yo_momma(response);
  });

}

google.maps.event.addDomListener(window, 'load', initialize);
<|endoftext|>


<commit_before>define(function(require) {
  var EXTERNAL_IPS_ATTRS = [
    'GUEST_IP',
    'AWS_IP_ADDRESS',
    'AZ_IPADDRESS',
    'SL_PRIMARYIPADDRESS'
  ]

  /*
    CONSTRUCTOR
   */

  return {
    'size': _size,
    'sizeFromB': _sizeFromB,
    'sizeFromKB': _sizeFromKB,
    'sizeFromMB': _sizeFromMB,
    'prettyTime': _prettyTime,
    'prettyTimeAxis': _prettyTimeAxis,
    'prettyPrintJSON': _prettyPrintJSON,
    'ipsStr': _ipsStr
  }

  /*
    FUNCTION DEFINITIONS
   */

  /*
    Returns a human readable size in Kilo, Mega, Giga or Tera bytes
    if no from_bytes, assumes value comes in Ks
  */
  function _size(value, from_bytes, sufix) {
    if (typeof(value) === "undefined") {
      value = 0;
    }
    var binarySufix = ["", "K", "M", "G", "T"];

    var i = from_bytes ? 0 : 1;
    while (value >= 1024 && i < 4) {
      value = value / 1024;
      i++;
    }
    value = Math.round(value * 10) / 10;

    if (value - Math.round(value) == 0) {
      value = Math.round(value);
    }

    if (sufix == undefined) {
      sufix = "B";
    }

    var st = value + binarySufix[i] + sufix;
    return st;
  }

  function _sizeFromB(value) {
    return _size(value, true);
  }

  function _sizeFromKB(value) {
    return _size(value);
  }

  function _sizeFromMB(value) {
    if (typeof(value) === "undefined") {
      value = 0;
    }
    var binarySufix =  ["MB", "GB", "TB"];
    var i = 0;
    while (value >= 1024 && i < 2) {
      value = value / 1024;
      i++;
    }
    value = Math.round(value * 10) / 10;

    if (value - Math.round(value) == 0) {
      value = Math.round(value);
    }

    var st = value + binarySufix[i];
    return st;
  }

  //introduces 0s before a number until in reaches 'length'.
  function _pad(number, length) {
    var str = '' + number;
    while (str.length < length)
        str = '0' + str;
    return str;
  }

  //turns a Unix-formatted time into a human readable string
  function _prettyTime(seconds) {
    var d = new Date();
    d.setTime(seconds * 1000);

    var secs = _pad(d.getSeconds(), 2);
    var hour = _pad(d.getHours(), 2);
    var mins = _pad(d.getMinutes(), 2);
    var day = _pad(d.getDate(), 2);
    var month = _pad(d.getMonth() + 1, 2); //getMonths returns 0-11
    var year = d.getFullYear();

    return hour + ":" + mins + ":" + secs + " " + day + "/" + month + "/" + year;
  }

  // Format time for plot axis
  // If show date, only date information is shown
  function _prettyTimeAxis(time, show_date) {
    var d = new Date();
    d.setTime(time * 1000);

    var secs = _pad(d.getSeconds(), 2);
    var hour = _pad(d.getHours(), 2);
    var mins = _pad(d.getMinutes(), 2);
    var day = _pad(d.getDate(), 2);
    var month = _pad(d.getMonth() + 1, 2); //getMonths returns 0-11
    var year = d.getFullYear();

    if (show_date)
        return day + "/" + month;
    else
        return hour + ":" + mins;
  }

  // Returns an HTML string with the json keys and values
  // Attempts to css format output, giving different values to
  // margins etc. according to depth level etc.
  // See example of use in plugins.
  function _prettyPrintJSON(template_json, padding, weight, border_bottom, padding_top_bottom) {
    var str = ""
    if (!template_json) { return "Not defined";}
    if (!padding) {padding = 10};
    if (!weight) {weight = "bold";}
    if (!border_bottom) {border_bottom = "1px solid #efefef";}
    if (!padding_top_bottom) {padding_top_bottom = 6;}
    var field = null;

    if (template_json.constructor == Array) {
      for (field = 0; field < template_json.length; ++field) {
        str += _prettyPrintRowJSON(field, template_json[field], padding, weight, border_bottom, padding_top_bottom);
      }
    } else {
      for (field in template_json) {
        str += _prettyPrintRowJSON(field, template_json[field], padding, weight, border_bottom, padding_top_bottom);
      }
    }
    return str;
  }

  function _prettyPrintRowJSON(field, value, padding, weight, border_bottom, padding_top_bottom) {
    var str = "";

    if (typeof value == 'object') {
      //name of field row
      str += '
\
        ' +
          field +
        '	\
        \
        	\

';
      //attributes rows
      //empty row - prettyprint - empty row
      str += _prettyPrintJSON(value, padding + 25, "normal", "0", 1);
    } else {
      str += '
\
        ' +
          field +
        '	\
        ' +
          value +
        '	\

';
    };

    return str;
  }

  // Return the IP or several IPs of a VM
  function _ipsStr(vm, divider) {
    var divider = divider || "
"
    var nic = vm.TEMPLATE.NIC;
    var ips = [];

    if (nic != undefined) {
      if (!$.isArray(nic)) {
        nic = [nic];
      }

      $.each(nic, function(index, value) {
        if (value.IP) {
          ips.push(value.IP);
        }

        if (value.IP6_GLOBAL) {
          ips.push(value.IP6_GLOBAL);
        }

        if (value.IP6_ULA) {
          ips.push(value.IP6_ULA);
        }
      });
    }

    var template = vm.TEMPLATE;
    var externalIP;
    $.each(EXTERNAL_IPS_ATTRS, function(index, IPAttr) {
      externalIP = template[IPAttr];
      if (externalIP && ($.inArray(externalIP, ips) == -1)) {
        ips.push(externalIP);
      }
    })

    if (ips.length > 0) {
      return ips.join(divider);
    } else {
      return '--';
    }
  };
})
<commit_msg>feature #3748: Add prettyDuration helper<commit_after>define(function(require) {
  var EXTERNAL_IPS_ATTRS = [
    'GUEST_IP',
    'AWS_IP_ADDRESS',
    'AZ_IPADDRESS',
    'SL_PRIMARYIPADDRESS'
  ]

  /*
    CONSTRUCTOR
   */

  return {
    'size': _size,
    'sizeFromB': _sizeFromB,
    'sizeFromKB': _sizeFromKB,
    'sizeFromMB': _sizeFromMB,
    'prettyDuration': _prettyDuration,
    'prettyTime': _prettyTime,
    'prettyTimeAxis': _prettyTimeAxis,
    'prettyPrintJSON': _prettyPrintJSON,
    'ipsStr': _ipsStr
  }

  /*
    FUNCTION DEFINITIONS
   */

  /*
    Returns a human readable size in Kilo, Mega, Giga or Tera bytes
    if no from_bytes, assumes value comes in Ks
  */
  function _size(value, from_bytes, sufix) {
    if (typeof(value) === "undefined") {
      value = 0;
    }
    var binarySufix = ["", "K", "M", "G", "T"];

    var i = from_bytes ? 0 : 1;
    while (value >= 1024 && i < 4) {
      value = value / 1024;
      i++;
    }
    value = Math.round(value * 10) / 10;

    if (value - Math.round(value) == 0) {
      value = Math.round(value);
    }

    if (sufix == undefined) {
      sufix = "B";
    }

    var st = value + binarySufix[i] + sufix;
    return st;
  }

  function _sizeFromB(value) {
    return _size(value, true);
  }

  function _sizeFromKB(value) {
    return _size(value);
  }

  function _sizeFromMB(value) {
    if (typeof(value) === "undefined") {
      value = 0;
    }
    var binarySufix =  ["MB", "GB", "TB"];
    var i = 0;
    while (value >= 1024 && i < 2) {
      value = value / 1024;
      i++;
    }
    value = Math.round(value * 10) / 10;

    if (value - Math.round(value) == 0) {
      value = Math.round(value);
    }

    var st = value + binarySufix[i];
    return st;
  }

  function _prettyDuration(duration) {
    var days = Math.floor(duration / 86400);
    duration -= days * 86400;

    var hours = Math.floor(duration / 3600) % 24;
    duration -= hours * 3600;

    var minutes = Math.floor(duration / 60) % 60;
    duration -= minutes * 60;

    var seconds = duration % 60;

    var str = "";
    if (days > 0) { str += days + 'd '};
    if (hours > 0) { str += hours + 'h '};
    str += minutes + 'm ';
    return str;
  }

  //introduces 0s before a number until in reaches 'length'.
  function _pad(number, length) {
    var str = '' + number;
    while (str.length < length)
        str = '0' + str;
    return str;
  }

  //turns a Unix-formatted time into a human readable string
  function _prettyTime(seconds) {
    var d = new Date();
    d.setTime(seconds * 1000);

    var secs = _pad(d.getSeconds(), 2);
    var hour = _pad(d.getHours(), 2);
    var mins = _pad(d.getMinutes(), 2);
    var day = _pad(d.getDate(), 2);
    var month = _pad(d.getMonth() + 1, 2); //getMonths returns 0-11
    var year = d.getFullYear();

    return hour + ":" + mins + ":" + secs + " " + day + "/" + month + "/" + year;
  }

  // Format time for plot axis
  // If show date, only date information is shown
  function _prettyTimeAxis(time, show_date) {
    var d = new Date();
    d.setTime(time * 1000);

    var secs = _pad(d.getSeconds(), 2);
    var hour = _pad(d.getHours(), 2);
    var mins = _pad(d.getMinutes(), 2);
    var day = _pad(d.getDate(), 2);
    var month = _pad(d.getMonth() + 1, 2); //getMonths returns 0-11
    var year = d.getFullYear();

    if (show_date)
        return day + "/" + month;
    else
        return hour + ":" + mins;
  }

  // Returns an HTML string with the json keys and values
  // Attempts to css format output, giving different values to
  // margins etc. according to depth level etc.
  // See example of use in plugins.
  function _prettyPrintJSON(template_json, padding, weight, border_bottom, padding_top_bottom) {
    var str = ""
    if (!template_json) { return "Not defined";}
    if (!padding) {padding = 10};
    if (!weight) {weight = "bold";}
    if (!border_bottom) {border_bottom = "1px solid #efefef";}
    if (!padding_top_bottom) {padding_top_bottom = 6;}
    var field = null;

    if (template_json.constructor == Array) {
      for (field = 0; field < template_json.length; ++field) {
        str += _prettyPrintRowJSON(field, template_json[field], padding, weight, border_bottom, padding_top_bottom);
      }
    } else {
      for (field in template_json) {
        str += _prettyPrintRowJSON(field, template_json[field], padding, weight, border_bottom, padding_top_bottom);
      }
    }
    return str;
  }

  function _prettyPrintRowJSON(field, value, padding, weight, border_bottom, padding_top_bottom) {
    var str = "";

    if (typeof value == 'object') {
      //name of field row
      str += '
\
        ' +
          field +
        '	\
        \
        	\

';
      //attributes rows
      //empty row - prettyprint - empty row
      str += _prettyPrintJSON(value, padding + 25, "normal", "0", 1);
    } else {
      str += '
\
        ' +
          field +
        '	\
        ' +
          value +
        '	\

';
    };

    return str;
  }

  // Return the IP or several IPs of a VM
  function _ipsStr(vm, divider) {
    var divider = divider || "
"
    var nic = vm.TEMPLATE.NIC;
    var ips = [];

    if (nic != undefined) {
      if (!$.isArray(nic)) {
        nic = [nic];
      }

      $.each(nic, function(index, value) {
        if (value.IP) {
          ips.push(value.IP);
        }

        if (value.IP6_GLOBAL) {
          ips.push(value.IP6_GLOBAL);
        }

        if (value.IP6_ULA) {
          ips.push(value.IP6_ULA);
        }
      });
    }

    var template = vm.TEMPLATE;
    var externalIP;
    $.each(EXTERNAL_IPS_ATTRS, function(index, IPAttr) {
      externalIP = template[IPAttr];
      if (externalIP && ($.inArray(externalIP, ips) == -1)) {
        ips.push(externalIP);
      }
    })

    if (ips.length > 0) {
      return ips.join(divider);
    } else {
      return '--';
    }
  };
})
<|endoftext|>


<commit_before>/*
 * Auto-attach ajax for forms
 *
 * <form action="..." method="post" data-ajaxsend data-options="...">
 * ...
 * <input type="submit" name="submit" value="Send" />
 * </form>
 *
 */

$(function(){

    // using jQuery
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    function sameOrigin(url) {
        // test that a given url is a same-origin URL
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }

    $("form[data-ajaxsend]").each(function(){

        var options = $(this).attr('data-ajaxsend-options') || "";
        if(options){
            options = options.split(';');
            var r = {};
            options.forEach(function(a){
                var b = a.trim().split(':');
                r[b[0]] = (b[1]||'').trim();
                return r
            });
        }

        options = $.extend({
            done_element: this,
            done_event: 'done',
            fail_element: this,
            fail_event: 'fail',
            //complete_element: this,
            //complete_event: 'complete',
            sending_element: this,
            sending_event: 'sending',
            beforesend_element: this,
            beforesend_event: 'beforesend',
            loading_img: 'http://s11.postimg.org/lb6hylp9r/loading.gif'
        }, r);

        var i = new Image();
        i.src = decodeURIComponent(options.loading_img);

        $(this).append($($("
").append(i)).hide());

        function disabled(form){
            form.find('input,textarea,select').attr('disabled', true);
        }

        function enabled(form){
            form.find('input,textarea,select').attr('disabled', false);
        }

        // capture submit
        $(this).on('submit', function(event){
            event.preventDefault();
            var $form = $(this);
            var formData = $form.serialize();

            /* si hay un file entre los campos usa el otro metodo */
            var filesInput = $form.find('input[type=file]');

            if(filesInput.length){

                // Create a new FormData object.
                formData = new FormData();

                for (var f = 0; f < filesInput.length; f++) {

                    // Loop through each of the selected files.
                    for (var i = 0; i < filesInput[f].files.length; i++) {
                      var file = filesInput[f].files[i];

                      // Add the file to the request.
                      formData.append(filesInput[f].name, file, file.name);
                    }
                }

                var formDataString = $form.serializeArray();

                for (var i = 0; i < formDataString.length; i++) {
                    formData.append(formDataString[i].name, formDataString[i].value);
                }
            }

            var xhr = $.ajax({
                type: 'POST',
                url: $form.attr('action'),
                data: formData,
                dataType: 'json',
                global: false,
                cache: false,
                //contentType: false, /* bug? no termina de procesar los datos la vista de django y POST viaja vacio */
                processData: false,
                beforeSend: function(jqXHR, settings){
                    $form.find('.loading').show();
                    disabled($form);
                    console.log('loading...');
                    $(options.beforesend_element).trigger(options.beforesend_event, jqXHR);

                    // CSRFToken protect
                    if (csrftoken && !csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                        jqXHR.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

            xhr.always(function(response){
                $form.find('.loading').hide();
                console.log('stop');
                enabled($form);
                $(options.sending_element).trigger(options.sending_event, response);
            });

            xhr.done(function(data, textStatus, jqXHR){
                $(options.done_element).trigger(options.done_event, {data:data, textStatus:textStatus, jqXHR:jqXHR});
                $form.trigger('reset'); // clean
            });

            xhr.fail(function(jqXHR, textStatus, errorThrown){
                $(options.fail_element, $form).trigger(options.fail_event, {jqXHR:jqXHR, textStatus:textStatus, errorThrown:errorThrown});
                try {
                    $.each(jqXHR.responseJSON.errors, function(key, val){
                        $form
                            .find("*[name="+key+"]")
                            .addClass('error')
                            .next('.error')
                            .css('display', 'block')
                            .text(val[0]);
                    });
                } catch(E){};
            });

            return false;
        });

        // tracking para google analytics
        // on submit
        $(this).on('done', function(event){
            var $form = $(this);
            var action = $form.attr('action') + '/submited/';
            var custom_tarck_pageview = $form.data('track_pageview');
            var track_pageview = action || custom_tarck_pageview;

            if(_gaq){
                _gaq.push(['_trackPageview', track_pageview]);
            } else if(ga) {
                ga('send', 'pageview', track_pageview);
            }
        });
    });

});
<commit_msg>fix js var for ga<commit_after>/*
 * Auto-attach ajax for forms
 *
 * <form action="..." method="post" data-ajaxsend data-options="...">
 * ...
 * <input type="submit" name="submit" value="Send" />
 * </form>
 *
 */

$(function(){

    // using jQuery
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    function sameOrigin(url) {
        // test that a given url is a same-origin URL
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }

    $("form[data-ajaxsend]").each(function(){

        var options = $(this).attr('data-ajaxsend-options') || "";
        if(options){
            options = options.split(';');
            var r = {};
            options.forEach(function(a){
                var b = a.trim().split(':');
                r[b[0]] = (b[1]||'').trim();
                return r
            });
        }

        options = $.extend({
            done_element: this,
            done_event: 'done',
            fail_element: this,
            fail_event: 'fail',
            //complete_element: this,
            //complete_event: 'complete',
            sending_element: this,
            sending_event: 'sending',
            beforesend_element: this,
            beforesend_event: 'beforesend',
            loading_img: 'http://s11.postimg.org/lb6hylp9r/loading.gif'
        }, r);

        var i = new Image();
        i.src = decodeURIComponent(options.loading_img);

        $(this).append($($("
").append(i)).hide());

        function disabled(form){
            form.find('input,textarea,select').attr('disabled', true);
        }

        function enabled(form){
            form.find('input,textarea,select').attr('disabled', false);
        }

        // capture submit
        $(this).on('submit', function(event){
            event.preventDefault();
            var $form = $(this);
            var formData = $form.serialize();

            /* si hay un file entre los campos usa el otro metodo */
            var filesInput = $form.find('input[type=file]');

            if(filesInput.length){

                // Create a new FormData object.
                formData = new FormData();

                for (var f = 0; f < filesInput.length; f++) {

                    // Loop through each of the selected files.
                    for (var i = 0; i < filesInput[f].files.length; i++) {
                      var file = filesInput[f].files[i];

                      // Add the file to the request.
                      formData.append(filesInput[f].name, file, file.name);
                    }
                }

                var formDataString = $form.serializeArray();

                for (var i = 0; i < formDataString.length; i++) {
                    formData.append(formDataString[i].name, formDataString[i].value);
                }
            }

            var xhr = $.ajax({
                type: 'POST',
                url: $form.attr('action'),
                data: formData,
                dataType: 'json',
                global: false,
                cache: false,
                //contentType: false, /* bug? no termina de procesar los datos la vista de django y POST viaja vacio */
                processData: false,
                beforeSend: function(jqXHR, settings){
                    $form.find('.loading').show();
                    disabled($form);
                    console.log('loading...');
                    $(options.beforesend_element).trigger(options.beforesend_event, jqXHR);

                    // CSRFToken protect
                    if (csrftoken && !csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                        jqXHR.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

            xhr.always(function(response){
                $form.find('.loading').hide();
                console.log('stop');
                enabled($form);
                $(options.sending_element).trigger(options.sending_event, response);
            });

            xhr.done(function(data, textStatus, jqXHR){
                $(options.done_element).trigger(options.done_event, {data:data, textStatus:textStatus, jqXHR:jqXHR});
                $form.trigger('reset'); // clean
            });

            xhr.fail(function(jqXHR, textStatus, errorThrown){
                $(options.fail_element, $form).trigger(options.fail_event, {jqXHR:jqXHR, textStatus:textStatus, errorThrown:errorThrown});
                try {
                    $.each(jqXHR.responseJSON.errors, function(key, val){
                        $form
                            .find("*[name="+key+"]")
                            .addClass('error')
                            .next('.error')
                            .css('display', 'block')
                            .text(val[0]);
                    });
                } catch(E){};
            });

            return false;
        });

        // tracking para google analytics
        // on submit
        $(this).on('done', function(event){
            var $form = $(this);
            var action = $form.attr('action') + '/submited/';
            var custom_tarck_pageview = $form.data('track_pageview');
            var track_pageview = action || custom_tarck_pageview;

            if(window._gaq){
                _gaq.push(['_trackPageview', track_pageview]);
            } else if(window.ga) {
                ga('send', 'pageview', track_pageview);
            }
        });
    });

});
<|endoftext|>


<commit_before>// flow-typed signature: b1b677fe36048ce994b3d3910c5a6a4e
// flow-typed version: <<STUB>>/@blueprintjs/core_v^1.6.0/flow_v0.43.1

import * as React from 'react'

declare module '@blueprintjs/core' {
  //
  // Constants
  //
  declare export type PRIMARY = 'PRIMARY'
  declare export type SUCCESS = 'SUCCESS'
  declare export type WARNING = 'WARNING'
  declare export type DANGER = 'DANGER'
  declare export type IntentType =
    | PRIMARY
    | SUCCESS
    | WARNING
    | DANGER
    | typeof undefined

  declare export interface Intent {
    static PRIMARY: PRIMARY,
    static SUCCESS: SUCCESS,
    static WARNING: WARNING,
    static DANGER: DANGER,
  }

  declare export type TOP_LEFT = 'TOP_LEFT'
  declare export type TOP = 'TOP'
  declare export type TOP_RIGHT = 'TOP_RIGHT'
  declare export type RIGHT_TOP = 'RIGHT_TOP'
  declare export type RIGHT = 'RIGHT'
  declare export type RIGHT_BOTTOM = 'RIGHT_BOTTOM'
  declare export type BOTTOM_RIGHT = 'BOTTOM_RIGHT'
  declare export type BOTTOM = 'BOTTOM'
  declare export type BOTTOM_LEFT = 'BOTTOM_LEFT'
  declare export type LEFT_BOTTOM = 'LEFT_BOTTOM'
  declare export type LEFT = 'LEFT'
  declare export type LEFT_TOP = 'LEFT_TOP'
  declare export type PositionType =
    | TOP_LEFT
    | TOP
    | TOP_RIGHT
    | RIGHT_TOP
    | RIGHT
    | RIGHT_BOTTOM
    | BOTTOM_RIGHT
    | BOTTOM
    | BOTTOM_LEFT
    | LEFT_BOTTOM
    | LEFT
    | LEFT_TOP

  declare export interface Position {
    static TOP_LEFT: TOP_LEFT,
    static TOP: TOP,
    static TOP_RIGHT: TOP_RIGHT,
    static RIGHT_TOP: RIGHT_TOP,
    static RIGHT: RIGHT,
    static RIGHT_BOTTOM: RIGHT_BOTTOM,
    static BOTTOM_RIGHT: BOTTOM_RIGHT,
    static BOTTOM: BOTTOM,
    static BOTTOM_LEFT: BOTTOM_LEFT,
    static LEFT_BOTTOM: LEFT_BOTTOM,
    static LEFT: LEFT,
    static LEFT_TOP: LEFT_TOP,
  }

  declare export type CLICK = 'CLICK'
  declare export type CLICK_TARGET_ONLY = 'CLICK_TARGET_ONLY'
  declare export type HOVER = 'HOVER'
  declare export type HOVER_TARGET_ONLY = 'HOVER_TARGET_ONLY'
  declare export type PopoverInteractionKindType =
    | CLICK
    | CLICK_TARGET_ONLY
    | HOVER
    | HOVER_TARGET_ONLY

  declare export interface PopoverInteractionKind {
    static CLICK: CLICK,
    static CLICK_TARGET_ONLY: CLICK_TARGET_ONLY,
    static HOVER: HOVER,
    static HOVER_TARGET_ONLY: HOVER_TARGET_ONLY,
  }

  //
  // Interfaces
  //
  declare export interface IProps {
    className?: string,
  }

  declare export interface IActionProps {
    disabled?: boolean,
    text?: string,
    iconName?: string,
    onClick?: (SyntheticEvent<*>) => any,
  }

  declare export interface IBackdropProps {
    backdropClassName?: string,
    backdropProps?: HTMLDivElement,
    canOutsideClickClose?: boolean,
    hasBackdrop?: boolean,
  }

  declare export interface IControlledProps {
    defaultValue?: string,
    onChange?: (SyntheticInputEvent<*>) => any,
    value?: string,
  }

  declare export interface IControlProps {
    checked?: boolean,
    defaultChecked?: boolean,
    disabled?: boolean,
    inputRef?: HTMLInputElement => any,
    label?: string,
    onChange?: (SyntheticInputEvent<*>) => any,
  }

  declare export interface IIntentProps {
    intent?: IntentType,
  }

  declare export interface ILinkProps {
    href?: string,
    target?: '_self' | '_blank' | '_parent' | '_top',
  }

  declare export interface IOptionProps {
    className?: string,
    disabled?: boolean,
    label?: string,
    value?: string,
  }

  declare export interface IOverlayableProps {
    autoFocus?: boolean,
    canEscapeKeyClose?: boolean,
    enforceFocus?: boolean,
    inline?: boolean,
    lazy?: boolean,
    onClose?: (SyntheticEvent<*>) => any,
    transitionDuration?: number,
  }

  //
  // Components
  //
  declare export class AnchorButton extends React.Component<
    {
      active?: boolean,
    } & IActionProps
  > {}

  declare export class Button extends React.Component<
    {
      active?: boolean,
    } & IActionProps
  > {}

  declare export class EditableText extends React.Component<
    {
      confirmOnEnterKey?: boolean,
      defaultValue?: string,
      disabled?: boolean,
      isEditing?: boolean,
      maxLength?: number,
      maxLines?: number,
      minLines?: number,
      minWidth?: number,
      multiline?: boolean,
      onCancel?: string => any,
      onChange?: string => any,
      onConfirm?: string => any,
      onEdit?: () => any,
      placeholder?: string,
      selectAllOnFocus?: boolean,
      value?: string,
    } & IProps &
      IIntentProps
  > {}

  declare export class Dialog extends React.Component<
    {
      iconName?: string,
      isCloseButtonShown?: boolean,
      isOpen: boolean,
      style: Object,
      title: React.Node,
    } & IProps &
      IBackdropProps &
      IOverlayableProps
  > {}

  declare export class InputGroup extends React.Component<
    {
      disabled?: boolean,
      intent?: IntentType,
      leftIconName?: string,
      placeholder?: string,
      rightElement?: React.Node,
      type?: string,
    } & IProps &
      IControlledProps
  > {}

  declare export class Menu extends React.Component<
    { ulRef?: (ref: HTMLUListElement) => any } & IProps
  > {}

  declare export class MenuItem extends React.Component<
    {
      label?: React.Node,
      shouldDismissPopover?: boolean,
      submenu?: Array<$PropertyType<MenuItem, 'props'>>,
      submenuViewportMargin?: { left?: number, right?: number },
      text: string,
      useSmartPositioning?: boolean,
    } & IProps &
      IActionProps &
      ILinkProps
  > {}

  declare export class NonIdealState extends React.Component<
    {
      action?: React.Node,
      description?: React.Node,
      title?: string,
      visual?: React.Node,
    } & IProps
  > {}

  declare export class Popover extends React.Component<
    {
      backdropProps?: HTMLDivElement,
      content?: React.Node,
      defaultIsOpen?: boolean,
      hoverCloseDelay?: number,
      hoverOpenDelay?: number,
      inheritDarkTheme?: boolean,
      interactionKind?: PopoverInteractionKindType,
      isDisabled?: boolean,
      isModal?: boolean,
      isOpen?: boolean,
      onInteraction?: (nextOpenState: boolean) => void,
      popoverClassName?: string,
      popoverDidOpen?: () => void,
      popoverWillClose?: () => void,
      popoverWillOpen?: () => void,
      portalClassName?: string,
      position?: PositionType,
      rootElementTag?: string,
      target?: React.Node,
      tetherOptions?: Object,
      useSmartArrowPositioning?: boolean,
    } & IOverlayableProps &
      IProps
  > {}

  declare export class Portal extends React.Component<{}> {}

  declare export class Radio extends React.Component<IControlProps & IProps> {}

  declare export class RadioGroup extends React.Component<{
    disabled?: boolean,
    label?: string,
    name?: string,
    onChange: (SyntheticInputEvent<*>) => any,
    options?: IOptionProps[],
    selectedValue?: string,
  }> {}

  declare export type Toast = {
    action?: IActionProps & ILinkProps,
    message: string,
    onDismiss?: (didTimoutExpire: boolean) => any,
    iconName?: string,
    timeout?: number,
  } & IProps &
    IIntentProps

  declare export class Toaster extends React.Component<{}> {
    static create(
      props: ?({
        autoFocus?: boolean,
        canEscapeKeyClear?: boolean,
        inline?: boolean,
        position?: Position,
      } & IProps),
      container: ?HTMLElement
    ): Toaster,
    show(props: Toast): string,
    update(key: string, props: Toast): void,
    dismiss(key: string): void,
    clear(): void,
    getToasts(): Toast[],
  }

  declare export class Tooltip extends React.Component<
    {
      content: React.Node,
      defaultIsOpen?: boolean,
      hoverCloseDelay?: number,
      hoverOpenDelay?: number,
      inheritDarkTheme?: boolean,
      inline?: boolean,
      isDisabled?: boolean,
      isOpen?: boolean,
      onInteraction?: (nextOpenState: boolean) => void,
      openOnTargetFocus?: boolean,
      portalClassName?: string,
      position?: PositionType,
      rootElementTag?: string,
      tooltipClassName?: string,
      transitionDuration?: number,
      useSmartArrowPositioning?: boolean,
      useSmartPositioning?: boolean,
    } & IIntentProps & IProps
  > {}
}
<commit_msg>chore(flow): change interfaces wtih static properties to classes<commit_after>// flow-typed signature: b1b677fe36048ce994b3d3910c5a6a4e
// flow-typed version: <<STUB>>/@blueprintjs/core_v^1.6.0/flow_v0.43.1

import * as React from 'react'

declare module '@blueprintjs/core' {
  //
  // Constants
  //
  declare export type PRIMARY = 'PRIMARY'
  declare export type SUCCESS = 'SUCCESS'
  declare export type WARNING = 'WARNING'
  declare export type DANGER = 'DANGER'
  declare export type IntentType =
    | PRIMARY
    | SUCCESS
    | WARNING
    | DANGER
    | typeof undefined

  declare export class Intent {
    static PRIMARY: PRIMARY,
    static SUCCESS: SUCCESS,
    static WARNING: WARNING,
    static DANGER: DANGER,
  }

  declare export type TOP_LEFT = 'TOP_LEFT'
  declare export type TOP = 'TOP'
  declare export type TOP_RIGHT = 'TOP_RIGHT'
  declare export type RIGHT_TOP = 'RIGHT_TOP'
  declare export type RIGHT = 'RIGHT'
  declare export type RIGHT_BOTTOM = 'RIGHT_BOTTOM'
  declare export type BOTTOM_RIGHT = 'BOTTOM_RIGHT'
  declare export type BOTTOM = 'BOTTOM'
  declare export type BOTTOM_LEFT = 'BOTTOM_LEFT'
  declare export type LEFT_BOTTOM = 'LEFT_BOTTOM'
  declare export type LEFT = 'LEFT'
  declare export type LEFT_TOP = 'LEFT_TOP'
  declare export type PositionType =
    | TOP_LEFT
    | TOP
    | TOP_RIGHT
    | RIGHT_TOP
    | RIGHT
    | RIGHT_BOTTOM
    | BOTTOM_RIGHT
    | BOTTOM
    | BOTTOM_LEFT
    | LEFT_BOTTOM
    | LEFT
    | LEFT_TOP

  declare export class Position {
    static TOP_LEFT: TOP_LEFT,
    static TOP: TOP,
    static TOP_RIGHT: TOP_RIGHT,
    static RIGHT_TOP: RIGHT_TOP,
    static RIGHT: RIGHT,
    static RIGHT_BOTTOM: RIGHT_BOTTOM,
    static BOTTOM_RIGHT: BOTTOM_RIGHT,
    static BOTTOM: BOTTOM,
    static BOTTOM_LEFT: BOTTOM_LEFT,
    static LEFT_BOTTOM: LEFT_BOTTOM,
    static LEFT: LEFT,
    static LEFT_TOP: LEFT_TOP,
  }

  declare export type CLICK = 'CLICK'
  declare export type CLICK_TARGET_ONLY = 'CLICK_TARGET_ONLY'
  declare export type HOVER = 'HOVER'
  declare export type HOVER_TARGET_ONLY = 'HOVER_TARGET_ONLY'
  declare export type PopoverInteractionKindType =
    | CLICK
    | CLICK_TARGET_ONLY
    | HOVER
    | HOVER_TARGET_ONLY

  declare export class PopoverInteractionKind {
    static CLICK: CLICK,
    static CLICK_TARGET_ONLY: CLICK_TARGET_ONLY,
    static HOVER: HOVER,
    static HOVER_TARGET_ONLY: HOVER_TARGET_ONLY,
  }

  //
  // Interfaces
  //
  declare export interface IProps {
    className?: string,
  }

  declare export interface IActionProps {
    disabled?: boolean,
    text?: string,
    iconName?: string,
    onClick?: (SyntheticEvent<*>) => any,
  }

  declare export interface IBackdropProps {
    backdropClassName?: string,
    backdropProps?: HTMLDivElement,
    canOutsideClickClose?: boolean,
    hasBackdrop?: boolean,
  }

  declare export interface IControlledProps {
    defaultValue?: string,
    onChange?: (SyntheticInputEvent<*>) => any,
    value?: string,
  }

  declare export interface IControlProps {
    checked?: boolean,
    defaultChecked?: boolean,
    disabled?: boolean,
    inputRef?: HTMLInputElement => any,
    label?: string,
    onChange?: (SyntheticInputEvent<*>) => any,
  }

  declare export interface IIntentProps {
    intent?: IntentType,
  }

  declare export interface ILinkProps {
    href?: string,
    target?: '_self' | '_blank' | '_parent' | '_top',
  }

  declare export interface IOptionProps {
    className?: string,
    disabled?: boolean,
    label?: string,
    value?: string,
  }

  declare export interface IOverlayableProps {
    autoFocus?: boolean,
    canEscapeKeyClose?: boolean,
    enforceFocus?: boolean,
    inline?: boolean,
    lazy?: boolean,
    onClose?: (SyntheticEvent<*>) => any,
    transitionDuration?: number,
  }

  //
  // Components
  //
  declare export class AnchorButton extends React.Component<
    {
      active?: boolean,
    } & IActionProps
  > {}

  declare export class Button extends React.Component<
    {
      active?: boolean,
    } & IActionProps
  > {}

  declare export class EditableText extends React.Component<
    {
      confirmOnEnterKey?: boolean,
      defaultValue?: string,
      disabled?: boolean,
      isEditing?: boolean,
      maxLength?: number,
      maxLines?: number,
      minLines?: number,
      minWidth?: number,
      multiline?: boolean,
      onCancel?: string => any,
      onChange?: string => any,
      onConfirm?: string => any,
      onEdit?: () => any,
      placeholder?: string,
      selectAllOnFocus?: boolean,
      value?: string,
    } & IProps &
      IIntentProps
  > {}

  declare export class Dialog extends React.Component<
    {
      iconName?: string,
      isCloseButtonShown?: boolean,
      isOpen: boolean,
      style: Object,
      title: React.Node,
    } & IProps &
      IBackdropProps &
      IOverlayableProps
  > {}

  declare export class InputGroup extends React.Component<
    {
      disabled?: boolean,
      intent?: IntentType,
      leftIconName?: string,
      placeholder?: string,
      rightElement?: React.Node,
      type?: string,
    } & IProps &
      IControlledProps
  > {}

  declare export class Menu extends React.Component<
    { ulRef?: (ref: HTMLUListElement) => any } & IProps
  > {}

  declare export class MenuItem extends React.Component<
    {
      label?: React.Node,
      shouldDismissPopover?: boolean,
      submenu?: Array<$PropertyType<MenuItem, 'props'>>,
      submenuViewportMargin?: { left?: number, right?: number },
      text: string,
      useSmartPositioning?: boolean,
    } & IProps &
      IActionProps &
      ILinkProps
  > {}

  declare export class NonIdealState extends React.Component<
    {
      action?: React.Node,
      description?: React.Node,
      title?: string,
      visual?: React.Node,
    } & IProps
  > {}

  declare export class Popover extends React.Component<
    {
      backdropProps?: HTMLDivElement,
      content?: React.Node,
      defaultIsOpen?: boolean,
      hoverCloseDelay?: number,
      hoverOpenDelay?: number,
      inheritDarkTheme?: boolean,
      interactionKind?: PopoverInteractionKindType,
      isDisabled?: boolean,
      isModal?: boolean,
      isOpen?: boolean,
      onInteraction?: (nextOpenState: boolean) => void,
      popoverClassName?: string,
      popoverDidOpen?: () => void,
      popoverWillClose?: () => void,
      popoverWillOpen?: () => void,
      portalClassName?: string,
      position?: PositionType,
      rootElementTag?: string,
      target?: React.Node,
      tetherOptions?: Object,
      useSmartArrowPositioning?: boolean,
    } & IOverlayableProps &
      IProps
  > {}

  declare export class Portal extends React.Component<{}> {}

  declare export class Radio extends React.Component<IControlProps & IProps> {}

  declare export class RadioGroup extends React.Component<{
    disabled?: boolean,
    label?: string,
    name?: string,
    onChange: (SyntheticInputEvent<*>) => any,
    options?: IOptionProps[],
    selectedValue?: string,
  }> {}

  declare export type Toast = {
    action?: IActionProps & ILinkProps,
    message: string,
    onDismiss?: (didTimoutExpire: boolean) => any,
    iconName?: string,
    timeout?: number,
  } & IProps &
    IIntentProps

  declare export class Toaster extends React.Component<{}> {
    static create(
      props: ?({
        autoFocus?: boolean,
        canEscapeKeyClear?: boolean,
        inline?: boolean,
        position?: Position,
      } & IProps),
      container: ?HTMLElement
    ): Toaster,
    show(props: Toast): string,
    update(key: string, props: Toast): void,
    dismiss(key: string): void,
    clear(): void,
    getToasts(): Toast[],
  }

  declare export class Tooltip extends React.Component<
    {
      content: React.Node,
      defaultIsOpen?: boolean,
      hoverCloseDelay?: number,
      hoverOpenDelay?: number,
      inheritDarkTheme?: boolean,
      inline?: boolean,
      isDisabled?: boolean,
      isOpen?: boolean,
      onInteraction?: (nextOpenState: boolean) => void,
      openOnTargetFocus?: boolean,
      portalClassName?: string,
      position?: PositionType,
      rootElementTag?: string,
      tooltipClassName?: string,
      transitionDuration?: number,
      useSmartArrowPositioning?: boolean,
      useSmartPositioning?: boolean,
    } & IIntentProps & IProps
  > {}
}
<|endoftext|>


<commit_before>import Realm from 'realm';
import { createRecord } from '../utilities';

/**
 * A stocktake batch.
 *
 * @property  {string}     id
 * @property  {Stocktake}  stocktake
 * @property  {ItemBatch}  itemBatch
 * @property  {number}     snapshotNumberOfPacks
 * @property  {number}     packSize
 * @property  {Date}       expiryDate
 * @property  {string}     batch
 * @property  {number}     costPrice
 * @property  {number}     sellPrice
 * @property  {number}     countedNumberOfPacks
 * @property  {number}     sortIndex
 */
export class StocktakeBatch extends Realm.Object {
  /**
   * Delete stocktake batch and associated item batch.
   *
   * @param  {Realm}  database
   */
  destructor(database) {
    if (this.snapshotNumberOfPacks === 0 && this.itemBatch.numberOfPacks === 0) {
      database.delete('ItemBatch', this.itemBatch);
    }
  }

  /**
   * Get snapshot of total quantity in batch.
   *
   * @return  {number}
   */
  get snapshotTotalQuantity() {
    return this.snapshotNumberOfPacks * this.packSize;
  }

  /**
   * Get total quantity in batch.
   *
   * @return  {number}
   */
  get countedTotalQuantity() {
    if (this.countedNumberOfPacks === null) return this.snapshotTotalQuantity;
    return this.countedNumberOfPacks * this.packSize;
  }

  /**
   * Get if stocktake will reduce stock on hand of item below zero.
   *
   * Stock on hand should never be negative. This can occur when stock has been issued
   * in a customer invoice for this batch before the parent stocktake was finalised.
   *
   * @return  {boolean}
   */
  get isReducedBelowMinimum() {
    const { totalQuantity: stockOnHand } = this.itemBatch;

    // Return true if |stockOnHand + stocktakebatch.difference| is negative.
    return stockOnHand + this.difference < 0;
  }

  /**
   * Get if snapshot is out-of-date.
   *
   * Returns true if the |snapshotTotalQuantity| does not match the |totalQuantity| of the
   * item batch this stocktake batch is associated with. Will occur if inventory has changed
   * since this stocktake batch was created. If the net change on this batch is 0, then return
   * false.
   *
   * @return  {boolean}
   */
  get isSnapshotOutdated() {
    return this.snapshotTotalQuantity !== this.itemBatch.totalQuantity;
  }

  /**
   * Get if stocktake batch has been counted.
   *
   * @return  {boolean}
   */
  get hasBeenCounted() {
    return this.countedNumberOfPacks !== null;
  }

  /**
   * Get id of item associated with this stocktake batch.
   *
   * @return  {string}
   */
  get itemId() {
    if (!this.itemBatch) return '';
    return this.itemBatch.item ? this.itemBatch.item.id : '';
  }

  /**
   * Get id of item batch associated with this stocktake batch.
   *
   * @return  {string}
   */
  get itemBatchId() {
    return this.itemBatch ? this.itemBatch.id : '';
  }

  /**
   * Get difference between counted quantity and snapshop quantity.
   *
   * @return  {number}
   */
  get difference() {
    return this.countedTotalQuantity - this.snapshotTotalQuantity;
  }

  /**
   * Set counted total quantity.
   *
   * @param  {number}  quantity
   */
  set countedTotalQuantity(quantity) {
    // Handle packsize of 0.
    this.countedNumberOfPacks = this.packSize ? quantity / this.packSize : 0;
  }

  /**
   * Finalise stocktake batch.
   *
   * Finalising will adjust inventory appropriately and will add a new transaction
   * batch in reducing or increasing transaction for this stocktake.
   *
   * @param  {Realm}  database
   */
  finalise(database) {
    // Update the item batch details.
    this.itemBatch.batch = this.batch;
    this.itemBatch.expiryDate = this.expiryDate;

    // Make inventory adjustments if there is a difference to apply.
    if (this.difference !== 0) {
      const isAddition = this.countedTotalQuantity > this.snapshotTotalQuantity;
      const inventoryAdjustment = isAddition
        ? this.stocktake.getAdditions(database)
        : this.stocktake.getReductions(database);

      // Create transaction item and transaction batch to store inventory adjustments in this
      // stocktake.
      const transactionItem = createRecord(
        database,
        'TransactionItem',
        inventoryAdjustment,
        this.itemBatch.item
      );
      const transactionBatch = createRecord(
        database,
        'TransactionBatch',
        transactionItem,
        this.itemBatch
      );

      // Apply difference from stocktake to actual stock on hand levels. Whether stock is increased
      // or decreased is determined by the transaction, use the absolute value of difference
      // (i.e. always treat as positive).
      const snapshotDifference = Math.abs(this.difference);
      transactionBatch.setTotalQuantity(database, snapshotDifference);
      database.save('TransactionBatch', transactionBatch);
    }
    database.save('ItemBatch', this.itemBatch);
  }

  /**
   * Get string representation of stocktake batch.
   *
   * @return  {string}
   */
  toString() {
    return `Stocktake batch representing ${this.itemBatch}`;
  }
}

StocktakeBatch.schema = {
  name: 'StocktakeBatch',
  primaryKey: 'id',
  properties: {
    id: 'string',
    stocktake: 'Stocktake',
    itemBatch: 'ItemBatch',
    snapshotNumberOfPacks: 'double',
    packSize: 'double',
    expiryDate: { type: 'date', optional: true },
    batch: 'string',
    costPrice: 'double',
    sellPrice: 'double',
    countedNumberOfPacks: { type: 'double', optional: true },
    sortIndex: { type: 'int', optional: true },
    option: { type: 'Options', optional: true },
  },
};

export default StocktakeBatch;
<commit_msg>Add StocktakeBatch shouldApplyReason helper<commit_after>import Realm from 'realm';
import { createRecord } from '../utilities';

/**
 * A stocktake batch.
 *
 * @property  {string}     id
 * @property  {Stocktake}  stocktake
 * @property  {ItemBatch}  itemBatch
 * @property  {number}     snapshotNumberOfPacks
 * @property  {number}     packSize
 * @property  {Date}       expiryDate
 * @property  {string}     batch
 * @property  {number}     costPrice
 * @property  {number}     sellPrice
 * @property  {number}     countedNumberOfPacks
 * @property  {number}     sortIndex
 */
export class StocktakeBatch extends Realm.Object {
  /**
   * Delete stocktake batch and associated item batch.
   *
   * @param  {Realm}  database
   */
  destructor(database) {
    if (this.snapshotNumberOfPacks === 0 && this.itemBatch.numberOfPacks === 0) {
      database.delete('ItemBatch', this.itemBatch);
    }
  }

  /**
   * Get snapshot of total quantity in batch.
   *
   * @return  {number}
   */
  get snapshotTotalQuantity() {
    return this.snapshotNumberOfPacks * this.packSize;
  }

  /**
   * Get total quantity in batch.
   *
   * @return  {number}
   */
  get countedTotalQuantity() {
    if (this.countedNumberOfPacks === null) return this.snapshotTotalQuantity;
    return this.countedNumberOfPacks * this.packSize;
  }

  /**
   * Get if stocktake will reduce stock on hand of item below zero.
   *
   * Stock on hand should never be negative. This can occur when stock has been issued
   * in a customer invoice for this batch before the parent stocktake was finalised.
   *
   * @return  {boolean}
   */
  get isReducedBelowMinimum() {
    const { totalQuantity: stockOnHand } = this.itemBatch;

    // Return true if |stockOnHand + stocktakebatch.difference| is negative.
    return stockOnHand + this.difference < 0;
  }

  /**
   * Get if snapshot is out-of-date.
   *
   * Returns true if the |snapshotTotalQuantity| does not match the |totalQuantity| of the
   * item batch this stocktake batch is associated with. Will occur if inventory has changed
   * since this stocktake batch was created. If the net change on this batch is 0, then return
   * false.
   *
   * @return  {boolean}
   */
  get isSnapshotOutdated() {
    return this.snapshotTotalQuantity !== this.itemBatch.totalQuantity;
  }

  /**
   * Get if stocktake batch has been counted.
   *
   * @return  {boolean}
   */
  get hasBeenCounted() {
    return this.countedNumberOfPacks !== null;
  }

  /**
   * Get id of item associated with this stocktake batch.
   *
   * @return  {string}
   */
  get itemId() {
    if (!this.itemBatch) return '';
    return this.itemBatch.item ? this.itemBatch.item.id : '';
  }

  /**
   * Get id of item batch associated with this stocktake batch.
   *
   * @return  {string}
   */
  get itemBatchId() {
    return this.itemBatch ? this.itemBatch.id : '';
  }

  /**
   * Get difference between counted quantity and snapshop quantity.
   *
   * @return  {number}
   */
  get difference() {
    return this.countedTotalQuantity - this.snapshotTotalQuantity;
  }

  /**
   * Returns whether or not a reason should be applied to this
   * stocktake batch.
   * @return {bool}
   */
  get shouldApplyReason() {
    return this.countedTotalQuantity !== this.snapshotTotalQuantity && !this.option;
  }

  /**
   * Set counted total quantity.
   *
   * @param  {number}  quantity
   */
  set countedTotalQuantity(quantity) {
    // Handle packsize of 0.
    this.countedNumberOfPacks = this.packSize ? quantity / this.packSize : 0;
  }

  /**
   * Finalise stocktake batch.
   *
   * Finalising will adjust inventory appropriately and will add a new transaction
   * batch in reducing or increasing transaction for this stocktake.
   *
   * @param  {Realm}  database
   */
  finalise(database) {
    // Update the item batch details.
    this.itemBatch.batch = this.batch;
    this.itemBatch.expiryDate = this.expiryDate;

    // Make inventory adjustments if there is a difference to apply.
    if (this.difference !== 0) {
      const isAddition = this.countedTotalQuantity > this.snapshotTotalQuantity;
      const inventoryAdjustment = isAddition
        ? this.stocktake.getAdditions(database)
        : this.stocktake.getReductions(database);

      // Create transaction item and transaction batch to store inventory adjustments in this
      // stocktake.
      const transactionItem = createRecord(
        database,
        'TransactionItem',
        inventoryAdjustment,
        this.itemBatch.item
      );
      const transactionBatch = createRecord(
        database,
        'TransactionBatch',
        transactionItem,
        this.itemBatch
      );

      // Apply difference from stocktake to actual stock on hand levels. Whether stock is increased
      // or decreased is determined by the transaction, use the absolute value of difference
      // (i.e. always treat as positive).
      const snapshotDifference = Math.abs(this.difference);
      transactionBatch.setTotalQuantity(database, snapshotDifference);
      database.save('TransactionBatch', transactionBatch);
    }
    database.save('ItemBatch', this.itemBatch);
  }

  /**
   * Get string representation of stocktake batch.
   *
   * @return  {string}
   */
  toString() {
    return `Stocktake batch representing ${this.itemBatch}`;
  }
}

StocktakeBatch.schema = {
  name: 'StocktakeBatch',
  primaryKey: 'id',
  properties: {
    id: 'string',
    stocktake: 'Stocktake',
    itemBatch: 'ItemBatch',
    snapshotNumberOfPacks: 'double',
    packSize: 'double',
    expiryDate: { type: 'date', optional: true },
    batch: 'string',
    costPrice: 'double',
    sellPrice: 'double',
    countedNumberOfPacks: { type: 'double', optional: true },
    sortIndex: { type: 'int', optional: true },
    option: { type: 'Options', optional: true },
  },
};

export default StocktakeBatch;
<|endoftext|>


<commit_before>(function() {

var MAXVALUE  = 1000000;

function AtariGoAi(params, parent) {
  this.params = params;
  this.parent = parent;
}

var findBot = Dagaz.AI.findBot;

Dagaz.AI.findBot = function(type, params, parent) {
  if ((type == "atari-go") || (type == "opening")) {
      return new AtariGoAi(params, parent);
  } else {
      return findBot(type, params, parent);
  }
}

var eval = function(board, player) {
  var r = _.chain(board.pieces)
   .filter(function(piece) {
        return piece.player == board.player;
    })
   .map(function(piece) {
        return piece.getValue(0);
    })
   .min()
   .value();
  if (r <= 1) {
      return -MAXVALUE;
  } else {
      return r;
  }
}

Dagaz.AI.eval = function(design, params, board) {
  var player = board.player;
  return eval(board, player) - eval(board, design.nextPlayer(player));
}

AtariGoAi.prototype.setContext = function(ctx, board) {
  if (parent !== null) {
      parent.setContext(ctx, board);
  }
  ctx.board = board;
}

AtariGoAi.prototype.getMove = function(ctx) {
  if (ctx.board.zSign == 0) {
      var move = _.chain(Dagaz.AI.generate(ctx, ctx.board))
       .filter(function(move) {
            if (move.actions.length != 1) return false;
            var action = move.actions[0];
            if (action[0] !== null) return false;
            if (action[1] === null) return false;
            return action[1][0] == (ctx.design.positions.length - 1) / 2;
         })
       .first()
       .value();
      if (move) {
          return { move: move, ai: "opening" };
      }
  }
  if (parent !== null) {
      return parent.getMove(ctx);
  }
}

})();
<commit_msg>Atari Go<commit_after><|endoftext|>


<commit_before>define(
  'ephox.porkbun.demo.Outlaw',

  [
    'ephox.wrap.D',
    'ephox.wrap.JQuery',
    'ephox.porkbun.Events',
    'ephox.scullion.Struct'
  ],

  function (D, $, Events, Struct) {
    var create = function (name) {
      var container = $('
');
      container.css({  width: '1px dashed gray' });

      var character = $('
');
      character.css({ width: '200px', float: 'left' });

      var img = $('');
      img.height('200px');

      var actions = $('
');
      actions.css({ float: 'right' });

      var caption = $('
');
      caption.text(name);
      caption.css({ textAlign: 'center', fontWeight: 'bold' });
      caption.append(actions);

      character.append(img, caption);
      container.append(character);

      var events = Events.create({
        shoot: Struct.immutable('target'),
        die: Struct.immutable()
      });

      var alive = true;

      var addAction = function (text, action) {
        var button = $('<button />');
        button.text(text);
        button.bind('click', action);

        actions.append(button);
      };

      //there's a pattern here screaming to get out
      var inSaloon;
      var enter = function(saloon) {
        saloon.enter(api);
        inSaloon = saloon;
      };

      var chaseStarted = function (event) {
        if (alive) {
          if (event.target() === api) {
            leave();
          }
        } else {
          throw "I am dead"
        }
      };

      var leave = function() {
        inSaloon.leave(api);
        inSaloon = undefined;
      };

      var shoot = function (outlaw) {
        outlaw.die();
        events.trigger.shoot(outlaw);
      };

      var die = function () {
        alive = false;
        img.attr('src', 'images/gravestone.jpg');
        actions.remove();
        stayingAwayFrom.events.chasing.unbind(chaseStarted);
        events.trigger.die();
      };

      var getElement = function () {
        return container;
      };

      //there's a pattern here screaming to get out
      var stayingAwayFrom;
      var stayAwayFrom = function(sherrif) {
        sherrif.events.chasing.bind(chaseStarted);
        stayingAwayFrom = sherrif;
      };

      var api = {
        name: D.getConstant(name),
        getElement: getElement,
        addAction: addAction,
        enter: enter,
        leave: leave,
        shoot: shoot,
        die: die,
        events: events.registry,
        stayAwayFrom: stayAwayFrom
      };
      return api;
    };

    return {
      create: create
    };
  }
);
<commit_msg>Cleanups<commit_after>define(
  'ephox.porkbun.demo.Outlaw',

  [
    'ephox.wrap.D',
    'ephox.wrap.JQuery',
    'ephox.porkbun.Events',
    'ephox.scullion.Struct'
  ],

  function (D, $, Events, Struct) {
    var create = function (name) {
      var container = $('
');
      container.css({  width: '1px dashed gray' });

      var character = $('
');
      character.css({ width: '200px', float: 'left' });

      var img = $('');
      img.height('200px');

      var actions = $('
');
      actions.css({ float: 'right' });

      var caption = $('
');
      caption.text(name);
      caption.css({ textAlign: 'center', fontWeight: 'bold' });
      caption.append(actions);

      character.append(img, caption);
      container.append(character);

      var getElement = function () {
        return container;
      };

      var addAction = function (text, action) {
        var button = $('<button />');
        button.text(text);
        button.bind('click', action);

        actions.append(button);
      };

      var events = Events.create({
        shoot: Struct.immutable('target'),
        die: Struct.immutable()
      });

      var establishment;
      var enter = function (saloon) {
        saloon.enter(api);
        establishment = saloon;
      };

      var leave = function () {
        establishment.leave(api);
        establishment = undefined;
      };

      var shoot = function (target) {
        target.die();
        events.trigger.shoot(target);
      };

      var alive = true;
      var die = function () {
        alive = false;
        img.attr('src', 'images/gravestone.jpg');
        actions.remove();
        stayingAwayFrom.events.chasing.unbind(chaseStarted);
        events.trigger.die();
      };

      var stayingAwayFrom;
      var stayAwayFrom = function(sherrif) {
        sherrif.events.chasing.bind(chaseStarted);
        stayingAwayFrom = sherrif;
      };

      var chaseStarted = function (event) {
        if (!alive) throw 'Cannot chase ' + name + ', he is dead!';
        if (event.target() === api) {
          leave();
        }
      };

      var api = {
        name: D.getConstant(name),
        getElement: getElement,
        addAction: addAction,
        enter: enter,
        leave: leave,
        shoot: shoot,
        die: die,
        events: events.registry,
        stayAwayFrom: stayAwayFrom
      };
      return api;
    };

    return {
      create: create
    };
  }
);
<|endoftext|>