<commit_before>/**
 * Tips
 * ====
 * - Set `user-agent` and `accept` headers when sending requests. Some services will not respond as expected without them.
 * - Set `pool` to false if you send lots of requests using "request" library.
 */

var request = require('request')
  , FeedParser = require(__dirname+'/..')
  , Iconv = require('iconv').Iconv;

function fetch(feed) {
  // Define our streams
  var req = request(feed, {timeout: 10000, pool: false});
  req.setMaxListeners(50);
  // Some feeds do not response without user-agent and accept headers.
  req.setHeader('user-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36')
     .setHeader('accept', 'text/html,application/xhtml+xml');

  var feedparser = new FeedParser();

  // Define our handlers
  req.on('error', done);
  req.on('response', function(res) {
    var stream = this
      , iconv
      , charset;

    if (res.statusCode != 200) return this.emit('error', new Error('Bad status code'));

    charset = getParams(res.headers['content-type'] || '').charset;

    // Use iconv if its not utf8 already.
    if (!iconv && charset && !/utf-*8/i.test(charset)) {
      try {
        iconv = new Iconv(charset, 'utf-8');
        console.log('Converting from charset %s to utf-8', charset);
        iconv.on('error', done);
        // If we're using iconv, stream will be the output of iconv
        // otherwise it will remain the output of request
        stream = this.pipe(iconv);
      } catch(err) {
        this.emit('error', err);
      }
    }

    // And boom goes the dynamite
    stream.pipe(feedparser);
  });

  feedparser.on('error', done);
  feedparser.on('end', done);
  feedparser.on('readable', function() {
    var post;
    while (post = this.read()) {
      console.log(post);
    }
  });
}

function getParams(str) {
  var params = str.split(';').reduce(function (params, param) {
    var parts = param.split('=').map(function (part) { return part.trim(); });
    if (parts.length === 2) {
      params[parts[0]] = parts[1];
    }
    return params;
  }, {});
  return params;
}

function done(err) {
  if (err) {
    console.log(err, err.stack);
    return process.exit(1);
  }
  server.close();
  process.exit();
}

// Don't worry about this. It's just a localhost file server so you can be
// certain the "remote" feed is available when you run this example.
var server = require('http').createServer(function (req, res) {
  var stream = require('fs').createReadStream(require('path').resolve(__dirname, '../test/feeds' + req.url));
  res.setHeader('Content-Type', 'text/xml; charset=Windows-1251');
  stream.pipe(res);
});
server.listen(0, function () {
  fetch('http://localhost:' + this.address().port + '/iconv.xml');
});
<commit_msg>Fix small typo.<commit_after>/**
 * Tips
 * ====
 * - Set `user-agent` and `accept` headers when sending requests. Some services will not respond as expected without them.
 * - Set `pool` to false if you send lots of requests using "request" library.
 */

var request = require('request')
  , FeedParser = require(__dirname+'/..')
  , Iconv = require('iconv').Iconv;

function fetch(feed) {
  // Define our streams
  var req = request(feed, {timeout: 10000, pool: false});
  req.setMaxListeners(50);
  // Some feeds do not respond without user-agent and accept headers.
  req.setHeader('user-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36')
     .setHeader('accept', 'text/html,application/xhtml+xml');

  var feedparser = new FeedParser();

  // Define our handlers
  req.on('error', done);
  req.on('response', function(res) {
    var stream = this
      , iconv
      , charset;

    if (res.statusCode != 200) return this.emit('error', new Error('Bad status code'));

    charset = getParams(res.headers['content-type'] || '').charset;

    // Use iconv if its not utf8 already.
    if (!iconv && charset && !/utf-*8/i.test(charset)) {
      try {
        iconv = new Iconv(charset, 'utf-8');
        console.log('Converting from charset %s to utf-8', charset);
        iconv.on('error', done);
        // If we're using iconv, stream will be the output of iconv
        // otherwise it will remain the output of request
        stream = this.pipe(iconv);
      } catch(err) {
        this.emit('error', err);
      }
    }

    // And boom goes the dynamite
    stream.pipe(feedparser);
  });

  feedparser.on('error', done);
  feedparser.on('end', done);
  feedparser.on('readable', function() {
    var post;
    while (post = this.read()) {
      console.log(post);
    }
  });
}

function getParams(str) {
  var params = str.split(';').reduce(function (params, param) {
    var parts = param.split('=').map(function (part) { return part.trim(); });
    if (parts.length === 2) {
      params[parts[0]] = parts[1];
    }
    return params;
  }, {});
  return params;
}

function done(err) {
  if (err) {
    console.log(err, err.stack);
    return process.exit(1);
  }
  server.close();
  process.exit();
}

// Don't worry about this. It's just a localhost file server so you can be
// certain the "remote" feed is available when you run this example.
var server = require('http').createServer(function (req, res) {
  var stream = require('fs').createReadStream(require('path').resolve(__dirname, '../test/feeds' + req.url));
  res.setHeader('Content-Type', 'text/xml; charset=Windows-1251');
  stream.pipe(res);
});
server.listen(0, function () {
  fetch('http://localhost:' + this.address().port + '/iconv.xml');
});
<|endoftext|>


<commit_before>
var ELEMENT = 'tag';
var ATTRIBUTE = 'attr';
var TEXT = 'text';
var COMMENT = 'comment';

function getContext(module, extContext){
  var BaseContext = module.at_base_context;

  if (!BaseContext)
  {
    var tmpl = module;
    var typeMap = {};
    typeMap[tmpl.TYPE_ELEMENT] = ELEMENT;
    typeMap[tmpl.TYPE_ATTRIBUTE] = ATTRIBUTE;
    typeMap[4] = ATTRIBUTE;
    typeMap[5] = ATTRIBUTE;
    typeMap[6] = ATTRIBUTE;
    typeMap[tmpl.TYPE_TEXT] = TEXT;
    typeMap[tmpl.TYPE_COMMENT] = COMMENT;

    BaseContext = module.at_base_context = function(ext){
      if (ext)
        for (var key in ext)
          this[key] = ext[key];
    };
    BaseContext.prototype = {
      version: module.DECLARATION_VERSION || 1,
      hasBindings: function(token){
        return !!token[tmpl.TOKEN_BINDINGS];
      },
      getAttrs: function(token){
        return (token[tmpl.TOKEN_TYPE] == tmpl.TYPE_ELEMENT && token[tmpl.ELEMENT_ATTRS]) || [];
      },
      getChildren: function(token){
        return (token[tmpl.TOKEN_TYPE] == tmpl.TYPE_ELEMENT && token[tmpl.ELEMENT_CHILDS]) || [];
      },
      tokenType: function(token){
        return typeMap[token[tmpl.TOKEN_TYPE]];
      },
      tokenName: function(token){
        switch (token[tmpl.TOKEN_TYPE])
        {
          case tmpl.TYPE_ELEMENT:
            return token[tmpl.ELEMENT_NAME];

          case tmpl.TYPE_ATTRIBUTE:
            return token[tmpl.ATTR_NAME];

          case 4:
            return 'class';

          case 5:
            return 'style';

          case 6:
            return 'event-' + token[1];

          default:
            return '#' + token[tmpl.TOKEN_TYPE];
        }
      },
      tokenValue: function(token, value){
        switch (token[tmpl.TOKEN_TYPE])
        {
          case tmpl.TYPE_ATTRIBUTE:
            if (arguments.length > 1)
              token[tmpl.ATTR_VALUE] = value;
            return token[tmpl.ATTR_VALUE] || '';

          case 4:
          case 5:
            if (arguments.length > 1)
              token[tmpl.ATTR_VALUE - 1] = value;
            return token[tmpl.ATTR_VALUE - 1] || '';

          case 6:
            if (arguments.length > 1)
              token[2] = value;
            return token[2] || token[1];

          case tmpl.TYPE_TEXT:
            if (arguments.length > 1)
              token[tmpl.TEXT_VALUE] = value;
            return token[tmpl.TEXT_VALUE];

          case tmpl.TYPE_COMMENT:
            if (arguments.length > 1)
              token[tmpl.COMMENT_VALUE] = value;
            return token[tmpl.COMMENT_VALUE];

          default:
            return '';
        }
      },
      walk: function(ast, handlers, parentToken, stIdx){
        for (var i = stIdx || 0, token; token = ast[i]; i++)
        {
          var tokenType = this.tokenType(token);
          var handler = handlers[tokenType];

          if (typeof handler == 'function')
            handler.call(this, token, parentToken);

          if (tokenType == ELEMENT)
          {
            switch (this.version)
            {
              case 1:
                var attrs = this.getAttrs(token);
                if (attrs)
                  this.walk(attrs, handlers, token);

                var children = this.getChildren(token);
                if (children)
                  this.walk(children, handlers, token);
                break;

              case 2:
              case 3:
                this.walk(token, handlers, token, 4);
                break;

              default:
                throw new Error('[ERROR] unsupported template declaration version: ' + this.version);
                process.exit(8);
            }
          }
        }
      },
      getBindingClassNames: function(binding){
        switch (this.version)
        {
          case 1:
          case 2:
            // unpredictable
            if (binding.length == 2 || binding[2] == -1)
              return false;

            if (binding.length == 3)
              // bool
              return [binding[0] + binding[1]];
            else
              // enum
              return binding[3].map(function(name){
                return binding[0] + name;
              });

          case 3:
            if (Array.isArray(binding[0]))
              return binding[0];

            // unpredictable
            if (!binding[2])
              return false;

            switch (binding[2])
            {
              case tmpl.CLASS_BINDING_BOOL:
                return [binding[0] + binding[3]];

              case tmpl.CLASS_BINDING_ENUM:
                return binding[5].map(function(name){
                  return binding[0] + name;
                });
              default:
                throw new Error('[ERROR] unknown binding type: ' + binding[2]);
            }

          default:
            throw new Error('[ERROR] unsupported version: ' + this.version);
        }
      },
      setBindingClassNames: function(binding, classes){
        switch (this.version)
        {
          case 1:
          case 2:
            switch (binding.length)
            {
              case 3: // bool
                binding[0] = '';
                binding[3] = Array.isArray(classes) ? classes[0] : classes;
                return;

              case 4: // enum
                binding[0] = '';
                binding[4] = Array.isArray(classes) ? classes : [classes];
                return;
            }
            break;

          case 3:
            binding[0] = Array.isArray(classes) ? classes : [classes];
            binding[3] = 0; // drop name as prefix overrided too
            break;

          default:
            throw new Error('[ERROR] unsupported version: ' + this.version);
        }
      }
    };
  }

  return new BaseContext(extContext);
}

function resolveContext(module, extContext){
  if (module && module.Template)
    return getContext(module, extContext);
  else
    throw new Error('[ERROR] basis.template module not found');
}

module.exports = {
  walk: function(ast, module, handlers, extContext){
    return resolveContext(module, extContext).walk(ast, handlers);
  },
  getBindingClassNames: function(module, token){
    return resolveContext(module).getBindingClassNames(token);
  },
  setBindingClassNames: function(module, token, classNames){
    return resolveContext(module).setBindingClassNames(token, classNames);
  },
  translate: function(ast){
    return JSON.stringify(ast);
  }
};
<commit_msg>better work with last version of basis.js template ast<commit_after>
var ELEMENT = 'tag';
var ATTRIBUTE = 'attr';
var TEXT = 'text';
var COMMENT = 'comment';

function getContext(module, extContext){
  var BaseContext = module.at_base_context;

  if (!BaseContext)
  {
    var tmpl = module;
    var ATTRIBUTES_AND_CHILDREN = tmpl.ELEMENT_ATTRIBUTES_AND_CHILDREN || tmpl.ELEMENT_ATTRS;
    var typeMap = {};
    typeMap[tmpl.TYPE_ELEMENT] = ELEMENT;
    typeMap[tmpl.TYPE_ATTRIBUTE] = ATTRIBUTE;
    typeMap[4] = ATTRIBUTE;
    typeMap[5] = ATTRIBUTE;
    typeMap[6] = ATTRIBUTE;
    typeMap[tmpl.TYPE_TEXT] = TEXT;
    typeMap[tmpl.TYPE_COMMENT] = COMMENT;

    BaseContext = module.at_base_context = function(ext){
      if (ext)
        for (var key in ext)
          this[key] = ext[key];
    };
    BaseContext.prototype = {
      version: module.DECLARATION_VERSION || 1,
      hasBindings: function(token){
        return !!token[tmpl.TOKEN_BINDINGS];
      },
      getAttrs: function(token){
        if (token[tmpl.TOKEN_TYPE] == tmpl.TYPE_ELEMENT)
          switch (this.version)
          {
            case 1:
              return token[tmpl.ELEMENT_ATTRS];

            case 2:
            case 3:
              return token.slice(ATTRIBUTES_AND_CHILDREN).filter(function(item){
                return typeMap[item[tmpl.TOKEN_TYPE]] == ATTRIBUTE;
              });

            default:
              throw new Error('[ERROR] unsupported template declaration version: ' + this.version);
              process.exit(8);
          }
      },
      getChildren: function(token){
        if (token[tmpl.TOKEN_TYPE] == tmpl.TYPE_ELEMENT)
          switch (this.version)
          {
            case 1:
              return token[tmpl.ELEMENT_CHILDS];

            case 2:
            case 3:
              return token.slice(ATTRIBUTES_AND_CHILDREN).filter(function(item){
                return typeMap[item[tmpl.TOKEN_TYPE]] != ATTRIBUTE;
              });

            default:
              throw new Error('[ERROR] unsupported template declaration version: ' + this.version);
              process.exit(8);
          }
      },
      tokenType: function(token){
        return typeMap[token[tmpl.TOKEN_TYPE]];
      },
      tokenName: function(token){
        switch (token[tmpl.TOKEN_TYPE])
        {
          case tmpl.TYPE_ELEMENT:
            return token[tmpl.ELEMENT_NAME];

          case tmpl.TYPE_ATTRIBUTE:
            return token[tmpl.ATTR_NAME];

          case 4:
            return 'class';

          case 5:
            return 'style';

          case 6:
            return 'event-' + token[1];

          default:
            return '#' + token[tmpl.TOKEN_TYPE];
        }
      },
      tokenValue: function(token, value){
        switch (token[tmpl.TOKEN_TYPE])
        {
          case tmpl.TYPE_ATTRIBUTE:
            if (arguments.length > 1)
              token[tmpl.ATTR_VALUE] = value;
            return token[tmpl.ATTR_VALUE] || '';

          case 4:
          case 5:
            if (arguments.length > 1)
              token[tmpl.ATTR_VALUE - 1] = value;
            return token[tmpl.ATTR_VALUE - 1] || '';

          case 6:
            if (arguments.length > 1)
              token[2] = value;
            return token[2] || token[1];

          case tmpl.TYPE_TEXT:
            if (arguments.length > 1)
              token[tmpl.TEXT_VALUE] = value;
            return token[tmpl.TEXT_VALUE];

          case tmpl.TYPE_COMMENT:
            if (arguments.length > 1)
              token[tmpl.COMMENT_VALUE] = value;
            return token[tmpl.COMMENT_VALUE];

          default:
            return '';
        }
      },
      walk: function(ast, handlers, parentToken, stIdx){
        for (var i = stIdx || 0, token; token = ast[i]; i++)
        {
          var tokenType = this.tokenType(token);
          var handler = handlers[tokenType];

          if (typeof handler == 'function')
            handler.call(this, token, parentToken);

          if (tokenType == ELEMENT)
          {
            switch (this.version)
            {
              case 1:
                var attrs = this.getAttrs(token);
                if (attrs)
                  this.walk(attrs, handlers, token);

                var children = this.getChildren(token);
                if (children)
                  this.walk(children, handlers, token);
                break;

              case 2:
              case 3:
                this.walk(token, handlers, token, ATTRIBUTES_AND_CHILDREN);
                break;

              default:
                throw new Error('[ERROR] unsupported template declaration version: ' + this.version);
                process.exit(8);
            }
          }
        }
      },
      getBindingClassNames: function(binding){
        switch (this.version)
        {
          case 1:
          case 2:
            // unpredictable
            if (binding.length == 2 || binding[2] == -1)
              return false;

            if (binding.length == 3)
              // bool
              return [binding[0] + binding[1]];
            else
              // enum
              return binding[3].map(function(name){
                return binding[0] + name;
              });

          case 3:
            if (Array.isArray(binding[0]))
              return binding[0];

            // unpredictable
            if (!binding[2])
              return false;

            switch (binding[2])
            {
              case tmpl.CLASS_BINDING_BOOL:
                return [binding[0] + binding[3]];

              case tmpl.CLASS_BINDING_ENUM:
                return binding[5].map(function(name){
                  return binding[0] + name;
                });
              default:
                throw new Error('[ERROR] unknown binding type: ' + binding[2]);
            }

          default:
            throw new Error('[ERROR] unsupported version: ' + this.version);
        }
      },
      setBindingClassNames: function(binding, classes){
        switch (this.version)
        {
          case 1:
          case 2:
            switch (binding.length)
            {
              case 3: // bool
                binding[0] = '';
                binding[3] = Array.isArray(classes) ? classes[0] : classes;
                return;

              case 4: // enum
                binding[0] = '';
                binding[4] = Array.isArray(classes) ? classes : [classes];
                return;
            }
            break;

          case 3:
            binding[0] = Array.isArray(classes) ? classes : [classes];
            binding[3] = 0; // drop name as prefix overrided too
            break;

          default:
            throw new Error('[ERROR] unsupported version: ' + this.version);
        }
      }
    };
  }

  return new BaseContext(extContext);
}

function resolveContext(module, extContext){
  if (module && module.Template)
    return getContext(module, extContext);
  else
    throw new Error('[ERROR] basis.template module not found');
}

module.exports = {
  walk: function(ast, module, handlers, extContext){
    return resolveContext(module, extContext).walk(ast, handlers);
  },
  getBindingClassNames: function(module, token){
    return resolveContext(module).getBindingClassNames(token);
  },
  setBindingClassNames: function(module, token, classNames){
    return resolveContext(module).setBindingClassNames(token, classNames);
  },
  translate: function(ast){
    return JSON.stringify(ast);
  }
};
<|endoftext|>


<commit_before>var REVERSE_CYCLE_HIGHLIGHTER_KEY_CODE = 68 //d
var CYCLE_HIGHLIGHTER_KEY_CODE = 70 //f
var RESET_HIGHLIGHTER_KEY_CODE = 82 //r
var SOLVE_UNIQUE_PAIRS_KEY_CODE = 83 //s

if(!has_run_before)
{
  var has_run_before = false
}

(function main()
{
  run_all_tests()
  if(!has_run_before)
    document.addEventListener("keyup", key_up, false)
  has_run_before = true

  reset_highlighter_index()
})()

function run_all_tests()
{
  test_get_number()
  test_get_neighbors_count()
  console.log("All tests passed")
}

function test_get_number()
{
  const board = [
    [1, 2],
    [3, 4]
  ]
  assert(1 == get_number(board, 0, 0))
  assert(2 == get_number(board, 1, 0))
  assert(3 == get_number(board, 0, 1))
  assert(4 == get_number(board, 1, 1))
}

function test_get_neighbors_count()
{
  const board = [
    [0, 1, 2, 0],
    [1, 0, 1, 1],
    [1, 1, 0, 1]
  ]
  assert(0 == get_neighbors_count(board, 0, 0, 9))
  assert(1 == get_neighbors_count(board, 3, 0, 1))
  assert(2 == get_neighbors_count(board, 0, 0, 1))
  assert(3 == get_neighbors_count(board, 2, 2, 1))
  assert(4 == get_neighbors_count(board, 1, 1, 1))
}

function get_highlighter_select(left_or_right)
{
  let name = (left_or_right === "left") ? "selectNumber" : "selectNumberG"
  return document.getElementById(name)
}

function key_up(event)
{
  if(event.keyCode == CYCLE_HIGHLIGHTER_KEY_CODE)
  {
    cycle_highlighter()
  }
  else if(event.keyCode == REVERSE_CYCLE_HIGHLIGHTER_KEY_CODE)
  {
    reverse_cycle_highlighter()
  }
  else if(event.keyCode == RESET_HIGHLIGHTER_KEY_CODE)
  {
    reset_highlighter_index()
  }
  else if(event.keyCode == SOLVE_UNIQUE_PAIRS_KEY_CODE)
  {
    solve_unique_pair()
  }
}

function get_max_highlighter_index(left_or_right)
{
  const left_highlighter_select = get_highlighter_select("left")
  const index_of_max_number = left_highlighter_select.length - 1
  return (left_or_right === "left") ? index_of_max_number - 1 : index_of_max_number
}

function get_min_highlighter_index(left_or_right)
{
  return (left_or_right === "left") ? 1 : 2
}

function get_min_number(board)
{
  return 0
}

function get_max_number(board)
{
  return board.length- 1
}

function cycle_highlighter()
{
  console.log("Incrementing the highlighter")

  if(!is_every_highlighter_indexes_valid())
  {
    reset_highlighter_index()
    return
  }

  let left = get_highlighter_select("left")
  let right = get_highlighter_select("right")

  right.selectedIndex++
  if(!is_valid_highlighter_index("right"))
  {
    left.selectedIndex++
    if(!is_valid_highlighter_index("left"))
    {
      reset_highlighter_index()
    }
    right.selectedIndex = left.selectedIndex + 1
  }
  highlightNumber()
}

function reverse_cycle_highlighter()
{
  console.log("Decrementing the highlighter")

  if(!is_every_highlighter_indexes_valid())
  {
    reset_highlighter_index()
    return
  }

  let left = get_highlighter_select("left")
  let right = get_highlighter_select("right")

  right.selectedIndex--
  if(!is_valid_highlighter_index("right") || right.selectedIndex <= left.selectedIndex)
  {
    left.selectedIndex--
    if(!is_valid_highlighter_index("left"))
    {
      left.selectedIndex = get_max_highlighter_index("left")
      right.selectedIndex = get_max_highlighter_index("right")
    }
    right.selectedIndex = get_max_highlighter_index("right")
  }
  highlightNumber()
}

function is_valid_highlighter_index(left_or_right)
{
  const index = get_highlighter_select(left_or_right).selectedIndex
  const min = get_min_highlighter_index(left_or_right)
  const max = get_max_highlighter_index(left_or_right)
  return (min <= index) && (index <= max)
}

function is_every_highlighter_indexes_valid()
{
  const left_index = get_highlighter_select("left").selectedIndex
  const right_index = get_highlighter_select("right").selectedIndex
  return is_valid_highlighter_index("left") && is_valid_highlighter_index("right") && (right_index > left_index )
}

function reset_highlighter_index()
{
  console.log("Resetting the highlighter")

  get_highlighter_select("left").selectedIndex = get_min_highlighter_index("left")
  get_highlighter_select("right").selectedIndex = get_min_highlighter_index("right")
  highlightNumber()
}

function solve_unique_pair()
{
  console.log("Solving unique pairs")
}

function get_neighbors_count(board, x, y, b)
{
  const min_x = 0
  const min_y = 0
  const max_x = board.length
  const max_y = board.length - 1
  let count = 0
  if (x > min_x && get_number(board, x - 1, y) == b) count++
  if (x < max_x && get_number(board, x + 1, y) == b) count++
  if (y > min_y && get_number(board, x, y - 1) == b) count++
  if (y < max_y && get_number(board, x, y + 1) == b) count++
  return count
}

function get_number(board, x, y)
{
  return board[y][x]
}

function get_html_board()
{
  return document.getElementById("DominosaTable")
}

function get_board(html_board)
{
  const html_tbody = html_board.getElementsByTagName("tbody")[0]
  const html_rows = html_tbody.getElementsByTagName("tr")
  let board = []
  for(const html_row of html_rows)
  {
    const html_cells = html_row.getElementsByTagName("td")
    let row = []
    for(const html_cell of html_cells)
    {
      const number = parseInt(html_cell.getElementsByTagName("div")[0].getElementsByTagName("div")[0].innerText)
      row.push(number)
    }
    board.push(row)
  }
  return board
}

function place_domino(x1, y1, x2, y2)
{
  placeHelper(x1, y1, x2, y2)
  removeHelper()
  placePiece()
}

/////////////
// Utility //
/////////////

function assert(condition, message)
{
  if(!condition)
  {
    alert(message)
  }
}
<commit_msg>Count the number of pairs with the numbers A and B<commit_after>var REVERSE_CYCLE_HIGHLIGHTER_KEY_CODE = 68 //d
var CYCLE_HIGHLIGHTER_KEY_CODE = 70 //f
var RESET_HIGHLIGHTER_KEY_CODE = 82 //r
var SOLVE_UNIQUE_PAIRS_KEY_CODE = 83 //s

if(!has_run_before)
{
  var has_run_before = false
}

(function main()
{
  run_all_tests()
  if(!has_run_before)
    document.addEventListener("keyup", key_up, false)
  has_run_before = true

  reset_highlighter_index()
})()

function run_all_tests()
{
  test_get_number()
  test_get_neighbors_count()
  test_get_pairs_count()
  console.log("All tests passed")
}

function test_get_number()
{
  const board = [
    [1, 2],
    [3, 4]
  ]
  assert(1 == get_number(board, 0, 0))
  assert(2 == get_number(board, 1, 0))
  assert(3 == get_number(board, 0, 1))
  assert(4 == get_number(board, 1, 1))
}

function test_get_neighbors_count()
{
  const board = [
    [0, 1, 2, 0],
    [1, 0, 1, 1],
    [1, 1, 0, 1]
  ]
  assert(0 == get_neighbors_count(board, 0, 0, 9))
  assert(1 == get_neighbors_count(board, 3, 0, 1))
  assert(2 == get_neighbors_count(board, 0, 0, 1))
  assert(3 == get_neighbors_count(board, 2, 2, 1))
  assert(4 == get_neighbors_count(board, 1, 1, 1))
}

function test_get_pairs_count()
{
  const board_0_pairs_of_0_1 = [
    [0, 2],
    [2, 0]
  ]
  const board_1_pairs_of_0_1 = [
    [0, 1],
    [0, 2]
  ]
  const board_2_pairs_of_0_1 = [
    [0, 1],
    [0, 0]
  ]
  const board_0_pairs_of_1_1 = [
    [0, 1],
    [2, 3]
  ]
  const board_1_pairs_of_1_1 = [
    [0, 1],
    [2, 1]
  ]
  const board_2_pairs_of_1_1 = [
    [0, 1],
    [1, 1]
  ]
  const board_4_pairs_of_1_1 = [
    [1, 1],
    [1, 1]
  ]
  assert(0 == get_pairs_count(board_0_pairs_of_0_1, 0, 1))
  assert(1 == get_pairs_count(board_1_pairs_of_0_1, 0, 1))
  assert(2 == get_pairs_count(board_2_pairs_of_0_1, 0, 1))
  assert(0 == get_pairs_count(board_0_pairs_of_1_1, 1, 1))
  assert(1 == get_pairs_count(board_1_pairs_of_1_1, 1, 1))
  assert(2 == get_pairs_count(board_2_pairs_of_1_1, 1, 1))
  assert(4 == get_pairs_count(board_4_pairs_of_1_1, 1, 1))
}

function get_highlighter_select(left_or_right)
{
  let name = (left_or_right === "left") ? "selectNumber" : "selectNumberG"
  return document.getElementById(name)
}

function key_up(event)
{
  if(event.keyCode == CYCLE_HIGHLIGHTER_KEY_CODE)
  {
    cycle_highlighter()
  }
  else if(event.keyCode == REVERSE_CYCLE_HIGHLIGHTER_KEY_CODE)
  {
    reverse_cycle_highlighter()
  }
  else if(event.keyCode == RESET_HIGHLIGHTER_KEY_CODE)
  {
    reset_highlighter_index()
  }
  else if(event.keyCode == SOLVE_UNIQUE_PAIRS_KEY_CODE)
  {
    solve_unique_pair()
  }
}

function get_max_highlighter_index(left_or_right)
{
  const left_highlighter_select = get_highlighter_select("left")
  const index_of_max_number = left_highlighter_select.length - 1
  return (left_or_right === "left") ? index_of_max_number - 1 : index_of_max_number
}

function get_min_highlighter_index(left_or_right)
{
  return (left_or_right === "left") ? 1 : 2
}

function get_min_number(board)
{
  return 0
}

function get_max_number(board)
{
  return board.length- 1
}

function cycle_highlighter()
{
  console.log("Incrementing the highlighter")

  if(!is_every_highlighter_indexes_valid())
  {
    reset_highlighter_index()
    return
  }

  let left = get_highlighter_select("left")
  let right = get_highlighter_select("right")

  right.selectedIndex++
  if(!is_valid_highlighter_index("right"))
  {
    left.selectedIndex++
    if(!is_valid_highlighter_index("left"))
    {
      reset_highlighter_index()
    }
    right.selectedIndex = left.selectedIndex + 1
  }
  highlightNumber()
}

function reverse_cycle_highlighter()
{
  console.log("Decrementing the highlighter")

  if(!is_every_highlighter_indexes_valid())
  {
    reset_highlighter_index()
    return
  }

  let left = get_highlighter_select("left")
  let right = get_highlighter_select("right")

  right.selectedIndex--
  if(!is_valid_highlighter_index("right") || right.selectedIndex <= left.selectedIndex)
  {
    left.selectedIndex--
    if(!is_valid_highlighter_index("left"))
    {
      left.selectedIndex = get_max_highlighter_index("left")
      right.selectedIndex = get_max_highlighter_index("right")
    }
    right.selectedIndex = get_max_highlighter_index("right")
  }
  highlightNumber()
}

function is_valid_highlighter_index(left_or_right)
{
  const index = get_highlighter_select(left_or_right).selectedIndex
  const min = get_min_highlighter_index(left_or_right)
  const max = get_max_highlighter_index(left_or_right)
  return (min <= index) && (index <= max)
}

function is_every_highlighter_indexes_valid()
{
  const left_index = get_highlighter_select("left").selectedIndex
  const right_index = get_highlighter_select("right").selectedIndex
  return is_valid_highlighter_index("left") && is_valid_highlighter_index("right") && (right_index > left_index )
}

function reset_highlighter_index()
{
  console.log("Resetting the highlighter")

  get_highlighter_select("left").selectedIndex = get_min_highlighter_index("left")
  get_highlighter_select("right").selectedIndex = get_min_highlighter_index("right")
  highlightNumber()
}

function solve_unique_pair()
{
  console.log("Solving unique pairs")
}

function get_pairs_count(board, a, b)
{
  let count = 0
  for(let y = 0; y < board.length; y++)
  {
    const row = board[y]
    for(let x = 0; x < row.length; x++)
    {
      const number = get_number(board, x, y)
      if(number == a)
      {
        count += get_neighbors_count(board, x, y, b)
      }
    }
  }
  if(a == b)
  {
    count /= 2
  }
  return count
}

function get_neighbors_count(board, x, y, b)
{
  const min_x = 0
  const min_y = 0
  const max_x = board.length
  const max_y = board.length - 1
  let count = 0
  if (x > min_x && get_number(board, x - 1, y) == b) count++
  if (x < max_x && get_number(board, x + 1, y) == b) count++
  if (y > min_y && get_number(board, x, y - 1) == b) count++
  if (y < max_y && get_number(board, x, y + 1) == b) count++
  return count
}

function get_number(board, x, y)
{
  return board[y][x]
}

function get_html_board()
{
  return document.getElementById("DominosaTable")
}

function get_board(html_board)
{
  const html_tbody = html_board.getElementsByTagName("tbody")[0]
  const html_rows = html_tbody.getElementsByTagName("tr")
  let board = []
  for(const html_row of html_rows)
  {
    const html_cells = html_row.getElementsByTagName("td")
    let row = []
    for(const html_cell of html_cells)
    {
      const number = parseInt(html_cell.getElementsByTagName("div")[0].getElementsByTagName("div")[0].innerText)
      row.push(number)
    }
    board.push(row)
  }
  return board
}

function place_domino(x1, y1, x2, y2)
{
  placeHelper(x1, y1, x2, y2)
  removeHelper()
  placePiece()
}

/////////////
// Utility //
/////////////

function assert(condition, message)
{
  if(!condition)
  {
    alert(message)
  }
}
<|endoftext|>


<commit_before>var is_cl = false;
var time = 5000;
var intervalId;

function startBgRotate() {
	//return;
	is_cl && console.log('startBgRotate');
	$('#background_cycler_I').css('opacity', 0);
	$('#background_cycler_I').fadeTo( "slow" , 1, function() {
		// Animation complete.
		$('#background_cycler_I').fadeIn(1500);
		intervalId = setInterval(function(){cycleImagesI_()}, time);
	});
}

function stopBgRotate() {is_cl && console.log('stopColor', intervalId);
	clearInterval(intervalId);
}
function changeBgRotate(index) {
	is_cl && console.log('changeBgRotate', index);
	stopBgRotate();
	$('#background_cycler_I .active').css('z-index', '1');
	$('#background_cycler_I .active').removeClass('active');
	$('#mob_img_box_I .active').removeClass('active');
	$('#background_cycler_I img:eq(' + index + ')').addClass('active').css('z-index', '2');
	$('#mob_img_box_I img:eq(' + index + ')').addClass('active');
	startBgRotate();
}
function cycleImagesI_() {
    cycleImagesI_Action('background_cycler_I');
    cycleImagesI_Action('mob_img_box_I');
}
function cycleImagesI_Action(id) {
	is_cl && console.log('cycleImagesI_Action', id);
    var $active = $('#' + id + ' .active');
    var $next = ($('#' + id + ' .active').next().length > 0) ? $('#' + id + ' .active').next() : $('#' + id + ' img:first');
    $next.css('z-index', 2);//move the next image up the pile
    $active.fadeOut(1500, function() {//fade out the top image
        $active.css('z-index', 1).show().removeClass('active');//reset the z-index and unhide the image
        $next.css('z-index', 3).addClass('active');//make the next image the top one
    });
}

function loadAndReplaceContent(id, url, callback) {
    is_cl && console.log('loadAndReplaceContent', id, url);
    //$( "#" +id ).load( url, function( response, status, xhr ) {
    //    if ( status == "error" ) {
    //        var msg = "Sorry but there was an error: ";
    //        $("#error").html(msg + xhr.status + " " + xhr.statusText);
    //    }
    //    $("#" + id).replaceWith(response);
    //    callback()
    //});

    $.ajax({
        url: url,
        cache: false,
        dataType: "html",
        success: function(response) {
            $("#" + id).replaceWith(response);
			callback && callback();
        }
    });

}

var loadPage = (function ($) {
    var jQuery = $;
    var my = {},
        privateVariable = 1,
        is_mobile = window.innerWidth < 768;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
        //privateMethod();
    };

    function loadNav(func) {
        loadAndReplaceContent('nav', '__ajax/i/i_nav.html', function() {
            $("a.kep img.kep").hover(function (i) {//is_cl && console.log(i + 'hover');
                $(this).attr("src", $(this).attr("src").replace('normal', 'hover'));
            }, function (i) {//is_cl && console.log(i + 'hover e');
                $(this).attr("src", $(this).attr("src").replace('hover', 'normal'));
            });
			func && func();
        });
    }

    function loadBg() {
        loadAndReplaceContent('background_cycler_box', '__ajax/i/i_bg.html', function(){

			startBgRotate();

        });
    }

    function loadFooter(func) {
        loadAndReplaceContent('footer', '__ajax/i/i_footer.html', function(){
            $('.c_body').css('min-height', (window.innerHeight - 95) + 'px');
			func && func();
        });
    }

    function loadContent(ajax, callback) {
        ajax = ajax || '__ajax/i/i_content_home.html';
        loadAndReplaceContent('content', ajax, callback);
    }

    my.home = function() {
        loadNav(function(){
            $('.navbar').addClass('navbar-fixed-top')
        });
        loadBg();
        loadContent(undefined, function() {
            is_mobile && $('section.bc_b06').css('margin-top', (Math.round(window.innerWidth * 0.5625) - 65) + 'px');
        });
        loadFooter(function(){
            // $('footer.bc_b06').css('position', 'fixed');
            is_mobile && $('footer').css('margin-top', '6em');
        });
    };

    my.about = function() {
		loadPage.body_bg('#1F5D68 url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_about.jpg")' +
		' no-repeat fixed center 3.5em / cover');
        loadNav();
        //loadBg();
        loadContent('__ajax/i/i_content_about2.html');
        loadFooter();
    };

    my.first_season = function() {
		loadPage.body_bg('#1A4168 url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_first_season.jpg")' +
			' no-repeat  fixed center 3.5em ');
        loadNav();
        //loadBg();
        loadContent('__ajax/i/i_content_first_season2.html');
        loadFooter();
    };

    my.terms = function() {
        $('body').css('background', 'rgba(0, 0, 0, 0) url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/'+
             'tv5_comp_lp/homepage/background.jpg") no-repeat fixed center center / cover ');
        loadNav();
        //loadBg();
        loadContent('__ajax/i/i_content_terms.html');
        loadFooter();
    };

    my.privacy = function() {
        $('body').css('background', 'rgba(0, 0, 0, 0) url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/'+
             'tv5_comp_lp/homepage/background.jpg") no-repeat fixed center center / cover ');
        loadNav();
        //loadBg();
        loadContent('__ajax/i/i_content_privacy.html');
        loadFooter();
    };

    my.press = function() {
		loadPage.body_bg('#fff url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_press_2.jpg")' +
			' no-repeat fixed center top / cover');
			//' no-repeat  top center fixed');
        loadNav();
        //loadBg();
        loadContent('__ajax/i/i_content_press2.html');
        loadFooter();
    };

    my.contact = function() {
        loadNav();
        loadBg();
        loadContent('__ajax/i/i_content_contact.html');
        loadFooter();
    };

	my.app = function() {
		loadPage.body_bg('#ECEFDC url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_mob_app.jpg")' +
		' no-repeat  fixed center 3.5em ');
		loadNav();
		//loadBg();
		loadContent('__ajax/i/i_content_app.html');
		loadFooter();
	};

	my.app2 = function() {
		loadPage.body_bg('#fff url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_mob_app2.jpg")' +
		' no-repeat  fixed center 3.5em ');
		loadNav();
		//loadBg();
		loadContent('__ajax/i/i_content_app2.html');
		loadFooter();
	};

	my.app3 = function() {
		loadPage.body_bg('#fff url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_mob_app2.jpg")' +
		' no-repeat  fixed center 3.5em ');
		loadNav();
		//loadBg();
		loadContent('__ajax/i/i_content_app3.html');
		loadFooter();
	};

    my.body_bg = function(value) {
		$('body').css('background', value);
    };

    return my;
}(jQuery));

function validateEmail(email) {
	var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return re.test(email);
}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    //is_cl && console.log('Query Variable ' + variable + ' not found');
}

//$(document).ready(function () {

    //loadimg();

    var file = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
    is_cl && console.log(file);

    if (file.indexOf('i_about') != -1 || getQueryVariable('go') == 'about') {
        loadPage.about();
    }
    else if (file.indexOf('contact') != -1 || getQueryVariable('go') == 'contact') {
        loadPage.contact();
    }
    else if (file.indexOf('first_season') != -1 || getQueryVariable('go') == 'first_season') {
        loadPage.first_season();
    }
    else if (file.indexOf('term') != -1 || getQueryVariable('go') == 'terms') {
        loadPage.terms();
    }
    else if (file.indexOf('privacy') != -1 || getQueryVariable('go') == 'privacy') {
        loadPage.privacy();
    }
    else if (file.indexOf('press') != -1 || getQueryVariable('go') == 'press') {
        loadPage.press();
    }
	else if (file.indexOf('app2') != -1 || getQueryVariable('go') == 'app2') {
        loadPage.app2();
    }
	else if (file.indexOf('app3') != -1 || getQueryVariable('go') == 'app3') {
        loadPage.app3();
    }
	else if (file.indexOf('app') != -1 || getQueryVariable('go') == 'app') {
        loadPage.app();
    }
    else {

        loadPage.home();
    }

//});<commit_msg>Anna és anikó kért módosításainak végrehajtása<commit_after>var is_cl = false;
var time = 5000;
var intervalId;

function startBgRotate() {
	//return;
	is_cl && console.log('startBgRotate');
	$('#background_cycler_I').css('opacity', 0);
	$('#background_cycler_I').fadeTo( "slow" , 1, function() {
		// Animation complete.
		$('#background_cycler_I').fadeIn(1500);
		intervalId = setInterval(function(){cycleImagesI_()}, time);
	});
}

function stopBgRotate() {is_cl && console.log('stopColor', intervalId);
	clearInterval(intervalId);
}
function changeBgRotate(index) {
	is_cl && console.log('changeBgRotate', index);
	stopBgRotate();
	$('#background_cycler_I .active').css('z-index', '1');
	$('#background_cycler_I .active').removeClass('active');
	$('#mob_img_box_I .active').removeClass('active');
	$('#background_cycler_I img:eq(' + index + ')').addClass('active').css('z-index', '2');
	$('#mob_img_box_I img:eq(' + index + ')').addClass('active');
	startBgRotate();
}
function cycleImagesI_() {
    cycleImagesI_Action('background_cycler_I');
    cycleImagesI_Action('mob_img_box_I');
}
function cycleImagesI_Action(id) {
	is_cl && console.log('cycleImagesI_Action', id);
    var $active = $('#' + id + ' .active');
    var $next = ($('#' + id + ' .active').next().length > 0) ? $('#' + id + ' .active').next() : $('#' + id + ' img:first');
    $next.css('z-index', 2);//move the next image up the pile
    $active.fadeOut(1500, function() {//fade out the top image
        $active.css('z-index', 1).show().removeClass('active');//reset the z-index and unhide the image
        $next.css('z-index', 3).addClass('active');//make the next image the top one
    });
}

function loadAndReplaceContent(id, url, callback) {
    is_cl && console.log('loadAndReplaceContent', id, url);
    //$( "#" +id ).load( url, function( response, status, xhr ) {
    //    if ( status == "error" ) {
    //        var msg = "Sorry but there was an error: ";
    //        $("#error").html(msg + xhr.status + " " + xhr.statusText);
    //    }
    //    $("#" + id).replaceWith(response);
    //    callback()
    //});

    $.ajax({
        url: url,
        cache: false,
        dataType: "html",
        success: function(response) {
            $("#" + id).replaceWith(response);
			callback && callback();
        }
    });

}

var loadPage = (function ($) {
    var jQuery = $;
    var my = {},
        privateVariable = 1,
        is_mobile = window.innerWidth < 768;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
        //privateMethod();
    };

    function loadNav(func) {
        loadAndReplaceContent('nav', '__ajax/i/i_nav.html', function() {
            $("a.kep img.kep").hover(function (i) {//is_cl && console.log(i + 'hover');
                $(this).attr("src", $(this).attr("src").replace('normal', 'hover'));
            }, function (i) {//is_cl && console.log(i + 'hover e');
                $(this).attr("src", $(this).attr("src").replace('hover', 'normal'));
            });
			func && func();
        });
    }

    function loadBg() {
        loadAndReplaceContent('background_cycler_box', '__ajax/i/i_bg.html', function(){

			startBgRotate();

        });
    }

    function loadFooter(func) {
        loadAndReplaceContent('footer', '__ajax/i/i_footer.html', function(){
            $('.c_body').css('min-height', (window.innerHeight - 95) + 'px');
			func && func();
        });
    }

    function loadContent(ajax, callback) {
        ajax = ajax || '__ajax/i/i_content_home.html';
        loadAndReplaceContent('content', ajax, callback);
    }

    my.home = function() {
        loadNav(function(){
            $('.navbar').addClass('navbar-fixed-top')
        });
        loadBg();
        loadContent(undefined, function() {
            is_mobile && $('section.bc_b06').css('margin-top', (Math.round(window.innerWidth * 0.5625) - 65) + 'px');
        });
        loadFooter(function(){
            // $('footer.bc_b06').css('position', 'fixed');
            is_mobile && $('footer').css('margin-top', '6em');
        });
    };

    my.about = function() {
		loadPage.body_bg('#1F5D68 url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_about.jpg")' +
		' no-repeat fixed center 3.5em / cover');
        loadNav();
        //loadBg();
        loadContent('__ajax/i/i_content_about2.html');
        loadFooter();
    };

    my.first_season = function() {
		loadPage.body_bg('#1A4168 url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_first_season.jpg")' +
			' no-repeat  fixed center 3.5em ');
        loadNav();
        //loadBg();
        loadContent('__ajax/i/i_content_first_season2.html');
        loadFooter();
    };

    my.terms = function() {
        $('body').css('background', 'rgba(0, 0, 0, 0) url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/'+
             'tv5_comp_lp/homepage/background.jpg") no-repeat fixed center center / cover ');
        loadNav();
        //loadBg();
        loadContent('__ajax/i/i_content_terms.html');
        loadFooter();
    };

    my.privacy = function() {
        $('body').css('background', 'rgba(0, 0, 0, 0) url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/'+
             'tv5_comp_lp/homepage/background.jpg") no-repeat fixed center center / cover ');
        loadNav();
        //loadBg();
        loadContent('__ajax/i/i_content_privacy.html');
        loadFooter();
    };

    my.press = function() {
		loadPage.body_bg('#fff url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_press.jpg")' +
			' no-repeat fixed center top / cover');
			//' no-repeat  top center fixed');
        loadNav();
        //loadBg();
        loadContent('__ajax/i/i_content_press2.html');
        loadFooter();
    };

    my.contact = function() {
        loadNav();
        loadBg();
        loadContent('__ajax/i/i_content_contact.html');
        loadFooter();
    };

	my.app = function() {
		loadPage.body_bg('#ECEFDC url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_mob_app.jpg")' +
		' no-repeat  fixed center 3.5em ');
		loadNav();
		//loadBg();
		loadContent('__ajax/i/i_content_app.html');
		loadFooter();
	};

	my.app2 = function() {
		loadPage.body_bg('#fff url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_mob_app2.jpg")' +
		' no-repeat  fixed center 3.5em ');
		loadNav();
		//loadBg();
		loadContent('__ajax/i/i_content_app2.html');
		loadFooter();
	};

	my.app3 = function() {
		loadPage.body_bg('#fff url("http://73adc0e8ebac205046b3-f166d868b29010bc304fe7760b66a9b0.r88.cf1.rackcdn.com/img/backgrounds/bg_mob_app2.jpg")' +
		' no-repeat  fixed center 3.5em ');
		loadNav();
		//loadBg();
		loadContent('__ajax/i/i_content_app3.html');
		loadFooter();
	};

    my.body_bg = function(value) {
		$('body').css('background', value);
    };

    return my;
}(jQuery));

function validateEmail(email) {
	var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return re.test(email);
}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    //is_cl && console.log('Query Variable ' + variable + ' not found');
}

//$(document).ready(function () {

    //loadimg();

    var file = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
    is_cl && console.log(file);

    if (file.indexOf('i_about') != -1 || getQueryVariable('go') == 'about') {
        loadPage.about();
    }
    else if (file.indexOf('contact') != -1 || getQueryVariable('go') == 'contact') {
        loadPage.contact();
    }
    else if (file.indexOf('first_season') != -1 || getQueryVariable('go') == 'first_season') {
        loadPage.first_season();
    }
    else if (file.indexOf('term') != -1 || getQueryVariable('go') == 'terms') {
        loadPage.terms();
    }
    else if (file.indexOf('privacy') != -1 || getQueryVariable('go') == 'privacy') {
        loadPage.privacy();
    }
    else if (file.indexOf('press') != -1 || getQueryVariable('go') == 'press') {
        loadPage.press();
    }
	else if (file.indexOf('app2') != -1 || getQueryVariable('go') == 'app2') {
        loadPage.app2();
    }
	else if (file.indexOf('app3') != -1 || getQueryVariable('go') == 'app3') {
        loadPage.app3();
    }
	else if (file.indexOf('app') != -1 || getQueryVariable('go') == 'app') {
        loadPage.app();
    }
    else {

        loadPage.home();
    }

//});<|endoftext|>


<commit_before>/* Copyright 2012 The Go Authors.   All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
'use strict';

/* Controllers */

angular.module('tour.controllers', []).

// Navigation controller
controller('EditorCtrl', ['$scope', '$routeParams', '$location', 'toc', 'i18n', 'run', 'fmt', 'editor', 'analytics', 'storage',
    function($scope, $routeParams, $location, toc, i18n, run, fmt, editor, analytics, storage) {
        var lessons = [];
        toc.lessons.then(function(v) {
            lessons = v;
            $scope.gotoPage($scope.curPage);

            // Store changes on the current file to local storage.
            $scope.$watch(function() {
                var f = file();
                return f && f.Content;
            }, function(val) {
                if (val) storage.set(file().Hash, val);
            });
        });

        $scope.toc = toc;
        $scope.lessonId = $routeParams.lessonId;
        $scope.curPage = parseInt($routeParams.pageNumber);
        $scope.curFile = 0;
        $scope.job = null;

        $scope.nextPageClick = function(event) {
            event.preventDefault();
            $scope.nextPage();
        };
        $scope.prevPageClick = function(event) {
            event.preventDefault();
            $scope.prevPage();
        };
        $scope.nextPage = function() {
            $scope.gotoPage($scope.curPage + 1);
        };
        $scope.prevPage = function() {
            $scope.gotoPage($scope.curPage - 1);
        };
        $scope.gotoPage = function(page) {
            var l = $routeParams.lessonId;
            if (page >= 1 && page <= lessons[$scope.lessonId].Pages.length) {
                $scope.curPage = page;
            } else {
                l = (page < 1) ? toc.prevLesson(l) : toc.nextLesson(l);
                if (l === '') { // If there's not previous or next
                    $location.path('/list');
                    return;
                }
                page = (page < 1) ? lessons[l].Pages.length : 1;
            }
            $location.path('/' + l + '/' + page);
            $scope.openFile($scope.curFile);
            analytics.trackView();
        };
        $scope.openFile = function(file) {
            $scope.curFile = file;
            editor.paint();
        };

        function log(mode, text) {
            $('.output.active').html('
' + text + '
');
        }

        function clearOutput() {
            $('.output.active').html('');
        }

        function file() {
            return lessons[$scope.lessonId].Pages[$scope.curPage - 1].Files[$scope.curFile];
        }

        $scope.run = function() {
            log('info', i18n.l('waiting'));
            var f = file();
            $scope.job = run(f.Content, $('.output.active > pre')[0], {
                path: f.Name
            }, function() {
                $scope.job = null;
                $scope.$apply();
            });
        };

        $scope.kill = function() {
            if ($scope.job !== null) $scope.job.Kill();
        };

        $scope.format = function() {
            log('info', i18n.l('waiting'));
            fmt(file().Content, editor.imports).then(
                function(data) {
                    if (data.data.Error !== '') {
                        log('stderr', data.data.Error);
                        return;
                    }
                    clearOutput();
                    file().Content = data.data.Body;
                },
                function(error) {
                    log('stderr', error);
                });
        };

        $scope.reset = function() {
            file().Content = file().OrigContent;
        };
    }
]);
<commit_msg>tour: kill running code snippets when changing page<commit_after>/* Copyright 2012 The Go Authors.   All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
'use strict';

/* Controllers */

angular.module('tour.controllers', []).

// Navigation controller
controller('EditorCtrl', ['$scope', '$routeParams', '$location', 'toc', 'i18n', 'run', 'fmt', 'editor', 'analytics', 'storage',
    function($scope, $routeParams, $location, toc, i18n, run, fmt, editor, analytics, storage) {
        var lessons = [];
        toc.lessons.then(function(v) {
            lessons = v;
            $scope.gotoPage($scope.curPage);

            // Store changes on the current file to local storage.
            $scope.$watch(function() {
                var f = file();
                return f && f.Content;
            }, function(val) {
                if (val) storage.set(file().Hash, val);
            });
        });

        $scope.toc = toc;
        $scope.lessonId = $routeParams.lessonId;
        $scope.curPage = parseInt($routeParams.pageNumber);
        $scope.curFile = 0;
        $scope.job = null;

        $scope.nextPageClick = function(event) {
            event.preventDefault();
            $scope.nextPage();
        };
        $scope.prevPageClick = function(event) {
            event.preventDefault();
            $scope.prevPage();
        };
        $scope.nextPage = function() {
            $scope.gotoPage($scope.curPage + 1);
        };
        $scope.prevPage = function() {
            $scope.gotoPage($scope.curPage - 1);
        };
        $scope.gotoPage = function(page) {
            $scope.kill();
            var l = $routeParams.lessonId;
            if (page >= 1 && page <= lessons[$scope.lessonId].Pages.length) {
                $scope.curPage = page;
            } else {
                l = (page < 1) ? toc.prevLesson(l) : toc.nextLesson(l);
                if (l === '') { // If there's not previous or next
                    $location.path('/list');
                    return;
                }
                page = (page < 1) ? lessons[l].Pages.length : 1;
            }
            $location.path('/' + l + '/' + page);
            $scope.openFile($scope.curFile);
            analytics.trackView();
        };
        $scope.openFile = function(file) {
            $scope.curFile = file;
            editor.paint();
        };

        function log(mode, text) {
            $('.output.active').html('
' + text + '
');
        }

        function clearOutput() {
            $('.output.active').html('');
        }

        function file() {
            return lessons[$scope.lessonId].Pages[$scope.curPage - 1].Files[$scope.curFile];
        }

        $scope.run = function() {
            log('info', i18n.l('waiting'));
            var f = file();
            $scope.job = run(f.Content, $('.output.active > pre')[0], {
                path: f.Name
            }, function() {
                $scope.job = null;
                $scope.$apply();
            });
        };

        $scope.kill = function() {
            if ($scope.job !== null) $scope.job.Kill();
        };

        $scope.format = function() {
            log('info', i18n.l('waiting'));
            fmt(file().Content, editor.imports).then(
                function(data) {
                    if (data.data.Error !== '') {
                        log('stderr', data.data.Error);
                        return;
                    }
                    clearOutput();
                    file().Content = data.data.Body;
                },
                function(error) {
                    log('stderr', error);
                });
        };

        $scope.reset = function() {
            file().Content = file().OrigContent;
        };
    }
]);
<|endoftext|>


<commit_before>'use strict';

import Component from './Component'
import CommandManager from './CommandManager'
import SurfaceManager from './SurfaceManager'
import MacroManager from './MacroManager'
import GlobalEventHandler from './GlobalEventHandler'
import DragManager from './DragManager'

function AbstractEditor() {
  AbstractEditor.super.apply(this, arguments);
  this._initialize(this.props);
}

AbstractEditor.Prototype = function() {

  this.didMount = function() {
    this.documentSession.on('didUpdate', this._documentSessionUpdated, this);
  };

  this.willReceiveProps = function(nextProps) {
    var newSession = nextProps.documentSession;
    var shouldDispose = newSession && newSession !== this.documentSession;
    if (shouldDispose) {
      this._dispose();
      this._initialize(nextProps);
    }
  };

  this.dispose = function() {
    this._dispose();
  };

  this._dispose = function() {
    this.surfaceManager.dispose();
    this.commandManager.dispose();
    this.globalEventHandler.dispose();
    this.dragManager.dispose();
    this.documentSession.off(this);
    // Note: we need to clear everything, as the childContext
    // changes which is immutable
    this.empty();
  };

  this.getChildContext = function() {
    return {
      controller: this,
      iconProvider: this.iconProvider,
      documentSession: this.documentSession,
      doc: this.doc, // TODO: remove in favor of documentSession
      componentRegistry: this.componentRegistry,
      surfaceManager: this.surfaceManager,
      commandManager: this.commandManager,
      tools: this.tools,
      labelProvider: this.labelProvider,
      converterRegistry: this.converterRegistry,
      globalEventHandler: this.globalEventHandler,
      editingBehavior: this.editingBehavior,
      dragManager: this.dragManager,
    };
  };

  this._initialize = function(props) {
    var configurator = props.configurator;
    var commands = configurator.getCommands();
    if (!props.documentSession) {
      throw new Error('DocumentSession instance required');
    }
    this.documentSession = props.documentSession;
    this.doc = this.documentSession.getDocument();
    this.saveHandler = configurator.getSaveHandler();
    this.documentSession.setSaveHandler(this.saveHandler);
    this.componentRegistry = configurator.getComponentRegistry();
    this.tools = configurator.getTools();
    this.surfaceManager = new SurfaceManager(this.documentSession);
    this.fileClient = configurator.getFileClient();
    this.commandManager = new CommandManager(this.getCommandContext(), commands);
    this.dragManager = new DragManager(configurator.createDragHandlers(), {
      documentSession: this.documentSession,
      surfaceManager: this.surfaceManager,
      commandManager: this.commandManager,
    });
    this.macroManager = new MacroManager(this.getMacroContext(), configurator.getMacros());
    this.iconProvider = configurator.getIconProvider();
    this.converterRegistry = configurator.getConverterRegistry();
    this.globalEventHandler = new GlobalEventHandler(this.documentSession, this.surfaceManager);
    this.editingBehavior = configurator.getEditingBehavior();
    this.labelProvider = configurator.getLabelProvider();
  };

  this.getCommandContext = function() {
    return {
      documentSession: this.documentSession,
      surfaceManager: this.surfaceManager,
      fileClient: this.fileClient,
      saveHandler: this.saveHandler,
      converterRegistry: this.converterRegistry
    };
  };

  this.getMacroContext = function() {
    return {
      documentSession: this.documentSession,
      surfaceManager: this.surfaceManager
    };
  };

  this.getToolbar = function() {
    throw new Error('This method is abstract.');
  };

  this._documentSessionUpdated = function() {
    var toolbar = this.getToolbar();
    if (toolbar) {
      var commandStates = this.commandManager.getCommandStates();
      toolbar.setProps({
        commandStates: commandStates
      });
    }
  };
};

Component.extend(AbstractEditor);

export default AbstractEditor;
<commit_msg>ES6 AbstractEditor.<commit_after>import Component from './Component'
import CommandManager from './CommandManager'
import SurfaceManager from './SurfaceManager'
import MacroManager from './MacroManager'
import GlobalEventHandler from './GlobalEventHandler'
import DragManager from './DragManager'

class AbstractEditor extends Component {

  constructor(...args) {
    super(...args)
    this._initialize(this.props)
  }

  didMount() {
    this.documentSession.on('didUpdate', this._documentSessionUpdated, this)
  }

  willReceiveProps(nextProps) {
    let newSession = nextProps.documentSession
    let shouldDispose = newSession && newSession !== this.documentSession
    if (shouldDispose) {
      this._dispose()
      this._initialize(nextProps)
    }
  }

  dispose() {
    this._dispose()
  }

  _dispose() {
    this.surfaceManager.dispose()
    this.commandManager.dispose()
    this.globalEventHandler.dispose()
    this.dragManager.dispose()
    this.documentSession.off(this)
    // Note: we need to clear everything, as the childContext
    // changes which is immutable
    this.empty()
  }

  getChildContext() {
    return {
      controller: this,
      iconProvider: this.iconProvider,
      documentSession: this.documentSession,
      doc: this.doc, // TODO: remove in favor of documentSession
      componentRegistry: this.componentRegistry,
      surfaceManager: this.surfaceManager,
      commandManager: this.commandManager,
      tools: this.tools,
      labelProvider: this.labelProvider,
      converterRegistry: this.converterRegistry,
      globalEventHandler: this.globalEventHandler,
      editingBehavior: this.editingBehavior,
      dragManager: this.dragManager,
    }
  }

  _initialize(props) {
    let configurator = props.configurator
    let commands = configurator.getCommands()
    if (!props.documentSession) {
      throw new Error('DocumentSession instance required');
    }
    this.documentSession = props.documentSession
    this.doc = this.documentSession.getDocument()
    this.saveHandler = configurator.getSaveHandler()
    this.documentSession.setSaveHandler(this.saveHandler)
    this.componentRegistry = configurator.getComponentRegistry()
    this.tools = configurator.getTools()
    this.surfaceManager = new SurfaceManager(this.documentSession)
    this.fileClient = configurator.getFileClient()
    this.commandManager = new CommandManager(this.getCommandContext(), commands)
    this.dragManager = new DragManager(configurator.createDragHandlers(), {
      documentSession: this.documentSession,
      surfaceManager: this.surfaceManager,
      commandManager: this.commandManager,
    });
    this.macroManager = new MacroManager(this.getMacroContext(), configurator.getMacros())
    this.iconProvider = configurator.getIconProvider()
    this.converterRegistry = configurator.getConverterRegistry()
    this.globalEventHandler = new GlobalEventHandler(this.documentSession, this.surfaceManager)
    this.editingBehavior = configurator.getEditingBehavior()
    this.labelProvider = configurator.getLabelProvider()
  }

  getCommandContext() {
    return {
      documentSession: this.documentSession,
      surfaceManager: this.surfaceManager,
      fileClient: this.fileClient,
      saveHandler: this.saveHandler,
      converterRegistry: this.converterRegistry
    }
  }

  getMacroContext() {
    return {
      documentSession: this.documentSession,
      surfaceManager: this.surfaceManager
    }
  }

  getToolbar() {
    throw new Error('This method is abstract.')
  }

  _documentSessionUpdated() {
    let toolbar = this.getToolbar()
    if (toolbar) {
      let commandStates = this.commandManager.getCommandStates()
      toolbar.setProps({
        commandStates: commandStates
      })
    }
  }
}

export default AbstractEditor
<|endoftext|>


<commit_before>/***********************
 *  CUSTOM TEMPLATES   *
 ***********************/

var myTemplateConfig = {
  colors: ["#F00", "#0F0", "#00F"], // branches colors, 1 per column
  branch: {
    lineWidth: 8,
    spacingX: 50
  },
  commit: {
    spacingY: -80,
    dot: {
      size: 12
    },
    message: {
      displayAuthor: true,
      displayBranch: false,
      displayHash: false,
      font: "normal 12pt Arial"
    },
    shouldDisplayTooltipsInCompactMode: false, // default = true
    tooltipHTMLFormatter: function (commit) {
      return "" + commit.sha1 + "" + ": " + commit.message;
    }
  }
};
var myTemplate = new GitGraph.Template(myTemplateConfig);

/***********************
 *    INITIALIZATION   *
 ***********************/

var config = {
  template: "blackarrow", // could be: "blackarrow" or "metro" or `myTemplate` (custom Template object)
  reverseArrow: false, // to make arrows point to ancestors, if displayed
  orientation: "vertical",
  // mode: "compact" // special compact mode: hide messages & compact graph
};
var gitGraph = new GitGraph(config);

/************************
 * BRANCHES AND COMMITS *
 ************************/

// Create branch named "master"
var master = gitGraph.branch("master");

// Commit on HEAD Branch which is "master"
gitGraph.commit("Initial commit");

// Add few commits on master
gitGraph.commit("My second commit").commit("Add awesome feature");

// Create a new "dev" branch from "master" with some custom configuration
var dev = master.branch({
  name: "dev",
  color: "#F00",
  commitDefaultOptions: {
    color: "#F00"
  }
});
dev.commit("Youhou \\o/");

// Commit again on "master"
master.commit("I'm the master !");

// Advanced commit method with style and specific author (HEAD)
var commitConfig = {
  dotColor: "white",
  dotSize: 10,
  dotStrokeWidth: 10,
  messageHashDisplay: false,
  messageAuthorDisplay: true,
  message: "Alors c'est qui le papa ?",
  tooltipDisplay: false,
  author: "Me <me@planee.fr>"
};
gitGraph.commit(commitConfig);

// Create another from "master"
var feature3 = master.branch("feature3")
feature3.commit().commit();

/***********************
 *      CHECKOUT       *
 ***********************/

// Checkout to create "test" from "master" branch
// master.checkout();

/***********************
 *       DETAILS       *
 ***********************/

var commitWithDetailsConfig = {
  message: "A commit with detailed message",
  detailId: "detail"
};
gitGraph.commit(commitWithDetailsConfig).commit();
dev.commit().commit(); // 2 default commits on "dev"

/***********************
 *    CUSTOMIZATION    *
 ***********************/

gitGraph.author = "Fabien0102 <fabien0102@planee.fr>";
master.commit();

/***********************
 *       MERGES        *
 ***********************/

master.checkout();

// Merge "dev" branch into HEAD (which is "master"), with a default message
dev.merge();

// Create a "test" branch and merge it into "master" with a custom message and tag
var test = gitGraph.branch("test");
test.commit("Final commit");
test.merge(master, "My special merge commit message");

// Then, continue committing on the "test" branch
test.commit({
  message: "It works !"
});

var fastForwardBranch = test.branch("fast-forward");
fastForwardBranch.commit("First commit on FF branch");
fastForwardBranch.commit("Second commit on FF branch");

// If not commented, it will prevent fast-forward
// test.commit("Make Fast Forward impossible");

fastForwardBranch.merge(test, {
  fastForward: true
});

/***********************
 *        TAGS         *
 ***********************/

// Add a tag to a commit
test.commit({
  message: "Here you can see something",
  tag: "a-tag"
});

// Don't display tag box
test.commit({
  message: "Here is a fresh new tag",
  tag: "my-tag",
  displayTagBox: false
});

// Tag current HEAD
test.commit("Tag this commit").tag("b-tag");
gitGraph
  .commit("This one has no tag")
  .commit("Tag this one")
  .tag({
    tag: "c-tag",
    tagColor: "green",
    displayTagBox: false
  });

// Perform a merge, with a tag
test.merge(master, {
  message: "New release",
  tag: "v1.0.0"
});

// Create different branches from an empty one and do some commits
var features = master.branch("features")
var feature1 = features.branch("feature1")
var feature2 = features.branch("feature2")
feature1.commit();
feature2.commit().commit();

/***********************
 *       EVENTS        *
 ***********************/

gitGraph.canvas.addEventListener("graph:render", function (event) {
  console.log(event.data.id, "has been rendered with a scaling factor of", gitGraph.scalingFactor);
});

gitGraph.canvas.addEventListener("commit:mouseover", function (event) {
  console.log("You're over a commit.", "Here is a bunch of data ->", event.data);
  this.style.cursor = "pointer";
});

gitGraph.canvas.addEventListener("commit:mouseout", function (event) {
  console.log("You just left this commit ->", event.data);
  this.style.cursor = "auto";
});

// Attach a handler to the commit
test.commit({
  message: "Click me!",
  author: "Nicolas <me@planee.fr>",
  onClick: function (commit, isOverCommit, event) {
    console.log("You just clicked my commit.", commit, event);
  }
});
<commit_msg>Update index.js to illustrate #150 issue<commit_after>/***********************
 *  CUSTOM TEMPLATES   *
 ***********************/

var myTemplateConfig = {
  colors: ["#F00", "#0F0", "#00F"], // branches colors, 1 per column
  branch: {
    lineWidth: 8,
    spacingX: 50
  },
  commit: {
    spacingY: -80,
    dot: {
      size: 12
    },
    message: {
      displayAuthor: true,
      displayBranch: false,
      displayHash: false,
      font: "normal 12pt Arial"
    },
    shouldDisplayTooltipsInCompactMode: false, // default = true
    tooltipHTMLFormatter: function (commit) {
      return "" + commit.sha1 + "" + ": " + commit.message;
    }
  }
};
var myTemplate = new GitGraph.Template(myTemplateConfig);

/***********************
 *    INITIALIZATION   *
 ***********************/

var config = {
  template: "blackarrow", // could be: "blackarrow" or "metro" or `myTemplate` (custom Template object)
  reverseArrow: false, // to make arrows point to ancestors, if displayed
  orientation: "vertical",
  // mode: "compact" // special compact mode: hide messages & compact graph
};
var gitGraph = new GitGraph(config);

/************************
 * BRANCHES AND COMMITS *
 ************************/

// Create branch named "master"
var master = gitGraph.branch("master");

// Commit on HEAD Branch which is "master"
gitGraph.commit("Initial commit");

// Add few commits on master
gitGraph.commit("My second commit").commit("Add awesome feature");

// Create a new "dev" branch from "master" with some custom configuration
var dev = master.branch({
  name: "dev",
  color: "#F00",
  commitDefaultOptions: {
    color: "#F00"
  }
});
dev.commit("Youhou \\o/");

// Commit again on "master"
master.commit("I'm the master !");

// Advanced commit method with style and specific author (HEAD)
var commitConfig = {
  dotColor: "white",
  dotSize: 10,
  dotStrokeWidth: 10,
  messageHashDisplay: false,
  messageAuthorDisplay: true,
  message: "Alors c'est qui le papa ?",
  tooltipDisplay: false,
  author: "Me <me@planee.fr>"
};
gitGraph.commit(commitConfig);

// Create another from "master"
var feature3 = master.branch("feature3")
feature3.commit().commit();

/***********************
 *      CHECKOUT       *
 ***********************/

// Checkout to create "test" from "master" branch
// master.checkout();

/***********************
 *       DETAILS       *
 ***********************/

var commitWithDetailsConfig = {
  message: "A commit with detailed message",
  detailId: "detail"
};
gitGraph.commit(commitWithDetailsConfig).commit();
dev.commit().commit(); // 2 default commits on "dev"

/***********************
 *    CUSTOMIZATION    *
 ***********************/

gitGraph.author = "Fabien0102 <fabien0102@planee.fr>";
master.commit();

/***********************
 *       MERGES        *
 ***********************/

master.checkout();

// Merge "dev" branch into HEAD (which is "master"), with a default message
dev.merge();

// Create a "test" branch and merge it into "master" with a custom message and tag
var test = gitGraph.branch("test");
test.commit("Final commit");
test.merge(master, "My special merge commit message");

// Then, continue committing on the "test" branch
test.commit({
  message: "It works !"
});

var fastForwardBranch = test.branch("fast-forward");
fastForwardBranch.commit("First commit on FF branch");
fastForwardBranch.commit("Second commit on FF branch");

// If not commented, it will prevent fast-forward
// test.commit("Make Fast Forward impossible");

fastForwardBranch.merge(test, {
  fastForward: true
});

/***********************
 *        TAGS         *
 ***********************/

// Add a tag to a commit
test.commit({
  message: "Here you can see something",
  tag: "a-tag"
});

// Don't display tag box
test.commit({
  message: "Here is a fresh new tag",
  tag: "my-tag",
  displayTagBox: false
});

// Tag current HEAD
test.commit("Tag this commit").tag("b-tag");
gitGraph
  .commit("This one has no tag")
  .commit("Tag this one")
  .tag({
    tag: "c-tag",
    tagColor: "green",
    displayTagBox: false
  });

// Perform a merge, with a tag
test.merge(master, {
  message: "New release",
  tag: "v1.0.0"
});

// Create different branches from an empty one and do some commits
var features = master.branch("features")
var feature1 = features.branch("feature1")
var feature2 = features.branch("feature2")
feature2.commit().commit();
feature1.commit();

/***********************
 *       EVENTS        *
 ***********************/

gitGraph.canvas.addEventListener("graph:render", function (event) {
  console.log(event.data.id, "has been rendered with a scaling factor of", gitGraph.scalingFactor);
});

gitGraph.canvas.addEventListener("commit:mouseover", function (event) {
  console.log("You're over a commit.", "Here is a bunch of data ->", event.data);
  this.style.cursor = "pointer";
});

gitGraph.canvas.addEventListener("commit:mouseout", function (event) {
  console.log("You just left this commit ->", event.data);
  this.style.cursor = "auto";
});

// Attach a handler to the commit
test.commit({
  message: "Click me!",
  author: "Nicolas <me@planee.fr>",
  onClick: function (commit, isOverCommit, event) {
    console.log("You just clicked my commit.", commit, event);
  }
});
<|endoftext|>