<commit_before>//////////////////////////////////////////////////////////////////////////////
/**
 * Create a new instance of vectorFeature
 *
 * @class
 * @extends geo.vectorFeature
 * @extends geo.d3.object
 * @returns {geo.d3.vectorFeature}
 */
//////////////////////////////////////////////////////////////////////////////
geo.d3.vectorFeature = function (arg) {
  'use strict';
  if (!(this instanceof geo.d3.vectorFeature)) {
    return new geo.d3.vectorFeature(arg);
  }
  arg = arg || {};
  geo.vectorFeature.call(this, arg);
  geo.d3.object.call(this);

  ////////////////////////////////////////////////////////////////////////////
  /**
   * @private
   */
  ////////////////////////////////////////////////////////////////////////////
  var m_this = this,
      s_init = this._init,
      s_exit = this._exit,
      s_update = this._update,
      m_buildTime = geo.timestamp(),
      m_style = {};

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Generate a unique ID for a marker definition
   * @private
   * @param {object} d Unused datum (for d3 compat)
   * @param {number} i The marker index
   * @param {string} position The marker's vector position (head or tail)
   */
  ////////////////////////////////////////////////////////////////////////////
  function markerID(d, i, position) {
    return m_this._d3id() + '_marker_' + i + '_' + position;
  }

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Add marker styles for vector arrows.
   * @private
   * @param {object[]} data The vector data array
   * @param {function} stroke The stroke accessor
   * @param {function} opacity The opacity accessor
   * @param {function} originStyle The marker style for the vector head
   * @param {function} endStyle The marker style for the vector tail
   */
  ////////////////////////////////////////////////////////////////////////////
  function updateMarkers(data, stroke, opacity, originStyle, endStyle) {

    var markerConfigs = {
      'arrow': {
        attrs: {'class': 'geo-vector-arrow', 'viewBox': '0 0 10 10', 'refX': '1', 'refY': '5', 'markerHeight': '5', 'markerWidth': '5', 'orient': 'auto'},
        path: 'M 0 0 L 10 5 L 0 10 z'
      },
      'point': {
        attrs: {'class': 'geo-vector-point', 'viewBox': '0 0 12 12', 'refX': '6', 'refY': '6', 'markerHeight': '8', 'markerWidth': '8', 'orient': 'auto'},
        path: 'M 6 3 A 3 3 0 1 1 5.99999 3 Z'
      },
      'bar': {
        attrs: {'class': 'geo-vector-bar', 'viewBox': '0 0 10 10', 'refX': '0', 'refY': '5', 'markerHeight': '6', 'markerWidth': '6', 'orient': 'auto'},
        path: 'M 0 0 L 2 0 L 2 10 L 0 10 z'
      },
      'wedge': {
        attrs: {'class': 'geo-vector-wedge', 'viewBox': '0 0 10 10', 'refX': '10', 'refY': '5', 'markerHeight': '5', 'markerWidth': '5', 'orient': 'auto'},
        path: 'M 0 0 L 1 0 L 10 5 L 1 10 L 0 10 L 9 5 L 0 0'
      }
    };

    //this allows for multiple VectorFeatures in a layer
    var markerGroup = m_this.renderer()._definitions()
      .selectAll('g.marker-group#' + m_this._d3id())
      .data(data.length ? [1] : []);

    markerGroup
      .enter()
      .append('g')
      .attr('id', m_this._d3id);

    markerGroup.exit().remove();

    var markers = data.reduce(function (markers, d, i) {
      var head = markerConfigs[endStyle(d, i)];
      var tail = markerConfigs[originStyle(d, i)];
      if (head) {
        markers.push({
          data: d,
          dataIndex: i,
          head: true
        });
      }
      if (tail) {
        markers.push({
          data: d,
          dataIndex: i,
          head: false
        });
      }
      return markers;
    }, []);

    var sel = markerGroup
      .selectAll('marker.geo-vector-marker')
      .data(markers);

    sel.enter()
      .append('marker')
      .attr('class', 'geo-vector-marker')
      .append('path');

    var renderer = m_this.renderer();

    sel
      .each(function (d) {
        var marker = d3.select(this);
        var markerData = d.head ? markerConfigs[endStyle(d.data, d.dataIndex)] : markerConfigs[originStyle(d.data, d.dataIndex)];
        Object.keys(markerData.attrs).map(function (attrName) {
          marker.attr(attrName, markerData.attrs[attrName]);
        });
      })
      .attr('id', function (d) {
        return markerID(d.data, d.dataIndex, d.head ? 'head' : 'tail');
      })
      .style('stroke', function (d) {
        return renderer._convertColor(stroke)(d.data, d.dataIndex);
      })
      .style('fill', function (d) {
        return renderer._convertColor(stroke)(d.data, d.dataIndex);
      })
      .style('opacity', function (d) {
        return opacity(d.data, d.dataIndex);
      })
      .select('path')
      .attr('d', function (d) {
        return d.head ? markerConfigs[endStyle(d.data, d.dataIndex)].path : markerConfigs[originStyle(d.data, d.dataIndex)].path;
      });

    sel.exit().remove();
  }

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Initialize
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._init = function (arg) {
    s_init.call(m_this, arg);
    return m_this;
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Build
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._build = function () {
    var data = m_this.data(),
        s_style = m_this.style.get(),
        m_renderer = m_this.renderer(),
        orig_func = m_this.origin(),
        size_func = m_this.delta(),
        cache = [],
        scale = m_this.style('scale'),
        max = Number.NEGATIVE_INFINITY;

    // call super-method
    s_update.call(m_this);

    // default to empty data array
    if (!data) { data = []; }

    // cache the georeferencing
    cache = data.map(function (d, i) {
      var origin = m_this.featureGcsToDisplay(orig_func(d, i)),
          delta = size_func(d, i);
      max = Math.max(max, delta.x * delta.x + delta.y * delta.y);
      return {
        x1: origin.x,
        y1: origin.y,
        dx: delta.x,
        dy: -delta.y
      };
    });

    max = Math.sqrt(max);
    if (!scale) {
      scale = 75 / max;
    }

    function getScale() {
      return scale / m_renderer.scaleFactor();
    }

    // fill in d3 renderer style object defaults
    m_style.id = m_this._d3id();
    m_style.data = data;
    m_style.append = 'line';
    m_style.attributes = {
      x1: function (d, i) {
        return cache[i].x1;
      },
      y1: function (d, i) {
        return cache[i].y1;
      },
      x2: function (d, i) {
        return cache[i].x1 + getScale() * cache[i].dx;
      },
      y2: function (d, i) {
        return cache[i].y1 + getScale() * cache[i].dy;
      },
      'marker-start': function (d, i) {
        return 'url(#' + markerID(d, i, 'tail') + ')';
      },
      'marker-end': function (d, i) {
        return 'url(#' + markerID(d, i, 'head') + ')';
      }
    };
    m_style.style = {
      stroke: function () { return true; },
      strokeColor: s_style.strokeColor,
      strokeWidth: s_style.strokeWidth,
      strokeOpacity: s_style.strokeOpacity,
      originStyle: s_style.originStyle,
      endStyle: s_style.endStyle
    };
    m_style.classes = ['d3VectorFeature'];

    // Add markers to the defition list
    updateMarkers(data, s_style.strokeColor, s_style.strokeOpacity, s_style.originStyle, s_style.endStyle);

    // pass to renderer to draw
    m_this.renderer()._drawFeatures(m_style);

    // update time stamps
    m_buildTime.modified();
    m_this.updateTime().modified();
    return m_this;
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Update
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._update = function () {
    s_update.call(m_this);

    if (m_this.getMTime() >= m_buildTime.getMTime()) {
      m_this._build();
    } else {
      updateMarkers(
        m_style.data,
        m_style.style.strokeColor,
        m_style.style.strokeOpacity,
        m_style.style.originStyle,
        m_style.style.endStyle
      );
    }

    return m_this;
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Exit
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._exit = function () {
    s_exit.call(m_this);
    m_style = {};
    updateMarkers([], null, null, null, null);
  };

  this._init(arg);
  return this;
};

inherit(geo.d3.vectorFeature, geo.vectorFeature);

// Now register it
geo.registerFeature('d3', 'vector', geo.d3.vectorFeature);
<commit_msg>ensure class is added to marker group<commit_after>//////////////////////////////////////////////////////////////////////////////
/**
 * Create a new instance of vectorFeature
 *
 * @class
 * @extends geo.vectorFeature
 * @extends geo.d3.object
 * @returns {geo.d3.vectorFeature}
 */
//////////////////////////////////////////////////////////////////////////////
geo.d3.vectorFeature = function (arg) {
  'use strict';
  if (!(this instanceof geo.d3.vectorFeature)) {
    return new geo.d3.vectorFeature(arg);
  }
  arg = arg || {};
  geo.vectorFeature.call(this, arg);
  geo.d3.object.call(this);

  ////////////////////////////////////////////////////////////////////////////
  /**
   * @private
   */
  ////////////////////////////////////////////////////////////////////////////
  var m_this = this,
      s_init = this._init,
      s_exit = this._exit,
      s_update = this._update,
      m_buildTime = geo.timestamp(),
      m_style = {};

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Generate a unique ID for a marker definition
   * @private
   * @param {object} d Unused datum (for d3 compat)
   * @param {number} i The marker index
   * @param {string} position The marker's vector position (head or tail)
   */
  ////////////////////////////////////////////////////////////////////////////
  function markerID(d, i, position) {
    return m_this._d3id() + '_marker_' + i + '_' + position;
  }

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Add marker styles for vector arrows.
   * @private
   * @param {object[]} data The vector data array
   * @param {function} stroke The stroke accessor
   * @param {function} opacity The opacity accessor
   * @param {function} originStyle The marker style for the vector head
   * @param {function} endStyle The marker style for the vector tail
   */
  ////////////////////////////////////////////////////////////////////////////
  function updateMarkers(data, stroke, opacity, originStyle, endStyle) {

    var markerConfigs = {
      'arrow': {
        attrs: {'class': 'geo-vector-arrow', 'viewBox': '0 0 10 10', 'refX': '1', 'refY': '5', 'markerHeight': '5', 'markerWidth': '5', 'orient': 'auto'},
        path: 'M 0 0 L 10 5 L 0 10 z'
      },
      'point': {
        attrs: {'class': 'geo-vector-point', 'viewBox': '0 0 12 12', 'refX': '6', 'refY': '6', 'markerHeight': '8', 'markerWidth': '8', 'orient': 'auto'},
        path: 'M 6 3 A 3 3 0 1 1 5.99999 3 Z'
      },
      'bar': {
        attrs: {'class': 'geo-vector-bar', 'viewBox': '0 0 10 10', 'refX': '0', 'refY': '5', 'markerHeight': '6', 'markerWidth': '6', 'orient': 'auto'},
        path: 'M 0 0 L 2 0 L 2 10 L 0 10 z'
      },
      'wedge': {
        attrs: {'class': 'geo-vector-wedge', 'viewBox': '0 0 10 10', 'refX': '10', 'refY': '5', 'markerHeight': '5', 'markerWidth': '5', 'orient': 'auto'},
        path: 'M 0 0 L 1 0 L 10 5 L 1 10 L 0 10 L 9 5 L 0 0'
      }
    };

    //this allows for multiple VectorFeatures in a layer
    var markerGroup = m_this.renderer()._definitions()
      .selectAll('g.marker-group#' + m_this._d3id())
      .data(data.length ? [1] : []);

    markerGroup
      .enter()
      .append('g')
      .attr('id', m_this._d3id)
      .attr('class', 'marker-group');

    markerGroup.exit().remove();

    var markers = data.reduce(function (markers, d, i) {
      var head = markerConfigs[endStyle(d, i)];
      var tail = markerConfigs[originStyle(d, i)];
      if (head) {
        markers.push({
          data: d,
          dataIndex: i,
          head: true
        });
      }
      if (tail) {
        markers.push({
          data: d,
          dataIndex: i,
          head: false
        });
      }
      return markers;
    }, []);

    var sel = markerGroup
      .selectAll('marker.geo-vector-marker')
      .data(markers);

    sel.enter()
      .append('marker')
      .attr('class', 'geo-vector-marker')
      .append('path');

    var renderer = m_this.renderer();

    sel
      .each(function (d) {
        var marker = d3.select(this);
        var markerData = d.head ? markerConfigs[endStyle(d.data, d.dataIndex)] : markerConfigs[originStyle(d.data, d.dataIndex)];
        Object.keys(markerData.attrs).map(function (attrName) {
          marker.attr(attrName, markerData.attrs[attrName]);
        });
      })
      .attr('id', function (d) {
        return markerID(d.data, d.dataIndex, d.head ? 'head' : 'tail');
      })
      .style('stroke', function (d) {
        return renderer._convertColor(stroke)(d.data, d.dataIndex);
      })
      .style('fill', function (d) {
        return renderer._convertColor(stroke)(d.data, d.dataIndex);
      })
      .style('opacity', function (d) {
        return opacity(d.data, d.dataIndex);
      })
      .select('path')
      .attr('d', function (d) {
        return d.head ? markerConfigs[endStyle(d.data, d.dataIndex)].path : markerConfigs[originStyle(d.data, d.dataIndex)].path;
      });

    sel.exit().remove();
  }

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Initialize
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._init = function (arg) {
    s_init.call(m_this, arg);
    return m_this;
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Build
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._build = function () {
    var data = m_this.data(),
        s_style = m_this.style.get(),
        m_renderer = m_this.renderer(),
        orig_func = m_this.origin(),
        size_func = m_this.delta(),
        cache = [],
        scale = m_this.style('scale'),
        max = Number.NEGATIVE_INFINITY;

    // call super-method
    s_update.call(m_this);

    // default to empty data array
    if (!data) { data = []; }

    // cache the georeferencing
    cache = data.map(function (d, i) {
      var origin = m_this.featureGcsToDisplay(orig_func(d, i)),
          delta = size_func(d, i);
      max = Math.max(max, delta.x * delta.x + delta.y * delta.y);
      return {
        x1: origin.x,
        y1: origin.y,
        dx: delta.x,
        dy: -delta.y
      };
    });

    max = Math.sqrt(max);
    if (!scale) {
      scale = 75 / max;
    }

    function getScale() {
      return scale / m_renderer.scaleFactor();
    }

    // fill in d3 renderer style object defaults
    m_style.id = m_this._d3id();
    m_style.data = data;
    m_style.append = 'line';
    m_style.attributes = {
      x1: function (d, i) {
        return cache[i].x1;
      },
      y1: function (d, i) {
        return cache[i].y1;
      },
      x2: function (d, i) {
        return cache[i].x1 + getScale() * cache[i].dx;
      },
      y2: function (d, i) {
        return cache[i].y1 + getScale() * cache[i].dy;
      },
      'marker-start': function (d, i) {
        return 'url(#' + markerID(d, i, 'tail') + ')';
      },
      'marker-end': function (d, i) {
        return 'url(#' + markerID(d, i, 'head') + ')';
      }
    };
    m_style.style = {
      stroke: function () { return true; },
      strokeColor: s_style.strokeColor,
      strokeWidth: s_style.strokeWidth,
      strokeOpacity: s_style.strokeOpacity,
      originStyle: s_style.originStyle,
      endStyle: s_style.endStyle
    };
    m_style.classes = ['d3VectorFeature'];

    // Add markers to the defition list
    updateMarkers(data, s_style.strokeColor, s_style.strokeOpacity, s_style.originStyle, s_style.endStyle);

    // pass to renderer to draw
    m_this.renderer()._drawFeatures(m_style);

    // update time stamps
    m_buildTime.modified();
    m_this.updateTime().modified();
    return m_this;
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Update
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._update = function () {
    s_update.call(m_this);

    if (m_this.getMTime() >= m_buildTime.getMTime()) {
      m_this._build();
    } else {
      updateMarkers(
        m_style.data,
        m_style.style.strokeColor,
        m_style.style.strokeOpacity,
        m_style.style.originStyle,
        m_style.style.endStyle
      );
    }

    return m_this;
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Exit
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._exit = function () {
    s_exit.call(m_this);
    m_style = {};
    updateMarkers([], null, null, null, null);
  };

  this._init(arg);
  return this;
};

inherit(geo.d3.vectorFeature, geo.vectorFeature);

// Now register it
geo.registerFeature('d3', 'vector', geo.d3.vectorFeature);
<|endoftext|>


<commit_before>jQuery(function( $ ){
    // Mobile Nav
    $('#mobile-nav .icon-menu').click( function(){

	    $('.genesis-nav-menu .menu-item').slideToggle();

    } );

});

;(function($) {

         // DOM Ready
        $(function() {

            // Binding a click event
            // From jQuery v.1.7.0 use .on() instead of .bind()
            $('#popup_button').bind('click', function(e) {

                // Prevents the default action to be triggered.
                e.preventDefault();

                // Triggering bPopup when click event is fired
                $('#subscribe_popup').bPopup({
                    easing: 'easeOutBack', //uses jQuery easing plugin
                    speed: 450,
                    transition: 'slideDown',
                    transitionClose: 'slideUp'
                });

            });

/*            $('.close').bind('click', bPopup().close();); */
        });

})(jQuery);

<commit_msg>Take 4.<commit_after>jQuery(function( $ ){
    // Mobile Nav
    $('#mobile-nav .icon-menu').click( function(){

	    $('.genesis-nav-menu .menu-item').slideToggle();

    } );

});

;(function($) {

         // DOM Ready
        $(function() {

            // Binding a click event
            // From jQuery v.1.7.0 use .on() instead of .bind()
            $('#popup_button').bind('click', function(e) {

                // Prevents the default action to be triggered.
                e.preventDefault();

                // Triggering bPopup when click event is fired
                $('#subscribe_popup').bPopup({
                    speed: 450,
                    transition: 'slideDown',
                    transitionClose: 'slideUp'
                });

            });

/*            $('.close').bind('click', bPopup().close();); */
        });

})(jQuery);

<|endoftext|>


<commit_before>var pivotal  = require("../libs/pivotal");
var _        = require('lodash');
var inspect  = require('eyes').inspector({ stream: null });

module.exports = {
  projects: function(req, res, next){
    var token = req.user ? req.user.token : null;

    if(!token){
      res.send({error: 'Not logged in'});
      return false;
    }

    pivotal.getProjects(token, function(error, data){
      if(error){res.send(error);}

      var projects = data.projects ? data.projects.project : [];

      var result = _.map(projects, function(project){
        return {
          name:   typeof project.name   === 'object' ? project.name.pop()   : project.name,
          id:     typeof project.id     === 'object' ? project.id.pop()     : project.id,
          public: typeof project.public === 'object' ? project.public.pop() : project.public,
        };
      });

      res.send(result);

    });

  }
};
<commit_msg>Build get single project api<commit_after>var pivotal  = require("../libs/pivotal");
var _        = require('lodash');
var inspect  = require('eyes').inspector({ stream: null });

module.exports = {
  projects: function(req, res, next){
    var token = req.user ? req.user.token : null;

    if(!token){
      res.send({error: 'Not logged in'});
      return false;
    }

    pivotal.getProjects({token: token}, function(error, data){
      if(error){res.send(error);}

      var projects = data.projects ? data.projects.project : [];

      var result = _.map(projects, function(project){
        return {
          name:   typeof project.name   === 'object' ? project.name.pop()   : project.name,
          id:     typeof project.id     === 'object' ? project.id.pop()     : project.id,
          public: typeof project.public === 'object' ? project.public.pop() : project.public,
        };
      });

      res.send(result);

    });
  },

  project: function(req, res, next){
    var token = req.user ? req.user.token : null;
    var id    = req.params.id;

    if(!token){
      res.send({error: 'Not logged in'});
      return false;
    }

    pivotal.getProjects({token: token, id: id}, function(error, data){
      if(error){res.send(error);}

      var project = _.map(data, function(field){
        return {
          name:   typeof field.name   === 'object' ? field.name.pop()   : field.name,
          id:     typeof field.id     === 'object' ? field.id.pop()     : field.id,
          public: typeof field.public === 'object' ? field.public.pop() : field.public
        };
      });

      res.send(project);

    });
  }
};
<|endoftext|>


<commit_before>const TJBot = require('tjbot');
const led = require('./lib/led.js');

console.log("Default configuration:" )
console.log(TJBot.prototype.defaultConfiguration);
console.log("Default speak config:")
console.log(TJBot.prototype.languages.speak);
console.log("Default listen config:")
console.log(TJBot.prototype.languages.listen)

console.log("init tjbot");
var hardware = ['led', 'microphone', 'servo','speaker'];
var configuration = require('./config.js');
var credentials = require('./credentials.js');
var tj = new TJBot(hardware, configuration, credentials);

function testLed(){
  console.log("test leds");
  console.log("red");
  led.setLED(1,0,0);
  tj.sleep(500);
  console.log("green");
  led.setLED(0,1,0);
  tj.sleep(500);
  console.log("blue");
  led.setLED(0,0,1);
  tj.sleep(500);
}

function testServo(){
  console.log("test servo arm");
  tj.wave();
}

function testSTT(){
  console.log("test speech to text");
  tj.speak("1 2 3 4 5 6");
}

function test(){
  testLed();
  testServo();
  testSTT();
}

test();
<commit_msg>update tjbot.js<commit_after>const TJBot = require('tjbot');
const led = require('./lib/led.js');

console.log("Default configuration:" )
console.log(TJBot.prototype.defaultConfiguration);
console.log("Default speak config:")
console.log(TJBot.prototype.languages.speak);
console.log("Default listen config:")
console.log(TJBot.prototype.languages.listen)

console.log("init tjbot");
var hardware = [ 'microphone','speaker', 'servo'];

var configuration = require('./config.js');
var credentials = require('./credentials.js');
console.log("configuration:");
console.log(configuration);
var tj = new TJBot(hardware, configuration, credentials);

function testLed(){
  console.log("test leds");
  console.log("red");
  led.setLED(1,0,0);
  tj.sleep(500);
  console.log("green");
  led.setLED(0,1,0);
  tj.sleep(500);
  console.log("blue");
  led.setLED(0,0,1);
  tj.sleep(500);
}

function testServo(){
  console.log("test servo arm");
  tj.wave();
}

function testTTS(){
  console.log("test Text To Speech");
  tj.speak("testando 1 2 3");
}

function test(){
  testLed();
  testServo();
  testTTS();
}

test();
<|endoftext|>


<commit_before>
function active_on(event, element){
        var parent = $($(element).parents('.select-search').first());
        var target = parent.find('.select-search-input');
        $(target).show(700);
        $(element).removeClass('search_disabled');
        $(element).addClass('search_active');
};

function disabled_on(event, element){
        var parent = $($(element).parents('.select-search').first());
        var target = parent.find('.select-search-input');
        target.hide();
        $(element).removeClass('search_active');
        $(element).addClass('search_disabled');

};

function onclick(event){
    if ($(this).hasClass( "search_active" )){
      disabled_on(event, this)
    }else{
       active_on(event, this)
    }

};

function init_select_search(select){

  $($(select).find('.select-search-input').first()).hide();
  $($(select).find('span.select-search-call').first()).on('click',onclick);

  $(select+' button').on('click',function(event){
        var button = $(this);
        var select_parent = $(button.parents('.select-search-input').first());
        var parent = $(button.parents('form').first());
        var target = parent.find('#'+button.data('target'));
        var ismultiple = $(target).attr('multiple') == 'multiple';
        var dict_post = {};
        var text = $($(button.parents('.input-group').first()).children().filter('input[type|="text"]')).val();
        dict_post['text'] = text;
        var url = button.data('url');
        $(button).addClass('disabled');
        $.get(url, dict_post, function(data) {
            if (data && data.constructor == Object ){
                //$(target).empty();
                for(var d in data){
                   if ($(target).find('option[value=\"'+d+'\"]').length == 0 && !(ismultiple && d==""))
                   {
                       $(target).append('<option class="newselection" value="'+d+'">'+data[d]+'</option>')
                   }
                }
            };
             $(button).removeClass('disabled');
             //disabled_on(event, select_parent);
             $(target).select2("open")
         });

     });
}

$(document).ready(function(){

});

<commit_msg>Fix search behavior<commit_after>
function active_on(event, element){
        var parent = $($(element).parents('.select-search').first());
        var target = parent.find('.select-search-input');
        $(target).show(700);
        $(element).removeClass('search_disabled');
        $(element).addClass('search_active');
};

function disabled_on(event, element){
        var parent = $($(element).parents('.select-search').first());
        var target = parent.find('.select-search-input');
        target.hide();
        $(element).removeClass('search_active');
        $(element).addClass('search_disabled');

};

function onclick(event){
    if ($(this).hasClass( "search_active" )){
      disabled_on(event, this)
    }else{
       active_on(event, this)
    }

};

function init_select_search(select){

  $($(select).find('.select-search-input').first()).hide();
  $($(select).find('span.select-search-call').first()).on('click',onclick);

  $(select+' button').on('click',function(event){
        var button = $(this);
        var select_parent = $(button.parents('.select-search-input').first());
        var parent = $(button.parents('form').first());
        var target = parent.find('#'+button.data('target'));
        var ismultiple = $(target).attr('multiple') == 'multiple';
        var dict_post = {};
        var text = $($(button.parents('.input-group').first()).children().filter('input[type|="text"]')).val();
        dict_post['text_to_search'] = text;
        var url = button.data('url');
        $(button).addClass('disabled');
        $.get(url, dict_post, function(data) {
            if (data && data.constructor == Object ){
                //$(target).empty();
                for(var d in data){
                   if ($(target).find('option[value=\"'+d+'\"]').length == 0 && !(ismultiple && d==""))
                   {
                       $(target).append('<option class="newselection" value="'+d+'">'+data[d]+'</option>')
                   }
                }
            };
             $(button).removeClass('disabled');
             //disabled_on(event, select_parent);
             $(target).select2("open")
         });

     });
}

$(document).ready(function(){

});

<|endoftext|>


<commit_before>import * as utils from 'base/utils';
import Component from 'base/component';

import {close as iconClose} from 'base/iconset';

var hidden = true;
var showNotes = false;
var pin = false;
var left = 0;
var top = 0;
var hookName = null;
var newHookName = null;

var DataNotes = Component.extend({

  init: function(config, context) {
    var _this = this;

    this.name = 'gapminder-datanotes';

    this.model_expects = [{
      name: "marker",
      type: "model"
    },{
      name: "language",
      type: "language"
    }];

    this.context = context;

    this.model_binds = {
      "change:language.strings": function(evt) {
        _this.ready();
      }
    }

    //contructor is the same as any component
    this._super(config, context);

    this.ui = utils.extend({
      //...add properties here
    }, this.ui);

    this.close = this.close.bind(this);
  },

  ready: function() {
    this.translator = this.model.language.getTFunction();
    //this.setValues();
  },

  readyOnce: function() {
    var _this = this;
    this.element = d3.select(this.placeholder);

    this.element.selectAll("div").remove();

    var container = this.element;

    container.append("div")
      .html(iconClose)
      .on("click", function() {
        d3.event.stopPropagation();
        _this.close();
      })
      .select("svg")
      .attr("width", "0px")
      .attr("height", "0px")
      .attr("class", "vzb-data-notes-close")
      .classed('vzb-hidden', true);

    container.append("div")
      .attr("class", "vzb-data-notes-body vzb-dialog-scrollable")

    container.append("div")
      .attr("class", "vzb-data-notes-link")

  },

  resize: function() {
    this.close();
  },

  close: function() {
    if(!hidden) {
      this.pin(false).hide();
    }
  },

  setHook: function(_hookName) {
    if(!this.readyOnce) return this;
    if(pin) {
      newHookName = _hookName;
      return this;
    }
    if(hookName) this.model.marker[hookName].off('change:which', this.close);
    hookName = newHookName = _hookName;
    this.model.marker[hookName].on('change:which', this.close);

    this.setValues();

    return this;
  },

  setValues: function() {
    if(!hookName) return;
    var hook = this.model.marker[hookName];
    var description = this.translator('description/' + hook.which);
    var showDescription = description != ('description/' + hook.which);
    if(showDescription) this.element.select('.vzb-data-notes-body').text(description);
    this.element.select('.vzb-data-notes-body').classed('vzb-hidden', !showDescription);

    var sourceLink = hook.getMetadata().sourceLink;
    this.element.select('.vzb-data-notes-link').classed('vzb-hidden', !sourceLink);

    if(sourceLink) {
      var _source = this.translator('hints/source');
      var sourceName = this.translator('sourceName/' + hook.which);
      var showSourceName = sourceName != ('sourceName/' + hook.which);
      this.element.select('.vzb-data-notes-link').html('' + (showSourceName ? (_source + ':') : '') +
        '' + (showSourceName ? sourceName : _source) + '');
    }
    showNotes = sourceLink != null || showDescription;
  },

  setPos: function(_left, _top, force) {
    left = _left;
    top = _top;
    if(pin && !force) return this;
    var parentHeight = this.parent.element.offsetHeight;
    var width = this.element.node().offsetWidth;
    var height = this.element.node().offsetHeight;
    var leftMove;
    var topMove;
    var leftPos = left - width;
    var topPos = top;
    if(leftPos < 10) {
      leftPos = 10;
      leftMove = true;
    }
    if((topPos + height + 10) > parentHeight) {
      topPos = parentHeight - height - 10;
      topMove = true;
    }

    if(leftMove && topMove) {
      topPos = top - height - 30;
    }

    this.element.style({'top': topPos + 'px', 'left': leftPos + 'px'});

    return this;
  },

  pin: function(arg) {
    if(hidden) return this;
    pin = !pin;
    if(arg != null) pin = arg;
    this.element.select('.vzb-data-notes-close').classed('vzb-hidden', !pin);
    this.element.classed('vzb-data-notes-pinned', pin);
    if(hookName != newHookName) this.setHook(newHookName);
    this.element.select('.vzb-data-notes-body').node().scrollTop = 0;
    if(!showNotes) {
      return this.hide();
    } else {
      return this.setPos(left, top, true);
    }
  },

  toggle: function(arg) {
    if(pin || !hookName) return this;
    if(arg == null) arg = !hidden;
    hidden = arg;
    this.element.classed("vzb-hidden", hidden || !showNotes);
    return this;
  },

  show: function() {
    return this.toggle(false);
  },

  hide: function() {
    return this.toggle(true);
  }

});

export default DataNotes;<commit_msg>Datanotes typo<commit_after>import * as utils from 'base/utils';
import Component from 'base/component';

import {close as iconClose} from 'base/iconset';

var hidden = true;
var showNotes = false;
var pin = false;
var left = 0;
var top = 0;
var hookName = null;
var newHookName = null;

var DataNotes = Component.extend({

  init: function(config, context) {
    var _this = this;

    this.name = 'gapminder-datanotes';

    this.model_expects = [{
      name: "marker",
      type: "model"
    },{
      name: "language",
      type: "language"
    }];

    this.context = context;

    this.model_binds = {
      "change:language.strings": function(evt) {
        _this.ready();
      }
    }

    //contructor is the same as any component
    this._super(config, context);

    this.ui = utils.extend({
      //...add properties here
    }, this.ui);

    this.close = this.close.bind(this);
  },

  ready: function() {
    this.translator = this.model.language.getTFunction();
    //this.setValues();
  },

  readyOnce: function() {
    var _this = this;
    this.element = d3.select(this.placeholder);

    this.element.selectAll("div").remove();

    var container = this.element;

    container.append("div")
      .html(iconClose)
      .on("click", function() {
        d3.event.stopPropagation();
        _this.close();
      })
      .select("svg")
      .attr("width", "0px")
      .attr("height", "0px")
      .attr("class", "vzb-data-notes-close")
      .classed('vzb-hidden', true);

    container.append("div")
      .attr("class", "vzb-data-notes-body vzb-dialog-scrollable")

    container.append("div")
      .attr("class", "vzb-data-notes-link")

  },

  resize: function() {
    this.close();
  },

  close: function() {
    if(!hidden) {
      this.pin(false).hide();
    }
  },

  setHook: function(_hookName) {
    if(!this._readyOnce) return this;
    if(pin) {
      newHookName = _hookName;
      return this;
    }
    if(hookName) this.model.marker[hookName].off('change:which', this.close);
    hookName = newHookName = _hookName;
    this.model.marker[hookName].on('change:which', this.close);

    this.setValues();

    return this;
  },

  setValues: function() {
    if(!hookName) return;
    var hook = this.model.marker[hookName];
    var description = this.translator('description/' + hook.which);
    var showDescription = description != ('description/' + hook.which);
    if(showDescription) this.element.select('.vzb-data-notes-body').text(description);
    this.element.select('.vzb-data-notes-body').classed('vzb-hidden', !showDescription);

    var sourceLink = hook.getMetadata().sourceLink;
    this.element.select('.vzb-data-notes-link').classed('vzb-hidden', !sourceLink);

    if(sourceLink) {
      var _source = this.translator('hints/source');
      var sourceName = this.translator('sourceName/' + hook.which);
      var showSourceName = sourceName != ('sourceName/' + hook.which);
      this.element.select('.vzb-data-notes-link').html('' + (showSourceName ? (_source + ':') : '') +
        '' + (showSourceName ? sourceName : _source) + '');
    }
    showNotes = sourceLink != null || showDescription;
  },

  setPos: function(_left, _top, force) {
    left = _left;
    top = _top;
    if(pin && !force) return this;
    var parentHeight = this.parent.element.offsetHeight;
    var width = this.element.node().offsetWidth;
    var height = this.element.node().offsetHeight;
    var leftMove;
    var topMove;
    var leftPos = left - width;
    var topPos = top;
    if(leftPos < 10) {
      leftPos = 10;
      leftMove = true;
    }
    if((topPos + height + 10) > parentHeight) {
      topPos = parentHeight - height - 10;
      topMove = true;
    }

    if(leftMove && topMove) {
      topPos = top - height - 30;
    }

    this.element.style({'top': topPos + 'px', 'left': leftPos + 'px'});

    return this;
  },

  pin: function(arg) {
    if(hidden) return this;
    pin = !pin;
    if(arg != null) pin = arg;
    this.element.select('.vzb-data-notes-close').classed('vzb-hidden', !pin);
    this.element.classed('vzb-data-notes-pinned', pin);
    if(hookName != newHookName) this.setHook(newHookName);
    this.element.select('.vzb-data-notes-body').node().scrollTop = 0;
    if(!showNotes) {
      return this.hide();
    } else {
      return this.setPos(left, top, true);
    }
  },

  toggle: function(arg) {
    if(pin || !hookName) return this;
    if(arg == null) arg = !hidden;
    hidden = arg;
    this.element.classed("vzb-hidden", hidden || !showNotes);
    return this;
  },

  show: function() {
    return this.toggle(false);
  },

  hide: function() {
    return this.toggle(true);
  }

});

export default DataNotes;<|endoftext|>


<commit_before>var normal = "SOCKS 127.0.0.1:7711";
var blackhole = "SOCKS 127.0.0.1:7711";

var fullParse = 0;	// Transmet tout.
var pathParse = 1;	// Transmet le nom du serveur et le chemin mais
			// pas les arguments CGI ni les ancres.
var parseURL = pathParse;

// Variable de compteur pour initaliser les tableaux
var i= 0;

// l'URl est acceptée si le nom du serveur se termine par l'un des domaines suivants
// ATTENTION : NE PLACEZ PAS D'EXPRESSION RÉGULIÈRE À LA FIN DES VALEURS
var GoodDomains = new Array();
i=0;

GoodDomains[i++] = "dareyourmind.net";

// Ajoutez ici tout bon réseau, selon le format :
// IP, virgule, [espace(s),] masque, point-virgule
var GoodNetworks = new Array();
i=0;

//GoodNetworks[i++] = "192.168.0.0,	255.255.0.0";	// NRIP

// Ajoutez ici tout mauvais réseau, selon le format :
// IP, virgule, [espace(s),] masque, point-virgule
var BadNetworks = new Array();
i=0;

BadNetworks[i++] = "62.161.94.0,	255.255.255.0";
BadNetworks[i++] = "72.55.138.94,	255.255.255.0";

// l'URl est refusée si le nom du serveur se termine par l'un des domaines suivants
// sauf s'il a été jugé acceptable par "GoodDomains" ou "GoodNetworks".
// ATTENTION : NE PLACEZ PAS D'EXPRESSION RÉGULIÈRE À LA FIN DES VALEURS.
var BadDomains = new Array();
i=0;

BadDomains[i++] = "yllier.comlu.com";
BadDomains[i++] = ".les-horaires.fr";
BadDomains[i++] = "247realmedia.com";
BadDomains[i++] = "a2dfp.net";
BadDomains[i++] = "a4mob.com";
BadDomains[i++] = "ad4you.org";
BadDomains[i++] = "admob.com";
BadDomains[i++] = "adnext.fr";
BadDomains[i++] = "adulthosting.com";
BadDomains[i++] = "adwhirl.com";
BadDomains[i++] = "affilipub.com";
BadDomains[i++] = "all.google.domains";
BadDomains[i++] = "allosponsor.com";
BadDomains[i++] = "assoc-amazon.com";
BadDomains[i++] = "au2m8.com";
BadDomains[i++] = "autoreflex.com";
BadDomains[i++] = "avenir-affiliation.fr";
BadDomains[i++] = "awltovhc.com";
BadDomains[i++] = "blogbang.com";
BadDomains[i++] = "box.shopoon.fr";
BadDomains[i++] = "buysellads.com";
BadDomains[i++] = "cashtrafic.com";
BadDomains[i++] = "chitika.net";
BadDomains[i++] = "clickintext.net";
BadDomains[i++] = "connect.cloudcell.com";
BadDomains[i++] = "contextweb.com";
BadDomains[i++] = "directtrack.com";
BadDomains[i++] = "easy-dating.org";
BadDomains[i++] = "fastclick.net";
BadDomains[i++] = "industrybrains.com";
BadDomains[i++] = "infolinks.com";
BadDomains[i++] = "ingameads.gameloft.com";
BadDomains[i++] = "kontera.com";
BadDomains[i++] = "lduhtrp.net";
BadDomains[i++] = "limasky.com";
BadDomains[i++] = "metrics.apple.com";
BadDomains[i++] = "nextstat.com";
BadDomains[i++] = "ohm.adstronic.net";
BadDomains[i++] = "outils.yesmessenger.com";
BadDomains[i++] = "pagead2.googlesyndication.com";
BadDomains[i++] = "pro-market.net";
BadDomains[i++] = "promobenef.com";
BadDomains[i++] = "pubdirecte.com";
BadDomains[i++] = "reactivpub.fr";
BadDomains[i++] = "remotejr.com";
BadDomains[i++] = "reussissonsensemble.fr";
BadDomains[i++] = "ringtoneexpressions.com";
BadDomains[i++] = "sbx.pagesjaunes.fr";
BadDomains[i++] = "script.banstex.com";
BadDomains[i++] = "smart.allocine.fr";
BadDomains[i++] = "sochr.com";
BadDomains[i++] = "softonic.fr";
BadDomains[i++] = "specificclick.net";
BadDomains[i++] = "static.p-comme-performance.com";
BadDomains[i++] = "tag.regieci.com";
BadDomains[i++] = "tootrash.com";
BadDomains[i++] = "tqlkg.com";
BadDomains[i++] = "track.effiliation.com";
BadDomains[i++] = "veoxa.com";
BadDomains[i++] = "video.unrulymedia.com";
BadDomains[i++] = "weborama.fr";
BadDomains[i++] = "wedoo.com";
BadDomains[i++] = "wipub.com";
BadDomains[i++] = "xiti.com";
BadDomains[i++] = "yceml.net";
BadDomains[i++] = "zodttd.com";
BadDomains[i++] = "mydas.mobi";
BadDomains[i++] = "adxpose.com";
BadDomains[i++] = "adbrite.com";
BadDomains[i++] = "qwapi.com";
BadDomains[i++] = ".doubleclick.net";
BadDomains[i++] = "wobble.s3.amazonaws.com";
BadDomains[i++] = "alexa-sitestats.s3.amazonaws.com";
BadDomains[i++] = "entrecard.s3.amazonaws.com";
BadDomains[i++] = "estat.com";
BadDomains[i++] = "estats.com";
BadDomains[i++] = "casino.com";
BadDomains[i++] = "banner.com";
BadDomains[i++] = "casalemedia.com";
BadDomains[i++] = "247realmedia.com";
BadDomains[i++] = "focalink.com";
BadDomains[i++] = ".branchez-vous.com";
BadDomains[i++] = "adserver.com";
BadDomains[i++] = "ad-inside.com";
BadDomains[i++] = "infolinks.com";
BadDomains[i++] = "limneos.net";
BadDomains[i++] = "activate.adobe.com";
BadDomains[i++] = "practivate.adobe.com";
BadDomains[i++] = "ereg.adobe.com";
BadDomains[i++] = "activate.wip3.adobe.com";
BadDomains[i++] = "wip3.adobe.com";
BadDomains[i++] = "3dns-3.adobe.com";
BadDomains[i++] = "3dns-2.adobe.com";
BadDomains[i++] = "adobe-dns.adobe.com";
BadDomains[i++] = "adobe-dns-2.adobe.com";
BadDomains[i++] = "adobe-dns-3.adobe.com";
BadDomains[i++] = "ereg.wip3.adobe.com";
BadDomains[i++] = "activate-sea.adobe.com";
BadDomains[i++] = "wwis-dubc1-vip60.adobe.com";
BadDomains[i++] = "activate-sjc0.adobe.com";

// l'URl est refusée si elle contient l'un des mots suivants
// sauf si elle a été jugée acceptable par "GoodNetworks".
// vous pouvez utiliser des expressions régulières.

var BadURL_Parts = new Array();
i=0;

BadURL_Parts[i++] = "/AD-INSIDE/images/";
BadURL_Parts[i++] = "/adrollo-custom-images/";
BadURL_Parts[i++] = "/adlog\.php";
BadURL_Parts[i++] = "/ads/";
BadURL_Parts[i++] = "/admaster\.";
BadURL_Parts[i++] = "/AdImages/";
BadURL_Parts[i++] = "\.adbox";
BadURL_Parts[i++] = "/adserver\.";
BadURL_Parts[i++] = "/ajs\.php";
BadURL_Parts[i++] = "\.bidwar";
BadURL_Parts[i++] = "footer_ad";
BadURL_Parts[i++] = "sidebar-ads";
BadURL_Parts[i++] = "\.ad-text";
BadURL_Parts[i++] = "\.ad_(left|right|center)";
BadURL_Parts[i++] = "/mb/commerce/purchase_form\.php";
BadURL_Parts[i++] = "/300x250";
BadURL_Parts[i++] = "/ad\.php";
BadURL_Parts[i++] = "/adunit\.";
BadURL_Parts[i++] = "/mac-ad";
BadURL_Parts[i++] = "header_ad";
BadURL_Parts[i++] = "/www/delivery/";
BadURL_Parts[i++] = "sbr.php";

// l'URl est refusée si le nom du serveur contient l'un des mots suivants
// sauf si elle a été jugée acceptable par "GoodDomains" ou "GoodNetworks".
// vous pouvez utiliser des expressions régulières
var BadHostParts = new Array();
i=0;

BadHostParts[i++] = "banner-ad";

// l'URl est refusée si un des noms commence par l'un des mots suivants
// sauf si elle a été jugée acceptable par "GoodNetworks".
// ATTENTION : NE PLACEZ PAS D'EXPRESSION RÉGULIÈRE AU DÉBUT DES VALEURS.
var BadURL_WordStarts = new Array();
i=0;

BadURL_WordStarts[i++] = "adsense";

// l'URl est refusée si le nom du serveur commence par l'un des mots suivants
// sauf si elle a été jugée acceptable par "GoodNetworks".
// ATTENTION : NE PLACEZ PAS D'EXPRESSION RÉGULIÈRE AU DÉBUT DES VALEURS.
var BadHostWordStarts = new Array();
i=0;

BadHostWordStarts[i++] = "servedby\.";
BadHostWordStarts[i++] = "oas";
BadHostWordStarts[i++] = "google-analytics";
BadHostWordStarts[i++] = "ad[s]?\.";
BadHostWordStarts[i++] = "bwp\.";
BadHostWordStarts[i++] = "adserv";
BadHostWordStarts[i++] = "affiliate";
BadHostWordStarts[i++] = "banner\.";
BadHostWordStarts[i++] = "banners\.";
BadHostWordStarts[i++] = "adimages\.";
BadHostWordStarts[i++] = "gcirm\.";
BadHostWordStarts[i++] = "ad[s]?[0-9]";
BadHostWordStarts[i++] = "adserv";
BadHostWordStarts[i++] = "ads-";

// l'URl est refusée si un des noms finit par l'un des mots suivants
// sauf si elle a été jugée acceptable par "GoodNetworks".
// ATTENTION : NE PLACEZ PAS D'EXPRESSION RÉGULIÈRE À LA FIN DES VALEURS.
var BadURL_WordEnds = new Array();
i=0;

BadURL_WordEnds[i++] = "(\-|/|_)ad[0-9]*\.(jpg|gif|png)";
BadURL_WordEnds[i++] = "/adlog\.php*";

// l'URl est refusée si le nom du serveur finit par l'un des mots suivants
// sauf si elle a été jugée acceptable par "GoodNetworks".
// ATTENTION : NE PLACEZ PAS D'EXPRESSION RÉGULIÈRE À LA FIN DES VALEURS.
var BadHostWordEnds = new Array();
i=0;

BadHostWordEnds[i++] = "tracker";

///////////////////////////
// Set up GoodDomainRegx //
///////////////////////////

for(i in GoodDomains) {
	GoodDomains[i] = GoodDomains[i].split(/\./).join("\\.");
}

var GoodDomainRegx = new RegExp("(" + GoodDomains.join("|") + ")$", "i");

//////////////////////////
// Set up BadDomainRegx //
//////////////////////////

for(i in BadDomains) {
	BadDomains[i] = BadDomains[i].split(/\./).join("\\.");
}

var BadDomainRegx = new RegExp("(" + BadDomains.join("|") + ")$", "i");

////////////////////////////
// Set up BadHostPartRegx //
////////////////////////////

for(i in BadHostParts) {
	BadHostParts[i] = BadHostParts[i].split(/\./).join("\\.");
}

var BadHostPartRegx = new RegExp(BadHostParts.join("|"), "i");

/////////////////////////////////
// Set up BadHostWordStartRegx //
/////////////////////////////////

for(i in BadHostWordStarts) {
	BadHostWordStarts[i] = BadHostWordStarts[i].split(/\./).join("\\.");
}

var BadHostWordStartRegx = new RegExp("(^|[^a-z0-9])(" + BadHostWordStarts.join("|") + ")", "i");

///////////////////////////////
// Set up BadHostWordEndRegx //
///////////////////////////////

for(i in BadHostWordEnds) {
	BadHostWordEnds[i] = BadHostWordEnds[i].split(/\./).join("\\.");
}

var BadHostWordEndRegx = new RegExp("(" + BadHostWordEnds.join("|") + ")([^a-z0-9]|$)", "i");

////////////////////////////
// SET UP BadURL_PartRegx //
////////////////////////////

for(i in BadURL_Parts) {
	BadURL_Parts[i] = BadURL_Parts[i].split(/\./).join("\\.");
}

var BadURL_PartRegx =  new RegExp(BadURL_Parts.join("|"), "i");

/////////////////////////////////
// SET UP BadURL_WordStartRegx //
/////////////////////////////////

for(i in BadURL_WordStarts) {
	BadURL_WordStarts[i] = BadURL_WordStarts[i].split(/\./).join("\\.");
}
var BadURL_WordStartRegx =  new RegExp("[^a-z0-9](" + BadURL_WordStarts.join("|") + ")", "i");

///////////////////////////////
// SET UP BadURL_WordEndRegx //
///////////////////////////////

for(i in BadURL_WordEnds) {
	BadURL_WordEnds[i] = BadURL_WordEnds[i].split(/\./).join("\\.");
}

var BadURL_WordEndRegx =  new RegExp("(" + BadURL_WordEnds.join("|") + ")([^a-z0-9]|$)", "i");

///////////////////////////////////////////
// Define the IsIPAddr function and vars //
///////////////////////////////////////////

var IpAddrRegx = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;

function IsNumIpAddr(host)
{
	var ipAry = host.match(IpAddrRegx);
	var isIPValid = false;

	if (ipAry) {
		isIPValid = true;
		for( i = 1; i <= 4; i++) {
			if (ipAry[i] >= 256) {
				isIPValid = false;
			}
		}
	}

	return isIPValid;
}

//////////////////////////////////
// Define the FindProxyFunction //
//////////////////////////////////

function FindProxyForURL(url, host)
{
	var TestResult;
	var FuncResult = normal;
	var str = "";
	var i = "";
	var tmpNet;
	var IsNumIP = IsNumIpAddr(host);
	var HasIPv4Address = true;
	var IPv4Address;

	///////////////////////////////////////////////////////////////////////
	// FTP patch for privoxy - Elric Scott schemalogic.com               //
	// At one time I recommended privoxy.  Since this is a security hole //
	// I recommend using Firefox + NoScript instead. See WARNING.txt     //
	///////////////////////////////////////////////////////////////////////

//	if (url.substr(0,4) == "ftp:") {
//		return "DIRECT";
//	}

	///////////////////////////////////////////////////////////////////////
	// Remove any anchors and arguments from the url if we are only      //
	// looking at the path part                                          //
	///////////////////////////////////////////////////////////////////////

	if (parseURL == pathParse) {
		str = url.match(/^[^\?#]*/);
		if (str != url) {
			url = str;
		}
	}

	///////////////////////////////////////////////////////////////////////
	// PASS LIST:   domains matched here will always be allowed.         //
	///////////////////////////////////////////////////////////////////////

	if (!IsNumIP && (TestResult = GoodDomainRegx.exec(host))) {
		return normal;
	}

	///////////////////////////////////////////////////////////////////////
	// Check to make sure we can get an IPv4 address from the given host //
	// name.  If we cannot do that then skip the Networks tests.         //
	///////////////////////////////////////////////////////////////////////

	if (IsNumIP) {
		IPv4Address = host;
	}
	else {
		if (isResolvable(host)) {
			IPv4Address = dnsResolve(host);
		}
		else {
			HasIPv4Address = false;
		}
	}

	if (HasIPv4Address) {
		///////////////////////////////////////////////////////////////////////
		// If the IP translates to one of the GoodNetworks we pass it        //
		// since it is considered to be safe.                                //
		///////////////////////////////////////////////////////////////////////

		for (i in GoodNetworks) {
			tmpNet = GoodNetworks[i].split(/,\s*/);
			if (isInNet(IPv4Address, tmpNet[0], tmpNet[1])) {
				return normal;
			}
		}

		///////////////////////////////////////////////////////////////////////
		// If the IP translates to one of the BadNetworks we fail it         //
		// since it is not considered to be safe.                            //
		///////////////////////////////////////////////////////////////////////

		for (i in BadNetworks) {
			tmpNet = BadNetworks[i].split(/,\s*/);
			if (isInNet(IPv4Address, tmpNet[0], tmpNet[1])) {
				return blackhole;
			}
		}
	}

	//////////////////////////////////////////////////////////
	// BLOCK LIST:	stuff matched here here will be blocked //
	//////////////////////////////////////////////////////////

	if (!IsNumIP && (TestResult = BadDomainRegx.exec(host))) {
		return blackhole;
	}
	if (!IsNumIP && (TestResult = BadHostPartRegx.exec(host))) {
		return blackhole;
	}
	if (TestResult = BadHostWordStartRegx.exec(host)) {
		return blackhole;
	}
	if (TestResult = BadHostWordEndRegx.exec(host)) {
		return blackhole;
	}
	if (TestResult = BadURL_PartRegx.exec(url)) {
		return blackhole;
	}
	if (TestResult = BadURL_WordStartRegx.exec(url)) {
		return blackhole;
	}
	if (TestResult = BadURL_WordEndRegx.exec(url)) {
		return blackhole;
	}

	return normal;
}

<commit_msg>test proxy.pac<commit_after>function FindProxyForURL(url,host) {

  return "SOCKS 127.0.0.1:7711";

}<|endoftext|>


<commit_before>var assert = require('assert');
var battle;

describe('Pressure', function () {
	afterEach(function () {
		battle.destroy();
	});

	it('should deduct 1 extra PP from opposing Pokemon moves targetting the user', function () {
		battle = BattleEngine.Battle.construct('battle-pressure-1', 'doublescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['rest']},
			{species: "Talonflame", ability: 'galewings', moves: ['peck']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['rest']},
			{species: "Talonflame", ability: 'galewings', moves: ['peck']}
		]);
		battle.commitDecisions(); // Team Preview
		battle.choose('p1', 'move 1, move 1 -1');
		battle.choose('p2', 'move 1, move 1 1');
		var move = Tools.getMove('peck');
		assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 55);
		assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
	});

	it.skip('should deduct PP if moves are redirected to the user', function () {
		battle = BattleEngine.Battle.construct('battle-pressure-redirect', 'doublescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['followme']},
			{species: "Talonflame", ability: 'galewings', moves: ['peck']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Clefable", ability: 'unaware', moves: ['followme']},
			{species: "Ho-Oh", ability: 'pressure', moves: ['peck']}
		]);
		battle.commitDecisions(); // Team Preview
		battle.choose('p1', 'move 1, move 1 2');
		battle.choose('p2', 'move 1, move 1 2');
		var move = Tools.getMove('peck');
		assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 55);
		assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
	});

	it('should deduct PP even if the move fails or misses', function () {
		battle = BattleEngine.Battle.construct();
		battle.join('p1', 'Guest 1', 1, [{species: "Giratina", ability: 'pressure', item: 'laggingtail', moves: ['mistyterrain', 'shadowforce']}]);
		battle.join('p2', 'Guest 2', 1, [{species: "Smeargle", ability: 'owntempo', moves: ['doubleedge', 'spore', 'moonblast']}]);
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('doubleedge')).pp, 22);
		battle.choose('p1', 'move 2');
		battle.choose('p2', 'move 2');
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('spore')).pp, 22);
		battle.choose('p2', 'move 3');
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('moonblast')).pp, 22);
	});

	it.skip('should deduct PP for each Pressure Pokemon targetted', function () {
		battle = BattleEngine.Battle.construct('battle-pressure-multi', 'triplescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['rest']},
			{species: "Palkia", ability: 'pressure', moves: ['rest']},
			{species: "Dialga", ability: 'pressure', moves: ['rest']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Kyurem", ability: 'pressure', moves: ['hail']},
			{species: "Zekrom", ability: 'teravolt', moves: ['spikes']},
			{species: "Reshiram", ability: 'turboblaze', moves: ['rockslide']}
		]);
		battle.commitDecisions(); // Team Preview
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('hail')).pp, 12);
		assert.strictEqual(battle.p2.active[1].getMoveData(Tools.getMove('spikes')).pp, 12);
		assert.strictEqual(battle.p2.active[2].getMoveData(Tools.getMove('rockslide')).pp, 13);
	});
});

describe('Pressure [Gen 4]', function () {
	afterEach(function () {
		battle.destroy();
	});

	it('should deduct 1 extra PP from any moves targetting the user', function () {
		battle = BattleEngine.Battle.construct('battle-dpp-pressure', 'gen4doublescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['rest']},
			{species: "Aerodactyl", ability: 'quickfeet', moves: ['peck']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['rest']},
			{species: "Aerodactyl", ability: 'quickfeet', moves: ['peck']}
		]);
		battle.choose('p1', 'move 1, move 1 -1');
		battle.choose('p2', 'move 1, move 1 1');
		var move = Tools.getMove('peck');
		assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 54);
		assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
	});

	it.skip('should deduct PP if moves are redirected to the user', function () {
		battle = BattleEngine.Battle.construct('battle-dpp-pressure-redirect', 'gen4doublescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['followme']},
			{species: "Aerodactyl", ability: 'quickfeet', moves: ['peck']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Clefable", ability: 'magicguard', moves: ['followme']},
			{species: "Ho-Oh", ability: 'pressure', moves: ['peck']}
		]);
		battle.commitDecisions(); // Team Preview
		battle.choose('p1', 'move 1, move 1 2');
		battle.choose('p2', 'move 1, move 1 2');
		var move = Tools.getMove('peck');
		assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 55);
		assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
	});

	it('should deduct PP even if the move fails or misses', function () {
		battle = BattleEngine.Battle.construct('battle-dpp-pressure-miss', 'gen4customgame');
		battle.join('p1', 'Guest 1', 1, [{species: "Giratina", ability: 'pressure', item: 'laggingtail', moves: ['shadowforce']}]);
		battle.join('p2', 'Guest 2', 1, [{species: "Smeargle", ability: 'owntempo', moves: ['doubleedge', 'dragonpulse']}]);
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('doubleedge')).pp, 22);
		battle.choose('p2', 'move 2');
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('dragonpulse')).pp, 14);
	});

	it.skip('should deduct PP for each Pressure Pokemon targetted', function () {
		battle = BattleEngine.Battle.construct('battle-dpp-pressure-multi', 'gen4doublescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Palkia", ability: 'pressure', moves: ['rest']},
			{species: "Dialga", ability: 'pressure', moves: ['rest']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Lugia", ability: 'pressure', moves: ['hail']},
			{species: "Ho-Oh", ability: 'pressure', moves: ['earthquake']}
		]);
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('hail')).pp, 12);
		assert.strictEqual(battle.p2.active[1].getMoveData(Tools.getMove('earthquake')).pp, 12);
	});

	it('should not deduct PP from self-targeting moves', function () {
		battle = BattleEngine.Battle.construct('battle-dpp-pressure-self', 'gen4customgame');
		battle.join('p1', 'Guest 1', 1, [{species: "Palkia", ability: 'pressure', moves: ['calmmind']}]);
		battle.join('p2', 'Guest 2', 1, [{species: "Dialga", ability: 'pressure', moves: ['calmmind']}]);
		battle.commitDecisions();
		var move = Tools.getMove('calmmind');
		assert.strictEqual(battle.p1.active[0].getMoveData(move).pp, 31);
		assert.strictEqual(battle.p1.active[0].getMoveData(move).pp, 31);
	});
});
<commit_msg>Release and update Pressure tests<commit_after>var assert = require('assert');
var battle;

describe('Pressure', function () {
	afterEach(function () {
		battle.destroy();
	});

	it('should deduct 1 extra PP from opposing Pokemon moves targetting the user', function () {
		battle = BattleEngine.Battle.construct('battle-pressure-1', 'doublescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['rest']},
			{species: "Talonflame", ability: 'galewings', moves: ['peck']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Giratina", ability: 'defiant', moves: ['rest']},
			{species: "Talonflame", ability: 'galewings', moves: ['peck']}
		]);
		battle.commitDecisions(); // Team Preview
		battle.choose('p1', 'move 1, move 1 -1');
		battle.choose('p2', 'move 1, move 1 1');
		var move = Tools.getMove('peck');
		assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 55);
		assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
	});

	it('should deduct PP if moves are redirected to the user', function () {
		battle = BattleEngine.Battle.construct('battle-pressure-redirect', 'doublescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['followme']},
			{species: "Talonflame", ability: 'galewings', moves: ['peck']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Clefable", ability: 'unaware', moves: ['followme']},
			{species: "Ho-Oh", ability: 'pressure', moves: ['peck']}
		]);
		battle.commitDecisions(); // Team Preview
		battle.choose('p1', 'move 1, move 1 2');
		battle.choose('p2', 'move 1, move 1 2');
		var move = Tools.getMove('peck');
		assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 55);
		assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
	});

	it('should deduct PP even if the move fails or misses', function () {
		battle = BattleEngine.Battle.construct();
		battle.join('p1', 'Guest 1', 1, [{species: "Giratina", ability: 'pressure', item: 'laggingtail', moves: ['mistyterrain', 'shadowforce']}]);
		battle.join('p2', 'Guest 2', 1, [{species: "Smeargle", ability: 'desolateland', moves: ['doubleedge', 'spore', 'moonblast', 'surf']}]);
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('doubleedge')).pp, 22);
		battle.choose('p1', 'move 2');
		battle.choose('p2', 'move 2');
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('spore')).pp, 22);
		battle.choose('p2', 'move 3');
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('moonblast')).pp, 22);
		battle.choose('p2', 'move 4');
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('surf')).pp, 22);
	});

	it('should deduct PP for each Pressure Pokemon targetted', function () {
		battle = BattleEngine.Battle.construct('battle-pressure-multi', 'triplescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['rest']},
			{species: "Palkia", ability: 'pressure', moves: ['rest']},
			{species: "Dialga", ability: 'pressure', moves: ['rest']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Kyurem", ability: 'pressure', moves: ['hail']},
			{species: "Zekrom", ability: 'teravolt', moves: ['spikes']},
			{species: "Reshiram", ability: 'turboblaze', moves: ['rockslide']}
		]);
		battle.commitDecisions(); // Team Preview
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('hail')).pp, 12);
		assert.strictEqual(battle.p2.active[1].getMoveData(Tools.getMove('spikes')).pp, 28);
		assert.strictEqual(battle.p2.active[2].getMoveData(Tools.getMove('rockslide')).pp, 13);
	});
});

describe('Pressure [Gen 4]', function () {
	afterEach(function () {
		battle.destroy();
	});

	it('should deduct 1 extra PP from any moves targetting the user', function () {
		battle = BattleEngine.Battle.construct('battle-dpp-pressure', 'gen4doublescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['rest']},
			{species: "Aerodactyl", ability: 'quickfeet', moves: ['peck']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['rest']},
			{species: "Aerodactyl", ability: 'quickfeet', moves: ['peck']}
		]);
		battle.choose('p1', 'move 1, move 1 -1');
		battle.choose('p2', 'move 1, move 1 1');
		var move = Tools.getMove('peck');
		assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 54);
		assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
	});

	it('should deduct PP if moves are redirected to the user', function () {
		battle = BattleEngine.Battle.construct('battle-dpp-pressure-redirect', 'gen4doublescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Giratina", ability: 'pressure', moves: ['followme']},
			{species: "Aerodactyl", ability: 'quickfeet', moves: ['peck']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Clefable", ability: 'magicguard', moves: ['followme']},
			{species: "Ho-Oh", ability: 'pressure', moves: ['peck']}
		]);
		battle.choose('p1', 'move 1, move 1 2');
		battle.choose('p2', 'move 1, move 1 2');
		var move = Tools.getMove('peck');
		assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 55);
		assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
	});

	it('should deduct PP even if the move fails or misses', function () {
		battle = BattleEngine.Battle.construct('battle-dpp-pressure-miss', 'gen4customgame');
		battle.join('p1', 'Guest 1', 1, [{species: "Giratina", ability: 'pressure', item: 'laggingtail', moves: ['shadowforce']}]);
		battle.join('p2', 'Guest 2', 1, [{species: "Smeargle", ability: 'owntempo', moves: ['doubleedge', 'dragonpulse']}]);
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('doubleedge')).pp, 22);
		battle.choose('p2', 'move 2');
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('dragonpulse')).pp, 14);
	});

	it('should deduct PP for each Pressure Pokemon targetted', function () {
		battle = BattleEngine.Battle.construct('battle-dpp-pressure-multi', 'gen4doublescustomgame');
		battle.join('p1', 'Guest 1', 1, [
			{species: "Palkia", ability: 'pressure', moves: ['rest']},
			{species: "Dialga", ability: 'pressure', moves: ['rest']}
		]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Lugia", ability: 'pressure', moves: ['hail']},
			{species: "Ho-Oh", ability: 'pressure', moves: ['earthquake']}
		]);
		battle.commitDecisions();
		assert.strictEqual(battle.p2.active[0].getMoveData(Tools.getMove('hail')).pp, 12);
		assert.strictEqual(battle.p2.active[1].getMoveData(Tools.getMove('earthquake')).pp, 12);
	});

	it('should not deduct PP from self-targeting moves', function () {
		battle = BattleEngine.Battle.construct('battle-dpp-pressure-self', 'gen4customgame');
		battle.join('p1', 'Guest 1', 1, [{species: "Palkia", ability: 'pressure', moves: ['calmmind']}]);
		battle.join('p2', 'Guest 2', 1, [{species: "Dialga", ability: 'pressure', moves: ['calmmind']}]);
		battle.commitDecisions();
		var move = Tools.getMove('calmmind');
		assert.strictEqual(battle.p1.active[0].getMoveData(move).pp, 31);
		assert.strictEqual(battle.p1.active[0].getMoveData(move).pp, 31);
	});
});
<|endoftext|>


<commit_before>/**
 *
 *
 *
 *
 *
 */

var util = require( 'util' )
var fs = require( 'fs' );
var log = require( 'npmlog' );

var globber = require( '../../lib/globber' );
var parser = require( './parser' );
var render = require( './render' );

function generate( options ) {

    setupStyles( './node_modules/sugarcoat/generators/pattern-library/templates/styles/furtive.css', '../generators/pattern-library/templates/styles/furtive.css' );
    setupStyles( './node_modules/sugarcoat/generators/pattern-library/templates/styles/pattern-lib.css', '../generators/pattern-library/templates/styles/pattern-lib.css' );

    globFiles( options )
        .then( readSections )
        .then( parseSections )
        .then( render );
}

/**
 *
 */
function globFiles( options ) {

    var globArr = options.sections.map( function( section ) {

        return globber( section.files );

    });

    return Promise.all( globArr ).then( function ( sections ) {

        sections.forEach( function( section, index ) {

            options.sections[ index ].files = section;
        });

        return options;
    });
}

/**
 *
 */
function readSections( options ) {

    var promiseArr = options.sections.map( function ( section, index ) {

        return Promise.all( section.files.map( function ( file, index ) {

            return new Promise( function ( resolve, reject ) {

                fs.readFile( file, 'utf8', function( err, src ) {

                    if ( err ) return reject( err );

                    section.files[ index ] = {
                        path: file,
                        src: src
                    }

                    resolve( section.files[ index ] );
                });
            });
        }));
    });

    return Promise.all( promiseArr ).then( function ( values ) {
        return options;
    });
}

/**
 *
 */
function parseSections( options ) {

    var parse = parser();

    options.sections.forEach( function ( section, index ) {

        section.files.map( function ( file, index ) {

            section.files[ index ].data = parse.parseComment( file.path, file.src, section.type, section.template );
        });
    });

    return options;
}

/**
 * setupStyles: reads in the style files for the pattern library and adds them to the project so we can access them
 */
function setupStyles ( oldFile, newFile ) {

    //read in furtive CSS
    fs.readFile( oldFile, 'utf8', function( err, data ) {

        if ( err ) throw err;

        var dir = '../generators/pattern-library/templates/styles/';

        if ( !fs.existsSync( dir ) ) {

            fs.mkdirSync( dir );
        }

        // console.log(data);
        fs.writeFile( newFile, data, function( err ){

            if ( err ) throw err;

            // console.log('file created!');
            log.info( 'CSS file created', newFile );
        });
    });
    console.log('css');
}

module.exports = generate;<commit_msg>add in setupfiles<commit_after>/**
 *
 *
 *
 *
 *
 */

var util = require( 'util' )
var fs = require( 'fs' );
var log = require( 'npmlog' );

var globber = require( '../../lib/globber' );
var parser = require( './parser' );
var render = require( './render' );

function generate( options ) {

    // setupStyles( './node_modules/sugarcoat/generators/pattern-library/templates/styles/furtive.css', '../generators/pattern-library/templates/styles/furtive.css' );
    // setupStyles( './node_modules/sugarcoat/generators/pattern-library/templates/styles/pattern-lib.css', '../generators/pattern-library/templates/styles/pattern-lib.css' );

    globFiles( options )
        .then( readSections )
        .then( parseSections )
        .then( render );
}

/**
 *
 */
function globFiles( options ) {

    var globArr = options.sections.map( function( section ) {

        return globber( section.files );

    });

    return Promise.all( globArr ).then( function ( sections ) {

        sections.forEach( function( section, index ) {

            options.sections[ index ].files = section;
        });

        return options;
    });
}

/**
 *
 */
function readSections( options ) {

    var promiseArr = options.sections.map( function ( section, index ) {

        return Promise.all( section.files.map( function ( file, index ) {

            return new Promise( function ( resolve, reject ) {

                fs.readFile( file, 'utf8', function( err, src ) {

                    if ( err ) return reject( err );

                    section.files[ index ] = {
                        path: file,
                        src: src
                    }

                    resolve( section.files[ index ] );
                });
            });
        }));
    });

    return Promise.all( promiseArr ).then( function ( values ) {
        return options;
    });
}

/**
 *
 */
function parseSections( options ) {

    var parse = parser();

    options.sections.forEach( function ( section, index ) {

        section.files.map( function ( file, index ) {

            section.files[ index ].data = parse.parseComment( file.path, file.src, section.type, section.template );
        });
    });

    return options;
}

/**
 * setupStyles: reads in the style files for the pattern library and adds them to the project so we can access them
 */
function setupStyles ( oldFile, newFile ) {

    //read in furtive CSS
    fs.readFile( oldFile, 'utf8', function( err, data ) {

        if ( err ) throw err;

        var dir = '../generators/pattern-library/templates/styles/';

        if ( !fs.existsSync( dir ) ) {

            fs.mkdirSync( dir );
        }

        // console.log(data);
        fs.writeFile( newFile, data, function( err ){

            if ( err ) throw err;

            // console.log('file created!');
            log.info( 'CSS file created', newFile );
        });
    });
    // console.log('css');
}

module.exports = generate;<|endoftext|>


<commit_before>/**
 * Scapegoat
 * https://github.com/brentertz/scapegoat
 *
 * Copyright (c) 2014 Brent Ertz
 * Licensed under the MIT license.
 */

var util = require('util');

 var i2c = require('i2c');
 var MASTER = 0x0f;

 var SLAVE = new i2c(MASTER, {device: '/dev/i2c-1', debug: false});

 var stepMode = {
   FULL :     'full',
   HALF :     'half',
   QUARTER:   'quarter',
   EIGTHTH :  'eigthth',
   SIXTEETH : 'sixteenth'
 };

 var bar = {
   A1: { 'label': 'A1', 'motor': 0x10, 'led': 0x11, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   A2: { 'label': 'A2', 'motor': 0x12, 'led': 0x13, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   A3: { 'label': 'A3', 'motor': 0x14, 'led': 0x15, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },

   B1: { 'label': 'B1', 'motor': 0x20, 'led': 0x21, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   B2: { 'label': 'B2', 'motor': 0x22, 'led': 0x23, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   B3: { 'label': 'B3', 'motor': 0x24, 'led': 0x25, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },

   C1: { 'label': 'C1', 'motor': 0x30, 'led': 0x31, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   C2: { 'label': 'C2', 'motor': 0x32, 'led': 0x33, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   C3: { 'label': 'C3', 'motor': 0x34, 'led': 0x35, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 }
 };

var movingDirection = {
  UP : 'up',
  DOWN : 'down',
  NONE : 'none'
};

var moveResponse = {
  href: '',
  receiver: '',
  positionTarget: -1,
  positionOld: -1,
  direction: '',
  difference: -1,
  stepmode: ''
};

var sendMessage = function(address, message) {

   SLAVE.setAddress(address);

   var bytes = [];

   for (var i = 0; i < message.length; ++i) {
       bytes.push(message.charCodeAt(i));
   }

   SLAVE.writeBytes(0, bytes, function(err) {
     console.log("ERROR: sendMessage("+message+") ->"+ err + " == "+(!err)+ " ==> "+(err != null));
     return err != null;
   });
}

 //------------------------------------------------------------------------------
var getBarReceiver = function(receiver) {

  if (typeof receiver !== 'string') return -1;

  if (receiver.toUpperCase() === 'A1') return bar.A1;
  if (receiver.toUpperCase() === 'A2') return bar.A2;
  if (receiver.toUpperCase() === 'A3') return bar.A3;

  if (receiver.toUpperCase() === 'B1') return bar.B1;
  if (receiver.toUpperCase() === 'B2') return bar.B2;
  if (receiver.toUpperCase() === 'B3') return bar.B3;

  if (receiver.toUpperCase() === 'C1') return bar.C1;
  if (receiver.toUpperCase() === 'C2') return bar.C2;
  if (receiver.toUpperCase() === 'C3') return bar.C3;

  return -1;
};

var getBarPosition = function(receiver) {

  if (typeof receiver.label !== 'string') return -1;

  if (receiver.label.toUpperCase() === 'A1') return bar.A1.position;
  if (receiver.label.toUpperCase() === 'A2') return bar.A2.position;
  if (receiver.label.toUpperCase() === 'A3') return bar.A3.position;

  if (receiver.label.toUpperCase() === 'B1') return bar.B1.position;
  if (receiver.label.toUpperCase() === 'B2') return bar.B2.position;
  if (receiver.label.toUpperCase() === 'B3') return bar.B3.position;

  if (receiver.label.toUpperCase() === 'C1') return bar.C1.position;
  if (receiver.label.toUpperCase() === 'C2') return bar.C2.position;
  if (receiver.label.toUpperCase() === 'C3') return bar.C3.position;

  return -1;
};

var setBarCalibration = function(receiver, status) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') bar.A1.calibrated = status;
  else if (receiver.label.toUpperCase() === 'A2') bar.A2.calibrated = status;
  else if (receiver.label.toUpperCase() === 'A3') bar.A3.calibrated = status;

  else if (receiver.label.toUpperCase() === 'B1') bar.B1.calibrated = status;
  else if (receiver.label.toUpperCase() === 'B2') bar.B2.calibrated = status;
  else if (receiver.label.toUpperCase() === 'B3') bar.B3.calibrated = status;

  else if (receiver.label.toUpperCase() === 'C1') bar.C1.calibrated = status;
  else if (receiver.label.toUpperCase() === 'C2') bar.C2.calibrated = status;
  else if (receiver.label.toUpperCase() === 'C3') bar.C3.calibrated = status;
  else return false;

  return true;
};

var setBarPosition = function(receiver, newPosition) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') bar.A1.position = newPosition;
  else if (receiver.label.toUpperCase() === 'A2') bar.A2.position = newPosition;
  else if (receiver.label.toUpperCase() === 'A3') bar.A3.position = newPosition;

  else if (receiver.label.toUpperCase() === 'B1') bar.B1.position = newPosition;
  else if (receiver.label.toUpperCase() === 'B2') bar.B2.position = newPosition;
  else if (receiver.label.toUpperCase() === 'B3') bar.B3.position = newPosition;

  else if (receiver.label.toUpperCase() === 'C1') bar.C1.position = newPosition;
  else if (receiver.label.toUpperCase() === 'C2') bar.C2.position = newPosition;
  else if (receiver.label.toUpperCase() === 'C3') bar.C3.position = newPosition;
  else return false;

  return true;
};

var getBarAnimation = function(receiver) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') return bar.A1.animation;
  else if (receiver.label.toUpperCase() === 'A2') return bar.A2.animation;
  else if (receiver.label.toUpperCase() === 'A3') return bar.A3.animation;

  else if (receiver.label.toUpperCase() === 'B1') return bar.B1.animation;
  else if (receiver.label.toUpperCase() === 'B2') return bar.B2.animation;
  else if (receiver.label.toUpperCase() === 'B3') return bar.B3.animation;

  else if (receiver.label.toUpperCase() === 'C1') return bar.C1.animation;
  else if (receiver.label.toUpperCase() === 'C2') return bar.C2.animation;
  else if (receiver.label.toUpperCase() === 'C3') return bar.C3.animation;
  else return false;

  return true;
};

var setBarAnimation = function(receiver, animation) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') bar.A1.animation = animation;
  else if (receiver.label.toUpperCase() === 'A2') bar.A2.animation = animation;
  else if (receiver.label.toUpperCase() === 'A3') bar.A3.animation = animation;

  else if (receiver.label.toUpperCase() === 'B1') bar.B1.animation = animation;
  else if (receiver.label.toUpperCase() === 'B2') bar.B2.animation = animation;
  else if (receiver.label.toUpperCase() === 'B3') bar.B3.animation = animation;

  else if (receiver.label.toUpperCase() === 'C1') bar.C1.animation = animation;
  else if (receiver.label.toUpperCase() === 'C2') bar.C2.animation = animation;
  else if (receiver.label.toUpperCase() === 'C3') bar.C3.animation = animation;
  else return false;

  return true;
};

var getBarToken = function(receiver) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') return bar.A1.token;
  else if (receiver.label.toUpperCase() === 'A2') return bar.A2.token;
  else if (receiver.label.toUpperCase() === 'A3') return bar.A3.token;

  else if (receiver.label.toUpperCase() === 'B1') return bar.B1.token;
  else if (receiver.label.toUpperCase() === 'B2') return bar.B2.token;
  else if (receiver.label.toUpperCase() === 'B3') return bar.B3.token;

  else if (receiver.label.toUpperCase() === 'C1') return bar.C1.token;
  else if (receiver.label.toUpperCase() === 'C2') return bar.C2.token;
  else if (receiver.label.toUpperCase() === 'C3') return bar.C3.token;
  else return false;

  return true;
};

var setBarToken = function(receiver, token) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') bar.A1.token = token;
  else if (receiver.label.toUpperCase() === 'A2') bar.A2.token = token;
  else if (receiver.label.toUpperCase() === 'A3') bar.A3.token = token;

  else if (receiver.label.toUpperCase() === 'B1') bar.B1.token = token;
  else if (receiver.label.toUpperCase() === 'B2') bar.B2.token = token;
  else if (receiver.label.toUpperCase() === 'B3') bar.B3.token = token;

  else if (receiver.label.toUpperCase() === 'C1') bar.C1.token = token;
  else if (receiver.label.toUpperCase() === 'C2') bar.C2.token = token;
  else if (receiver.label.toUpperCase() === 'C3') bar.C3.token = token;
  else return false;

  return true;
};

var getBarMotor = function(receiver) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') return bar.A1.motor;
  else if (receiver.label.toUpperCase() === 'A2') return bar.A2.motor;
  else if (receiver.label.toUpperCase() === 'A3') return bar.A3.motor;

  else if (receiver.label.toUpperCase() === 'B1') return bar.B1.motor;
  else if (receiver.label.toUpperCase() === 'B2') return bar.B2.motor;
  else if (receiver.label.toUpperCase() === 'B3') return bar.B3.motor;

  else if (receiver.label.toUpperCase() === 'C1') return bar.C1.motor;
  else if (receiver.label.toUpperCase() === 'C2') return bar.C2.motor;
  else if (receiver.label.toUpperCase() === 'C3') return bar.C3.motor;
  else return false;

  return true;
}

/**
 * Escape special characters in the given string of html.
 *
 * @param  {String} receiver
 * @param  {Number} position
 * @param  {String} speed
 * @return {Boolean}
 */
var move = function(receiver, position, speed) {

    var barReceiver = -1;

    // -------------------------------------------------------------------------
    // Validate
    if (
      typeof receiver !== 'string' ||
      typeof receiver === 'undefined'
    ) {
      if (typeof receiver === 'object') {
        if (typeof receiver.label === 'string') {
          barReceiver = receiver;
        } else {
          return false;
        }
      }
    }

    if (
      typeof position === 'string' ||
      typeof position === 'undefined' ||
      position < 0 ||
      position > 100
    ) {
      return false;
    }

    if (speed === '' || typeof position === 'undefined') speed = stepMode.HALF;

    if (speed != stepMode.FULL) {
      if (speed != stepMode.HALF) {
        if (speed != stepMode.QUARTER) {
          if (speed != stepMode.EIGTHTH) {
            if (speed != stepMode.SIXTEETH) {
              return false;
            }
          }
        }
      }
    }

    // Get Receiver/ Bar
    if (barReceiver === -1) {
      barReceiver = getBarReceiver(receiver);
      if (barReceiver === -1) return false; // No Receiver found
    }

    //console.log("MOVE:"+barReceiver.label+"/"+position+"/"+speed);

    // -------------------------------------------------------------------------
    // 2) Parse Resonse Object Parameter

    // Duplicate JSON Resonse Object
    var response = moveResponse;

    // -------------------------------------------------------------------------
    // Check calibration
    if (! barReceiver.calibrated) {

      console.log("Bar: "+getBarMotor(barReceiver));

      console.console.log("Calibration: "+sendMessage( getBarMotor(barReceiver), "INIT:calibrate"));

      // Send calibration
      setBarCalibration(barReceiver, true) == false ?
      console.log("ERROR: setBarCalibration("+barReceiver.label+","+true+")") :
      console.log("Calibration OK");

      setBarPosition(barReceiver, 0) == false ?
      console.log("ERROR: setBarPosition("+barReceiver.label+","+0+")") :
      console.log("Reset Position OK");

    }

    // -------------------------------------------------------------------------
    // Set receiver
    response.receiver = barReceiver.label;

    // -------------------------------------------------------------------------
    // Check old position
    response.positionOld = getBarPosition(barReceiver);

    // -------------------------------------------------------------------------
    // Set stepmode
    response.stepmode = speed;

    // -------------------------------------------------------------------------
    // Set new position
    setBarPosition(barReceiver, position) == false ?
    console.log("ERROR: setBarPosition("+barReceiver.label+","+position+")") :
    console.log("Set Target Position OK");

    response.positionTarget = getBarPosition(barReceiver);

    // -------------------------------------------------------------------------
    // Check moving direction & position difference
    if (response.positionOld < response.positionTarget) {

      response.direction = movingDirection.UP;
      response.difference = response.positionTarget - response.positionOld;

    } else if (response.positionOld > response.positionTarget) {

      response.direction = movingDirection.DOWN;
      response.difference = response.positionOld - response.positionTarget;

    } else {

      response.direction = movingDirection.NONE;
      response.difference = 0;

    }

    // 3) Send I2C-Request

    // -------------------------------------------------------------------------
    //console.log(response);
    console.log(util.inspect(response, {showHidden: true, depth: null}));
    return true;
};

module.exports.move = move;
module.exports.stepMode = stepMode;
module.exports.bar = bar;
module.exports.direction = movingDirection;

module.exports.getBarReceiver = getBarReceiver;
<commit_msg>sendMessage<commit_after>/**
 * Scapegoat
 * https://github.com/brentertz/scapegoat
 *
 * Copyright (c) 2014 Brent Ertz
 * Licensed under the MIT license.
 */

var util = require('util');

 var i2c = require('i2c');
 var MASTER = 0x0f;

 var SLAVE = new i2c(MASTER, {device: '/dev/i2c-1', debug: false});

 var stepMode = {
   FULL :     'full',
   HALF :     'half',
   QUARTER:   'quarter',
   EIGTHTH :  'eigthth',
   SIXTEETH : 'sixteenth'
 };

 var bar = {
   A1: { 'label': 'A1', 'motor': 0x10, 'led': 0x11, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   A2: { 'label': 'A2', 'motor': 0x12, 'led': 0x13, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   A3: { 'label': 'A3', 'motor': 0x14, 'led': 0x15, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },

   B1: { 'label': 'B1', 'motor': 0x20, 'led': 0x21, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   B2: { 'label': 'B2', 'motor': 0x22, 'led': 0x23, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   B3: { 'label': 'B3', 'motor': 0x24, 'led': 0x25, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },

   C1: { 'label': 'C1', 'motor': 0x30, 'led': 0x31, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   C2: { 'label': 'C2', 'motor': 0x32, 'led': 0x33, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 },
   C3: { 'label': 'C3', 'motor': 0x34, 'led': 0x35, 'calibrated': false, 'position': -1, 'animation': '', 'token': 0 }
 };

var movingDirection = {
  UP : 'up',
  DOWN : 'down',
  NONE : 'none'
};

var moveResponse = {
  href: '',
  receiver: '',
  positionTarget: -1,
  positionOld: -1,
  direction: '',
  difference: -1,
  stepmode: ''
};

var sendMessage = function(address, message) {

   SLAVE.setAddress(address);

   var bytes = [];

   for (var i = 0; i < message.length; ++i) {
       bytes.push(message.charCodeAt(i));
   }

   SLAVE.writeBytes(0, bytes, function(err) {
     console.log("ERROR: sendMessage("+message+") ->"+ err + " == "+(!err)+ " ==> "+(err != null));
     return !err;
   });
}

 //------------------------------------------------------------------------------
var getBarReceiver = function(receiver) {

  if (typeof receiver !== 'string') return -1;

  if (receiver.toUpperCase() === 'A1') return bar.A1;
  if (receiver.toUpperCase() === 'A2') return bar.A2;
  if (receiver.toUpperCase() === 'A3') return bar.A3;

  if (receiver.toUpperCase() === 'B1') return bar.B1;
  if (receiver.toUpperCase() === 'B2') return bar.B2;
  if (receiver.toUpperCase() === 'B3') return bar.B3;

  if (receiver.toUpperCase() === 'C1') return bar.C1;
  if (receiver.toUpperCase() === 'C2') return bar.C2;
  if (receiver.toUpperCase() === 'C3') return bar.C3;

  return -1;
};

var getBarPosition = function(receiver) {

  if (typeof receiver.label !== 'string') return -1;

  if (receiver.label.toUpperCase() === 'A1') return bar.A1.position;
  if (receiver.label.toUpperCase() === 'A2') return bar.A2.position;
  if (receiver.label.toUpperCase() === 'A3') return bar.A3.position;

  if (receiver.label.toUpperCase() === 'B1') return bar.B1.position;
  if (receiver.label.toUpperCase() === 'B2') return bar.B2.position;
  if (receiver.label.toUpperCase() === 'B3') return bar.B3.position;

  if (receiver.label.toUpperCase() === 'C1') return bar.C1.position;
  if (receiver.label.toUpperCase() === 'C2') return bar.C2.position;
  if (receiver.label.toUpperCase() === 'C3') return bar.C3.position;

  return -1;
};

var setBarCalibration = function(receiver, status) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') bar.A1.calibrated = status;
  else if (receiver.label.toUpperCase() === 'A2') bar.A2.calibrated = status;
  else if (receiver.label.toUpperCase() === 'A3') bar.A3.calibrated = status;

  else if (receiver.label.toUpperCase() === 'B1') bar.B1.calibrated = status;
  else if (receiver.label.toUpperCase() === 'B2') bar.B2.calibrated = status;
  else if (receiver.label.toUpperCase() === 'B3') bar.B3.calibrated = status;

  else if (receiver.label.toUpperCase() === 'C1') bar.C1.calibrated = status;
  else if (receiver.label.toUpperCase() === 'C2') bar.C2.calibrated = status;
  else if (receiver.label.toUpperCase() === 'C3') bar.C3.calibrated = status;
  else return false;

  return true;
};

var setBarPosition = function(receiver, newPosition) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') bar.A1.position = newPosition;
  else if (receiver.label.toUpperCase() === 'A2') bar.A2.position = newPosition;
  else if (receiver.label.toUpperCase() === 'A3') bar.A3.position = newPosition;

  else if (receiver.label.toUpperCase() === 'B1') bar.B1.position = newPosition;
  else if (receiver.label.toUpperCase() === 'B2') bar.B2.position = newPosition;
  else if (receiver.label.toUpperCase() === 'B3') bar.B3.position = newPosition;

  else if (receiver.label.toUpperCase() === 'C1') bar.C1.position = newPosition;
  else if (receiver.label.toUpperCase() === 'C2') bar.C2.position = newPosition;
  else if (receiver.label.toUpperCase() === 'C3') bar.C3.position = newPosition;
  else return false;

  return true;
};

var getBarAnimation = function(receiver) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') return bar.A1.animation;
  else if (receiver.label.toUpperCase() === 'A2') return bar.A2.animation;
  else if (receiver.label.toUpperCase() === 'A3') return bar.A3.animation;

  else if (receiver.label.toUpperCase() === 'B1') return bar.B1.animation;
  else if (receiver.label.toUpperCase() === 'B2') return bar.B2.animation;
  else if (receiver.label.toUpperCase() === 'B3') return bar.B3.animation;

  else if (receiver.label.toUpperCase() === 'C1') return bar.C1.animation;
  else if (receiver.label.toUpperCase() === 'C2') return bar.C2.animation;
  else if (receiver.label.toUpperCase() === 'C3') return bar.C3.animation;
  else return false;

  return true;
};

var setBarAnimation = function(receiver, animation) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') bar.A1.animation = animation;
  else if (receiver.label.toUpperCase() === 'A2') bar.A2.animation = animation;
  else if (receiver.label.toUpperCase() === 'A3') bar.A3.animation = animation;

  else if (receiver.label.toUpperCase() === 'B1') bar.B1.animation = animation;
  else if (receiver.label.toUpperCase() === 'B2') bar.B2.animation = animation;
  else if (receiver.label.toUpperCase() === 'B3') bar.B3.animation = animation;

  else if (receiver.label.toUpperCase() === 'C1') bar.C1.animation = animation;
  else if (receiver.label.toUpperCase() === 'C2') bar.C2.animation = animation;
  else if (receiver.label.toUpperCase() === 'C3') bar.C3.animation = animation;
  else return false;

  return true;
};

var getBarToken = function(receiver) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') return bar.A1.token;
  else if (receiver.label.toUpperCase() === 'A2') return bar.A2.token;
  else if (receiver.label.toUpperCase() === 'A3') return bar.A3.token;

  else if (receiver.label.toUpperCase() === 'B1') return bar.B1.token;
  else if (receiver.label.toUpperCase() === 'B2') return bar.B2.token;
  else if (receiver.label.toUpperCase() === 'B3') return bar.B3.token;

  else if (receiver.label.toUpperCase() === 'C1') return bar.C1.token;
  else if (receiver.label.toUpperCase() === 'C2') return bar.C2.token;
  else if (receiver.label.toUpperCase() === 'C3') return bar.C3.token;
  else return false;

  return true;
};

var setBarToken = function(receiver, token) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') bar.A1.token = token;
  else if (receiver.label.toUpperCase() === 'A2') bar.A2.token = token;
  else if (receiver.label.toUpperCase() === 'A3') bar.A3.token = token;

  else if (receiver.label.toUpperCase() === 'B1') bar.B1.token = token;
  else if (receiver.label.toUpperCase() === 'B2') bar.B2.token = token;
  else if (receiver.label.toUpperCase() === 'B3') bar.B3.token = token;

  else if (receiver.label.toUpperCase() === 'C1') bar.C1.token = token;
  else if (receiver.label.toUpperCase() === 'C2') bar.C2.token = token;
  else if (receiver.label.toUpperCase() === 'C3') bar.C3.token = token;
  else return false;

  return true;
};

var getBarMotor = function(receiver) {

  if (typeof receiver.label !== 'string') return false;

  if (receiver.label.toUpperCase() === 'A1') return bar.A1.motor;
  else if (receiver.label.toUpperCase() === 'A2') return bar.A2.motor;
  else if (receiver.label.toUpperCase() === 'A3') return bar.A3.motor;

  else if (receiver.label.toUpperCase() === 'B1') return bar.B1.motor;
  else if (receiver.label.toUpperCase() === 'B2') return bar.B2.motor;
  else if (receiver.label.toUpperCase() === 'B3') return bar.B3.motor;

  else if (receiver.label.toUpperCase() === 'C1') return bar.C1.motor;
  else if (receiver.label.toUpperCase() === 'C2') return bar.C2.motor;
  else if (receiver.label.toUpperCase() === 'C3') return bar.C3.motor;
  else return false;

  return true;
}

/**
 * Escape special characters in the given string of html.
 *
 * @param  {String} receiver
 * @param  {Number} position
 * @param  {String} speed
 * @return {Boolean}
 */
var move = function(receiver, position, speed) {

    var barReceiver = -1;

    // -------------------------------------------------------------------------
    // Validate
    if (
      typeof receiver !== 'string' ||
      typeof receiver === 'undefined'
    ) {
      if (typeof receiver === 'object') {
        if (typeof receiver.label === 'string') {
          barReceiver = receiver;
        } else {
          return false;
        }
      }
    }

    if (
      typeof position === 'string' ||
      typeof position === 'undefined' ||
      position < 0 ||
      position > 100
    ) {
      return false;
    }

    if (speed === '' || typeof position === 'undefined') speed = stepMode.HALF;

    if (speed != stepMode.FULL) {
      if (speed != stepMode.HALF) {
        if (speed != stepMode.QUARTER) {
          if (speed != stepMode.EIGTHTH) {
            if (speed != stepMode.SIXTEETH) {
              return false;
            }
          }
        }
      }
    }

    // Get Receiver/ Bar
    if (barReceiver === -1) {
      barReceiver = getBarReceiver(receiver);
      if (barReceiver === -1) return false; // No Receiver found
    }

    //console.log("MOVE:"+barReceiver.label+"/"+position+"/"+speed);

    // -------------------------------------------------------------------------
    // 2) Parse Resonse Object Parameter

    // Duplicate JSON Resonse Object
    var response = moveResponse;

    // -------------------------------------------------------------------------
    // Check calibration
    if (! barReceiver.calibrated) {

      console.log("Bar: "+getBarMotor(barReceiver));

      console.log("Calibration: "+sendMessage( getBarMotor(barReceiver), "INIT:calibrate"));

      // Send calibration
      setBarCalibration(barReceiver, true) == false ?
      console.log("ERROR: setBarCalibration("+barReceiver.label+","+true+")") :
      console.log("Calibration OK");

      setBarPosition(barReceiver, 0) == false ?
      console.log("ERROR: setBarPosition("+barReceiver.label+","+0+")") :
      console.log("Reset Position OK");

    }

    // -------------------------------------------------------------------------
    // Set receiver
    response.receiver = barReceiver.label;

    // -------------------------------------------------------------------------
    // Check old position
    response.positionOld = getBarPosition(barReceiver);

    // -------------------------------------------------------------------------
    // Set stepmode
    response.stepmode = speed;

    // -------------------------------------------------------------------------
    // Set new position
    setBarPosition(barReceiver, position) == false ?
    console.log("ERROR: setBarPosition("+barReceiver.label+","+position+")") :
    console.log("Set Target Position OK");

    response.positionTarget = getBarPosition(barReceiver);

    // -------------------------------------------------------------------------
    // Check moving direction & position difference
    if (response.positionOld < response.positionTarget) {

      response.direction = movingDirection.UP;
      response.difference = response.positionTarget - response.positionOld;

    } else if (response.positionOld > response.positionTarget) {

      response.direction = movingDirection.DOWN;
      response.difference = response.positionOld - response.positionTarget;

    } else {

      response.direction = movingDirection.NONE;
      response.difference = 0;

    }

    // 3) Send I2C-Request

    // -------------------------------------------------------------------------
    //console.log(response);
    console.log(util.inspect(response, {showHidden: true, depth: null}));
    return true;
};

module.exports.move = move;
module.exports.stepMode = stepMode;
module.exports.bar = bar;
module.exports.direction = movingDirection;

module.exports.getBarReceiver = getBarReceiver;
<|endoftext|>