<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * Legend panel. Generates the legend. Specific options are:
 * legendPosition - top / bottom / left / right. Default: bottom
 * legendSize - The size of the legend in pixels. Default: 25
 *
 * Has the following protovis extension points:
 *
 * legend_ - for the legend Panel
 * legendRule_ - for the legend line (when applicable)
 * legendDot_ - for the legend marker (when applicable)
 * legendLabel_ - for the legend label
 *
 */
def
.type('pvc.LegendPanel', pvc.BasePanel)
.init(function(chart, parent, options) {

    this.base(chart, parent, options);

    // Undo base Clickable handling
    // It doesn't matter if the chart's clickable is false.
    // Legend clickable depends on each legend group scene's clickMode.
    var I = pvc.visual.Interactive;
    if(this._ibits & I.Interactive) { this._ibits |= I.Clickable; }
})
.add({
    pvRule: null,
    pvDot: null,
    pvLabel: null,

    anchor: 'bottom',

    pvLegendPanel: null,

    textMargin:  6,    // The space *between* the marker and the text, in pixels.
    itemPadding: 2.5,  // Half the space *between* legend items, in pixels.
    markerSize:  15,   // *diameter* of marker *zone* (the marker itself may be a little smaller)
    font:  '10px sans-serif',

    /**
     * @override
     */
    _calcLayout: function(layoutInfo){
        return this._getBulletRootScene().layout(layoutInfo);
    },

    /**
     * @override
     */
    _createCore: function(layoutInfo) {
      var clientSize = layoutInfo.clientSize,
          rootScene = this._getBulletRootScene(),
          itemPadding = rootScene.vars.itemPadding,
          contentSize = rootScene.vars.size;

       // Names are for horizontal layout (anchor = top or bottom)
      var isHorizontal = this.isAnchorTopOrBottom();
      var a_top    = isHorizontal ? 'top' : 'left';
      var a_bottom = this.anchorOpposite(a_top);    // top or bottom
      var a_width  = this.anchorLength(a_top);      // width or height
      var a_height = this.anchorOrthoLength(a_top); // height or width
      var a_center = isHorizontal ? 'center' : 'middle';
      var a_left   = isHorizontal ? 'left' : 'top';
      var a_right  = this.anchorOpposite(a_left);   // left or right

      // When V1 compat or size is fixed to less/more than content needs,
      // it is still needed to align content inside

      // We align all rows left (or top), using the length of the widest row.
      // So "center" is a kind of centered-left align?

      var leftOffset = 0;
      switch(this.align){
          case a_right:
              leftOffset = clientSize[a_width] - contentSize.width;
              break;

          case a_center:
              leftOffset = (clientSize[a_width] - contentSize.width) / 2;
              break;
      }

      this.pvPanel.overflow("hidden");

      // ROW - A panel instance per row
      var pvLegendRowPanel = this.pvPanel.add(pv.Panel)
          .data(rootScene.vars.rows) // rows are "lists" of bullet item scenes
          [a_left  ](leftOffset)
          [a_top   ](function() {
              var prevRow = this.sibling();
              return prevRow ? (prevRow[a_top] + prevRow[a_height] + itemPadding[a_height]) : 0;
          })
          [a_width ](function(row) { return row.size.width;  })
          [a_height](function(row) { return row.size.height; })
          ;

      var wrapper;
      if(this.compatVersion() <= 1) {
          wrapper = function(v1f) {
              return function(itemScene) { return v1f.call(this, itemScene.vars.value.rawValue); };
          };
      }

      // ROW > ITEM - A pvLegendPanel instance per bullet item in a row
      this.pvLegendPanel = new pvc.visual.Panel(this, pvLegendRowPanel, {
              extensionId:   'panel',
              wrapper:       wrapper,
              noSelect:      false,
              noHover:       true,
              noClick:       false, // see also #_onClick below and constructor change of Clickable
              noClickSelect: true   // just rubber-band (the click is for other behaviors)
          })
          .lockMark('data', function(row) { return row.items; }) // each row has a list of bullet item scenes
          .lock(a_right,  null)
          .lock(a_bottom, null)
          .lockMark(a_left, function(clientScene) {
              var itemPadding  = clientScene.vars.itemPadding;
              var prevItem = this.sibling();
              return prevItem ?
                      (prevItem[a_left] + prevItem[a_width] + itemPadding[a_width]) :
                      0;
          })
          .lockMark('height', function(itemScene) { return itemScene.vars.clientSize.height; })
          .lockMark(a_top,
                  isHorizontal ?
                  // Center items in row's height, that may be higher
                  function(itemScene) {
                      var vars = itemScene.vars;
                      return vars.row.size.height / 2 - vars.clientSize.height / 2;
                  } :
                  // Left align items of a same column
                  0)
          .lockMark('width',
                  isHorizontal ?
                  function(itemScene) { return itemScene.vars.clientSize.width; } :

                   // The biggest child width of the column
                  function(/*itemScene*/) { return this.parent.width(); })
          .pvMark
          .def("hidden", "false")
          .fillStyle(function() { // TODO: ??
              return this.hidden() == "true" ?
                     "rgba(200,200,200,1)" :
                     "rgba(200,200,200,0.0001)";
          });

      // ROW > ITEM > MARKER
      var pvLegendMarkerPanel = new pvc.visual.Panel(this, this.pvLegendPanel)
          .pvMark
          .left(0)
          .top (0)
          .right (null)
          .bottom(null)
          .width (function(itemScene){ return itemScene.vars.markerSize; })
          .height(function(itemScene){ return itemScene.vars.clientSize.height; })
          ;

      if(pvc.debug >= 20) {
          pvLegendRowPanel.strokeStyle('red');
          this.pvLegendPanel.strokeStyle('green');
          pvLegendMarkerPanel.strokeStyle('blue');
      }

      /* RULE/MARKER */
      rootScene.childNodes.forEach(function(groupScene) {
          var pvGroupPanel = new pvc.visual.Panel(this, pvLegendMarkerPanel)
                  .pvMark
                  .visible(function(itemScene) { return itemScene.parent === groupScene; });

          groupScene.renderer().create(this, pvGroupPanel, groupScene.extensionPrefix, wrapper);
      }, this);

      /* LABEL */
      this.pvLabel = new pvc.visual.Label(this, pvLegendMarkerPanel.anchor("right"), {
              extensionId: 'label',
              wrapper: wrapper
          })
          .intercept('textStyle', function(itemScene) {
              var baseTextStyle = this.delegateExtension() || "black";
              return itemScene.isOn() ?
                  baseTextStyle :
                  pvc.toGrayScale(baseTextStyle, null, undefined, 150);
          })
          .pvMark
          .textAlign('left') // panel type anchors don't adjust textAlign this way
          .text(function(itemScene) { return itemScene.vars.value.label; })
          // -4 is to compensate for now the label being anchored to the panel instead of the rule or the dot...
          .lock('textMargin', function(itemScene) { return itemScene.vars.textMargin - 4; })
          .font(function(itemScene) { return itemScene.vars.font; }) // TODO: lock?
          .textDecoration(function(itemScene) { return itemScene.isOn() ? "" : "line-through"; });

      if(pvc.debug >= 16) {
          var font = this.font;
          var textHeight = pv.Text.fontHeight(font) * 2/3;

          pvLegendMarkerPanel.anchor("right")
              // Single-point panel (w=h=0)
              .add(pv.Panel)
                  [this.anchorLength()](0)
                  [this.anchorOrthoLength()](0)
                  .fillStyle(null)
                  .strokeStyle(null)
                  .lineWidth(0)
               .add(pv.Line)
                  .data(function(scene) {
                      var labelBBox = pvc.text.getLabelBBox(
                              pv.Text.measureWidth(scene.vars.value.label, font),
                              textHeight,  // shared stuff
                              'left',
                              'middle',
                              0,
                              2);
                      var corners = labelBBox.source.points();

                      // Close the path
                      // not changing corners on purpose
                      if(corners.length > 1) { corners = corners.concat(corners[0]); }

                      return corners;
                  })
                  .left(function(p) { return p.x; })
                  .top (function(p) { return p.y; })
                  .strokeStyle('red')
                  .lineWidth(0.5)
                  .strokeDasharray('-');
      }
    },

    _onClick: function(context) {
        var scene = context.scene;
        if(def.fun.is(scene.execute) && scene.executable()) {
            scene.execute();
        }
    },

    _getExtensionPrefix: function() { return 'legend'; },
    _getExtensionId:     function() { return 'area';   },

    // Catches both the marker and the label.
    // Also, if selection changes, renderInteractive re-renders these.
    _getSelectableMarks: function() { return [this.pvLegendPanel]; },

    _getBulletRootScene: function(){
        var rootScene = this._rootScene;
        if(!rootScene){
            // The legend root scene contains all datums of its chart
            rootScene = new pvc.visual.legend.BulletRootScene(null, {
                panel:       this,
                source:      this.chart.data,
                horizontal:  this.isAnchorTopOrBottom(),
                font:        this.font,
                markerSize:  this.markerSize,
                textMargin:  this.textMargin,
                itemPadding: this.itemPadding
            });

            this._rootScene = rootScene;
        }

        return rootScene;
    }
});<commit_msg>[FEAT] (Legend Tooltip Label Trimming) Legend items' labels are now trimmed on overflow, and the tooltip shows the original text. Still need to better place the tooltip relative to the label. Still need an option for not showing the tooltip (like in the axis panel).<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * Legend panel. Generates the legend. Specific options are:
 * legendPosition - top / bottom / left / right. Default: bottom
 * legendSize - The size of the legend in pixels. Default: 25
 *
 * Has the following protovis extension points:
 *
 * legend_ - for the legend Panel
 * legendRule_ - for the legend line (when applicable)
 * legendDot_ - for the legend marker (when applicable)
 * legendLabel_ - for the legend label
 *
 */
def
.type('pvc.LegendPanel', pvc.BasePanel)
.init(function(chart, parent, options) {

    this.base(chart, parent, options);

    // Undo base Clickable handling.
    // It doesn't matter if the chart's clickable is false.
    // Legend clickable depends on each legend group scene's clickMode.
    var I = pvc.visual.Interactive;
    if(this._ibits & I.Interactive) { this._ibits |= I.Clickable; }
})
.add({
    pvRule: null,
    pvDot: null,
    pvLabel: null,

    anchor: 'bottom',

    pvLegendPanel: null,

    textMargin:  6,    // The space *between* the marker and the text, in pixels.
    itemPadding: 2.5,  // Half the space *between* legend items, in pixels.
    markerSize:  15,   // *diameter* of marker *zone* (the marker itself may be a little smaller)
    font:  '10px sans-serif',

    /**
     * @override
     */
    _calcLayout: function(layoutInfo){
        return this._getBulletRootScene().layout(layoutInfo);
    },

    /**
     * @override
     */
    _createCore: function(layoutInfo) {
      var clientSize = layoutInfo.clientSize,
          rootScene = this._getBulletRootScene(),
          itemPadding = rootScene.vars.itemPadding,
          contentSize = rootScene.vars.contentSize;

       // Names are for horizontal layout (anchor = top or bottom)
      var isHorizontal = this.isAnchorTopOrBottom();
      var a_top    = isHorizontal ? 'top' : 'left';
      var a_bottom = this.anchorOpposite(a_top);    // top or bottom
      var a_width  = this.anchorLength(a_top);      // width or height
      var a_height = this.anchorOrthoLength(a_top); // height or width
      var a_center = isHorizontal ? 'center' : 'middle';
      var a_left   = isHorizontal ? 'left' : 'top';
      var a_right  = this.anchorOpposite(a_left);   // left or right

      // When V1 compat or size is fixed to less/more than content needs,
      // it is still needed to align content inside

      // We align all rows left (or top), using the length of the widest row.
      // So "center" is a kind of centered-left align?

      var leftOffset = 0;
      switch(this.align){
          case a_right:
              leftOffset = clientSize[a_width] - contentSize.width;
              break;

          case a_center:
              leftOffset = (clientSize[a_width] - contentSize.width) / 2;
              break;
      }

      this.pvPanel.overflow("hidden");

      // ROW - A panel instance per row
      var pvLegendRowPanel = this.pvPanel.add(pv.Panel)
          .data(rootScene.vars.rows) // rows are "lists" of bullet item scenes
          [a_left  ](leftOffset)
          [a_top   ](function() {
              var prevRow = this.sibling();
              return prevRow ? (prevRow[a_top] + prevRow[a_height] + itemPadding[a_height]) : 0;
          })
          [a_width ](function(row) { return row.size.width;  })
          [a_height](function(row) { return row.size.height; })
          ;

      var wrapper;
      if(this.compatVersion() <= 1) {
          wrapper = function(v1f) {
              return function(itemScene) { return v1f.call(this, itemScene.vars.value.rawValue); };
          };
      }

      // ROW > ITEM - A pvLegendPanel instance per bullet item in a row
      this.pvLegendPanel = new pvc.visual.Panel(this, pvLegendRowPanel, {
              extensionId:   'panel',
              wrapper:       wrapper,
              noSelect:      false,
              noHover:       true,
              noClick:       false, // see also #_onClick below and constructor change of Clickable
              noClickSelect: true   // just rubber-band (the click is for other behaviors)
          })
          .lockMark('data', function(row) { return row.items; }) // each row has a list of bullet item scenes
          .lock(a_right,  null)
          .lock(a_bottom, null)
          .lockMark(a_left, function(clientScene) {
              var itemPadding  = clientScene.vars.itemPadding;
              var prevItem = this.sibling();
              return prevItem ?
                      (prevItem[a_left] + prevItem[a_width] + itemPadding[a_width]) :
                      0;
          })
          .lockMark('height', function(itemScene) { return itemScene.vars.clientSize.height; })
          .lockMark(a_top,
                  isHorizontal ?
                  // Center items in row's height, that may be higher
                  function(itemScene) {
                      var vars = itemScene.vars;
                      return vars.row.size.height / 2 - vars.clientSize.height / 2;
                  } :
                  // Left align items of a same column
                  0)
          .lockMark('width',
                  isHorizontal ?
                  function(itemScene) { return itemScene.vars.clientSize.width; } :

                   // The biggest child width of the column
                  function(/*itemScene*/) { return this.parent.width(); })
          .pvMark
          .def("hidden", "false")
          .fillStyle(function() { // TODO: ??
              return this.hidden() == "true" ?
                     "rgba(200,200,200,1)" :
                     "rgba(200,200,200,0.0001)";
          });

      // ROW > ITEM > MARKER
      var pvLegendMarkerPanel = new pvc.visual.Panel(this, this.pvLegendPanel)
          .pvMark
          .left(0)
          .top (0)
          .right (null)
          .bottom(null)
          .width (function(itemScene){ return itemScene.vars.markerSize; })
          .height(function(itemScene){ return itemScene.vars.clientSize.height; })
          ;

      if(pvc.debug >= 20) {
          pvLegendRowPanel.strokeStyle('red');
          this.pvLegendPanel.strokeStyle('green');
          pvLegendMarkerPanel.strokeStyle('blue');
      }

      /* RULE/MARKER */
      rootScene.childNodes.forEach(function(groupScene) {
          var pvGroupPanel = new pvc.visual.Panel(this, pvLegendMarkerPanel)
                  .pvMark
                  .visible(function(itemScene) { return itemScene.parent === groupScene; });

          groupScene.renderer().create(this, pvGroupPanel, groupScene.extensionPrefix, wrapper);
      }, this);

      /* LABEL */
      this.pvLabel = new pvc.visual.Label(this, pvLegendMarkerPanel.anchor('right'), {
              extensionId: 'label',
              noTooltip:   false,
              noClick:     false,
              wrapper:     wrapper
          })
          .intercept('textStyle', function(itemScene) {
              var baseTextStyle = this.delegateExtension() || "black";
              return itemScene.isOn() ?
                  baseTextStyle :
                  pvc.toGrayScale(baseTextStyle, null, undefined, 150);
          })
          .pvMark
          .textAlign('left') // panel type anchors don't adjust textAlign this way
          .text(function(itemScene) {
            var vars = itemScene.vars;
            return pvc.text.trimToWidthB(
              vars.labelWidthMax,
              itemScene.labelText(),
              vars.font,
              "..",
              false);
          })
          // -4 is to compensate for now the label being anchored to the panel instead of the rule or the dot...
          .lock('textMargin', function(itemScene) { return itemScene.vars.textMargin - 4; })
          .font(function(itemScene) { return itemScene.vars.font; }) // TODO: lock?
          .textDecoration(function(itemScene) { return itemScene.isOn() ? "" : "line-through"; });

      if(pvc.debug >= 16) {
          pvLegendMarkerPanel.anchor("right")
              // Single-point panel (w=h=0)
              .add(pv.Panel)
                  [this.anchorLength()](0)
                  [this.anchorOrthoLength()](0)
                  .fillStyle(null)
                  .strokeStyle(null)
                  .lineWidth(0)
               .add(pv.Line)
                  .data(function(scene) {
                      var vars = scene.vars;
                      var textHeight = scene.labelTextSize().height * 2/3;
                      var labelBBox  = pvc.text.getLabelBBox(
                              vars.labelWidthMax,
                              textHeight,
                              'left',
                              'middle',
                              0,
                              2);
                      var corners = labelBBox.source.points();

                      // Close the path
                      // not changing corners on purpose
                      if(corners.length > 1) { corners = corners.concat(corners[0]); }

                      return corners;
                  })
                  .left(function(p) { return p.x; })
                  .top (function(p) { return p.y; })
                  .strokeStyle('red')
                  .lineWidth(0.5)
                  .strokeDasharray('-');
      }
    },

    _onClick: function(context) {
        var scene = context.scene;
        if(def.fun.is(scene.execute) && scene.executable()) {
            scene.execute();
        }
    },

    _getExtensionPrefix: function() { return 'legend'; },
    _getExtensionId:     function() { return 'area';   },

    // Catches both the marker and the label.
    // Also, if selection changes, renderInteractive re-renders these.
    _getSelectableMarks: function() { return [this.pvLegendPanel]; },

    _getBulletRootScene: function(){
        var rootScene = this._rootScene;
        if(!rootScene){
            // The legend root scene contains all datums of its chart
            rootScene = new pvc.visual.legend.BulletRootScene(null, {
                panel:       this,
                source:      this.chart.data,
                horizontal:  this.isAnchorTopOrBottom(),
                font:        this.font,
                markerSize:  this.markerSize,
                textMargin:  this.textMargin,
                itemPadding: this.itemPadding
            });

            this._rootScene = rootScene;
        }

        return rootScene;
    },

    _getTooltipFormatter: function(tipOptions) {
        tipOptions.isLazy = false;
        return function(context) {
          var valueVar = context.scene.vars.value;
          return valueVar.absLabel || valueVar.label;
        };
    }
});<|endoftext|>


<commit_before>!function($) {

    'use strict';

    var filterData = {};
    var bootstrapTableFilter;
    var serverUrl;

    var getTypeByValues = function(vals, useAjax) {
        var typeFloat = true, typeInt = true;
        $.each(vals, function(i, val) {
            if (typeInt && (parseInt(val) != val)) {
                typeInt = false;
            }
            if (typeFloat && (parseFloat(val) != val)) {
                typeFloat = false;
            }
        });
        if (typeInt || typeFloat) {
            return {type: 'range'};
        }
        if (useAjax) {
            return {type: 'selectAjax', source: 'XXXXX'}
        }
        return {type: 'select'};
    };
    var getCols = function(cols, data, useAjax) {
        var ret = {};
        $.each(cols, function(i, col) {
            ret[col.field] = {
                field: col.field,
                label: col.title,
                values: []
            };
        });
        $.each(data, function(i, row) {
            $.each(ret, function(field, filter) {
                if (ret[field].values.indexOf(row[field]) < 0) {
                    ret[field].values.push(row[field]);
                }
            });
        });
        $.each(ret, function(field, def) {
            ret[field] = $.extend(ret[field], getTypeByValues(def.values));
        });
        return ret;
    };
    var rowFilter = function(item, i) {
        var filterType;
        var ret = true;
        $.each(item, function(field, value) {
            filterType = false;
            try {
                filterType = bootstrapTableFilter.getFilterType(field);
                if (filterType && typeof filterData[field] !== 'undefined') {
                    ret = ret && bootstrapTableFilter.checkFilterTypeValue(filterType, filterData[field], value);
                }
            }
            catch (e) {}
        });
        return ret;
    };

    $.fn.bootstrapTableFilter.externals.push(function() {
        if (this.options.connectTo) {
            bootstrapTableFilter = this;
            var $bootstrapTable = $(this.options.connectTo);
            var data = $bootstrapTable.bootstrapTable('getData');
            var cols = $bootstrapTable.bootstrapTable('getColumns');
            var dataSourceServer = false;
            var filters = getCols(cols, data, dataSourceServer);

            $.each(filters, function(field, filter) {
                bootstrapTableFilter.addFilter(filter);
            });
            serverUrl = $bootstrapTable.bootstrapTable('getServerUrl');
            if (serverUrl) {
                this.$el.on('submit.bs.table.filter', function() {
                    filterData = bootstrapTableFilter.getData();
                    var delimiter = serverUrl.indexOf('?') < 0 ? '?' : '&';
                    var url = serverUrl + delimiter + 'filter=' + encodeURIComponent(JSON.stringify(filterData));
//                    console.log(url);
                    $bootstrapTable.bootstrapTable('updateSearch');
                });
            }
            else {
                $bootstrapTable.bootstrapTable('registerSearchCallback', rowFilter);
                this.$el.on('submit.bs.table.filter', function() {
                    filterData = bootstrapTableFilter.getData();
                    $bootstrapTable.bootstrapTable('updateSearch');
                });
            }
        }
    });

}(jQuery);<commit_msg>WHen table uses ajax source, data for filter are also got from the same ajax source using different get params<commit_after>!function($) {

    'use strict';

    var filterData = {};
    var bootstrapTableFilter;
    var serverUrl;

    var getTypeByValues = function(filter) {
        var typeFloat = true, typeInt = true;
        $.each(filter.values, function(i, val) {
            if (typeInt && (parseInt(val) != val)) {
                typeInt = false;
            }
            if (typeFloat && (parseFloat(val) != val)) {
                typeFloat = false;
            }
        });
        if (typeInt || typeFloat) {
            return {type: 'range'};
        }
        if (serverUrl) {
            var delimiter = serverUrl.indexOf('?') < 0 ? '?' : '&';
            return {
                type: 'ajaxSelect',
                source: serverUrl + delimiter + 'resourceFor=' + filter.field
            };
        }
        return {type: 'select'};
    };
    var getCols = function(cols, data, useAjax) {
        var ret = {};
        $.each(cols, function(i, col) {
            ret[col.field] = {
                field: col.field,
                label: col.title,
                values: []
            };
        });
        $.each(data, function(i, row) {
            $.each(ret, function(field, filter) {
                if (ret[field].values.indexOf(row[field]) < 0) {
                    ret[field].values.push(row[field]);
                }
            });
        });
        $.each(ret, function(field, def) {
            ret[field] = $.extend(ret[field], getTypeByValues(def));
        });
        return ret;
    };
    var rowFilter = function(item, i) {
        var filterType;
        var ret = true;
        $.each(item, function(field, value) {
            filterType = false;
            try {
                filterType = bootstrapTableFilter.getFilterType(field);
                if (filterType && typeof filterData[field] !== 'undefined') {
                    ret = ret && bootstrapTableFilter.checkFilterTypeValue(filterType, filterData[field], value);
                }
            }
            catch (e) {}
        });
        return ret;
    };

    $.fn.bootstrapTableFilter.externals.push(function() {
        if (this.options.connectTo) {
            bootstrapTableFilter = this;
            var $bootstrapTable = $(this.options.connectTo);
            var data = $bootstrapTable.bootstrapTable('getData');
            var cols = $bootstrapTable.bootstrapTable('getColumns');
            serverUrl = $bootstrapTable.bootstrapTable('getServerUrl');
            var dataSourceServer = false;
            var filters = getCols(cols, data, dataSourceServer);

            $.each(filters, function(field, filter) {
                bootstrapTableFilter.addFilter(filter);
            });
            if (serverUrl) {
                this.$el.on('submit.bs.table.filter', function() {
                    filterData = bootstrapTableFilter.getData();
                    var delimiter = serverUrl.indexOf('?') < 0 ? '?' : '&';
                    var url = serverUrl + delimiter + 'filter=' + encodeURIComponent(JSON.stringify(filterData));
//                    console.log(url);
                    $bootstrapTable.bootstrapTable('refresh', {url: url});
                });
            }
            else {
                $bootstrapTable.bootstrapTable('registerSearchCallback', rowFilter);
                this.$el.on('submit.bs.table.filter', function() {
                    filterData = bootstrapTableFilter.getData();
                    $bootstrapTable.bootstrapTable('updateSearch');
                });
            }
        }
    });

}(jQuery);<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2014 NTHUOJ team

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var displayInfo = false;
var loginInfo = false;

window.onload = function() {
    alert("You have new messages!");
}
function info() {
    if(displayInfo == false){
        document.getElementById("information").style.display = "block";
        displayInfo = !displayInfo;
    }
    else{
        document.getElementById("information").style.display = "none";
        displayInfo = !displayInfo;
    }
}
function sendinfo() {
    var text = document.getElementById("txt").value;
    var orgintext = document.getElementById("information").innerHTML;
    document.getElementById("information").innerHTML = orgintext + '
' + text + '
'
    //alert(orgintext);
    alert("You have new messages!" + text);
}
function log_in() {
    //alert('1');
    document.getElementById("notlogin").style.display = "none";
    //document.getElementById("notlogin").innerHTML
    //document.getElementById("notlogin").style.display="none";
}
$(function() {
    setInterval(function() {
        $.get('/get_time/', function(data) {
            $('#time').html(data);
        });
    }, 450);
})
<commit_msg>remove debug info<commit_after>/*
The MIT License (MIT)

Copyright (c) 2014 NTHUOJ team

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var displayInfo = false;
var loginInfo = false;

window.onload = function() {
    alert("You have new messages!");
}
function info() {
    if(displayInfo == false){
        document.getElementById("information").style.display = "block";
        displayInfo = !displayInfo;
    }
    else{
        document.getElementById("information").style.display = "none";
        displayInfo = !displayInfo;
    }
}
function sendinfo() {
    var text = document.getElementById("txt").value;
    var orgintext = document.getElementById("information").innerHTML;
    document.getElementById("information").innerHTML = orgintext + '
' + text + '
';
    alert("You have new messages!" + text);
}
function log_in() {
    document.getElementById("notlogin").style.display = "none";
}
$(function() {
    setInterval(function() {
        $.get('/get_time/', function(data) {
            $('#time').html(data);
        });
    }, 450);
})
<|endoftext|>


<commit_before>const DocumentDBClient = require('documentdb').DocumentClient;
const config = {
    DatabaseId: "mean-dev",
    CollectionId: "users",
    Host: process.env.DocDb_Host,
    AuthKey: process.env.DocDb_AuthKey,
};

config.CollLink = 'dbs/' + config.DatabaseId + '/colls/' + config.CollectionId

module.exports = function (context, message) {

    let err = null;

    const docDbClient = new DocumentDBClient(config.Host, { masterKey: config.AuthKey });
    const querySpec = {
        //query: 'SELECT * FROM c',
        query: 'SELECT * FROM c WHERE (c.twitter[\'$id\'] = @userid AND \'twitter\' = @platform) AND (c.instagram[\'$id\'] = @userid AND \'instagram\' = @platform) AND (c.facebook[\'$id\'] = @userid AND \'facebook\' = @platform)',
        parameters: [{
            name: '@userid',
            value: message.userid
        },
        {
            name: '@platform',
            value: message.platform
        }]
    };

    docDbClient.queryDocuments(config.CollLink, querySpec).toArray(function (err, results) {
        context.log(err);
        context.log(results);

        let userdata = results[0];

        if (!userdata || userdata == undefined) {
            context.log('Not tracking user');

            err = new Error('Not tracking user');
        }

        if ((!userdata.twitter || userdata.twitter == undefined)
            && (!userdata.facebook || userdata.facebook == undefined)
            || (!userdata.instagram || userdata.instagram == undefined)) {
            context.log('No social profiles');

            err = new Error('No social profiles');
        }

        if (!userdata.id) {
            context.log('No user id');

            err = new Error('No social profiles');
        }

        let data = new Object();

        if (!err) {
            data.userid = userdata.id;
            data.platform = message.platform;
            data.mediaid = message.mediaid;

            if (message.twitter) {
                context.log('adding twitter');

                data.twitter = {
                    id: message.twitter.$id,
                    token: message.twitter.token,
                    username: message.twitter.username,
                };
            }

            if (message.instagram) {
                context.log('adding instagram');

                data.instagram = {
                    id: message.instagram.$id,
                    token: message.instagram.token,
                    username: message.instagram.username,
                };
            }

            if (message.facebook) {
                context.log('adding facebook');

                data.facebook = {
                    id: message.facebook.$id,
                    token: message.facebook.token,
                    username: message.facebook.email,
                };
            }
        }

        context.done(err, data);
    });

};<commit_msg>fix break<commit_after>const DocumentDBClient = require('documentdb').DocumentClient;
const config = {
    DatabaseId: "mean-dev",
    CollectionId: "users",
    Host: process.env.DocDb_Host,
    AuthKey: process.env.DocDb_AuthKey,
};

config.CollLink = 'dbs/' + config.DatabaseId + '/colls/' + config.CollectionId

module.exports = function (context, message) {

    let err = null;

    const docDbClient = new DocumentDBClient(config.Host, { masterKey: config.AuthKey });
    const querySpec = {
        //query: 'SELECT * FROM c',
        query: 'SELECT * FROM c WHERE (c.twitter[\'$id\'] = @userid AND \'twitter\' = @platform) AND (c.instagram[\'$id\'] = @userid AND \'instagram\' = @platform) AND (c.facebook[\'$id\'] = @userid AND \'facebook\' = @platform)',
        parameters: [{
            name: '@userid',
            value: message.userid
        },
        {
            name: '@platform',
            value: message.platform
        }]
    };

    docDbClient.queryDocuments(config.CollLink, querySpec).toArray(function (err, results) {
        context.log(err);
        context.log(results);

        let userdata = results[0];

        if (!userdata || userdata == undefined) {
            context.log('Not tracking user');

            err = new Error('Not tracking user');
            return;
        }

        if ((!userdata.twitter || userdata.twitter == undefined)
            && (!userdata.facebook || userdata.facebook == undefined)
            || (!userdata.instagram || userdata.instagram == undefined)) {
            context.log('No social profiles');

            err = new Error('No social profiles');
        }

        if (!userdata.id) {
            context.log('No user id');

            err = new Error('No social profiles');
        }

        let data = new Object();

        if (!err) {
            data.userid = userdata.id;
            data.platform = message.platform;
            data.mediaid = message.mediaid;

            if (message.twitter) {
                context.log('adding twitter');

                data.twitter = {
                    id: message.twitter.$id,
                    token: message.twitter.token,
                    username: message.twitter.username,
                };
            }

            if (message.instagram) {
                context.log('adding instagram');

                data.instagram = {
                    id: message.instagram.$id,
                    token: message.instagram.token,
                    username: message.instagram.username,
                };
            }

            if (message.facebook) {
                context.log('adding facebook');

                data.facebook = {
                    id: message.facebook.$id,
                    token: message.facebook.token,
                    username: message.facebook.email,
                };
            }
        }

        context.done(err, data);
    });
};<|endoftext|>


<commit_before>'use strict';

var partial       = require('es5-ext/lib/Function/prototype/partial')
  , d             = require('es5-ext/lib/Object/descriptor')
  , forEach       = require('es5-ext/lib/Object/for-each')
  , startsWith    = require('es5-ext/lib/String/prototype/starts-with')
  , ee            = require('event-emitter/lib/core')
  , castAttribute = require('dom-ext/lib/Element/prototype/cast-attribute')
  , nextTick      = require('next-tick')
  , Db            = require('dbjs')

  , Input;

module.exports = Input = function (document, ns/*, options*/) {
	var options = Object(arguments[2]);
	this.document = document;
	this.ns = ns;
	this.control = this.dom = document.createElement('input');
	if (options.name) this.name = options.name;
	this.castKnownAttributes(options);
	this.dom._dbjsInput = this;
	document.addEventListener('reset',
		partial.call(nextTick, this.onchange.bind(this)), false);
};

ee(Object.defineProperties(Input.prototype, {
	_value: d(null),
	knownAttributes: d({ class: true, id: true, required: true, style: true }),
	changed: d(false),
	required: d(false),
	valid: d(false),
	name: d.gs(function () { return this._name; }, function (name) {
		this._name = name;
		this.control.setAttribute('name', name);
	}),
	onchange: d(function () {
		var value = this.value, changedChanged;
		if (value !== this._value) {
			if (!this.changed) {
				this.changed = true;
				changedChanged = true;
			}
		} else if (this.changed) {
			this.changed = false;
			changedChanged = true;
		}
		this.emit('change', value);
		if (changedChanged) this.emit('change:changed', this.changed);
		if (!this.required || (this.valid === (value != null))) return;
		this.emit('change:valid', this.valid = !this.valid);
	}),
	toDOM: d(function () { return this.dom; }),
	value: d.gs(function () {
		var value = this.control.value.trim();
		return (value === '') ? null : value;
	}, function (value) {
		if (value == null) {
			value = null;
			this.control.value = '';
			this.control.removeAttribute('value');
		} else {
			if (value.__toString) value = value.__toString.__value.call(value);
			else value = String(value);
			this.control.value = value;
			this.control.setAttribute('value', value);
		}
		this._value = value;
		if (this.changed) this.emit('change:changed', this.changed = false);
	}),
	castAttribute: d(function (name, value) {
		castAttribute.call(this.dom, name, value);
	}),
	castKnownAttributes: d(function (attrs) {
		forEach(attrs, function (value, name) {
			if (this.knownAttributes[name] ||
					(startsWith.call(name, 'data-'))) {
				this.castAttribute(name, value);
			}
		}, this);
	})
}));

Object.defineProperty(Db.Base, 'DOMInput', d(Input));
<commit_msg>Fix validity resolution<commit_after>'use strict';

var partial       = require('es5-ext/lib/Function/prototype/partial')
  , d             = require('es5-ext/lib/Object/descriptor')
  , forEach       = require('es5-ext/lib/Object/for-each')
  , startsWith    = require('es5-ext/lib/String/prototype/starts-with')
  , ee            = require('event-emitter/lib/core')
  , castAttribute = require('dom-ext/lib/Element/prototype/cast-attribute')
  , nextTick      = require('next-tick')
  , Db            = require('dbjs')

  , Input;

module.exports = Input = function (document, ns/*, options*/) {
	var options = Object(arguments[2]);
	this.document = document;
	this.ns = ns;
	this.control = this.dom = document.createElement('input');
	if (options.name) this.name = options.name;
	this.castKnownAttributes(options);
	this.dom._dbjsInput = this;
	document.addEventListener('reset',
		partial.call(nextTick, this.onchange.bind(this)), false);
};

ee(Object.defineProperties(Input.prototype, {
	_value: d(null),
	knownAttributes: d({ class: true, id: true, required: true, style: true }),
	changed: d(false),
	required: d(false),
	valid: d(false),
	name: d.gs(function () { return this._name; }, function (name) {
		this._name = name;
		this.control.setAttribute('name', name);
	}),
	onchange: d(function () {
		var value = this.value, changedChanged;
		if (value !== this._value) {
			if (!this.changed) {
				this.changed = true;
				changedChanged = true;
			}
		} else if (this.changed) {
			this.changed = false;
			changedChanged = true;
		}
		this.emit('change', value);
		if (changedChanged) this.emit('change:changed', this.changed);
		if (this.valid === (!this.required || (value != null))) return;
		this.emit('change:valid', this.valid = !this.valid);
	}),
	toDOM: d(function () { return this.dom; }),
	value: d.gs(function () {
		var value = this.control.value.trim();
		return (value === '') ? null : value;
	}, function (value) {
		if (value == null) {
			value = null;
			this.control.value = '';
			this.control.removeAttribute('value');
		} else {
			if (value.__toString) value = value.__toString.__value.call(value);
			else value = String(value);
			this.control.value = value;
			this.control.setAttribute('value', value);
		}
		this._value = value;
		if (this.changed) this.emit('change:changed', this.changed = false);
	}),
	castAttribute: d(function (name, value) {
		castAttribute.call(this.dom, name, value);
	}),
	castKnownAttributes: d(function (attrs) {
		forEach(attrs, function (value, name) {
			if (this.knownAttributes[name] ||
					(startsWith.call(name, 'data-'))) {
				this.castAttribute(name, value);
			}
		}, this);
	})
}));

Object.defineProperty(Db.Base, 'DOMInput', d(Input));
<|endoftext|>


<commit_before>'use strict';

var aFrom        = require('es5-ext/array/from')
  , compact      = require('es5-ext/array/#/compact')
  , isCopy       = require('es5-ext/array/#/is-copy')
  , copy         = require('es5-ext/object/copy')
  , assign       = require('es5-ext/object/assign')
  , isObject     = require('es5-ext/object/is-object')
  , callable     = require('es5-ext/object/valid-callable')
  , toArray      = require('es6-iterator/to-array')
  , d            = require('d/d')
  , memoize      = require('memoizee/lib/regular')
  , memPrimitive = require('memoizee/lib/primitive')
  , makeEl       = require('dom-ext/document/#/make-element')
  , append       = require('dom-ext/element/#/append')
  , clear        = require('dom-ext/element/#/clear')
  , remove       = require('dom-ext/element/#/remove')
  , replaceCont  = require('dom-ext/element/#/replace-content')
  , dispatchEvnt = require('dom-ext/html-element/#/dispatch-event-2')
  , DOMInput     = require('../_controls/input')
  , eventOpts    = require('../_event-options')
  , setup        = require('../')

  , isArray = Array.isArray, map = Array.prototype.map
  , defineProperty = Object.defineProperty
  , defineProperties = Object.defineProperties
  , getName = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'name').get
  , Input, render, renderItem;

require('memoizee/lib/ext/method');

render = function (options) {
	var el = this.make;
	return el('div', { class: 'dbjs-file' },
		this.valueDOM = this.multiple ? el('ul') : el('span'),
		el('label', { class: 'dbjs-file-input' }, options.label,
			this.control = el('input', { type: 'file' })));
};

renderItem = function (file) {
	var el = this.make, data = {};
	data.dom = el(this.multiple ? 'li' : 'span', { 'data-id': file.__id__ });
	append.call(data.dom,
		el('a', { href: file._url, target: '_blank' }, file._name), " ",
		data.control = el('input', { type: 'hidden', name: this.name,
			value: file.__id__ }),
		el('a', { class: 'clear', onclick: this.removeItem.bind(this, data.dom) },
			"x"));
	return data;
};

Input = function (document, type/*, options*/) {
	var options = Object(arguments[2]);
	this.make = makeEl.bind(document);
	this.controls = [];
	if (options.multiple) this.multiple = true;
	((options.render == null) || callable(options.render));
	defineProperty(this, 'renderItem', d((options.renderItem == null) ?
			renderItem : callable(options.renderItem)));
	DOMInput.call(this, document, type, options);
	if (this.multiple) this.control.setAttribute('multiple', 'multiple');
	this.control.setAttribute('accept', toArray(type.accept).join(','));
};

Input.prototype = Object.create(DOMInput.prototype, assign({
	constructor: d(Input),
	multiple: d(false),
	_value: d(null),
	controlAttributes: d(assign(copy(DOMInput.prototype.controlAttributes),
		{ required: true })),
	dbAttributes: d(assign(copy(DOMInput.prototype.dbAttributes),
		{ required: true })),
	_render: d(function (options) {
		this.dom = (options.render || render).call(this, options);
		this.controls.push(this.control);
	}),
	name: d.gs(getName, function (name) {
		this._name = name;
		name = this.name;
		this.controls.forEach(function (input) { input.name = name; });
	}),
	inputValue: d.gs(function () {
		var value;
		if (!this.multiple) {
			if (this.control.files[0]) return this.control.files[0];
			if (!this.valueDOM.firstChild) return null;
			return this.valueDOM.firstChild.getAttribute('data-id');
		}
		value = map.call(this.valueDOM.childNodes, function (node) {
			var id = node.getAttribute('data-id');
			if (!id) {
				throw new TypeError("Missing id (data-id attribute) on file item");
			}
			return id;
		}).concat(aFrom(this.control.files));
		return value.length ? value : null;
	}, function (nu) {
		var old = this.inputValue, changed;
		this._value = nu;
		if (this.multiple) {
			if (nu) {
				if (!old || !isCopy.call(nu, old)) {
					this.control.value = null;
					replaceCont.call(this.valueDOM, nu.map(this._renderItem));
					changed = true;
				}
			} else {
				clear.call(this.valueDOM);
			}
		} else if (nu !== old) {
			this.control.value = null;
			if (nu) {
				replaceCont.call(this.valueDOM, this._renderItem(nu));
				this.dom.classList.add('filled');
			} else {
				clear.call(this.valueDOM);
				this.dom.classList.remove('filled');
			}
			changed = true;
		}
		if (changed) {
			try {
				dispatchEvnt.call(this.control, 'change', eventOpts);
			} catch (ignore) {}
		} else {
			this.onChange();
		}
	}),
	value: d.gs(function () {
		var value = this.inputValue;
		if (value == null) return null;
		if (this.multiple) return value.map(this.type.toInputValue, this.type);
		return this.type.toInputValue(value);
	}, function (value) {
		if (value == null) {
			value = null;
		} else if (this.multiple) {
			value = toArray(value);
			if (value.length) {
				value = compact.call(value.map(this.type.toInputValue, this.type));
			}
			if (!value.length) value = null;
		} else {
			value = this.type.toInputValue(value);
		}

		this.inputValue = value;
	}),
	onChange: d(function () {
		var value, changed, valid, emitChanged, emitValid;
		value = this.inputValue;
		changed = (this.multiple && (this._value != null) && (value != null)) ?
				isCopy.call(value, this._value) : (value !== this._value);
		valid = this.required ? (value != null) : true;

		if (this.changed !== changed) {
			this.changed = changed;
			emitChanged = true;
		}
		if (this.valid !== valid) {
			this.valid = valid;
			emitValid = true;
		}

		this.emit('change', value);
		if (emitChanged) this.emit('change:changed', this.changed);
		if (emitValid) this.emit('change:valid', this.valid);
	}),
	removeItem: d(function (dom) {
		remove.call(dom);
		if (!this.multiple) this.dom.classList.remove('filled');
		dispatchEvnt.call(this.control, 'change', eventOpts);
	})
}, memPrimitive(function (file) {
	var data;
	file = this.type.getById(file);
	data = this.renderItem(file);
	this.controls.push(data.control);
	return data.dom;
}, { method: '_renderItem' })));

module.exports = memoize(function (db) {
	defineProperties(setup(db).File, {
		fromInputValue: d(function (value) {
			if (value == null) return null;
			if (isArray(value) && (value.length === 2)) {
				if (typeof value[0] === 'string') {
					if (isObject(value[1])) return value[1];
				} else if (typeof value[1] === 'string') {
					if (isObject(value[0])) return value[0];
				}
				return value;
			}
			if (isObject(value)) return value;
			value = value.trim();
			if (!value) return null;
			return this.getById(value);
		}),
		DOMInput: d(Input),
		toDOMInput: d(function (document/*, options*/) {
			var options = Object(arguments[1]);
			if (options.multiple || (options.type !== 'checkbox')) {
				return new this.DOMInput(document, this, options);
			}
			return db.Object.toDOMInput(document, options);
		})
	});
});
<commit_msg>Rely on first child element<commit_after>'use strict';

var aFrom        = require('es5-ext/array/from')
  , compact      = require('es5-ext/array/#/compact')
  , isCopy       = require('es5-ext/array/#/is-copy')
  , copy         = require('es5-ext/object/copy')
  , assign       = require('es5-ext/object/assign')
  , isObject     = require('es5-ext/object/is-object')
  , callable     = require('es5-ext/object/valid-callable')
  , toArray      = require('es6-iterator/to-array')
  , d            = require('d/d')
  , memoize      = require('memoizee/lib/regular')
  , memPrimitive = require('memoizee/lib/primitive')
  , makeEl       = require('dom-ext/document/#/make-element')
  , append       = require('dom-ext/element/#/append')
  , clear        = require('dom-ext/element/#/clear')
  , remove       = require('dom-ext/element/#/remove')
  , replaceCont  = require('dom-ext/element/#/replace-content')
  , dispatchEvnt = require('dom-ext/html-element/#/dispatch-event-2')
  , DOMInput     = require('../_controls/input')
  , eventOpts    = require('../_event-options')
  , setup        = require('../')

  , isArray = Array.isArray, map = Array.prototype.map
  , defineProperty = Object.defineProperty
  , defineProperties = Object.defineProperties
  , getName = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'name').get
  , Input, render, renderItem;

require('memoizee/lib/ext/method');

render = function (options) {
	var el = this.make;
	return el('div', { class: 'dbjs-file' },
		this.valueDOM = this.multiple ? el('ul') : el('span'),
		el('label', { class: 'dbjs-file-input' }, options.label,
			this.control = el('input', { type: 'file' })));
};

renderItem = function (file) {
	var el = this.make, data = {};
	data.dom = el(this.multiple ? 'li' : 'span', { 'data-id': file.__id__ });
	append.call(data.dom,
		el('a', { href: file._url, target: '_blank' }, file._name), " ",
		data.control = el('input', { type: 'hidden', name: this.name,
			value: file.__id__ }),
		el('a', { class: 'clear', onclick: this.removeItem.bind(this, data.dom) },
			"x"));
	return data;
};

Input = function (document, type/*, options*/) {
	var options = Object(arguments[2]);
	this.make = makeEl.bind(document);
	this.controls = [];
	if (options.multiple) this.multiple = true;
	((options.render == null) || callable(options.render));
	defineProperty(this, 'renderItem', d((options.renderItem == null) ?
			renderItem : callable(options.renderItem)));
	DOMInput.call(this, document, type, options);
	if (this.multiple) this.control.setAttribute('multiple', 'multiple');
	this.control.setAttribute('accept', toArray(type.accept).join(','));
};

Input.prototype = Object.create(DOMInput.prototype, assign({
	constructor: d(Input),
	multiple: d(false),
	_value: d(null),
	controlAttributes: d(assign(copy(DOMInput.prototype.controlAttributes),
		{ required: true })),
	dbAttributes: d(assign(copy(DOMInput.prototype.dbAttributes),
		{ required: true })),
	_render: d(function (options) {
		this.dom = (options.render || render).call(this, options);
		this.controls.push(this.control);
	}),
	name: d.gs(getName, function (name) {
		this._name = name;
		name = this.name;
		this.controls.forEach(function (input) { input.name = name; });
	}),
	inputValue: d.gs(function () {
		var value;
		if (!this.multiple) {
			if (this.control.files[0]) return this.control.files[0];
			if (!this.valueDOM.firstElementChild) return null;
			return this.valueDOM.firstElementChild.getAttribute('data-id');
		}
		value = map.call(this.valueDOM.childNodes, function (node) {
			var id = node.getAttribute('data-id');
			if (!id) {
				throw new TypeError("Missing id (data-id attribute) on file item");
			}
			return id;
		}).concat(aFrom(this.control.files));
		return value.length ? value : null;
	}, function (nu) {
		var old = this.inputValue, changed;
		this._value = nu;
		if (this.multiple) {
			if (nu) {
				if (!old || !isCopy.call(nu, old)) {
					this.control.value = null;
					replaceCont.call(this.valueDOM, nu.map(this._renderItem));
					changed = true;
				}
			} else {
				clear.call(this.valueDOM);
			}
		} else if (nu !== old) {
			this.control.value = null;
			if (nu) {
				replaceCont.call(this.valueDOM, this._renderItem(nu));
				this.dom.classList.add('filled');
			} else {
				clear.call(this.valueDOM);
				this.dom.classList.remove('filled');
			}
			changed = true;
		}
		if (changed) {
			try {
				dispatchEvnt.call(this.control, 'change', eventOpts);
			} catch (ignore) {}
		} else {
			this.onChange();
		}
	}),
	value: d.gs(function () {
		var value = this.inputValue;
		if (value == null) return null;
		if (this.multiple) return value.map(this.type.toInputValue, this.type);
		return this.type.toInputValue(value);
	}, function (value) {
		if (value == null) {
			value = null;
		} else if (this.multiple) {
			value = toArray(value);
			if (value.length) {
				value = compact.call(value.map(this.type.toInputValue, this.type));
			}
			if (!value.length) value = null;
		} else {
			value = this.type.toInputValue(value);
		}

		this.inputValue = value;
	}),
	onChange: d(function () {
		var value, changed, valid, emitChanged, emitValid;
		value = this.inputValue;
		changed = (this.multiple && (this._value != null) && (value != null)) ?
				isCopy.call(value, this._value) : (value !== this._value);
		valid = this.required ? (value != null) : true;

		if (this.changed !== changed) {
			this.changed = changed;
			emitChanged = true;
		}
		if (this.valid !== valid) {
			this.valid = valid;
			emitValid = true;
		}

		this.emit('change', value);
		if (emitChanged) this.emit('change:changed', this.changed);
		if (emitValid) this.emit('change:valid', this.valid);
	}),
	removeItem: d(function (dom) {
		remove.call(dom);
		if (!this.multiple) this.dom.classList.remove('filled');
		dispatchEvnt.call(this.control, 'change', eventOpts);
	})
}, memPrimitive(function (file) {
	var data;
	file = this.type.getById(file);
	data = this.renderItem(file);
	this.controls.push(data.control);
	return data.dom;
}, { method: '_renderItem' })));

module.exports = memoize(function (db) {
	defineProperties(setup(db).File, {
		fromInputValue: d(function (value) {
			if (value == null) return null;
			if (isArray(value) && (value.length === 2)) {
				if (typeof value[0] === 'string') {
					if (isObject(value[1])) return value[1];
				} else if (typeof value[1] === 'string') {
					if (isObject(value[0])) return value[0];
				}
				return value;
			}
			if (isObject(value)) return value;
			value = value.trim();
			if (!value) return null;
			return this.getById(value);
		}),
		DOMInput: d(Input),
		toDOMInput: d(function (document/*, options*/) {
			var options = Object(arguments[1]);
			if (options.multiple || (options.type !== 'checkbox')) {
				return new this.DOMInput(document, this, options);
			}
			return db.Object.toDOMInput(document, options);
		})
	});
});
<|endoftext|>


<commit_before>const fs = require('fs-extra')
const path = require('path')
const chalk = require('chalk')
const lineEnd = require('os').EOL

module.exports = cwd => {

  const ROOT = '.mu'
  const insert = (string, index, substr) => string.slice(0, index) + substr + string.slice(index)
  const reverted = str => {
    console.log(chalk.green('✓\t' + str))
  }
  const removed = str => {
    console.log(chalk.red('✗\t' + str))
  }

  return {
    undo: {
      deleted: writeFile,
      modified: writeFile,
      renamed: rename,
      added: remove
    }
  }

  function remove(file) {
    const status = fs.statSync(file)
    if (status && status.isFile()) {
      fs.removeSync(file)
      removed(file)
    }
  }

  function rename(oldpath, newPath) {
    fs.renameSync(newPath, oldpath)
  }

  function writeFile(file, filehash, mtime) {
    const fileArray = fs.readJsonSync(path.join(cwd, ROOT, 'disk_mem', 'files', insert(filehash, 2, '/')), 'utf8')
    let linehash, data = ''
    while (linehash = fileArray.pop()) {
      data += fs.readFileSync(path.join(cwd, ROOT, 'disk_mem', 'lines', insert(linehash, 2, '/')), 'utf8') + lineEnd
    }
    fs.outputFileSync(file, data)
    fs.utimesSync(file, +new Date(), mtime)

    reverted(file)
  }
}
<commit_msg>fixes write file bug in frank<commit_after>const fs = require('fs-extra')
const path = require('path')
const chalk = require('chalk')
const lineEnd = require('os').EOL

module.exports = cwd => {

  const ROOT = '.mu'
  const insert = (string, index, substr) => string.slice(0, index) + substr + string.slice(index)
  const reverted = str => {
    console.log(chalk.green('✓\t' + str))
  }
  const removed = str => {
    console.log(chalk.red('✗\t' + str))
  }

  return {
    undo: {
      deleted: writeFile,
      modified: writeFile,
      renamed: rename,
      added: remove
    }
  }

  function remove(file) {
    const status = fs.statSync(file)
    if (status && status.isFile()) {
      fs.removeSync(file)
      removed(file)
    }
  }

  function rename(oldpath, newPath) {
    fs.renameSync(newPath, oldpath)
  }

  function writeFile(file, filehash, mtime) {
    const fileArray = fs.readJsonSync(path.join(cwd, ROOT, 'disk_mem', 'files', insert(filehash, 2, '/')), 'utf8')
    let linehash, data = ''
    let firstLineHash = fileArray.pop()
    while (linehash = fileArray.pop()) {
      data = fs.readFileSync(path.join(cwd, ROOT, 'disk_mem', 'lines', insert(linehash, 2, '/')), 'utf8') + lineEnd + data
    }
    fs.outputFileSync(file, data)
    fs.utimesSync(file, +new Date(), mtime)

    reverted(file)
  }
}
<|endoftext|>


<commit_before>import extend from './extend';
import without from './without';
import _rebind from './rebind';
import _functor from './functor';

export {
    extend,
    without,
    _rebind,
    _functor
}
<commit_msg>Export helpers<commit_after>export { default as extend } from './extend';
export { default as without } from './without';
export { default as _rebind } from './rebind';
export { default as _functor } from './functor';<|endoftext|>


<commit_before>import Vue from 'vue'
import App from './History'
import {storage, message} from 'src/helpers/chrome-api'
import AppConfig from 'src/app-config'

Vue.config.productionTip = false
Vue.config.devtools = false

document.title = chrome.i18n.getMessage('history_title')

storage.sync.get('config')
  .then(({config}) => {
    new Vue({ // eslint-disable-line no-new
      el: '#app',
      render (createElement) {
        return createElement(App, {
          props: {
            config: this.config,
            i18n: key => chrome.i18n.getMessage(key)
          }
        })
      },
      data () {
        return {
          config: config || new AppConfig()
        }
      },
      created () {
        storage.sync.listen('config', changes => {
          let config = changes.config.newValue
          if (config) {
            this.config = config
          }
        })
      }
    })

    message.self.on('PANEL_READY', (data, sender, sendResponse) => {
      // trigger the paste command
      sendResponse({noSearchHistory: true})
    })
  })
<commit_msg>Refactored history<commit_after>import Vue from 'vue'
import App from './History'
import {storage, message} from 'src/helpers/chrome-api'
import AppConfig from 'src/app-config'

Vue.config.productionTip = false
Vue.config.devtools = false

document.title = chrome.i18n.getMessage('history_title')

storage.sync.get('config')
  .then(({config = new AppConfig()}) => {
    const vm = new Vue({
      el: '#app',
      data: {config},
      render (createElement) {
        return createElement(App, {
          props: {
            config: this.config,
            i18n: key => chrome.i18n.getMessage(key)
          }
        })
      }
    })

    storage.sync.listen('config', changes => {
      let config = changes.config.newValue
      if (config) {
        vm.config = config
      }
    })

    message.self.on('PANEL_READY', (data, sender, sendResponse) => {
      // trigger the paste command
      sendResponse({noSearchHistory: true})
    })
  })
<|endoftext|>


<commit_before>(function(root) {

    var hyve = (typeof require == 'function' && !(typeof define == 'function' && define.amd)) ? require('../src/hyve.core.js') : root.hyve

    hyve.feeds.twitter = {
        methods : ['search', 'friends', 'popular'],
        interval : 2000,
        interval_friends : 60000,
        result_type : 'mixed', // mixed, recent, popular
        since_ids : {},
        oauth_consumer_key : '',
        oauth_nonce  : '',
        oauth_signature : '',
        oauth_signature_method : 'HMAC-SHA1',
        oauth_timestamp : '',
        oauth_token : '',
        oauth_version : '1.0',
        feed_urls : {
            search: 'http://search.twitter.com/search.json?q={{query}}&lang=en&include_entities=True{{#&result_type=#result_type}}{{since}}{{#&callback=#callback}}',
            friends: 'https://api.twitter.com/1/statuses/home_timeline.json',
            popular: 'http://search.twitter.com/search.json?q={{query}}&lang=en&rpp=25&include_entities=True{{#&result_type=#result_type}}{{since}}{{#&callback=#callback}}'
        },
        format_url : function(query){
            var since_arg
            if (this.since_ids[query]){
                since_arg = '&since_id='+this.since_ids[query]
            }
            return {
                      query: query
                    , result_type: this.result_type
                    , since: since_arg
                    , key: 'oauth_consumer_key='  + this.oauth_consumer_key
                    , nonce: '&oauth_nonce=' + this.oauth_nonce
                    , signature: '&oauth_signature=' + this.oauth_signature
                    , signature_method: '&oauth_signature_method=' + this.oauth_signature_method
                    , timestamp: '&oauth_timestamp=' + this.oauth_timestamp
                    , token: '&oauth_token=' + this.oauth_token
                    , version: '&oauth_version=' + this.oauth_version
            }
        },
        parsers : {
            search : function(data, query, callback){
                if (data.refresh_url){
                    hyve.feeds.twitter.since_ids[query] = data.refresh_url.replace(/\?since_id=([0-9]+).*/ig, "$1")
                }
                if (!this.items_seen){
                    this.items_seen = {}
                }
                if (data.results){
                    data.results.forEach(function(item){
                        if (!this.items_seen[item.id_str.toString()]){
                            this.items_seen[item.id_str.toString()] = true
                            var links = []
                            if (item.entities.urls) {
                                item.entities.urls.forEach(function(url){
                                    if(url.expanded_url){
                                        links.push(url.expanded_url)
                                    } else {
                                        links.push("http://"+url.url)
                                    }
                                })
                            }
                            var weight = 1
                            var likes = ''
                            if (item.metadata.result_type == 'popular'){
                                likes = item.metadata.recent_retweets
                                weight = likes
                            }

                            hyve.process({
                                'service' : 'twitter',
                                'type' : 'text',
                                'query' : query,
                                'user' : {
                                    'id' : item.from_user_id_str,
                                    'real_name': item.from_user,
                                    'name': item.from_user_name,
                                    'avatar' : item.profile_image_url,
                                    'profile' : "http://twitter.com/"+item.from_user
                                },
                                'likes' : likes,
                                'id' : item.id_str,
                                'date' : item.created_at,
                                'text' : item.text,
                                'links' : links,
                                'source' : 'http://twitter.com/'+
                                           item.from_user+
                                           '/status/'+item.id,
                                'weight' : weight
                            },callback)
                        }
                    },this)
                }
            },

            friends : function(data, query, callback) {
                if (data) {
                    if (!this.items_seen) this.items_seen = {}

                    data.forEach(function(item)  {

                        id = item.id_str

                        var weight = 1
                        if (item.retweet_count) {
                            weight = item.retweet_count
                        }

                        if (!this.items_seen[id]) {
                           this.items_seen[id] = true

                            hyve.process({
                                'service': 'twitter',
                                'type': 'text',
                                'query': query,
                                'user' : {
                                    'id': item.user.id_str,
                                    'name': item.user.name,
                                    'avatar': item.user.profile_image_url,
                                    'profile':  "http://twitter.com/" + item.user.screen_name
                                },
                                'id': id,
                                'date': item.created_at,
                                'text': item.text,
                                'source': "http://twitter.com/" + item.user.screen_name + "/status/" + id,
                                'weight': weight
                            }, callback)
                        }
                    }, this);
                }
            },

            popular: function(data, query, callback) {

                var sorted_items = []

                if (data.results) {
                    data.results.forEach(function(item) {
                        var weight = 1
                        var recent_retweets = item.metadata.recent_retweets
                        if (recent_retweets > 1) {
                            weight = recent_retweets
                        }
                        item.weight = weight
                        sorted_items.push(item)

                        item.links = []
                        if (item.entities.urls) {
                            item.entities.urls.forEach(function(url){
                                if(url.expanded_url){
                                    item.links.push(url.expanded_url)
                                } else {
                                    item.links.push("http://"+url.url)
                                }
                            })
                        }

                    })

                    sorted_items.sort(function(a, b) {
                        return b.weight - a.weight
                    })

                    sorted_items.forEach(function(item) {
                        hyve.process({
                            'service' : 'twitter',
                            'type' : 'text',
                            'query' : query,
                            'user' : {
                                'id' : item.from_user_id_str,
                                'avatar' : item.profile_image_url,
                                'profile' : "http://twitter.com/"+item.from_user
                            },
                            'id' : item.id_str,
                            'date' : item.created_at,
                            'text' : item.text,
                            'links' : item.links,
                            'source' : 'http://twitter.com/'+
                                       item.from_user+
                                       '/status/'+item.id,
                            'weight' : item.weight
                        }, callback)
                    }, this)

                    //popular is called once, clear interval
                    hyve.stop(['twitter'])
                }
            }
        }
    }
})(this)
<commit_msg>fix twitter name/real_name mappings<commit_after>(function(root) {

    var hyve = (typeof require == 'function' && !(typeof define == 'function' && define.amd)) ? require('../src/hyve.core.js') : root.hyve

    hyve.feeds.twitter = {
        methods : ['search', 'friends', 'popular'],
        interval : 2000,
        interval_friends : 60000,
        result_type : 'mixed', // mixed, recent, popular
        since_ids : {},
        oauth_consumer_key : '',
        oauth_nonce  : '',
        oauth_signature : '',
        oauth_signature_method : 'HMAC-SHA1',
        oauth_timestamp : '',
        oauth_token : '',
        oauth_version : '1.0',
        feed_urls : {
            search: 'http://search.twitter.com/search.json?q={{query}}&lang=en&include_entities=True{{#&result_type=#result_type}}{{since}}{{#&callback=#callback}}',
            friends: 'https://api.twitter.com/1/statuses/home_timeline.json',
            popular: 'http://search.twitter.com/search.json?q={{query}}&lang=en&rpp=25&include_entities=True{{#&result_type=#result_type}}{{since}}{{#&callback=#callback}}'
        },
        format_url : function(query){
            var since_arg
            if (this.since_ids[query]){
                since_arg = '&since_id='+this.since_ids[query]
            }
            return {
                      query: query
                    , result_type: this.result_type
                    , since: since_arg
                    , key: 'oauth_consumer_key='  + this.oauth_consumer_key
                    , nonce: '&oauth_nonce=' + this.oauth_nonce
                    , signature: '&oauth_signature=' + this.oauth_signature
                    , signature_method: '&oauth_signature_method=' + this.oauth_signature_method
                    , timestamp: '&oauth_timestamp=' + this.oauth_timestamp
                    , token: '&oauth_token=' + this.oauth_token
                    , version: '&oauth_version=' + this.oauth_version
            }
        },
        parsers : {
            search : function(data, query, callback){
                if (data.refresh_url){
                    hyve.feeds.twitter.since_ids[query] = data.refresh_url.replace(/\?since_id=([0-9]+).*/ig, "$1")
                }
                if (!this.items_seen){
                    this.items_seen = {}
                }
                if (data.results){
                    data.results.forEach(function(item){
                        if (!this.items_seen[item.id_str.toString()]){
                            this.items_seen[item.id_str.toString()] = true
                            var links = []
                            if (item.entities.urls) {
                                item.entities.urls.forEach(function(url){
                                    if(url.expanded_url){
                                        links.push(url.expanded_url)
                                    } else {
                                        links.push("http://"+url.url)
                                    }
                                })
                            }
                            var weight = 1
                            var likes = ''
                            if (item.metadata.result_type == 'popular'){
                                likes = item.metadata.recent_retweets
                                weight = likes
                            }

                            hyve.process({
                                'service' : 'twitter',
                                'type' : 'text',
                                'query' : query,
                                'user' : {
                                    'id' : item.from_user_id_str,
                                    'real_name': item.from_user_name,
                                    'name': item.from_user,
                                    'avatar' : item.profile_image_url,
                                    'profile' : "http://twitter.com/"+item.from_user
                                },
                                'likes' : likes,
                                'id' : item.id_str,
                                'date' : item.created_at,
                                'text' : item.text,
                                'links' : links,
                                'source' : 'http://twitter.com/'+
                                           item.from_user+
                                           '/status/'+item.id,
                                'weight' : weight
                            },callback)
                        }
                    },this)
                }
            },

            friends : function(data, query, callback) {
                if (data) {
                    if (!this.items_seen) this.items_seen = {}

                    data.forEach(function(item)  {

                        id = item.id_str

                        var weight = 1
                        if (item.retweet_count) {
                            weight = item.retweet_count
                        }

                        if (!this.items_seen[id]) {
                           this.items_seen[id] = true

                            console.log('TWITTA',item)

                            hyve.process({
                                'service': 'twitter',
                                'type': 'text',
                                'query': query,
                                'user' : {
                                    'id': item.user.id_str,
                                    'name': item.user.screen_name,
                                    'real_name': item.user.name,
                                    'avatar': item.user.profile_image_url,
                                    'profile':  "http://twitter.com/" + item.user.screen_name
                                },
                                'id': id,
                                'date': item.created_at,
                                'text': item.text,
                                'source': "http://twitter.com/" + item.user.screen_name + "/status/" + id,
                                'weight': weight
                            }, callback)
                        }
                    }, this);
                }
            },

            popular: function(data, query, callback) {

                var sorted_items = []

                if (data.results) {
                    data.results.forEach(function(item) {
                        var weight = 1
                        var recent_retweets = item.metadata.recent_retweets
                        if (recent_retweets > 1) {
                            weight = recent_retweets
                        }
                        item.weight = weight
                        sorted_items.push(item)

                        item.links = []
                        if (item.entities.urls) {
                            item.entities.urls.forEach(function(url){
                                if(url.expanded_url){
                                    item.links.push(url.expanded_url)
                                } else {
                                    item.links.push("http://"+url.url)
                                }
                            })
                        }

                    })

                    sorted_items.sort(function(a, b) {
                        return b.weight - a.weight
                    })

                    sorted_items.forEach(function(item) {
                        hyve.process({
                            'service' : 'twitter',
                            'type' : 'text',
                            'query' : query,
                            'user' : {
                                'id' : item.from_user_id_str,
                                'avatar' : item.profile_image_url,
                                'profile' : "http://twitter.com/"+item.from_user
                            },
                            'id' : item.id_str,
                            'date' : item.created_at,
                            'text' : item.text,
                            'links' : item.links,
                            'source' : 'http://twitter.com/'+
                                       item.from_user+
                                       '/status/'+item.id,
                            'weight' : item.weight
                        }, callback)
                    }, this)

                    //popular is called once, clear interval
                    hyve.stop(['twitter'])
                }
            }
        }
    }
})(this)
<|endoftext|>


<commit_before>import colors from '../settings/colors';

export default {
  root: {
    maxWidth: '250px',
    width: '100%',
  },
  input: {
    appearance: 'none',
    backgroundColor: colors.inputs,
    border: '0',
    borderRadius: '3px',
    boxSizing: 'border-box',
    color: colors.white,
    fontSize: '16px',
    lineHeight: '16px',
    padding: '6.5px',
    width: '100%',
    outline: 'none',
    ':focus': {
      outline: 'none'
    }
  },
  label: {
    boxSizing: 'border-box',
    color: colors.primaryText,
    display: 'block',
    paddingBottom: '8px',
    paddingLeft: '8px',
    textTransform: 'capitalize',
    width: '100%'
  },
  disabled: {
    opacity: '0.38'
  },
  error: {
    display: 'block',
    paddingTop: '6px',
    paddingLeft: '8px',
    color: colors.error
  }
};
<commit_msg>:lipstick: Decreased fontSize<commit_after>import colors from '../settings/colors';

export default {
  root: {
    maxWidth: '250px',
    width: '100%',
  },
  input: {
    appearance: 'none',
    backgroundColor: colors.inputs,
    border: '0',
    borderRadius: '3px',
    boxSizing: 'border-box',
    color: colors.white,
    fontSize: '16px',
    lineHeight: '16px',
    padding: '6.5px',
    width: '100%',
    outline: 'none',
    ':focus': {
      outline: 'none'
    }
  },
  label: {
    boxSizing: 'border-box',
    color: colors.primaryText,
    display: 'block',
    paddingBottom: '8px',
    paddingLeft: '8px',
    textTransform: 'capitalize',
    width: '100%'
  },
  disabled: {
    opacity: '0.38'
  },
  error: {
    display: 'block',
    paddingTop: '6px',
    paddingLeft: '8px',
    color: colors.error,
    fontSize: '14px'
  }
};
<|endoftext|>


<commit_before>module.exports = function(options) {
  var that = this;

  if (!options.root) {
    throw new Error('provide root as array of parts of an relative path e.g.: [__dirname, \'..\', \'..\'] ');
  }

  var path = require('path');
  var os = require('os');
  var root = path.join.apply(this, options.root);

  var rpath = function(relative) {
    return path.resolve(root+'/'+relative);
  };

  if (!options.cli) {
    options.cli = rpath('/bin/cli.'+(os.platform() === 'win32' ? 'bat' : 'sh'));
  }

  this.cucumber = {};

  this.cucumber.extendWith = function(functions) {
    var fn;

    if (typeof(functions) === 'string') {
      fn = require(root+'/'+functions);
    } else {
      fn = functions;
    }

    Object.keys(fn).forEach(function(key) {
      that.cucumber.World.prototype[key] = fn[key];
    });
  };

  this.cucumber.injectWorld = function(World) {
    that.cucumber.World = World;

    var Promise = require('bluebird');

    World.prototype.directory = rpath;

    that.cucumber.extendWith(require('../../tests/js/test-fn-utils.js'));

    World.prototype.debug = require('debug')('cucumber-world');

    World.prototype.cli = function(parameters, execOptions) {
      var that = this;
      var execFile = require('child_process').execFile;

      this.debug('call cli command');
      this.debug(parameters);

      return new Promise(function (resolve, reject) {
        var child = execFile(options.cli, parameters, execOptions, function(error, stdout, stderr) {
          if (error) {
            that.debug(stderr, stdout);
            error += "\nstdout: \n"+stdout;

            reject(error);
          } else {
            resolve(stdout);
          }
        });
      });
    };
  };

  this.cucumber.useStepDefinitions = function(stepNames, scope) {
    stepNames.forEach(function(name) {
      var stepDefinitions = require('../../tests/js/'+name+'-step-definitions.js');

      stepDefinitions.call(scope);
    });
  };
};<commit_msg>make cli in TestSuite enhancable with env parameters<commit_after>module.exports = function(options) {
  var that = this;

  if (!options.root) {
    throw new Error('provide root as array of parts of an relative path e.g.: [__dirname, \'..\', \'..\'] ');
  }

  var path = require('path');
  var os = require('os');
  var root = path.join.apply(this, options.root);

  var rpath = function(relative) {
    return path.resolve(root+'/'+relative);
  };

  if (!options.cli) {
    options.cli = rpath('/bin/cli.'+(os.platform() === 'win32' ? 'bat' : 'sh'));
  }

  this.cucumber = {};

  this.cucumber.extendWith = function(functions) {
    var fn;

    if (typeof(functions) === 'string') {
      fn = require(root+'/'+functions);
    } else {
      fn = functions;
    }

    Object.keys(fn).forEach(function(key) {
      that.cucumber.World.prototype[key] = fn[key];
    });
  };

  this.cucumber.injectWorld = function(World) {
    that.cucumber.World = World;

    var Promise = require('bluebird');

    World.prototype.directory = rpath;

    that.cucumber.extendWith(require('../../tests/js/test-fn-utils.js'));

    World.prototype.debug = require('debug')('cucumber-world');

    World.prototype.setOption = function(name, value) {
      options[name] = value;
    };

    World.prototype.cli = function(parameters, execOptions) {
      var that = this;
      var execFile = require('child_process').execFile;

      this.debug('call cli command');
      this.debug(parameters);

      if (execOptions.extendEnv) {
        var env = {}, e;
        for (e in process.env) {
          env[e] = process.env[e];
        }
        for (e in execOptions.extendEnv) {
          env[e] = execOptions.extendEnv[e];
        }
        execOptions.env = env;
        delete execOptions.extendEnv;
      }

      return new Promise(function (resolve, reject) {
        var child = execFile(options.cli, parameters, execOptions, function(error, stdout, stderr) {
          if (error) {
            that.debug(stderr, stdout);
            error += "\nstdout: \n"+stdout;

            reject(error);
          } else {
            resolve(stdout);
          }
        });
      });
    };

    // options: manager
    World.prototype.dql = function(dql, parameters, options, execOptions) {
      if (!options) options = {};
      if (!options.manager) options.manager = 'default';

      /* globals Buffer */
      var jsonParameters = JSON.stringify(parameters);
      var encodedParameters = new Buffer(jsonParameters).toString('base64');

      return this.cli(['testing:dql', '--manager='+options.manager, '--base64', dql, encodedParameters], execOptions)
        .then(function(stdout) {
          var result = JSON.parse(stdout);

          return result;
        });
    };
  };

  this.cucumber.useStepDefinitions = function(stepNames, scope) {
    stepNames.forEach(function(name) {
      var stepDefinitions = require('../../tests/js/'+name+'-step-definitions.js');

      stepDefinitions.call(scope);
    });
  };
};<|endoftext|>


<commit_before>import Rx from 'rx'
import Logger from '../utils/logger.js'

export default () => {
  let damage = 1
  const attackSpeed = 1 * 1000

  let state = {
    ias: 100,
    exp: 0,
    expEarnedInLevel: 0,
    expToLevelUp: 200,
    chest: {
      gold: 0,
      items: []
    },
    level: {
      current: 1,
      totalXp: 0,
      currentXp: 0,
      xpToLevelUp: 200,
      totalXpToLevelUp: 200
    }
  }

  const expRequired = (level) => Math.pow(level + 1, 2.4) * 200

  const gainExp = (exp) => {
    state.level.totalXp += exp
    if (state.level.totalXpToLevelUp <= state.level.totalXp) {
      levelUp()
      state.level.currentXp = state.level.totalXp - state.level.totalXpToLevelUp
      state.level.xpToLevelUp = expRequired(state.level.current) - state.level.totalXp
    } else {
      state.level.currentXp += exp
    }
  }

  const levelUp = () => {
    state.level.current++
    damage++
    state.totalXpToLevelUp = expRequired(state.level)
    Logger.log(`gz you are level ${state.level}`)
  }

  const hitTillDeath = (target) => {
    return Rx.Observable
      .interval(attackSpeed / state.ias)
      .takeWhile(() => !target.isDead())
  }

  const hit = (target) => {
    Logger.log(`hit monster for ${damage} damage.`)
    target.receiveAttack(damage)
    Logger.log(`monster life's : ${target.currentLife()} hp.`)
  }

  const gainRewards = (rewards) => {
    gainExp(rewards.exp)
    state.chest.gold += rewards.chest.gold
    state.chest.items.concat(rewards.chest.items)
    Logger.log(rewards.chest.items)
    Logger.log(`New gold value ${state.chest.gold}`)
  }

  return { hitTillDeath, gainRewards, state, hit, gainExp }
}
<commit_msg>So buggy much fixes<commit_after>import Rx from 'rx'
import Logger from '../utils/logger.js'

export default () => {
  let damage = 1
  const attackSpeed = 1 * 1000

  let state = {
    ias: 10,
    chest: {
      gold: 0,
      items: []
    },
    level: {
      current: 1,
      totalXp: 0,
      currentXp: 0,
      xpToLevelUp: 100,
      totalXpToLevelUp: 100
    }
  }

  const expRequired = (level) => Math.pow(level, 2) * 100

  const gainExp = (exp) => {
    state.level.totalXp += exp
    if (state.level.totalXpToLevelUp <= state.level.totalXp) {
      state.level.currentXp = Math.abs(state.level.totalXpToLevelUp - state.level.totalXp)
      levelUp()
      state.level.xpToLevelUp = expRequired(state.level.current) - state.level.totalXp
    } else {
      state.level.currentXp += exp
    }
  }

  const levelUp = () => {
    state.level.current++
    damage++
    state.level.totalXpToLevelUp = expRequired(state.level.current)
    Logger.log(`gz you are level ${state.level.current}`)
  }

  const hitTillDeath = (target) => {
    return Rx.Observable
      .interval(attackSpeed / state.ias)
      .takeWhile(() => !target.isDead())
  }

  const hit = (target) => {
    Logger.log(`hit monster for ${damage} damage.`)
    target.receiveAttack(damage)
    Logger.log(`monster life's : ${target.currentLife()} hp.`)
  }

  const gainRewards = (rewards) => {
    gainExp(rewards.exp)
    state.chest.gold += rewards.chest.gold
    state.chest.items.concat(rewards.chest.items)
    Logger.log(rewards.chest.items)
    Logger.log(`New gold value ${state.chest.gold}`)
  }

  return { hitTillDeath, gainRewards, state, hit, gainExp }
}
<|endoftext|>