<commit_before>const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0

const navigationKey = isMac ? 'ctrl' : 'ctrl+shift'

export const keyMap = {
  // Navigation to screens
  // PROPOSAL STAGE
  // 'go-flow-editor': 'g f',
  // 'go-nlu': 'g n',
  // 'go-content': 'g c',
  // 'go-emulator': 'g e',
  // 'go-module-qna': 'g m q',

  // Flow-Editor Actions
  'flow-add-node': `${navigationKey}+a`,
  'flow-save': `${navigationKey}+s`,
  'emulator-focus': `e`,
  cancel: 'esc'
}

export const isInputFocused = () => {
  const tag = document.activeElement && document.activeElement.tagName
  const inputTypes = ['textarea', 'input', 'button']
  return tag && inputTypes.includes(tag.toLowerCase())
}
<commit_msg>added check for other elements as input<commit_after>const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0

const navigationKey = isMac ? 'ctrl' : 'ctrl+shift'

export const keyMap = {
  // Navigation to screens
  // PROPOSAL STAGE
  // 'go-flow-editor': 'g f',
  // 'go-nlu': 'g n',
  // 'go-content': 'g c',
  // 'go-emulator': 'g e',
  // 'go-module-qna': 'g m q',

  // Flow-Editor Actions
  'flow-add-node': `${navigationKey}+a`,
  'flow-save': `${navigationKey}+s`,
  'emulator-focus': `e`,
  cancel: 'esc'
}

export const isInputFocused = () => {
  if (!document.activeElement) {
    return false
  }

  const tag = document.activeElement.tagName
  const isEditable = document.activeElement.isContentEditable || document.activeElement.contenteditable === 'true'
  const inputTypes = ['textarea', 'input', 'button']
  return (tag && inputTypes.includes(tag.toLowerCase())) || isEditable
}
<|endoftext|>


<commit_before>$(document).ready(function(){

  'use strict';

  function load_new_items(){
    var sign = load_path.indexOf('?') >= 0 ? '&' : '?'
    $.get(load_path + sign + 'page=' + (++page_num), function(data, e) {
      if(data.length < 5) {
        var page_num = 0;
        return false;
      }
      data_container.append(data);
    }).complete(function() {
      loading_pic.hide();
    });
  }

  function loading_hidden(){
    return !loading_pic.is(':visible');
  }

  function near_bottom(){
    return $(window).scrollTop() > $(document).height() - $(window).height() - bottom_px_limit;
  }

  if($('*[data-scrollinity-path]').length > 0) {
    var page_num        = 1
    var load_path       = $('*[data-scrollinity-path]').data('scrollinity-path');
    var loading_pic     = $('*[data-scrollinity-loading-pic]');
    var data_container  = $('#' + $('*[data-scrollinity-data-container]').data('scrollinity-data-container'));
    var bottom_px_limit = $('*[data-scrollinity-bottom-px-limit]').data('scrollinity-bottom-px-limit');

    $(window).on('scroll.scrollinity', function(){
      if(loading_hidden() && near_bottom()) {
        if(page_num > 0) {
          loading_pic.show();
          load_new_items();
        }
      }
    });
  }
  else {
    $(window).off('scroll.scrollinity');
  }

});<commit_msg>Change .complete to .always, as .complete has been deprecated since jQuery 1.8<commit_after>$(document).ready(function(){

  'use strict';

  function load_new_items(){
    var sign = load_path.indexOf('?') >= 0 ? '&' : '?'
    $.get(load_path + sign + 'page=' + (++page_num), function(data, e) {
      if(data.length < 5) {
        var page_num = 0;
        return false;
      }
      data_container.append(data);
    }).always(function() {
      loading_pic.hide();
    });
  }

  function loading_hidden(){
    return !loading_pic.is(':visible');
  }

  function near_bottom(){
    return $(window).scrollTop() > $(document).height() - $(window).height() - bottom_px_limit;
  }

  if($('*[data-scrollinity-path]').length > 0) {
    var page_num        = 1
    var load_path       = $('*[data-scrollinity-path]').data('scrollinity-path');
    var loading_pic     = $('*[data-scrollinity-loading-pic]');
    var data_container  = $('#' + $('*[data-scrollinity-data-container]').data('scrollinity-data-container'));
    var bottom_px_limit = $('*[data-scrollinity-bottom-px-limit]').data('scrollinity-bottom-px-limit');

    $(window).on('scroll.scrollinity', function(){
      if(loading_hidden() && near_bottom()) {
        if(page_num > 0) {
          loading_pic.show();
          load_new_items();
        }
      }
    });
  }
  else {
    $(window).off('scroll.scrollinity');
  }

});<|endoftext|>


<commit_before>/**
 * Chart provider for rendering dashboard chart with flot, which
 * provides Canvas-based interactivity.
 */
(function() {

    var self = ds.charts.provider({
      name:          'flot',
      is_interactive: true,
      description: 'flot renders interactive charts using HTML canvas. '
                 + 'It does not support stream graphs, but can be a better '
                 + 'choice for rendering large numbers of graphs or lengthy '
                 + 'time periods.'
    })

    var log = ds.log.logger('ds.charts.flot')

    /* =============================================================================
       Helpers
       ============================================================================= */

    function get_default_options() {
      var theme_colors = ds.charts.util.get_colors()
      var default_options = {
        colors: ds.charts.util.get_palette(),
        series: {
          lines: {
            show: true,
            lineWidth: 1,
            steps: false,
            fill: false
          },
          valueLabels: { show: false },
          points: { show: false },
          bars: { lineWidth: 1, show: false },
          stack: null
        },
        xaxis: {
          mode: "time",
          tickFormatter: function(value, axis) {
            // Take care of time series axis
            if (axis.tickSize && axis.tickSize.length === 2) {
              if (axis.tickSize[1] === 'year' && axis.tickSize[0] >= 1)
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('YYYY')
              if (axis.tickSize[1] === 'month' && axis.tickSize[0] >= 1 || axis.tickSize[1] === 'year')
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM-\'YY')
              if (axis.tickSize[1] === 'day' && axis.tickSize[0] >= 1 || axis.tickSize[1] === 'month')
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM/DD')
              if (axis.tickSize[1] === 'hour' && axis.tickSize[0] >= 12)
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM/DD hA')
            }
            return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('h:mm A')
          },
          tickColor: theme_colors.minorGridLineColor,
          font: {
            color: theme_colors.fgcolor,
            size: 12
          }
        },
        yaxes: [
          {
            position: 'left',
            tickFormatter: d3.format(',.3s'),
            reserveSpace: 30,
            labelWidth: 30,
            tickColor: theme_colors.minorGridLineColor,
            font: {
              color: theme_colors.fgcolor,
              size: 12
            }
          },
          {
            position: 'right',
            tickFormatter: d3.format(',.3s'),
            font: {
              color: theme_colors.fgcolor,
              size: 12
            }
          }
        ],
        points: {
          show: false,
          radius: 2,
          symbol: "circle"
        },
        shadowSize: 0,
        legend: { show: false },
        grid: {
          borderWidth: 1,
          hoverable: true,
          clickable: true,
          autoHighlight: false,
          /* grid.color actually sets the color of the legend
           * text. WTH? */
          color: theme_colors.fgcolor,
          borderColor: theme_colors.minorGridLineColor
        },
        selection: {
          mode: "x",
          color: "red"
        },
        multihighlight: {
          mode: "x"
        },
        crosshair: {
          mode: "x",
          color: "#BBB",
          lineWidth: 1
        }
      }
      return default_options
    }

    function get_flot_options(item, base) {
      var options      = item.options || {}
      var flot_options = $.extend(true, {}, get_default_options(), base)

      flot_options.colors = ds.charts.util.get_palette(options.palette)

      if (options.y1 && options.y1.min)
        flot_options.yaxes[0].min = options.y1.min
      if (options.y2 && options.y2.min)
        flot_options.yaxes[1].min = options.y2.min

      if (options.y1 && options.y1.max)
        flot_options.yaxes[0].max = options.y1.max
      if (options.y2 && options.y2.max)
        flot_options.yaxes[1].max = options.y2.max

      if (options.y1 && options.y1.label)
        flot_options.yaxes[0].axisLabel = options.y1.label
      if (options.y2 && options.y2.label)
        flot_options.yaxes[1].axisLabel = options.y2.label

      if (item.show_max_value || item.show_min_value || item.show_last_value) {
        flot_options.series.valueLabels = {
          show: true,
          showMaxValue:item.show_max_value,
          showMinValue: item.show_min_value,
          showLastValue: item.show_last_value,
          showAsHtml: true,
          labelFormatter: d3.format(',.3s'),
          yoffset: -20
        }
      }

      return flot_options
    }

    function show_tooltip(x, y, contents) {
      $('
' + contents + '
').css( {
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5
      }).appendTo("body").show()
    }

    function setup_plugins(container, context) {
      $(container).bind("multihighlighted", function(event, pos, items) {
        if ( !items )
          return
        var series = context.plot.getData()
        var item   = items[0]
        var point  = series[item.serieIndex].data[item.dataIndex]
        var format = d3.format(',.3s')
        var is_percent = context.item.stack_mode && (context.item.stack_mode === ds.charts.StackMode.PERCENT)

        var contents = ds.templates.flot.tooltip({
          time: point[0],
          items: items.map(function(item) {
                   var s = series[item.serieIndex]
                   var value = is_percent
                             ? s.percents[item.dataIndex]
                             : s.data[item.dataIndex][1]
                   return {
                     series: s,
                     value: is_percent ? format(value) + '%' : format(value)
                   }
                 })
        })

        $("#ds-tooltip").remove()
        show_tooltip(pos.pageX, pos.pageY, contents)
      })

      $(container).bind("unmultihighlighted", function(event) {
        $("#ds-tooltip").remove()
      })
    }

    function render_legend(item, query, options) {
      var legend_id = '#ds-legend-' + item.item_id
      if ( item.legend === ds.models.chart.LegendType.SIMPLE ) {
        render_simple_legend(legend_id, item, query, options)
      } else if ( item.legend === ds.models.chart.LegendType.TABLE ) {
        // TODO - render a summation_table as the legend
      }
    }

    function render_simple_legend(legend_id, item, query, options) {
      var legend = ''
      var data = query.chart_data('flot')
      for (var i = 0; i < data.length; i++) {
        var series = data[i]
        if (item.hide_zero_series && series.summation.sum === 0)
          continue
        var label = series.label
        var color = options.colors[i % options.colors.length]

        var cell = '
'
                 + ''
                 + '' + label + ''
                 + '
'
        legend += cell
      }
      var elt = $(legend_id)
      elt.html(legend)
      elt.equalize({equalize: 'outerWidth', reset: true })
    }

    function render(e, item, query, options, data) {
      if (typeof(data) === 'undefined')
        data = query.chart_data('flot')
      var context = {
          plot: null,
          item: item,
          query: query
      }
      setup_plugins(e, context)
      try {
        context.plot = $.plot($(e), data, options)
      } catch (ex) {
        log.error('Error rendering item ' + item.item_id
                 + ': ' + ex.message)
      }
      render_legend(item, query, options)
      return context
    }

    /* =============================================================================
       Chart provider interface
       ============================================================================= */

    self.process_series = function(series) {
      var result = {}
      if (series.summation) {
        result.summation = series.summation
      }
      result.label = series.target
      result.data = series.datapoints.map(function(point) {
                      return [point[1] * 1000, point[0]]
                    })
      return result
    }

    self.simple_line_chart = function(e, item, query) {
      var options = get_flot_options(item, {
        grid: { show: false }
      })

      render(e, item, query, options, [query.chart_data('flot')[0]])

      return self
    }

    self.standard_line_chart = function(e, item, query) {
      render(e, item, query, get_flot_options(item))
      return self
    }

    self.simple_area_chart = function(e, item, query) {
      var options = get_flot_options(item, {
        grid: { show: false },
        series: {
          lines: { fill: 1.0 },
          grid: { show: false }
        }
      })

      render(e, item, query, options, [query.chart_data('flot')[0]])

      return self
    }

    self.stacked_area_chart = function(e, item, query) {
      var options = get_flot_options(item, {
        series: {
          lines: { fill: 1},
          stack: true,
          streamgraph: { show: false }
        }
      })

      if (item.stack_mode === ds.charts.StackMode.PERCENT) {
        options.series.stack = false
        options.series.stackpercent = true
        options.yaxes[0].max = 100
        options.yaxes[0].min = 0
      } else if (item.stack_mode == ds.charts.StackMode.STREAM) {
        options.series.streamgraph.show = true
        options.series.stack = false
        options.series.stackpercent = false
      } else if (item.stack_mode == ds.charts.StackMode.NONE) {
        options.series.stack = false
        options.series.stackpercent = false
        options.series.lines.fill = false
      }

      render(e, item, query, options)

      return self
    }

    self.donut_chart = function(e, item, query) {
      var options = get_flot_options(item, {
        crosshair: { mode: null },
        multihighlight: { mode: null },
        series: {
          lines: { show: false },
          pie: {
            show: true,
            radius: 'auto',
            innerRadius: item.is_pie ? 0 : 0.35,
            label: { show: item.labels }
          }
        },
        grid: { show: false, hoverable: false }
      })

      var transform = item.transform || 'sum'
      var data = query.chart_data('flot').map(function(series) {
                   if (item.hide_zero_series && series.summation.sum === 0)
                     return undefined
                   return {
                     label: series.label,
                     summation: series.summation,
                     data: [ series.label, series.summation[transform] ]
                   }
                 }).filter(function(item) { return item })

      render(e, item, query, options, data)

      return self
    }

    var THREE_HOURS_MS = 1000 * 60 * 60 * 3
    var ONE_HOUR_MS = 1000 * 60 * 60 * 1

    self.bar_chart = function(e, item, query) {
      var series      = query.chart_data('flot')[0]
      var ts_start    = series.data[0][0]
      var ts_end      = series.data[series.data.length - 1][0]
      var ts_length   = ts_end - ts_start
      var sample_size = ts_length / series.data.length

      var bar_scaling = 0.85
      if (ts_length > THREE_HOURS_MS) {
        bar_scaling = 0.15
      } else if (ts_length > ONE_HOUR_MS) {
        bar_scaling = 0.65
      } else {
        bar_scaling = 0.85
      }

      var options = get_flot_options(item, {
        series: {
          lines: { show: false },
          stack: true,
          bars: {
            show: true,
            fill: 0.8,
            barWidth: sample_size * bar_scaling
          }
        }
      })

      if (item.stack_mode === ds.charts.StackMode.PERCENT) {
        options.series.stack = false
        options.series.stackpercent = true
        options.yaxes[0].max = 100
        options.yaxes[0].min = 0
      } else if (item.stack_mode == ds.charts.StackMode.NONE) {
        options.series.stack = false
        options.series.stackpercent = false
      }

      render(e, item, query, options)

      return self
    }

    self.discrete_bar_chart = function(e, item, query) {
      var is_horizontal = item.orientation === 'horizontal'
      var options = get_flot_options(item, {
        xaxis: { mode: null },
        multihighlight: { mode: null },
        crosshair: { mode: null },
        grid: {
          borderWidth: 0,
          color: 'transparent',
          borderColor: 'transparent',
          labelMargin: 10
        },
        series: {
          lines: { show: false },
          bars: {
            horizontal: is_horizontal,
            show: true,
            barWidth: 0.8,
            align: 'center',
            fill: 0.75,
            numbers: {
              show: item.show_numbers,
              xAlign: 'center',
              font: '10pt Helvetica',
              fontColor: '#f9f9f9', // TODO: get from theme
              formatter: d3.format(item.format),
              yAlign: function(y) { return y },
              xAlign: function(x) { return x }
            }
          }
        }
      })

      var transform = item.transform || 'sum'
      var index = 0
      var data = query.chart_data('flot').map(function(series) {
                   if (item.hide_zero_series && series.summation.sum === 0)
                     return undefined
                   return {
                     label: series.label,
                     data: [
                       is_horizontal
                            ? [ series.summation[transform], index]
                            : [index, series.summation[transform]]
                     ],
                     color: options.colors[options.colors % index++]
                   }
                 }).filter(function(item) { return item })
      index = 0
      var ticks = data.map(function(series) {
                              return [index++, series.label]
                            })

      if (is_horizontal) {
        options.yaxes[0].tickLength = 0
        options.yaxes[0].ticks = ticks
        options.xaxis.tickFormatter = null
        options.series.bars.numbers.xOffset = -18
        if (item.show_grid) {
          options.xaxis.axisLabel = options.yaxes[0].axisLabel
          options.yaxes[0].axisLabel = transform.charAt(0).toUpperCase() + transform.substring(1)
        } else {
          options.xaxis.ticks = []
          options.yaxes[0].axisLabel = null
        }
      } else {
        options.xaxis.tickLength = 0
        options.xaxis.ticks = ticks
        options.series.bars.numbers.yOffset = 12
        if (!item.show_grid) {
          options.yaxes[0].ticks = []
          options.yaxes[0].axisLabel = null
        } else {
          options.xaxis.axisLabel = transform.charAt(0).toUpperCase() + transform.substring(1)
        }
      }

      render(e, item, query, options, data)

      return self
    }

    ds.charts.registry.register(self)

})()
<commit_msg>Remove caveats in flot renderer description<commit_after>/**
 * Chart provider for rendering dashboard chart with flot, which
 * provides Canvas-based interactivity.
 */
(function() {

    var self = ds.charts.provider({
      name:          'flot',
      is_interactive: true,
      description: 'flot renders interactive charts using HTML canvas.'
    })

    var log = ds.log.logger('ds.charts.flot')

    /* =============================================================================
       Helpers
       ============================================================================= */

    function get_default_options() {
      var theme_colors = ds.charts.util.get_colors()
      var default_options = {
        colors: ds.charts.util.get_palette(),
        series: {
          lines: {
            show: true,
            lineWidth: 1,
            steps: false,
            fill: false
          },
          valueLabels: { show: false },
          points: { show: false },
          bars: { lineWidth: 1, show: false },
          stack: null
        },
        xaxis: {
          mode: "time",
          tickFormatter: function(value, axis) {
            // Take care of time series axis
            if (axis.tickSize && axis.tickSize.length === 2) {
              if (axis.tickSize[1] === 'year' && axis.tickSize[0] >= 1)
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('YYYY')
              if (axis.tickSize[1] === 'month' && axis.tickSize[0] >= 1 || axis.tickSize[1] === 'year')
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM-\'YY')
              if (axis.tickSize[1] === 'day' && axis.tickSize[0] >= 1 || axis.tickSize[1] === 'month')
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM/DD')
              if (axis.tickSize[1] === 'hour' && axis.tickSize[0] >= 12)
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM/DD hA')
            }
            return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('h:mm A')
          },
          tickColor: theme_colors.minorGridLineColor,
          font: {
            color: theme_colors.fgcolor,
            size: 12
          }
        },
        yaxes: [
          {
            position: 'left',
            tickFormatter: d3.format(',.3s'),
            reserveSpace: 30,
            labelWidth: 30,
            tickColor: theme_colors.minorGridLineColor,
            font: {
              color: theme_colors.fgcolor,
              size: 12
            }
          },
          {
            position: 'right',
            tickFormatter: d3.format(',.3s'),
            font: {
              color: theme_colors.fgcolor,
              size: 12
            }
          }
        ],
        points: {
          show: false,
          radius: 2,
          symbol: "circle"
        },
        shadowSize: 0,
        legend: { show: false },
        grid: {
          borderWidth: 1,
          hoverable: true,
          clickable: true,
          autoHighlight: false,
          /* grid.color actually sets the color of the legend
           * text. WTH? */
          color: theme_colors.fgcolor,
          borderColor: theme_colors.minorGridLineColor
        },
        selection: {
          mode: "x",
          color: "red"
        },
        multihighlight: {
          mode: "x"
        },
        crosshair: {
          mode: "x",
          color: "#BBB",
          lineWidth: 1
        }
      }
      return default_options
    }

    function get_flot_options(item, base) {
      var options      = item.options || {}
      var flot_options = $.extend(true, {}, get_default_options(), base)

      flot_options.colors = ds.charts.util.get_palette(options.palette)

      if (options.y1 && options.y1.min)
        flot_options.yaxes[0].min = options.y1.min
      if (options.y2 && options.y2.min)
        flot_options.yaxes[1].min = options.y2.min

      if (options.y1 && options.y1.max)
        flot_options.yaxes[0].max = options.y1.max
      if (options.y2 && options.y2.max)
        flot_options.yaxes[1].max = options.y2.max

      if (options.y1 && options.y1.label)
        flot_options.yaxes[0].axisLabel = options.y1.label
      if (options.y2 && options.y2.label)
        flot_options.yaxes[1].axisLabel = options.y2.label

      if (item.show_max_value || item.show_min_value || item.show_last_value) {
        flot_options.series.valueLabels = {
          show: true,
          showMaxValue:item.show_max_value,
          showMinValue: item.show_min_value,
          showLastValue: item.show_last_value,
          showAsHtml: true,
          labelFormatter: d3.format(',.3s'),
          yoffset: -20
        }
      }

      return flot_options
    }

    function show_tooltip(x, y, contents) {
      $('
' + contents + '
').css( {
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5
      }).appendTo("body").show()
    }

    function setup_plugins(container, context) {
      $(container).bind("multihighlighted", function(event, pos, items) {
        if ( !items )
          return
        var series = context.plot.getData()
        var item   = items[0]
        var point  = series[item.serieIndex].data[item.dataIndex]
        var format = d3.format(',.3s')
        var is_percent = context.item.stack_mode && (context.item.stack_mode === ds.charts.StackMode.PERCENT)

        var contents = ds.templates.flot.tooltip({
          time: point[0],
          items: items.map(function(item) {
                   var s = series[item.serieIndex]
                   var value = is_percent
                             ? s.percents[item.dataIndex]
                             : s.data[item.dataIndex][1]
                   return {
                     series: s,
                     value: is_percent ? format(value) + '%' : format(value)
                   }
                 })
        })

        $("#ds-tooltip").remove()
        show_tooltip(pos.pageX, pos.pageY, contents)
      })

      $(container).bind("unmultihighlighted", function(event) {
        $("#ds-tooltip").remove()
      })
    }

    function render_legend(item, query, options) {
      var legend_id = '#ds-legend-' + item.item_id
      if ( item.legend === ds.models.chart.LegendType.SIMPLE ) {
        render_simple_legend(legend_id, item, query, options)
      } else if ( item.legend === ds.models.chart.LegendType.TABLE ) {
        // TODO - render a summation_table as the legend
      }
    }

    function render_simple_legend(legend_id, item, query, options) {
      var legend = ''
      var data = query.chart_data('flot')
      for (var i = 0; i < data.length; i++) {
        var series = data[i]
        if (item.hide_zero_series && series.summation.sum === 0)
          continue
        var label = series.label
        var color = options.colors[i % options.colors.length]

        var cell = '
'
                 + ''
                 + '' + label + ''
                 + '
'
        legend += cell
      }
      var elt = $(legend_id)
      elt.html(legend)
      elt.equalize({equalize: 'outerWidth', reset: true })
    }

    function render(e, item, query, options, data) {
      if (typeof(data) === 'undefined')
        data = query.chart_data('flot')
      var context = {
          plot: null,
          item: item,
          query: query
      }
      setup_plugins(e, context)
      try {
        context.plot = $.plot($(e), data, options)
      } catch (ex) {
        log.error('Error rendering item ' + item.item_id
                 + ': ' + ex.message)
      }
      render_legend(item, query, options)
      return context
    }

    /* =============================================================================
       Chart provider interface
       ============================================================================= */

    self.process_series = function(series) {
      var result = {}
      if (series.summation) {
        result.summation = series.summation
      }
      result.label = series.target
      result.data = series.datapoints.map(function(point) {
                      return [point[1] * 1000, point[0]]
                    })
      return result
    }

    self.simple_line_chart = function(e, item, query) {
      var options = get_flot_options(item, {
        grid: { show: false }
      })

      render(e, item, query, options, [query.chart_data('flot')[0]])

      return self
    }

    self.standard_line_chart = function(e, item, query) {
      render(e, item, query, get_flot_options(item))
      return self
    }

    self.simple_area_chart = function(e, item, query) {
      var options = get_flot_options(item, {
        grid: { show: false },
        series: {
          lines: { fill: 1.0 },
          grid: { show: false }
        }
      })

      render(e, item, query, options, [query.chart_data('flot')[0]])

      return self
    }

    self.stacked_area_chart = function(e, item, query) {
      var options = get_flot_options(item, {
        series: {
          lines: { fill: 1},
          stack: true,
          streamgraph: { show: false }
        }
      })

      if (item.stack_mode === ds.charts.StackMode.PERCENT) {
        options.series.stack = false
        options.series.stackpercent = true
        options.yaxes[0].max = 100
        options.yaxes[0].min = 0
      } else if (item.stack_mode == ds.charts.StackMode.STREAM) {
        options.series.streamgraph.show = true
        options.series.stack = false
        options.series.stackpercent = false
      } else if (item.stack_mode == ds.charts.StackMode.NONE) {
        options.series.stack = false
        options.series.stackpercent = false
        options.series.lines.fill = false
      }

      render(e, item, query, options)

      return self
    }

    self.donut_chart = function(e, item, query) {
      var options = get_flot_options(item, {
        crosshair: { mode: null },
        multihighlight: { mode: null },
        series: {
          lines: { show: false },
          pie: {
            show: true,
            radius: 'auto',
            innerRadius: item.is_pie ? 0 : 0.35,
            label: { show: item.labels }
          }
        },
        grid: { show: false, hoverable: false }
      })

      var transform = item.transform || 'sum'
      var data = query.chart_data('flot').map(function(series) {
                   if (item.hide_zero_series && series.summation.sum === 0)
                     return undefined
                   return {
                     label: series.label,
                     summation: series.summation,
                     data: [ series.label, series.summation[transform] ]
                   }
                 }).filter(function(item) { return item })

      render(e, item, query, options, data)

      return self
    }

    var THREE_HOURS_MS = 1000 * 60 * 60 * 3
    var ONE_HOUR_MS = 1000 * 60 * 60 * 1

    self.bar_chart = function(e, item, query) {
      var series      = query.chart_data('flot')[0]
      var ts_start    = series.data[0][0]
      var ts_end      = series.data[series.data.length - 1][0]
      var ts_length   = ts_end - ts_start
      var sample_size = ts_length / series.data.length

      var bar_scaling = 0.85
      if (ts_length > THREE_HOURS_MS) {
        bar_scaling = 0.15
      } else if (ts_length > ONE_HOUR_MS) {
        bar_scaling = 0.65
      } else {
        bar_scaling = 0.85
      }

      var options = get_flot_options(item, {
        series: {
          lines: { show: false },
          stack: true,
          bars: {
            show: true,
            fill: 0.8,
            barWidth: sample_size * bar_scaling
          }
        }
      })

      if (item.stack_mode === ds.charts.StackMode.PERCENT) {
        options.series.stack = false
        options.series.stackpercent = true
        options.yaxes[0].max = 100
        options.yaxes[0].min = 0
      } else if (item.stack_mode == ds.charts.StackMode.NONE) {
        options.series.stack = false
        options.series.stackpercent = false
      }

      render(e, item, query, options)

      return self
    }

    self.discrete_bar_chart = function(e, item, query) {
      var is_horizontal = item.orientation === 'horizontal'
      var options = get_flot_options(item, {
        xaxis: { mode: null },
        multihighlight: { mode: null },
        crosshair: { mode: null },
        grid: {
          borderWidth: 0,
          color: 'transparent',
          borderColor: 'transparent',
          labelMargin: 10
        },
        series: {
          lines: { show: false },
          bars: {
            horizontal: is_horizontal,
            show: true,
            barWidth: 0.8,
            align: 'center',
            fill: 0.75,
            numbers: {
              show: item.show_numbers,
              xAlign: 'center',
              font: '10pt Helvetica',
              fontColor: '#f9f9f9', // TODO: get from theme
              formatter: d3.format(item.format),
              yAlign: function(y) { return y },
              xAlign: function(x) { return x }
            }
          }
        }
      })

      var transform = item.transform || 'sum'
      var index = 0
      var data = query.chart_data('flot').map(function(series) {
                   if (item.hide_zero_series && series.summation.sum === 0)
                     return undefined
                   return {
                     label: series.label,
                     data: [
                       is_horizontal
                            ? [ series.summation[transform], index]
                            : [index, series.summation[transform]]
                     ],
                     color: options.colors[options.colors % index++]
                   }
                 }).filter(function(item) { return item })
      index = 0
      var ticks = data.map(function(series) {
                              return [index++, series.label]
                            })

      if (is_horizontal) {
        options.yaxes[0].tickLength = 0
        options.yaxes[0].ticks = ticks
        options.xaxis.tickFormatter = null
        options.series.bars.numbers.xOffset = -18
        if (item.show_grid) {
          options.xaxis.axisLabel = options.yaxes[0].axisLabel
          options.yaxes[0].axisLabel = transform.charAt(0).toUpperCase() + transform.substring(1)
        } else {
          options.xaxis.ticks = []
          options.yaxes[0].axisLabel = null
        }
      } else {
        options.xaxis.tickLength = 0
        options.xaxis.ticks = ticks
        options.series.bars.numbers.yOffset = 12
        if (!item.show_grid) {
          options.yaxes[0].ticks = []
          options.yaxes[0].axisLabel = null
        } else {
          options.xaxis.axisLabel = transform.charAt(0).toUpperCase() + transform.substring(1)
        }
      }

      render(e, item, query, options, data)

      return self
    }

    ds.charts.registry.register(self)

})()
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { styled } from '@storybook/theming';
import { Link } from '@storybook/router';
import { SyntaxHighlighter } from '@storybook/components';

import { createElement } from 'react-syntax-highlighter';
import { EVENT_ID } from './events';

const StyledStoryLink = styled(Link)(({ theme }) => ({
  display: 'block',
  textDecoration: 'none',
  borderRadius: theme.appBorderRadius,

  '&:hover': {
    background: theme.background.hoverable,
  },
}));

const SelectedStoryHighlight = styled.div(({ theme }) => ({
  background: theme.background.hoverable,
  borderRadius: theme.appBorderRadius,
}));

const StyledSyntaxHighlighter = styled(SyntaxHighlighter)(({ theme }) => ({
  fontSize: theme.typography.size.s2 - 1,
}));

const areLocationsEqual = (a, b) =>
  a.startLoc.line === b.startLoc.line &&
  a.startLoc.col === b.startLoc.col &&
  a.endLoc.line === b.endLoc.line &&
  a.endLoc.col === b.endLoc.col;

const getLocationKeys = locationsMap =>
  locationsMap
    ? Array.from(Object.keys(locationsMap)).sort(
        (key1, key2) => locationsMap[key1].startLoc.line - locationsMap[key2].startLoc.line
      )
    : [];

export default class StoryPanel extends Component {
  state = { source: 'loading source...' };

  componentDidMount() {
    this.mounted = true;
    const { api } = this.props;

    api.on(EVENT_ID, this.listener);
  }

  componentDidUpdate() {
    if (this.selectedStoryRef) {
      this.selectedStoryRef.scrollIntoView();
    }
  }

  componentWillUnmount() {
    const { api } = this.props;

    api.off(EVENT_ID, this.listener);
  }

  setSelectedStoryRef = ref => {
    this.selectedStoryRef = ref;
  };

  listener = ({ source, currentLocation, locationsMap }) => {
    const locationsKeys = getLocationKeys(locationsMap);

    this.setState({
      source,
      currentLocation,
      locationsMap,
      locationsKeys,
    });
  };

  createPart = (rows, stylesheet, useInlineStyles) =>
    rows.map((node, i) =>
      createElement({
        node,
        stylesheet,
        useInlineStyles,
        key: `code-segement${i}`,
      })
    );

  createStoryPart = (rows, stylesheet, useInlineStyles, location, id) => {
    const { currentLocation } = this.state;
    const first = location.startLoc.line - 1;
    const last = location.endLoc.line;

    const storyRows = rows.slice(first, last);
    const story = this.createPart(storyRows, stylesheet, useInlineStyles);
    const storyKey = `${first}-${last}`;

    if (location && currentLocation && areLocationsEqual(location, currentLocation)) {
      return (
        <SelectedStoryHighlight key={storyKey} ref={this.setSelectedStoryRef}>
          {story}
        </SelectedStoryHighlight>
      );
    }

    return (

    );
  };

  createParts = (rows, stylesheet, useInlineStyles) => {
    const { locationsMap, locationsKeys } = this.state;

    const parts = [];
    let lastRow = 0;

    locationsKeys.forEach(key => {
      const location = locationsMap[key];
      const first = location.startLoc.line - 1;
      const last = location.endLoc.line;

      const start = this.createPart(rows.slice(lastRow, first), stylesheet, useInlineStyles);
      const storyPart = this.createStoryPart(rows, stylesheet, useInlineStyles, location, key);

      parts.push(start);
      parts.push(storyPart);

      lastRow = last;
    });

    const lastPart = this.createPart(rows.slice(lastRow), stylesheet, useInlineStyles);

    parts.push(lastPart);

    return parts;
  };

  lineRenderer = ({ rows, stylesheet, useInlineStyles }) => {
    const { locationsMap, locationsKeys } = this.state;

    // because of the usage of lineRenderer, all lines will be wrapped in a span
    // these spans will recieve all classes on them for some reason
    // which makes colours casecade incorrectly
    // this removed that list of classnames
    const myrows = rows.map(({ properties, ...rest }) => ({
      ...rest,
      properties: { className: [] },
    }));

    if (!locationsMap || !locationsKeys.length) {
      return this.createPart(myrows, stylesheet, useInlineStyles);
    }

    const parts = this.createParts(myrows, stylesheet, useInlineStyles);

    return {parts};
  };

  render() {
    const { active } = this.props;
    const { source } = this.state;

    return active ? (

    ) : null;
  }
}

StoryPanel.propTypes = {
  active: PropTypes.bool.isRequired,
  api: PropTypes.shape({
    selectStory: PropTypes.func.isRequired,
    emit: PropTypes.func,
    on: PropTypes.func,
    off: PropTypes.func,
  }).isRequired,
};
<commit_msg>Add color inherit to StyledStoryLink<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { styled } from '@storybook/theming';
import { Link } from '@storybook/router';
import { SyntaxHighlighter } from '@storybook/components';

import { createElement } from 'react-syntax-highlighter';
import { EVENT_ID } from './events';

const StyledStoryLink = styled(Link)(({ theme }) => ({
  display: 'block',
  textDecoration: 'none',
  borderRadius: theme.appBorderRadius,
  color: 'inherit',

  '&:hover': {
    background: theme.background.hoverable,
  },
}));

const SelectedStoryHighlight = styled.div(({ theme }) => ({
  background: theme.background.hoverable,
  borderRadius: theme.appBorderRadius,
}));

const StyledSyntaxHighlighter = styled(SyntaxHighlighter)(({ theme }) => ({
  fontSize: theme.typography.size.s2 - 1,
}));

const areLocationsEqual = (a, b) =>
  a.startLoc.line === b.startLoc.line &&
  a.startLoc.col === b.startLoc.col &&
  a.endLoc.line === b.endLoc.line &&
  a.endLoc.col === b.endLoc.col;

const getLocationKeys = locationsMap =>
  locationsMap
    ? Array.from(Object.keys(locationsMap)).sort(
        (key1, key2) => locationsMap[key1].startLoc.line - locationsMap[key2].startLoc.line
      )
    : [];

export default class StoryPanel extends Component {
  state = { source: 'loading source...' };

  componentDidMount() {
    this.mounted = true;
    const { api } = this.props;

    api.on(EVENT_ID, this.listener);
  }

  componentDidUpdate() {
    if (this.selectedStoryRef) {
      this.selectedStoryRef.scrollIntoView();
    }
  }

  componentWillUnmount() {
    const { api } = this.props;

    api.off(EVENT_ID, this.listener);
  }

  setSelectedStoryRef = ref => {
    this.selectedStoryRef = ref;
  };

  listener = ({ source, currentLocation, locationsMap }) => {
    const locationsKeys = getLocationKeys(locationsMap);

    this.setState({
      source,
      currentLocation,
      locationsMap,
      locationsKeys,
    });
  };

  createPart = (rows, stylesheet, useInlineStyles) =>
    rows.map((node, i) =>
      createElement({
        node,
        stylesheet,
        useInlineStyles,
        key: `code-segement${i}`,
      })
    );

  createStoryPart = (rows, stylesheet, useInlineStyles, location, id) => {
    const { currentLocation } = this.state;
    const first = location.startLoc.line - 1;
    const last = location.endLoc.line;

    const storyRows = rows.slice(first, last);
    const story = this.createPart(storyRows, stylesheet, useInlineStyles);
    const storyKey = `${first}-${last}`;

    if (location && currentLocation && areLocationsEqual(location, currentLocation)) {
      return (
        <SelectedStoryHighlight key={storyKey} ref={this.setSelectedStoryRef}>
          {story}
        </SelectedStoryHighlight>
      );
    }

    return (

    );
  };

  createParts = (rows, stylesheet, useInlineStyles) => {
    const { locationsMap, locationsKeys } = this.state;

    const parts = [];
    let lastRow = 0;

    locationsKeys.forEach(key => {
      const location = locationsMap[key];
      const first = location.startLoc.line - 1;
      const last = location.endLoc.line;

      const start = this.createPart(rows.slice(lastRow, first), stylesheet, useInlineStyles);
      const storyPart = this.createStoryPart(rows, stylesheet, useInlineStyles, location, key);

      parts.push(start);
      parts.push(storyPart);

      lastRow = last;
    });

    const lastPart = this.createPart(rows.slice(lastRow), stylesheet, useInlineStyles);

    parts.push(lastPart);

    return parts;
  };

  lineRenderer = ({ rows, stylesheet, useInlineStyles }) => {
    const { locationsMap, locationsKeys } = this.state;

    // because of the usage of lineRenderer, all lines will be wrapped in a span
    // these spans will recieve all classes on them for some reason
    // which makes colours casecade incorrectly
    // this removed that list of classnames
    const myrows = rows.map(({ properties, ...rest }) => ({
      ...rest,
      properties: { className: [] },
    }));

    if (!locationsMap || !locationsKeys.length) {
      return this.createPart(myrows, stylesheet, useInlineStyles);
    }

    const parts = this.createParts(myrows, stylesheet, useInlineStyles);

    return {parts};
  };

  render() {
    const { active } = this.props;
    const { source } = this.state;

    return active ? (

    ) : null;
  }
}

StoryPanel.propTypes = {
  active: PropTypes.bool.isRequired,
  api: PropTypes.shape({
    selectStory: PropTypes.func.isRequired,
    emit: PropTypes.func,
    on: PropTypes.func,
    off: PropTypes.func,
  }).isRequired,
};
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import {connect} from 'dva'
import {routerRedux} from 'dva/router'
import {Table} from 'antd'
import classnames from 'classnames'
import TableBodyWrapper from './TableBodyWrapper'

function DataTable({dispatch, location, curTab, className, pagination, animate, ...props}) {

  const getBodyWrapperProps = {
    page: location.query.page || 1,
    current: pagination.current || 1
  }

  const getBodyWrapper = (body) => (<TableBodyWrapper {...getBodyWrapperProps} body={body}/>)

  const onPageChange = (page) => {
    const {query} = location
    const pathname = curTab.path || location.pathname
    dispatch(routerRedux.push({
      pathname: pathname,
      query: {
        ...query,
        current: page.current,
        pageSize: page.pageSize
      }
    }))
  }

  let tableProps = {
    simple: true,
    bordered: true,
    scroll: {x: 1200},
    onChange: onPageChange,
    pagination: !!pagination && {...pagination, showSizeChanger: true, showQuickJumper: true, showTotal: total => `共 ${total} 条`},
    ...props
  }
  if(animate) {
    tableProps.getBodyWrapper = getBodyWrapper
    tableProps.className = classnames(className, "table-motion")
  }

  return (
    <Table {...tableProps}/>
  )
}

DataTable.propTypes = {
  animate: PropTypes.bool,
  rowKey: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.func
  ]).isRequired,
  pagination: PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.object,
  ]).isRequired,
  columns: PropTypes.array.isRequired,
  dataSource: PropTypes.array.isRequired,
  className: PropTypes.string
}

DataTable.defaultProps = {
  animate: true
}

function mapStateToProps({ routing, app }) {
  return { location: routing.locationBeforeTransitions, curTab: app.curTab }
}

export default connect(mapStateToProps)(DataTable)
<commit_msg>fix DataTable.js<commit_after>import React, {Component, PropTypes} from 'react'
import {connect} from 'dva'
import {routerRedux} from 'dva/router'
import {Table} from 'antd'
import classnames from 'classnames'
import TableBodyWrapper from './TableBodyWrapper'

function DataTable({dispatch, location, className, pagination, animate, ...props}) {

  const getBodyWrapperProps = {
    page: location.query.page || 1,
    current: pagination.current || 1
  }

  const getBodyWrapper = (body) => (<TableBodyWrapper {...getBodyWrapperProps} body={body}/>)

  const onPageChange = (page) => {
    const {query} = location
    const pathname = location.pathname
    dispatch(routerRedux.push({
      pathname: pathname,
      query: {
        ...query,
        current: page.current,
        pageSize: page.pageSize
      }
    }))
  }

  let tableProps = {
    simple: true,
    bordered: true,
    scroll: {x: 1200},
    onChange: onPageChange,
    pagination: !!pagination && {...pagination, showSizeChanger: true, showQuickJumper: true, showTotal: total => `共 ${total} 条`},
    ...props
  }
  if(animate) {
    tableProps.getBodyWrapper = getBodyWrapper
    tableProps.className = classnames(className, "table-motion")
  }

  return (
    <Table {...tableProps}/>
  )
}

DataTable.propTypes = {
  animate: PropTypes.bool,
  rowKey: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.func
  ]).isRequired,
  pagination: PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.object,
  ]).isRequired,
  columns: PropTypes.array.isRequired,
  dataSource: PropTypes.array.isRequired,
  className: PropTypes.string
}

DataTable.defaultProps = {
  animate: true
}

function mapStateToProps({ routing, app }) {
  return { location: routing.locationBeforeTransitions }
}

export default connect(mapStateToProps)(DataTable)
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * A brief overview of this source file: what is its purpose.
 */

var sprintf = require('sprintf').sprintf;
var uuid = require('node-uuid');
var common = require('./../common');

var WfClient = require('wf-client');

// Workflows

// Absolute path from the app
var WORKFLOW_PATH = './lib/workflows/';

/*
 * WFAPI Constructor
 */
function Wfapi(options) {
    this.log = options.log;
    options.path = WORKFLOW_PATH;

    this.client = new WfClient(options);
    this.connected = false;
}

Wfapi.prototype.connect = function (cb) {
    this.log.debug('Loading the WFAPI workflows...');
    return attemptInitWorkflows.call(this, cb);
};

/*
 * Attemps to init all the workflows and retries until they all have been
 * created.
 */
function attemptInitWorkflows(cb) {
    var self = this;
    var timeout = null;

    this.client.initWorkflows(onInit);

    function onInit(err) {
        if (err) {
            self.log.error('Error loading workflows, retrying');
            self.connected = false;

            if (!timeout) {
                attemptInitWorkflows.call(self, cb);
            }
        } else {
            clearTimeout(timeout);
            timeout = null;
            self.connected = true;
            self.log.info('All workflows have been loaded');
            if (cb) cb();
        }
    }

    function timeoutCallback() {
        attemptInitWorkflows.call(self);
    }

    timeout = setTimeout(timeoutCallback, 10000);
}

/*
 * Pings WFAPI by getting the provision workflow
 */
Wfapi.prototype.ping = function (callback) {
    this.client.ping(function (err, pong) {
        return callback(err);
    });
};

/*
 * Takes care of figuring out if clients are passing request-id or x-request-id.
 */
function getRequestHeaders(req) {
    if (req.headers['x-request-id']) {
        return { 'x-request-id': req.headers['x-request-id'] };
    } else {
        return {};
    }
}

/*
 * Queues a provision job.
 */
Wfapi.prototype.createProvisionJob = function (req, cb) {
    var self = this;
    var params = req.params;
    var vm_uuid = params.uuid || uuid();
    var options = { headers: getRequestHeaders(req) };

    params.task = 'provision';
    params.target = '/provision-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.current_state = 'provisioning';

    self.client.createJob('provision', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Provision job ' + job.uuid + ' queued for VM ' +
            vm_uuid);
        cb(null, vm_uuid, job.uuid);
    });
};

/*
 * Queues a start job.
 */
Wfapi.prototype.createStartJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = req.params;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'start';
    params.target = '/start-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.current_state = req.vm.state;

    self.client.createJob('start', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Start job ' + job.uuid + ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a stop job.
 */
Wfapi.prototype.createStopJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = req.params;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'stop';
    params.target = '/stop-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.current_state = req.vm.state;

    self.client.createJob('stop', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Stop job ' + job.uuid + ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a reboot job.
 */
Wfapi.prototype.createRebootJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = req.params;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'reboot';
    params.target = '/reboot-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.current_state = req.vm.state;

    self.client.createJob('reboot', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Reboot job ' + job.uuid + ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a reprovision job.
 */
Wfapi.prototype.createReprovisionJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = req.params;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'reprovision';
    params.target = '/reprovision-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.server_uuid = req.vm.server_uuid;

    self.client.createJob('reprovision', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Reprovision job ' + job.uuid + ' queued for VM ' +
            vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a destroy job.
 */
Wfapi.prototype.createDestroyJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = req.params;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'destroy';
    params.target = '/destroy-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.owner_uuid = req.vm.owner_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.current_state = req.vm.state;

    if (req.headers['x-joyent-context']) {
        try {
            params.context = JSON.parse(req.headers['x-joyent-context']);
        } catch (e) {
            // Moooving forward, no big deal
        }
    }

    self.client.createJob('destroy', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Destroy job ' + job.uuid + ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues an update job.
 */
Wfapi.prototype.createUpdateJob = function (req, params, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'update';
    params.target = '/update-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.owner_uuid = req.vm.owner_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.last_modified = req.vm.last_modified;

    if (req.params.context !== undefined) {
        params.context = req.params.context;
    }

    self.client.createJob('update', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Update job ' + job.uuid + ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues an add nics (update) job.
 */
Wfapi.prototype.createAddNicsJob = function (req, networks, cb) {
    var self = this;
    var params = { networks: networks };
    var vm_uuid = req.vm.uuid;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'add_nics';
    params.target = '/add-nics-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.owner_uuid = req.vm.owner_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.last_modified = req.vm.last_modified;
    params.oldResolvers = req.vm.resolvers;
    params.wantResolvers = true;

    if (req.params.context !== undefined) {
        params.context = req.params.context;
    }

    // If internal_metadata.set_resolvers === false, we always want
    // to leave the resolvers as empty
    if (req.vm.internal_metadata !== undefined &&
        typeof (req.vm.internal_metadata) === 'object' &&
        req.vm.internal_metadata.set_resolvers === false) {
        params.wantResolvers = false;
    }

    self.client.createJob('add-nics', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Add NICs job ' + job.uuid + ' queued for VM '+
            vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a remove nics (update) job.
 */
Wfapi.prototype.createRemoveNicsJob = function (req, macs, cb) {
    var self = this;
    var params = { remove_nics: macs };
    var vm_uuid = req.vm.uuid;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'remove_nics';
    params.target = '/remove-nics-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.owner_uuid = req.vm.owner_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.last_modified = req.vm.last_modified;
    params.wantResolvers = true;

    if (req.params.context !== undefined) {
        params.context = req.params.context;
    }

    // If internal_metadata.set_resolvers === false, we always want
    // to leave the resolvers as empty
    if (req.vm.internal_metadata !== undefined &&
        typeof (req.vm.internal_metadata) === 'object' &&
        req.vm.internal_metadata.set_resolvers === false) {
        params.wantResolvers = false;
    }

    // Sent the MACs of the NICs in order
    params.oldMacs = [];
    for (var i = 0; i < req.vm.nics.length; i++) {
        params.oldMacs.push(req.vm.nics[i].mac);
    }

    self.client.createJob('remove-nics', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Remove NICs job ' + job.uuid + ' queued for VM '+
            vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Generates a timestamp for the default snapshot name
 */
function formatTimestamp(now) {
    if (!now) {
        now = new Date();
    }

    return now.getFullYear() + '' +
        sprintf('%02d', now.getMonth() + 1) + '' +
        sprintf('%02d', now.getDate()) + 'T' +
        sprintf('%02d', now.getHours()) + '' +
        sprintf('%02d', now.getMinutes()) + '' +
        sprintf('%02d', now.getSeconds()) + 'Z';
}

/*
 * Queues a snapshot job.
 */
Wfapi.prototype.createSnapshotJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = req.params;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'snapshot';
    params.target = '/snapshot-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.server_uuid = req.vm.server_uuid;

    if (!params['snapshot_name']) {
        params['snapshot_name'] = formatTimestamp();
    }

    self.client.createJob('snapshot', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Snapshot job ' + job.uuid +
            ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a rollback job.
 */
Wfapi.prototype.createRollbackJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = req.params;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'snapshot';
    params.target = '/rollback-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.vm_state = req.vm.state;
    params.server_uuid = req.vm.server_uuid;

    self.client.createJob('rollback', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Rollback job ' + job.uuid +
            ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a delete snapshot job.
 */
Wfapi.prototype.createDeleteSnapshotJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = req.params;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'snapshot';
    params.target = '/delete-snapshot-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.vm_state = req.vm.state;
    params.server_uuid = req.vm.server_uuid;

    self.client.createJob('delete-snapshot', params, options,
      function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Delete snapshot job ' + job.uuid +
            ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Retrieves a job from WFAPI.
 */
Wfapi.prototype.getJob = function (jobUuid, cb) {
    this.client.getJob(jobUuid, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        cb(null, common.translateJob(job));
    });
};

/*
 * Lists jobs from WFAPI.
 */
Wfapi.prototype.listJobs = function (params, cb) {
    var query = {};

    if (params.execution) {
        query.execution = params.execution;
    }

    if (params.task) {
        query.task = params.task;
    }

    if (params.vm_uuid) {
        query.vm_uuid = params.vm_uuid;
    }

    this.client.listJobs(query, function (err, jobs) {
        if (err) {
            cb(err);
            return;
        }

        var theJobs = [];
        for (var i = 0; i < jobs.length; i++) {
            theJobs.push(common.translateJob(jobs[i]));
        }

        cb(null, theJobs);
    });
};

module.exports = Wfapi;
<commit_msg>ZAPI-378: Should not pass req.params directly to wf jobs<commit_after>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * A brief overview of this source file: what is its purpose.
 */

var sprintf = require('sprintf').sprintf;
var uuid = require('node-uuid');
var common = require('./../common');
var clone = common.clone;

var WfClient = require('wf-client');

// Workflows

// Absolute path from the app
var WORKFLOW_PATH = './lib/workflows/';

/*
 * WFAPI Constructor
 */
function Wfapi(options) {
    this.log = options.log;
    options.path = WORKFLOW_PATH;

    this.client = new WfClient(options);
    this.connected = false;
}

Wfapi.prototype.connect = function (cb) {
    this.log.debug('Loading the WFAPI workflows...');
    return attemptInitWorkflows.call(this, cb);
};

/*
 * Attemps to init all the workflows and retries until they all have been
 * created.
 */
function attemptInitWorkflows(cb) {
    var self = this;
    var timeout = null;

    this.client.initWorkflows(onInit);

    function onInit(err) {
        if (err) {
            self.log.error('Error loading workflows, retrying');
            self.connected = false;

            if (!timeout) {
                attemptInitWorkflows.call(self, cb);
            }
        } else {
            clearTimeout(timeout);
            timeout = null;
            self.connected = true;
            self.log.info('All workflows have been loaded');
            if (cb) cb();
        }
    }

    function timeoutCallback() {
        attemptInitWorkflows.call(self);
    }

    timeout = setTimeout(timeoutCallback, 10000);
}

/*
 * Pings WFAPI by getting the provision workflow
 */
Wfapi.prototype.ping = function (callback) {
    this.client.ping(function (err, pong) {
        return callback(err);
    });
};

/*
 * Takes care of figuring out if clients are passing request-id or x-request-id.
 */
function getRequestHeaders(req) {
    if (req.headers['x-request-id']) {
        return { 'x-request-id': req.headers['x-request-id'] };
    } else {
        return {};
    }
}

/*
 * Queues a provision job.
 */
Wfapi.prototype.createProvisionJob = function (req, cb) {
    var self = this;
    var params = clone(req.params);
    var vm_uuid = params.uuid || uuid();
    var options = { headers: getRequestHeaders(req) };

    params.task = 'provision';
    params.target = '/provision-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.current_state = 'provisioning';
    delete params.uuid;

    self.client.createJob('provision', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Provision job ' + job.uuid + ' queued for VM ' +
            vm_uuid);
        cb(null, vm_uuid, job.uuid);
    });
};

/*
 * Queues a start job.
 */
Wfapi.prototype.createStartJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = {};
    var options = { headers: getRequestHeaders(req) };

    params.task = 'start';
    params.target = '/start-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.current_state = req.vm.state;

    self.client.createJob('start', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Start job ' + job.uuid + ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a stop job.
 */
Wfapi.prototype.createStopJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = {};
    var options = { headers: getRequestHeaders(req) };

    params.task = 'stop';
    params.target = '/stop-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.current_state = req.vm.state;

    self.client.createJob('stop', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Stop job ' + job.uuid + ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a reboot job.
 */
Wfapi.prototype.createRebootJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = {};
    var options = { headers: getRequestHeaders(req) };

    params.task = 'reboot';
    params.target = '/reboot-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.current_state = req.vm.state;

    self.client.createJob('reboot', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Reboot job ' + job.uuid + ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a reprovision job.
 */
Wfapi.prototype.createReprovisionJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = { 'image_uuid': req.params['image_uuid'] };
    var options = { headers: getRequestHeaders(req) };

    params.task = 'reprovision';
    params.target = '/reprovision-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.server_uuid = req.vm.server_uuid;

    self.client.createJob('reprovision', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Reprovision job ' + job.uuid + ' queued for VM ' +
            vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a destroy job.
 */
Wfapi.prototype.createDestroyJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = {};
    var options = { headers: getRequestHeaders(req) };

    params.task = 'destroy';
    params.target = '/destroy-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.owner_uuid = req.vm.owner_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.current_state = req.vm.state;

    if (req.headers['x-joyent-context']) {
        try {
            params.context = JSON.parse(req.headers['x-joyent-context']);
        } catch (e) {
            // Moooving forward, no big deal
        }
    }

    self.client.createJob('destroy', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Destroy job ' + job.uuid + ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues an update job.
 */
Wfapi.prototype.createUpdateJob = function (req, params, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'update';
    params.target = '/update-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.owner_uuid = req.vm.owner_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.last_modified = req.vm.last_modified;

    if (req.params.context !== undefined) {
        params.context = req.params.context;
    }

    self.client.createJob('update', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Update job ' + job.uuid + ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues an add nics (update) job.
 */
Wfapi.prototype.createAddNicsJob = function (req, networks, cb) {
    var self = this;
    var params = { networks: networks };
    var vm_uuid = req.vm.uuid;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'add_nics';
    params.target = '/add-nics-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.owner_uuid = req.vm.owner_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.last_modified = req.vm.last_modified;
    params.oldResolvers = req.vm.resolvers;
    params.wantResolvers = true;

    if (req.params.context !== undefined) {
        params.context = req.params.context;
    }

    // If internal_metadata.set_resolvers === false, we always want
    // to leave the resolvers as empty
    if (req.vm.internal_metadata !== undefined &&
        typeof (req.vm.internal_metadata) === 'object' &&
        req.vm.internal_metadata.set_resolvers === false) {
        params.wantResolvers = false;
    }

    self.client.createJob('add-nics', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Add NICs job ' + job.uuid + ' queued for VM '+
            vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a remove nics (update) job.
 */
Wfapi.prototype.createRemoveNicsJob = function (req, macs, cb) {
    var self = this;
    var params = { remove_nics: macs };
    var vm_uuid = req.vm.uuid;
    var options = { headers: getRequestHeaders(req) };

    params.task = 'remove_nics';
    params.target = '/remove-nics-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.owner_uuid = req.vm.owner_uuid;
    params.server_uuid = req.vm.server_uuid;
    params.last_modified = req.vm.last_modified;
    params.wantResolvers = true;

    if (req.params.context !== undefined) {
        params.context = req.params.context;
    }

    // If internal_metadata.set_resolvers === false, we always want
    // to leave the resolvers as empty
    if (req.vm.internal_metadata !== undefined &&
        typeof (req.vm.internal_metadata) === 'object' &&
        req.vm.internal_metadata.set_resolvers === false) {
        params.wantResolvers = false;
    }

    // Sent the MACs of the NICs in order
    params.oldMacs = [];
    for (var i = 0; i < req.vm.nics.length; i++) {
        params.oldMacs.push(req.vm.nics[i].mac);
    }

    self.client.createJob('remove-nics', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Remove NICs job ' + job.uuid + ' queued for VM '+
            vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Generates a timestamp for the default snapshot name
 */
function formatTimestamp(now) {
    if (!now) {
        now = new Date();
    }

    return now.getFullYear() + '' +
        sprintf('%02d', now.getMonth() + 1) + '' +
        sprintf('%02d', now.getDate()) + 'T' +
        sprintf('%02d', now.getHours()) + '' +
        sprintf('%02d', now.getMinutes()) + '' +
        sprintf('%02d', now.getSeconds()) + 'Z';
}

/*
 * Queues a snapshot job.
 */
Wfapi.prototype.createSnapshotJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = {
        'snapshot_name': req.params['snapshot_name'] || formatTimestamp()
    };
    var options = { headers: getRequestHeaders(req) };

    params.task = 'snapshot';
    params.target = '/snapshot-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.server_uuid = req.vm.server_uuid;

    self.client.createJob('snapshot', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Snapshot job ' + job.uuid +
            ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a rollback job.
 */
Wfapi.prototype.createRollbackJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = { 'snapshot_name': req.params['snapshot_name'] };
    var options = { headers: getRequestHeaders(req) };

    params.task = 'snapshot';
    params.target = '/rollback-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.vm_state = req.vm.state;
    params.server_uuid = req.vm.server_uuid;

    self.client.createJob('rollback', params, options, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Rollback job ' + job.uuid +
            ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Queues a delete snapshot job.
 */
Wfapi.prototype.createDeleteSnapshotJob = function (req, cb) {
    var self = this;
    var vm_uuid = req.vm.uuid;
    var params = { 'snapshot_name': req.params['snapshot_name'] };
    var options = { headers: getRequestHeaders(req) };

    params.task = 'snapshot';
    params.target = '/delete-snapshot-' + vm_uuid;
    params.vm_uuid = vm_uuid;
    params.vm_state = req.vm.state;
    params.server_uuid = req.vm.server_uuid;

    self.client.createJob('delete-snapshot', params, options,
      function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        self.log.debug('Delete snapshot job ' + job.uuid +
            ' queued for VM ' + vm_uuid);
        cb(null, job.uuid);
    });
};

/*
 * Retrieves a job from WFAPI.
 */
Wfapi.prototype.getJob = function (jobUuid, cb) {
    this.client.getJob(jobUuid, function (err, job) {
        if (err) {
            cb(err);
            return;
        }

        cb(null, common.translateJob(job));
    });
};

/*
 * Lists jobs from WFAPI.
 */
Wfapi.prototype.listJobs = function (params, cb) {
    var query = {};

    if (params.execution) {
        query.execution = params.execution;
    }

    if (params.task) {
        query.task = params.task;
    }

    if (params.vm_uuid) {
        query.vm_uuid = params.vm_uuid;
    }

    this.client.listJobs(query, function (err, jobs) {
        if (err) {
            cb(err);
            return;
        }

        var theJobs = [];
        for (var i = 0; i < jobs.length; i++) {
            theJobs.push(common.translateJob(jobs[i]));
        }

        cb(null, theJobs);
    });
};

module.exports = Wfapi;
<|endoftext|>


<commit_before>// Copyright 2014-2015 runtime.js project authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';
var MACAddress = require('./mac-address');
var Interface = require('./interface');
var IP4Address = require('./ip4-address');
var route = require('./route');

var intf = new Interface(MACAddress.ZERO);
var ip = new IP4Address(127, 0, 0, 1);
var mask = new IP4Address(127, 0, 0, 255);
intf.disableArp();
intf.setName('loopback');
intf.configure(ip, mask);

intf.ontransmit = function(u8headers, u8data) {
  setTimeout(function() {
    if (u8data) {
      var u8 = new Uint8Array(u8headers.length + u8data.length);
      u8.set(u8headers, 0);
      u8.set(u8data, u8headers.length);
      intf.receive(u8);
    } else {
      intf.receive(u8headers);
    }
  }, 0);
};

var subnet = ip.and(mask);
route.addSubnet(subnet, mask, null, intf);

module.exports = intf;
<commit_msg>Fix loopback interface netmask<commit_after>// Copyright 2014-2015 runtime.js project authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';
var MACAddress = require('./mac-address');
var Interface = require('./interface');
var IP4Address = require('./ip4-address');
var route = require('./route');

var intf = new Interface(MACAddress.ZERO);
var ip = new IP4Address(127, 0, 0, 1);
var mask = new IP4Address(255, 0, 0, 0);
intf.disableArp();
intf.setName('loopback');
intf.configure(ip, mask);

intf.ontransmit = function(u8headers, u8data) {
  setTimeout(function() {
    if (u8data) {
      var u8 = new Uint8Array(u8headers.length + u8data.length);
      u8.set(u8headers, 0);
      u8.set(u8data, u8headers.length);
      intf.receive(u8);
    } else {
      intf.receive(u8headers);
    }
  }, 0);
};

var subnet = ip.and(mask);
route.addSubnet(subnet, mask, null, intf);

module.exports = intf;
<|endoftext|>


<commit_before>/**
 * Abstract overlay widget
 *
 * @copyright 2005-2010 silverorange Inc.
 */

// {{{ function SwatAbstractOverlay()

/**
 * Creates an abstract overlay widget
 *
 * @param string id
 */
function SwatAbstractOverlay(id)
{
	this.id = id;
	this.container = document.getElementById(this.id);
	this.value_field = document.getElementById(this.id + '_value');

	this.is_open = false;
	this.is_drawn = false;

	// list of select elements to hide for IE6
	this.select_elements = [];

	YAHOO.util.Event.onDOMReady(this.init, this, true);
	YAHOO.util.Event.onContentReady(this.id,
		this.createOverlay, this, true);
}

SwatAbstractOverlay.close_text = 'Close';

// }}}
// {{{ SwatAbstractOverlay.prototype.init

SwatAbstractOverlay.prototype.init = function()
{
	this.draw();
	this.drawCloseDiv();
}

// }}}
// {{{ SwatAbstractOverlay.prototype.draw

SwatAbstractOverlay.prototype.draw = function()
{
	this.overlay_content = document.createElement('div');
	this.overlay_content.id = this.id + '_overlay';
	YAHOO.util.Dom.addClass(this.overlay_content, 'swat-overlay');
	this.overlay_content.style.display = 'none';

	this.overlay_content.appendChild(this.getHeader());
	this.overlay_content.appendChild(this.getBody());
	this.overlay_content.appendChild(this.getFooter());

	this.toggle_button = this.getToggleButton();
	this.toggle_button.appendChild(this.overlay_content);

	this.container.appendChild(this.toggle_button);
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getToggleButton

SwatAbstractOverlay.prototype.getToggleButton = function()
{
	var toggle_button = document.createElement('button');
	YAHOO.util.Dom.addClass(toggle_button, 'swat-overlay-toggle-button');

	// the type property is readonly in IE so use setAttribute() here
	toggle_button.setAttribute('type', 'button');

	YAHOO.util.Event.on(toggle_button, 'click', this.toggle, this, true);

	return toggle_button;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getHeader

SwatAbstractOverlay.prototype.getHeader = function()
{
	var header = document.createElement('div');
	YAHOO.util.Dom.addClass(header, 'hd');
	header.appendChild(this.getCloseLink());
	return header;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getBody

SwatAbstractOverlay.prototype.getBody = function()
{
	var body = document.createElement('div');
	YAHOO.util.Dom.addClass(body, 'bd');
	return body;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getFooter

SwatAbstractOverlay.prototype.getFooter = function()
{
	var footer = document.createElement('div');
	YAHOO.util.Dom.addClass(footer, 'ft');
	return footer;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getCloseLink

SwatAbstractOverlay.prototype.getCloseLink = function()
{
	var close_link = document.createElement('a');
	close_link.className = 'swat-overlay-close-link';
	close_link.href = '#';
	close_link.appendChild(document.createTextNode(
		SwatAbstractOverlay.close_text));

	YAHOO.util.Event.on(close_link, 'click', this.handleCloseLink, this, true);

	return close_link;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.createOverlay

/**
 * Creates overlay widget when toggle button has been drawn
 */
SwatAbstractOverlay.prototype.createOverlay = function(event)
{
	this.overlay = new YAHOO.widget.Overlay(this.id + '_overlay',
		{ visible: false, constraintoviewport: true });

	this.overlay.body.appendChild(this.getBodyContent());

	this.overlay.render(this.container);
	this.overlay_content.style.display = 'block';
	this.is_drawn = true;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.close

/**
 * Closes this overlay
 */
SwatAbstractOverlay.prototype.close = function()
{
	this.hideCloseDiv();

	this.overlay.hide();
	SwatZIndexManager.lowerElement(this.overlay_content);
	this.is_open = false;

	this.removeKeyPressHandler();
}

// }}}
// {{{ SwatAbstractOverlay.prototype.open

/**
 * Opens this overlay
 */
SwatAbstractOverlay.prototype.open = function()
{
	this.showCloseDiv();

	this.overlay.cfg.setProperty('context', this.getOverlayContext());

	this.overlay.show();
	this.is_open = true;

	SwatZIndexManager.raiseElement(this.overlay_content);

	this.addKeyPressHandler();
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getOverlayContext

/**
 * Get the context for positioning the overlay
 */
SwatAbstractOverlay.prototype.getOverlayContext = function()
{
	return [this.toggle_button, 'tl', 'bl'];
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getBodyContent

/**
 * Draws this overlay
 */
SwatAbstractOverlay.prototype.getBodyContent = function()
{
	return document.createElement('div');
}

// }}}
// {{{ SwatAbstractOverlay.prototype.toggle

SwatAbstractOverlay.prototype.toggle = function()
{
	if (this.is_open)
		this.close();
	else
		this.open();
}

// }}}
// {{{ SwatAbstractOverlay.prototype.drawCloseDiv

SwatAbstractOverlay.prototype.drawCloseDiv = function()
{
	this.close_div = document.createElement('div');

	this.close_div.className = 'swat-overlay-close-div';
	this.close_div.style.display = 'none';

	YAHOO.util.Event.on(this.close_div, 'click', this.close, this, true);

	this.container.appendChild(this.close_div);
}

// }}}
// {{{ SwatAbstractOverlay.prototype.showCloseDiv

SwatAbstractOverlay.prototype.showCloseDiv = function()
{
	if (YAHOO.env.ua.ie == 6) {
		this.select_elements = document.getElementsByTagName('select');
		for (var i = 0; i < this.select_elements.length; i++) {
			this.select_elements[i].style._visibility =
				this.select_elements[i].style.visibility;

			this.select_elements[i].style.visibility = 'hidden';
		}
	}

	this.close_div.style.height = YAHOO.util.Dom.getDocumentHeight() + 'px';
	this.close_div.style.display = 'block';
	SwatZIndexManager.raiseElement(this.close_div);
}

// }}}
// {{{ SwatAbstractOverlay.prototype.hideCloseDiv

SwatAbstractOverlay.prototype.hideCloseDiv = function()
{
	SwatZIndexManager.lowerElement(this.close_div);
	this.close_div.style.display = 'none';
	if (YAHOO.env.ua.ie == 6) {
		for (var i = 0; i < this.select_elements.length; i++) {
			this.select_elements[i].style.visibility =
				this.select_elements[i].style._visibility;
		}
	}
}

// }}}
// {{{ SwatAbstractOverlay.prototype.handleKeyPress

SwatAbstractOverlay.prototype.handleKeyPress = function(e)
{
	YAHOO.util.Event.preventDefault(e);

	// close preview on backspace or escape
	if (e.keyCode == 8 || e.keyCode == 27)
		this.close();
}

// }}}
// {{{ SwatAbstractOverlay.prototype.handleKeyPress

SwatAbstractOverlay.prototype.handleKeyPress = function(e)
{
	// close preview on escape or enter key
	if (e.keyCode == 27 || e.keyCode == 13) {
		YAHOO.util.Event.preventDefault(e);
		this.close();
	}
}

// }}}
// {{{ SwatAbstractOverlay.prototype.addKeyPressHandler

SwatAbstractOverlay.prototype.addKeyPressHandler = function()
{
	YAHOO.util.Event.on(document, 'keypress',
		this.handleKeyPress, this, true);
}

// }}}
// {{{ SwatAbstractOverlay.prototype.removeKeyPressHandler

SwatAbstractOverlay.prototype.removeKeyPressHandler = function()
{
	YAHOO.util.Event.removeListener(document, 'keypress',
		this.handleKeyPress, this, true);
}

// }}}
// {{{ SwatAbstractOverlay.prototype.handleCloseLink

SwatAbstractOverlay.prototype.handleCloseLink = function(e)
{
	YAHOO.util.Event.preventDefault(e);
	this.close();
}

// }}}
<commit_msg>Make close link more accessible and do createOverlay onDOMReady like the other draw methods. Fixes IE init bug.<commit_after>/**
 * Abstract overlay widget
 *
 * @copyright 2005-2010 silverorange Inc.
 */

// {{{ function SwatAbstractOverlay()

/**
 * Creates an abstract overlay widget
 *
 * @param string id
 */
function SwatAbstractOverlay(id)
{
	this.id = id;
	this.container = document.getElementById(this.id);
	this.value_field = document.getElementById(this.id + '_value');

	this.is_open = false;
	this.is_drawn = false;

	// list of select elements to hide for IE6
	this.select_elements = [];

	YAHOO.util.Event.onDOMReady(this.init, this, true);
}

SwatAbstractOverlay.close_text = 'Close';

// }}}
// {{{ SwatAbstractOverlay.prototype.init

SwatAbstractOverlay.prototype.init = function()
{
	this.draw();
	this.drawCloseDiv();
	this.createOverlay();
}

// }}}
// {{{ SwatAbstractOverlay.prototype.draw

SwatAbstractOverlay.prototype.draw = function()
{
	this.overlay_content = document.createElement('div');
	this.overlay_content.id = this.id + '_overlay';
	YAHOO.util.Dom.addClass(this.overlay_content, 'swat-overlay');
	this.overlay_content.style.display = 'none';

	this.overlay_content.appendChild(this.getHeader());
	this.overlay_content.appendChild(this.getBody());
	this.overlay_content.appendChild(this.getFooter());

	this.toggle_button = this.getToggleButton();
	this.toggle_button.appendChild(this.overlay_content);

	this.container.appendChild(this.toggle_button);
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getToggleButton

SwatAbstractOverlay.prototype.getToggleButton = function()
{
	var toggle_button = document.createElement('button');
	YAHOO.util.Dom.addClass(toggle_button, 'swat-overlay-toggle-button');

	// the type property is readonly in IE so use setAttribute() here
	toggle_button.setAttribute('type', 'button');

	YAHOO.util.Event.on(toggle_button, 'click', this.toggle, this, true);

	return toggle_button;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getHeader

SwatAbstractOverlay.prototype.getHeader = function()
{
	var header = document.createElement('div');
	YAHOO.util.Dom.addClass(header, 'hd');
	header.appendChild(this.getCloseLink());
	return header;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getBody

SwatAbstractOverlay.prototype.getBody = function()
{
	var body = document.createElement('div');
	YAHOO.util.Dom.addClass(body, 'bd');
	return body;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getFooter

SwatAbstractOverlay.prototype.getFooter = function()
{
	var footer = document.createElement('div');
	YAHOO.util.Dom.addClass(footer, 'ft');
	return footer;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getCloseLink

SwatAbstractOverlay.prototype.getCloseLink = function()
{
	var close_link = document.createElement('a');
	close_link.className = 'swat-overlay-close-link';
	close_link.href = '#close';
	close_link.appendChild(document.createTextNode(
		SwatAbstractOverlay.close_text));

	YAHOO.util.Event.on(close_link, 'click', this.handleCloseLink, this, true);

	return close_link;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.createOverlay

/**
 * Creates overlay widget when toggle button has been drawn
 */
SwatAbstractOverlay.prototype.createOverlay = function(event)
{
	this.overlay = new YAHOO.widget.Overlay(this.id + '_overlay',
		{ visible: false, constraintoviewport: true });

	this.overlay.body.appendChild(this.getBodyContent());

	this.overlay.render(this.container);
	this.overlay_content.style.display = 'block';
	this.is_drawn = true;
}

// }}}
// {{{ SwatAbstractOverlay.prototype.close

/**
 * Closes this overlay
 */
SwatAbstractOverlay.prototype.close = function()
{
	this.hideCloseDiv();

	this.overlay.hide();
	SwatZIndexManager.lowerElement(this.overlay_content);
	this.is_open = false;

	this.removeKeyPressHandler();
}

// }}}
// {{{ SwatAbstractOverlay.prototype.open

/**
 * Opens this overlay
 */
SwatAbstractOverlay.prototype.open = function()
{
	this.showCloseDiv();

	this.overlay.cfg.setProperty('context', this.getOverlayContext());

	this.overlay.show();
	this.is_open = true;

	SwatZIndexManager.raiseElement(this.overlay_content);

	this.addKeyPressHandler();
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getOverlayContext

/**
 * Get the context for positioning the overlay
 */
SwatAbstractOverlay.prototype.getOverlayContext = function()
{
	return [this.toggle_button, 'tl', 'bl'];
}

// }}}
// {{{ SwatAbstractOverlay.prototype.getBodyContent

/**
 * Draws this overlay
 */
SwatAbstractOverlay.prototype.getBodyContent = function()
{
	return document.createElement('div');
}

// }}}
// {{{ SwatAbstractOverlay.prototype.toggle

SwatAbstractOverlay.prototype.toggle = function()
{
	if (this.is_open)
		this.close();
	else
		this.open();
}

// }}}
// {{{ SwatAbstractOverlay.prototype.drawCloseDiv

SwatAbstractOverlay.prototype.drawCloseDiv = function()
{
	this.close_div = document.createElement('div');

	this.close_div.className = 'swat-overlay-close-div';
	this.close_div.style.display = 'none';

	YAHOO.util.Event.on(this.close_div, 'click', this.close, this, true);

	this.container.appendChild(this.close_div);
}

// }}}
// {{{ SwatAbstractOverlay.prototype.showCloseDiv

SwatAbstractOverlay.prototype.showCloseDiv = function()
{
	if (YAHOO.env.ua.ie == 6) {
		this.select_elements = document.getElementsByTagName('select');
		for (var i = 0; i < this.select_elements.length; i++) {
			this.select_elements[i].style._visibility =
				this.select_elements[i].style.visibility;

			this.select_elements[i].style.visibility = 'hidden';
		}
	}

	this.close_div.style.height = YAHOO.util.Dom.getDocumentHeight() + 'px';
	this.close_div.style.display = 'block';
	SwatZIndexManager.raiseElement(this.close_div);
}

// }}}
// {{{ SwatAbstractOverlay.prototype.hideCloseDiv

SwatAbstractOverlay.prototype.hideCloseDiv = function()
{
	SwatZIndexManager.lowerElement(this.close_div);
	this.close_div.style.display = 'none';
	if (YAHOO.env.ua.ie == 6) {
		for (var i = 0; i < this.select_elements.length; i++) {
			this.select_elements[i].style.visibility =
				this.select_elements[i].style._visibility;
		}
	}
}

// }}}
// {{{ SwatAbstractOverlay.prototype.handleKeyPress

SwatAbstractOverlay.prototype.handleKeyPress = function(e)
{
	YAHOO.util.Event.preventDefault(e);

	// close preview on backspace or escape
	if (e.keyCode == 8 || e.keyCode == 27)
		this.close();
}

// }}}
// {{{ SwatAbstractOverlay.prototype.handleKeyPress

SwatAbstractOverlay.prototype.handleKeyPress = function(e)
{
	// close preview on escape or enter key
	if (e.keyCode == 27 || e.keyCode == 13) {
		YAHOO.util.Event.preventDefault(e);
		this.close();
	}
}

// }}}
// {{{ SwatAbstractOverlay.prototype.addKeyPressHandler

SwatAbstractOverlay.prototype.addKeyPressHandler = function()
{
	YAHOO.util.Event.on(document, 'keypress',
		this.handleKeyPress, this, true);
}

// }}}
// {{{ SwatAbstractOverlay.prototype.removeKeyPressHandler

SwatAbstractOverlay.prototype.removeKeyPressHandler = function()
{
	YAHOO.util.Event.removeListener(document, 'keypress',
		this.handleKeyPress, this, true);
}

// }}}
// {{{ SwatAbstractOverlay.prototype.handleCloseLink

SwatAbstractOverlay.prototype.handleCloseLink = function(e)
{
	YAHOO.util.Event.preventDefault(e);
	this.close();
}

// }}}
<|endoftext|>


<commit_before>/* eslint-disable no-console */
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const path = require('path')

const zmdVersion = require('../package.json').version

function controllerFactory (handler) {
  return (req, res) => {
    handler(req.body.md, req.body.opts, (err, result) => {
      if (err) {
        Raven.captureException(err, {req})
        console.error(err)
        res.status(500).json(null)
        return
      }

      res.json(result)
    })
  }
}

const Raven = require('raven')
Raven.config(process.env.SENTRY_DSN, {
  release: process.env.SENTRY_RELEASE || zmdVersion,
  environment: process.env.SENTRY_ENVIRONMENT || process.env.ZDS_ENVIRONMENT,
}).install()

const {
  toEPUB,
  toHTML,
  toLatex,
  toLatexDocument,
} = require('./handlers')(Raven)

const app = express()

app.use(cors())

app.use(Raven.requestHandler())
app.use(Raven.errorHandler())

app.use('/static', express.static(path.join(__dirname, 'static')))

app.use(bodyParser.json({limit: '5mb'}))

app.post('/epub', controllerFactory(toEPUB))
app.post('/html', controllerFactory(toHTML))
app.post('/latex', controllerFactory(toLatex))
app.post('/latex-document', controllerFactory(toLatexDocument))

const munin = require('./munin')
app.get('/munin/config/:plugin', munin('config'))
app.get('/munin/:plugin', munin())

app.get('/', (req, res) => {
  res.send('zmd is running\n')
})

module.exports = app
<commit_msg>zmd: limit payload size<commit_after>/* eslint-disable no-console */
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const path = require('path')

const zmdVersion = require('../package.json').version

function controllerFactory (handler) {
  return (req, res) => {
    handler(req.body.md, req.body.opts, (err, result) => {
      if (err) {
        Raven.captureException(err, {req, result})
        res.status(500).json(result)
        return
      }

      res.json(result)
    })
  }
}

const Raven = require('raven')
Raven.config(process.env.SENTRY_DSN, {
  release: process.env.SENTRY_RELEASE || zmdVersion,
  environment: process.env.SENTRY_ENVIRONMENT || process.env.ZDS_ENVIRONMENT,
}).install()

const {
  toEPUB,
  toHTML,
  toLatex,
  toLatexDocument,
} = require('./handlers')(Raven)

const app = express()

app.use(cors())

app.use(Raven.requestHandler())
app.use(Raven.errorHandler())

app.use('/static', express.static(path.join(__dirname, 'static')))

app.post('/epub', bodyParser.json({limit: '5mb'}), controllerFactory(toEPUB))
app.post('/html', bodyParser.json({limit: '300kb'}), controllerFactory(toHTML))
app.post('/latex', bodyParser.json({limit: '5mb'}), controllerFactory(toLatex))
app.post('/latex-document', bodyParser.json({limit: '5mb'}), controllerFactory(toLatexDocument))

const munin = require('./munin')
app.get('/munin/config/:plugin', munin('config'))
app.get('/munin/:plugin', munin())

app.get('/', (req, res) => {
  res.send('zmd is running\n')
})

module.exports = app
<|endoftext|>


<commit_before>var remote = require('remote');
var dialog = remote.require('dialog');

Template.dashboardSettings.events({
  'click .btn-usage-analytics-on': function () {
    localStorage.setItem('metrics.enabled', true);
    Session.set('metrics.enabled', true);
  },
  'click .btn-usage-analytics-off': function () {
    localStorage.setItem('metrics.enabled', false);
    Session.set('metrics.enabled', false);
  }
});

Template.dashboardSettings.helpers({
  metricsEnabled: function () {
    if (Session.get('metrics.enabled') === undefined) {
      Session.set('metrics.enabled', localStorage.getItem('metrics.enabled'));
    }
    return Session.get('metrics.enabled');
  },
  memory: function () {
    return Session.get('boot2dockerMemoryUsage');
  },
  disk: function () {
    return Session.get('boot2dockerDiskUsage');
  }
});
<commit_msg>fixing settings page<commit_after>var remote = require('remote');
var dialog = remote.require('dialog');
var level = require('levelup');
var db = level(path.join(process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'], 'Library/Application Support/Kitematic/data', 'db'));

Template.dashboardSettings.events({
  'click .btn-usage-analytics-on': function () {
    db.put('metrics.enabled', true);
    Session.set('metrics.enabled', true);
  },
  'click .btn-usage-analytics-off': function () {
    db.put('metrics.enabled', false);
    Session.set('metrics.enabled', false);
  }
});

Template.dashboardSettings.helpers({
  metricsEnabled: function () {
    if (Session.get('metrics.enabled') === undefined) {
      db.get('metrics.enabled', function (err, value) {
        Session.set('metrics.enabled', value);
      });
    }
    return Session.get('metrics.enabled');
  },
  memory: function () {
    return Session.get('boot2dockerMemoryUsage');
  },
  disk: function () {
    return Session.get('boot2dockerDiskUsage');
  }
});
<|endoftext|>


<commit_before>"use strict";

/*global module, require*/

var d3 = require("d3");

module.exports = function(container, drawErrors, drawLayerControl, drawImport) {
    var el = container.append("div")
	    .attr("id", "toolbar");

    return {
	draw: function(errorDialogueState, layerDialogueState, importDialogueState) {

	    buttons.exit().remove();

	    buttons.enter()
		.append("span")
		.text(function(d, i) {
		    return d.toolText;
		});

	    // These need to interact with dialogue.drawButtons?

	}
    };
};
<commit_msg>Removed unused file.<commit_after><|endoftext|>


<commit_before>import React from 'react';
import { NavLink } from 'fluxible-router';

class NavigationComponent extends React.Component {
  render() {
    return (

          <NavLink className='navbar-brand' routeName='uploader'>Gy</NavLink>

              <NavLink activeClass='active' className='nav-link' routeName='settings'>

              </NavLink>

    );
  }
}

export default NavigationComponent;
<commit_msg>設定ページを開いているときには設定ページへの導線を消す<commit_after>import React from 'react';
import { connectToStores } from 'fluxible-addons-react';
import { NavLink } from 'fluxible-router';
import RouteStore from '../stores/RouteStore';

class NavigationComponent extends React.Component {
  static contentTypes = {
    getStore: React.PropTypes.func.isRequired
  };

  static propTypes = {
    currentRoute: React.PropTypes.object
  };

  render() {
    return (

          <NavLink className='navbar-brand' routeName='uploader'>Gy</NavLink>

              <NavLink className='nav-link' routeName='settings'>

              </NavLink>

    );
  }
}

NavigationComponent = connectToStores(NavigationComponent, [RouteStore], (context) => ({
  currentRoute: context.getStore(RouteStore).getCurrentRoute()
}));
export default NavigationComponent;
<|endoftext|>