text:
* Date:    May 14, 2015
* Author:  Jaime A. Rodriguez <hi.i.am.jaime@gmail.com>
* Version: 1.5
* License: http://opensource.org/licenses/MIT

Creates a Navigation UL based on a JSON file. Uses JSON to structure navigation pages and attributes. It can detect what page is active and assign classes to them for special treatment.

## Usage

~~~ php
	$topNavData = '{
		"pages": [
			{
				"title": "Nav 1",
				"link": "/nav1/"
			}, {
				"title": "Nav 2",
				"link": "/nav2/",
				"pages": [
					{
						"title": "Subnav 1",
						"link": "/downloads/fpo.pdf",
						"target": "_blank"
					}
				]
			}
		]
	}';

	$topNav = new \Module\Navigation\Builder($topNavData);
~~~

~~~ html
	<!-- In body somewhere -->
	<nav class="top">
		<?= $topNav->show(); ?>
	</nav>
~~~

## Changelog

### Version 1.5

* Added the menu, submenu, and .active.child classes

### Version 1.4

* Now automatically sets $_SERVER['SCRIPT_NAME'] as current page
* Added multiple hook points for manipulating navigations

### Version 1.2

* Added a track parameter

redpajama_set_name: RedPajamaGithub


text:
import neuralnet from '../../index'

console.log('////////////////// RUNNING SINUS APPROXIMATION EXAMPLE //////////////////');

let nTrainingData = 200;
let nTestData = 10;

var i;
var trainingData = [];
var testData = [];

for (i = 0; i < nTrainingData; i++) {
    let index = (Math.PI / nTrainingData) * i;

    trainingData.push({
        input: [index + 0.01],
        output: [Math.sin(index)]
    });
}

for (i = 0; i < nTestData; i++) {
    let index = (Math.PI / nTestData) * i;

    testData.push({
        input: [index],
        output: [Math.sin(index)]
    });
}

let handle = neuralnet.create([1, 10, 1]);

var epoch = 0;
while (true) {
    for (i = 0; i < trainingData.length; i++) {

        neuralnet.setInputValues(handle, trainingData[i].input);

        neuralnet.getOutputValues(handle);

        neuralnet.backPropagate(handle, trainingData[i].output);
    }

    let error = 0.0;
    let cnt = 0;

    for (i = 0; i < testData.length; i++) {

        neuralnet.setInputValues(handle, testData[i].input);

        var output = neuralnet.getOutputValues(handle);

        for (var z = 0; z < output.length; z++) {
            error += Math.abs(output[z] - testData[i].output[z]);
            cnt++;
        }
    }

    error = error / cnt;

    console.log('Epoch ' + (epoch++) + ', Error: ' + error);

    if (error < 0.04)
        break;
}

neuralnet.setInputValues(handle, [Math.PI / 2]);
var r = neuralnet.getOutputValues(handle, [Math.PI / 2]);
console.log('Result for sin(PI / 2) is ' + r[0]);

neuralnet.setInputValues(handle, [Math.PI]);
var r1 = neuralnet.getOutputValues(handle, [Math.PI]);
console.log('Result for sin(PI) is ' + r1[0]);

neuralnet.setInputValues(handle, [0]);
var r2 = neuralnet.getOutputValues(handle, [0]);
console.log('Result for sin(0) is ' + r2[0]);

neuralnet.setInputValues(handle, [0.5]);
var r2 = neuralnet.getOutputValues(handle, [0]);
console.log('Result for sin(0.5) is ' + r2[0]);

neuralnet.clear(handle);


text:
from copy import deepcopy, copy

import pandas as pd

from QUANTAXIS.QAFetch.QATdx import QA_fetch_get_stock_realtime

class QA_DataStruct_Stock_block():

    def __init__(self, DataFrame):
        self.data = DataFrame
        assert isinstance(DataFrame.index, pd.MultiIndex)
        self.index = self.data.index.remove_unused_levels()

    def __repr__(self):
        return '< QA_DataStruct_Stock_Block >'

    def __call__(self):
        """调用直接返回内部的数据

        Returns:
            [type] -- [description]
        """

        return self.data

    def new(self, data):
        """通过data新建一个stock_block

        Arguments:
            data {[type]} -- [description]

        Returns:
            [type] -- [description]
        """
        temp = copy(self)
        temp.__init__(data)
        return temp

    @property
    def len(self):
        """返回DataStruct的长度

        Returns:
            [type] -- [description]
        """

        return len(self.data)

    @property
    def block_name(self):
        """返回所有的板块名

        Returns:
            [type] -- [description]
        """

        return self.index.levels[0].tolist()

    @property
    def code(self):
        """返回唯一的证券代码

        Returns:
            [type] -- [description]
        """

        return self.index.levels[1].tolist()

    @property
    def view_code(self):
        """按股票排列的查看blockname的视图

        Returns:
            [type] -- [description]
        """

        return self.data.groupby(level=1).apply(
            lambda x:
            [item for item in x.index.remove_unused_levels().levels[0]]
        )

    @property
    def view_block(self):
        """按版块排列查看的code的视图

        Returns:
            [type] -- [description]
        """

        return self.data.groupby(level=0).apply(
            lambda x:
            [item for item in x.index.remove_unused_levels().levels[1]]
        )

    def show(self):
        """展示DataStruct

        Returns:
            dataframe -- [description]
        """

        return self.data

    def get_code(self, code):
        """getcode 获取某一只股票的板块

        Arguments:
            code {str} -- 股票代码

        Returns:
            DataStruct -- [description]
        """
        # code= [code] if isinstance(code,str) else
        return self.new(self.data.loc[(slice(None), code), :])

    def get_block(self, block_name):
        """getblock 获取板块, block_name是list或者是单个str

        Arguments:
            block_name {[type]} -- [description]

        Returns:
            [type] -- [description]
        """
        # block_name = [block_name] if isinstance(
        #     block_name, str) else block_name
        # return QA_DataStruct_Stock_block(self.data[self.data.blockname.apply(lambda x: x in block_name)])

        return self.new(self.data.loc[(block_name, slice(None)), :])

    def get_both_code(self, code):
        """get_both_code 获取几个股票相同的版块

        Arguments:
            code {[type]} -- [description]

        Returns:
            [type] -- [description]
        """

        return self.new(self.data.loc[(slice(None), code), :])

    def get_both_block(self, block_list):
        n = len(block_list)
        count = self.get_block(block_list).data.assign(countx=1).groupby('code').countx.count()
        return count[count==n].index.tolist()

    # def getdtype(self, dtype):
    #     """getdtype

    #     Arguments:
    #         dtype {str} -- gn-概念/dy-地域/fg-风格/zs-指数

    #     Returns:
    #         [type] -- [description]
    #     """

    #     return QA_DataStruct_Stock_block(self.data[self.data['type'] == dtype])

    # def get_price(self, _block_name=None):
    #     """get_price

    #     Keyword Arguments:
    #         _block_name {[type]} -- [description] (default: {None})

    #     Returns:
    #         [type] -- [description]
    #     """

    #     if _block_name is not None:
    #         try:
    #             code = self.data[self.data['blockname']
    #                              == _block_name].code.unique().tolist()
    #             # try to get a datastruct package of lastest price
    #             return QA_fetch_get_stock_realtime(code)

    #         except:
    #             return "Wrong Block Name! Please Check"
    #     else:
    #         code = self.data.code.unique().tolist()
    #         return QA_fetch_get_stock_realtime(code)


text:
(function() {
  var __hasProp = Object.prototype.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

  arcs.models.Comment = (function(_super) {

    __extends(Comment, _super);

    function Comment() {
      Comment.__super__.constructor.apply(this, arguments);
    }

    Comment.prototype.urlRoot = arcs.baseURL + 'comments';

    return Comment;

  })(Backbone.Model);

}).call(this);


text: create database sqlmodedb;


text:
module.exports = function(grunt) {
  var assert = require("assert");
  var fs   = require("fs");
  var path = require("path");

  var SubProcess  = require("../../../utils/subprocess");
  var extend_args = function extend_args(args, check, to_add) {
    if (check) {
      args.push.apply(args, to_add);
    }
  };

  var gpp_task = function() {
    // Prepare task and options.
    var options = this.options({
      coverage: true,
      debug:    true,
      include:  null,
      optimise: null,
      standard: "c++11",

      // Required options.
      objects_path: null
    }, this.data);

    // Assert require parameters were provided.
    assert(options.objects_path, "A path of the object files is required.");

    // Build paths.
    var sources = grunt.file.expandMapping(options.src, options.objects_path, {
      ext:    ".o",
      extDot: "last"
    });

    // Check all additional include files.
    // If any of them was modified after the target re-build it.
    var include_last_modified = 0;
    if (options.include && options.include.length > 0) {
      // Find greatest last modified time for each include path.
      var times = options.include.map(function(include) {
        var headers = grunt.file.expand(include + "/**/*.{h,hpp}");
        headers = headers.map(function(header) {
          return fs.statSync(header).mtime.getTime();
        });

        if (headers.length === 1) {
          return headers[0];
        }
        return Math.max.apply(Math, headers);
      });

      if (times.length === 1) {
        include_last_modified = times[0];
      }
      include_last_modified = Math.max.apply(Math, times) || 0;
    }

    // Filter paths based on last edit time.
    sources = sources.filter(function(source) {
      try {
        var src    = fs.statSync(source.src[0]).mtime.getTime();
        var target = fs.statSync(source.dest).mtime.getTime();
        return Math.max(src, include_last_modified) >= target;

      } catch(ex) { /* NOOP */ }
      return true;
    });
    if (sources.length === 0) {
      grunt.log.ok("Objects up to date, nothing to do.");
      return;
    }

    // Ensure paths exist.
    sources.map(function(source) {
      var target = path.dirname(source.dest);
      if (!fs.existsSync(target)) {
        grunt.file.mkdir(target);
      }
    });
    if (grunt.option("no-write")) {
      return;
    }

    // Build arguments.
    var args = ["-c", "-std=" + options.standard];
    extend_args(args, options.debug, ["-g"]);
    extend_args(args, options.coverage, ["-fprofile-arcs", "-ftest-coverage"]);
    extend_args(args, options.optimise !== null, ["-O" + options.optimise]);

    if (Array.isArray(options.include) && options.include.length > 0) {
      args.push.apply(args, options.include.map(function(include) {
        return "-I" + path.normalize(include);
      }));
    }

    // Generare SubProcess instances.
    var children = sources.map(function(source) {
      var instance_args = [];
      instance_args.push.apply(instance_args, args);
      instance_args.push("-o", source.dest, source.src[0]);
      return new SubProcess(grunt.log, {
        args: instance_args,
        cmd:  "g++"
      });
    });

    // And compile!
    var done = this.async();
    SubProcess.spawnAll(children, grunt.option("parallel")).then(function() {
      done();
    }).fail(function(code) {
      done(new Error(code));
    });
  };

  grunt.registerMultiTask("g++", "Compile C++ sources into objects.", gpp_task);
};


text:
require 'spec_helper'

describe Puppet::Type.type(:karaf_kar) do

  before :each do
    described_class.stubs(:defaultprovider).returns providerclass
  end

  let :providerclass do
    described_class.provide(:fake_karaf_kar_provider) { mk_resource_methods }
  end

  it "should have :name as it's namevar" do
    described_class.key_attributes.should == [:name]
  end

  describe "when validating attributes" do
    [:name, :location, :host, :port, :karaf_user, :user, :retries, :delay].each do |param|
      it "should have a #{param} parameter" do
        described_class.attrtype(param).should == :param
      end
    end

    [:ensure].each do |property|
      it "should have a #{property} property" do
        described_class.attrtype(property).should == :property
      end
    end
  end

  describe "when validating values" do
    describe "for name" do
      it "should support an alphanumerical name" do
        described_class.new(:name => 'kar', :ensure => :present)[:name].should == 'kar'
      end

      it "should support underscores" do
        described_class.new(:name => 'kar_name', :ensure => :present)[:name].should == 'kar_name'
      end

      it "should support hyphens" do
        described_class.new(:name => 'kar-name', :ensure => :present)[:name].should == 'kar-name'
      end

      it "should support periods" do
        described_class.new(:name => 'kar.name', :ensure => :present)[:name].should == 'kar.name'
      end

      it "should not support spaces" do
        expect { described_class.new(:name => 'kar name', :ensure => :present) }.to raise_error(Puppet::Error, /kar name is not a valid kar name/)
      end
    end

    describe "for ensure" do
      it "should support present" do
        described_class.new(:name => 'kar', :ensure => 'present')[:ensure].should == :present
      end

      it "should support absent" do
        described_class.new(:name => 'kar', :ensure => 'absent')[:ensure].should == :absent
      end

      it "should not support other values" do
        expect { described_class.new(:name => 'kar', :ensure => 'foo') }.to raise_error(Puppet::Error, /Invalid value "foo"/)
      end

      it "should not have a default value" do
        described_class.new(:name => 'kar')[:ensure].should == nil
      end
    end

    describe "for location" do
      it "should support a value" do
        described_class.new(:name => 'kar', :location => 'file:/tmp/test.kar', :ensure => :present)[:location].should == 'file:/tmp/test.kar'
      end
    end

    #
    ## Common params
    #
    describe "for host" do
      it "should support a value" do
        described_class.new(:name => 'kar', :host => 'hostname', :ensure => :present)[:host].should == 'hostname'
      end
    end

    describe "for port" do
      it "should support a numerical value" do
        described_class.new(:name => 'kar', :port => '8000', :ensure => :present)[:port].should == 8000
      end

      it "should have a default value of 4800" do
        described_class.new(:name => 'kar', :ensure => :present)[:port].should == 8101
      end

      it "should not support shorter than 4 digits" do
        expect { described_class.new(:name => 'kar', :port => '123', :ensure => :present) }.to raise_error(Puppet::Error, /123 is not a valid port./)
      end

      it "should not support longer than 5 digits" do
        expect { described_class.new(:name => 'kar', :port => '123456', :ensure => :present) }.to raise_error(Puppet::Error, /123456 is not a valid port./)
      end

      it "should not support a non-numeric value" do
        expect { described_class.new(:name => 'kar', :port => 'a', :ensure => :present) }.to raise_error(Puppet::Error, /a is not a valid port./)
      end
    end

    describe "for karaf_user" do
      it "should support an alpha name" do
        described_class.new(:name => 'kar', :karaf_user => 'user', :ensure => :present)[:karaf_user].should == 'user'
      end

      it "should support underscores" do
        described_class.new(:name => 'kar', :karaf_user => 'karaf_user', :ensure => :present)[:karaf_user].should == 'karaf_user'
      end

      it "should support hyphens" do
        described_class.new(:name => 'kar', :karaf_user => 'karaf-user', :ensure => :present)[:karaf_user].should == 'karaf-user'
      end

      it "should have a default value of karaf" do
        described_class.new(:name => 'kar', :ensure => :present)[:karaf_user].should == 'karaf'
      end

      it "should not support spaces" do
        expect { described_class.new(:name => 'kar', :karaf_user => 'karaf user', :ensure => :present) }.to raise_error(Puppet::Error, /karaf user is not a valid karaf admin username/)
      end
    end

    describe "for user" do
      it "should support an alpha name" do
        Puppet.features.expects(:root?).returns(true).once
        described_class.new(:name => 'kar', :user => 'karaf', :ensure => :present)[:user].should == 'karaf'
      end

      it "should support underscores" do
        Puppet.features.expects(:root?).returns(true).once
        described_class.new(:name => 'kar', :user => 'karaf_user', :ensure => :present)[:user].should == 'karaf_user'
      end

      it "should support hyphens" do
        Puppet.features.expects(:root?).returns(true).once
        described_class.new(:name => 'kar', :user => 'karaf-user', :ensure => :present)[:user].should == 'karaf-user'
      end

      it "should not have a default value of admin" do
        described_class.new(:name => 'kar', :ensure => :present)[:user].should == nil
      end

      it "should not support spaces" do
        Puppet.features.expects(:root?).returns(true).once
        expect { described_class.new(:name => 'kar', :user => 'karaf user') }.to raise_error(Puppet::Error, /karaf user is not a valid user name/)
      end

      it "should fail if not running as root" do
        Puppet.features.expects(:root?).returns(false).once
        expect { described_class.new(:name => 'kar', :user => 'karaf') }.to raise_error(Puppet::Error, /Only root can execute commands as other users/)
      end
    end

    describe "for retries" do
      it "should support a numerical value" do
        described_class.new(:name => 'kar', :retries => '2', :ensure => :present)[:retries].should == 2
      end

      it "should have a default value of 5" do
        described_class.new(:name => 'kar', :ensure => :present)[:retries].should == 5
      end

      it "should not support a non-numeric value" do
        expect { described_class.new(:name => 'kar', :retries => 'a', :ensure => :present) }.to raise_error(Puppet::Error, /a is not a valid retries value./)
      end
    end

    describe "for delay" do
      it "should support a numerical value" do
        described_class.new(:name => 'kar', :delay => '2', :ensure => :present)[:delay].should == 2
      end

      it "should have a default value of 5" do
        described_class.new(:name => 'kar', :ensure => :present)[:delay].should == 5
      end

      it "should not support a non-numeric value" do
        expect { described_class.new(:name => 'kar', :delay => 'a', :ensure => :present) }.to raise_error(Puppet::Error, /a is not a valid retry delay value./)
      end
    end
  end

end


text:
package proto

type Category struct {
	Name    string           `json:"name,omitempty"`
	Details *CategoryDetails `json:"details,omitempty"`
}

type CategoryDetails struct {
	CreatedAt string `json:"createdAt,omitempty"`
	CreatedBy string `json:"createdBy,omitempty"`
}

func NewCategoryRequest() Request {
	return Request{
		Flags:    &Flags{},
		Category: &Category{},
	}
}

func NewCategoryResult() Result {
	return Result{
		Errors:     &[]string{},
		Categories: &[]Category{},
	}
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix


text:
package aphrender

import (
	"bytes"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/dictyBase/apihelpers/aphtest"
	"github.com/dictyBase/go-middlewares/middlewares/pagination"
)

type Permission struct {
	ID          string `json:"-"`
	Permission  string `json:"permission"`
	Description string `json:"description"`
}

func (p Permission) GetID() string {
	return p.ID
}

func TestResource(t *testing.T) {
	jsonBlob := []byte(`
		{
			"links": {
				"self":"https://api.dictybase.org/1.0/permissions/10"
			},
			"data": {
				"type": "permissions",
				"id": "10",
				"attributes": {
					"permission": "gene curation",
					"description": "Authority to edit gene information"
				}
			}
		}
	`)
	perm := &Permission{
		ID:          "10",
		Permission:  "gene curation",
		Description: "Authority to edit gene information",
	}
	srvinfo := aphtest.NewTestApiInfo()
	w := httptest.NewRecorder()
	Resource(perm, srvinfo, w)

	if w.Header().Get("Content-Type") != "application/vnd.api+json" {
		t.Fatalf("no jsonapi response header %s", w.Header().Get("Content-Type"))
	}
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status code %d\n", w.Code)
	}
	expJson := aphtest.IndentJSON(jsonBlob)
	matchJson := aphtest.IndentJSON(w.Body.Bytes())
	if bytes.Compare(expJson, matchJson) != 0 {
		t.Fatalf("expected \n%s jsonapi error response does not match with \n%s\n", string(expJson), string(matchJson))
	}
}

func TestResourceCollection(t *testing.T) {
	jsonBlob := []byte(`
		{
			"links": {
				"self":"https://api.dictybase.org/1.0/permissions?page[number]=5&page[size]=10",
				"first":"https://api.dictybase.org/1.0/permissions?page[number]=1&page[size]=10",
				"prev":"https://api.dictybase.org/1.0/permissions?page[number]=4&page[size]=10",
				"next":"https://api.dictybase.org/1.0/permissions?page[number]=6&page[size]=10",
				"last":"https://api.dictybase.org/1.0/permissions?page[number]=10&page[size]=10"
			},
			"data": [{
				"type": "permissions",
				"id": "10",
				"attributes": {
					"permission": "gene curation",
					"description": "Authority to edit gene information"
				},
				"links": {
					"self": "https://api.dictybase.org/1.0/permissions/10"
				}
			}],
			"meta": {
				"pagination": {
					"number": 5,
					"records": 100,
					"size": 10,
					"total": 10
				}
			}
		}
	`)
	pageOpt := &pagination.Props{
		Records: 100,
		Entries: 10,
		Current: 5,
	}
	srvinfo := aphtest.NewTestApiInfo()
	permissions := []*Permission{
		&Permission{
			ID:          "10",
			Permission:  "gene curation",
			Description: "Authority to edit gene information",
		},
	}
	w := httptest.NewRecorder()
	ResourceCollection(permissions, srvinfo, w, pageOpt)
	if w.Header().Get("Content-Type") != "application/vnd.api+json" {
		t.Fatalf("no jsonapi response header %s", w.Header().Get("Content-Type"))
	}
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status code %d\n", w.Code)
	}
	expJson := aphtest.IndentJSON(jsonBlob)
	matchJson := aphtest.IndentJSON(w.Body.Bytes())
	if bytes.Compare(expJson, matchJson) != 0 {
		t.Fatalf("expected \n%s jsonapi error response does not match with \n%s\n", string(expJson), string(matchJson))
	}
}


text:
<?php
namespace SepaQr;

use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\WriterInterface;

function formatMoney($value) {
    return sprintf('EUR%s', number_format($value, 2, '.', ''));
}

class SepaQr extends QrCode
{
    const UTF_8 = 1;
    const ISO8859_1 = 2;
    const ISO8859_2 = 3;
    const ISO8859_4 = 4;
    const ISO8859_5 = 5;
    const ISO8859_7 = 6;
    const ISO8859_10 = 7;
    const ISO8859_15 = 8;

    private $sepaValues = array(
        'serviceTag' => 'BCD',
        'version' => 2,
        'characterSet' => 1,
        'identification' => 'SCT'
    );

    public function __construct($text = '')
    {
        parent::__construct($text);

        $this->setErrorCorrectionLevel(new ErrorCorrectionLevel(ErrorCorrectionLevel::MEDIUM));
    }

    public function setServiceTag(string $serviceTag = 'BCD')
    {
        if ($serviceTag !== 'BCD') {
            throw new Exception('Invalid service tag');
        }

        $this->sepaValues['serviceTag'] = $serviceTag;

        return $this;
    }

    public function setVersion(int $version = 2)
    {
        if (!in_array($version, range(1, 2))) {
            throw new Exception('Invalid version');
        }

        $this->sepaValues['version'] = $version;

        return $this;
    }

    public function setCharacterSet($characterSet = self::UTF_8)
    {
        $characterSet = (int)$characterSet;

        if (!in_array($characterSet, range(1, 8))) {
            throw new Exception('Invalid character set');
        }

        $this->sepaValues['characterSet'] = $characterSet;
        return $this;
    }

    public function setIdentification($identification = 'SCT')
    {
        if ($identification !== 'SCT') {
            throw new Exception('Invalid identification code');
        }

        $this->sepaValues['identification'] = $identification;

        return $this;
    }

    public function setBic($bic)
    {
        $this->sepaValues['bic'] = $bic;
        return $this;
    }

    public function setName($name)
    {
        $this->sepaValues['name'] = $name;
        return $this;
    }

    public function setIban($iban)
    {
        $this->sepaValues['iban'] = $iban;
        return $this;
    }

    public function setAmount($amount)
    {
        $this->sepaValues['amount'] = (float)$amount;
        return $this;
    }

    public function setPurpose($purpose)
    {
        $this->sepaValues['purpose'] = $purpose;
        return $this;
    }

    public function setRemittanceReference($remittanceReference)
    {
        if (isset($this->sepaValues['remittanceText'])) {
            throw new Exception('Use either structured or unstructured remittance information');
        }

        $this->sepaValues['remittanceReference'] = (string)$remittanceReference;
        return $this;
    }

    public function setRemittanceText($remittanceText)
    {
        if (isset($this->sepaValues['remittanceReference'])) {
            throw new Exception('Use either structured or unstructured remittance information');
        }

        $this->sepaValues['remittanceText'] = $remittanceText;
        return $this;
    }

    public function setInformation($information)
    {
        $this->sepaValues['information'] = $information;
        return $this;
    }

    public function validateSepaValues($values)
    {
        if ($values['version'] === 1 && !$values['bic']) {
            throw new Exception('Missing BIC of the beneficiary bank');
        }

        if ($values['bic']) {
            if (strlen($values['bic']) < 8) {
                throw new Exception('BIC of the beneficiary bank cannot be shorter than 8 characters');
            }

            if (strlen($values['bic']) > 11) {
                throw new Exception('BIC of the beneficiary bank cannot be longer than 11 characters');
            }
        }

        if (!$values['name']) {
            throw new Exception('Missing name of the beneficiary');
        }

        if (strlen($values['name']) > 70) {
            throw new Exception('Name of the beneficiary cannot be longer than 70 characters');
        }

        if (!$values['iban']) {
            throw new Exception('Missing account number of the beneficiary');
        }

        if (strlen($values['iban']) > 34) {
            throw new Exception('Account number of the beneficiary cannot be longer than 34 characters');
        }

        if ($values['amount']) {
            if ($values['amount'] < 0.01) {
                throw new Exception('Amount of the credit transfer cannot be smaller than 0.01 Euro');
            }

            if ($values['amount'] > 999999999.99) {
                throw new Exception('Amount of the credit transfer cannot be higher than 999999999.99 Euro');
            }
        }

        if ($values['remittanceReference'] && strlen($values['remittanceReference']) > 35) {
            throw new Exception('Structured remittance information cannot be longer than 35 characters');
        }

        if ($values['remittanceText'] && strlen($values['remittanceText']) > 140) {
            throw new Exception('Unstructured remittance information cannot be longer than 140 characters');
        }

        if ($values['information'] && strlen($values['information']) > 70) {
            throw new Exception('Beneficiary to originator information cannot be longer than 70 characters');
        }
    }

    public function encodeMessage()
    {
        $defaults = array(
            'bic' => '',
            'name' => '',
            'iban' => '',
            'amount' => 0,
            'purpose' => '',
            'remittanceReference' => '',
            'remittanceText' => '',
            'information' => ''
        );

        $values = array_merge($defaults, $this->sepaValues);

        $this->validateSepaValues($values);

        return rtrim(implode("\n", array(
            $values['serviceTag'],
            sprintf('%03d', $values['version']),
            $values['characterSet'],
            $values['identification'],
            $values['bic'],
            $values['name'],
            $values['iban'],
            $values['amount'] > 0 ? formatMoney($values['amount']) : '',
            $values['purpose'],
            $values['remittanceReference'],
            $values['remittanceText'],
            $values['information']
        )), "\n");
    }

    public function getWriter(string $name = null): WriterInterface
    {
        $this->setText($this->encodeMessage());

        return parent::getWriter($name);
    }
}


text:
package org.apache.hadoop.hdfs.server.namenode.ha;

import static org.junit.Assert.assertEquals;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.HAUtil;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.MiniDFSCluster.DataNodeProperties;
import org.apache.hadoop.hdfs.MiniDFSNNTopology;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManagerTestUtil;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.namenode.NameNodeAdapter;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Test;

import java.util.function.Supplier;

/**
 * The hotornot.com of unit tests: makes sure that the standby not only
 * has namespace information, but also has the correct block reports, etc.
 */
public class TestStandbyIsHot {
  protected static final Logger LOG = LoggerFactory.getLogger(
      TestStandbyIsHot.class);
  private static final String TEST_FILE_DATA = "hello highly available world";
  private static final String TEST_FILE = "/testStandbyIsHot";
  private static final Path TEST_FILE_PATH = new Path(TEST_FILE);

  static {
    DFSTestUtil.setNameNodeLogLevel(Level.ALL);
  }

  @Test(timeout=60000)
  public void testStandbyIsHot() throws Exception {
    Configuration conf = new Configuration();
    // We read from the standby to watch block locations
    HAUtil.setAllowStandbyReads(conf, true);
    conf.setInt(DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_KEY, 1);
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
      .nnTopology(MiniDFSNNTopology.simpleHATopology())
      .numDataNodes(3)
      .build();
    try {
      cluster.waitActive();
      cluster.transitionToActive(0);

      NameNode nn1 = cluster.getNameNode(0);
      NameNode nn2 = cluster.getNameNode(1);

      FileSystem fs = HATestUtil.configureFailoverFs(cluster, conf);

      Thread.sleep(1000);
      System.err.println("==================================");
      DFSTestUtil.writeFile(fs, TEST_FILE_PATH, TEST_FILE_DATA);
      // Have to force an edit log roll so that the standby catches up
      nn1.getRpcServer().rollEditLog();
      System.err.println("==================================");

      // Block locations should show up on standby.
      LOG.info("Waiting for block locations to appear on standby node");
      waitForBlockLocations(cluster, nn2, TEST_FILE, 3);

      // Trigger immediate heartbeats and block reports so
      // that the active "trusts" all of the DNs
      cluster.triggerHeartbeats();
      cluster.triggerBlockReports();

      // Change replication
      LOG.info("Changing replication to 1");
      fs.setReplication(TEST_FILE_PATH, (short)1);
      BlockManagerTestUtil.computeAllPendingWork(
          nn1.getNamesystem().getBlockManager());
      waitForBlockLocations(cluster, nn1, TEST_FILE, 1);

      nn1.getRpcServer().rollEditLog();

      LOG.info("Waiting for lowered replication to show up on standby");
      waitForBlockLocations(cluster, nn2, TEST_FILE, 1);

      // Change back to 3
      LOG.info("Changing replication to 3");
      fs.setReplication(TEST_FILE_PATH, (short)3);
      BlockManagerTestUtil.computeAllPendingWork(
          nn1.getNamesystem().getBlockManager());
      nn1.getRpcServer().rollEditLog();

      LOG.info("Waiting for higher replication to show up on standby");
      waitForBlockLocations(cluster, nn2, TEST_FILE, 3);

    } finally {
      cluster.shutdown();
    }
  }

  /**
   * Regression test for HDFS-2795:
   *  - Start an HA cluster with a DN.
   *  - Write several blocks to the FS with replication 1.
   *  - Shutdown the DN
   *  - Wait for the NNs to declare the DN dead. All blocks will be under-replicated.
   *  - Restart the DN.
   * In the bug, the standby node would only very slowly notice the blocks returning
   * to the cluster.
   */
  @Test(timeout=60000)
  public void testDatanodeRestarts() throws Exception {
    Configuration conf = new Configuration();
    conf.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, 1024);
    // We read from the standby to watch block locations
    HAUtil.setAllowStandbyReads(conf, true);
    conf.setLong(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, 0);
    conf.setInt(DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_KEY, 1);
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
      .nnTopology(MiniDFSNNTopology.simpleHATopology())
      .numDataNodes(1)
      .build();
    try {
      NameNode nn0 = cluster.getNameNode(0);
      NameNode nn1 = cluster.getNameNode(1);

      cluster.transitionToActive(0);

      // Create 5 blocks.
      DFSTestUtil.createFile(cluster.getFileSystem(0),
          TEST_FILE_PATH, 5*1024, (short)1, 1L);

      HATestUtil.waitForStandbyToCatchUp(nn0, nn1);

      // Stop the DN.
      DataNode dn = cluster.getDataNodes().get(0);
      String dnName = dn.getDatanodeId().getXferAddr();
      DataNodeProperties dnProps = cluster.stopDataNode(0);

      // Make sure both NNs register it as dead.
      BlockManagerTestUtil.noticeDeadDatanode(nn0, dnName);
      BlockManagerTestUtil.noticeDeadDatanode(nn1, dnName);

      BlockManagerTestUtil.updateState(nn0.getNamesystem().getBlockManager());
      BlockManagerTestUtil.updateState(nn1.getNamesystem().getBlockManager());
      assertEquals(5, nn0.getNamesystem().getUnderReplicatedBlocks());

      // The SBN will not have any blocks in its neededReplication queue
      // since the SBN doesn't process replication.
      assertEquals(0, nn1.getNamesystem().getUnderReplicatedBlocks());

      LocatedBlocks locs = nn1.getRpcServer().getBlockLocations(
          TEST_FILE, 0, 1);
      assertEquals("Standby should have registered that the block has no replicas",
          0, locs.get(0).getLocations().length);

      cluster.restartDataNode(dnProps);
      // Wait for both NNs to re-register the DN.
      cluster.waitActive(0);
      cluster.waitActive(1);
      cluster.waitFirstBRCompleted(0, 10000);
      cluster.waitFirstBRCompleted(1, 10000);

      BlockManagerTestUtil.updateState(nn0.getNamesystem().getBlockManager());
      BlockManagerTestUtil.updateState(nn1.getNamesystem().getBlockManager());
      assertEquals(0, nn0.getNamesystem().getUnderReplicatedBlocks());
      assertEquals(0, nn1.getNamesystem().getUnderReplicatedBlocks());

      locs = nn1.getRpcServer().getBlockLocations(
          TEST_FILE, 0, 1);
      assertEquals("Standby should have registered that the block has replicas again",
          1, locs.get(0).getLocations().length);
    } finally {
      cluster.shutdown();
    }
  }

  static void waitForBlockLocations(final MiniDFSCluster cluster,
      final NameNode nn,
      final String path, final int expectedReplicas)
      throws Exception {
    GenericTestUtils.waitFor(new Supplier<Boolean>() {

      @Override
      public Boolean get() {
        try {
          LocatedBlocks locs = NameNodeAdapter.getBlockLocations(nn, path, 0, 1000);
          DatanodeInfo[] dnis = locs.getLastLocatedBlock().getLocations();
          for (DatanodeInfo dni : dnis) {
            Assert.assertNotNull(dni);
          }
          int numReplicas = dnis.length;

          LOG.info("Got " + numReplicas + " locs: " + locs);
          if (numReplicas > expectedReplicas) {
            cluster.triggerDeletionReports();
          }
          cluster.triggerHeartbeats();
          return numReplicas == expectedReplicas;
        } catch (IOException e) {
          LOG.warn("No block locations yet: " + e.getMessage());
          return false;
        }
      }
    }, 500, 20000);

  }
}


text:
{% extends "desktop/sections/base.html" %}
{% set section_id = 'learn' %}
{% set three_columns = True %}

{% block leftcolumn %}

		{{ _('Learn') }}

{{ _("Get the latest on Firefox 4 for Android's features") }}

{% endblock %}

{% block middlecolumn %}

{{ _('Type Less, Browse More') }}

{{ _('Firefox learns your favorite sites to help you get where you want to go with minimal typing and more speed.') }}

{{ _('Customize Your Browser') }}

{{ _('Add features and functionality that help make your browser your own. Install add-ons directly to your mobile.') }}

{{ _('Stay in Sync') }}

{{ _('Securely access your history, passwords, bookmarks and even open tabs across all your devices.') }}

{% endblock %}

{% block rightcolumn %}

{{ _('Performance & Productivity') }}

{{ _('Built on the same technology platform as Firefox for the desktop, Firefox for mobile is optimized for power and efficiency.') }}

{{ _('Share, Find, Save') }}

{{ _('Share interesting content with friends in a single tap.') }}

{{ _('Location-Aware Browsing') }}

{{ _('Save time by letting sites know where you are (opt-in only).') }}

	{{ _('See Firefox 4 for Android in action') }}
{% endblock %}


text:
package org.apache.camel.component.jms.issues;

import java.util.concurrent.Future;

import javax.jms.ConnectionFactory;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jms.CamelJmsTestHelper;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge;

public class JmsInOutIssueTest extends CamelTestSupport {

    @Test
    public void testInOutWithRequestBody() throws Exception {
        String reply = template.requestBody("activemq:queue:in", "Hello World", String.class);
        assertEquals("Bye World", reply);
    }

    @Test
    public void testInOutTwoTimes() throws Exception {
        String reply = template.requestBody("activemq:queue:in", "Hello World", String.class);
        assertEquals("Bye World", reply);

        reply = template.requestBody("activemq:queue:in", "Hello Camel", String.class);
        assertEquals("Bye World", reply);
    }

    @Test
    public void testInOutWithAsyncRequestBody() throws Exception {
        Future<String> reply = template.asyncRequestBody("activemq:queue:in", "Hello World", String.class);
        assertEquals("Bye World", reply.get());
    }

    @Test
    public void testInOutWithSendExchange() throws Exception {
        Exchange out = template.send("activemq:queue:in", ExchangePattern.InOut, new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setBody("Hello World");
            }
        });

        assertEquals("Bye World", out.getOut().getBody());
    }

    @Test
    public void testInOutWithAsyncSendExchange() throws Exception {
        Future<Exchange> out = template.asyncSend("activemq:queue:in", new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.setPattern(ExchangePattern.InOut);
                exchange.getIn().setBody("Hello World");
            }
        });

        assertEquals("Bye World", out.get().getOut().getBody());
    }

    @Override
    protected CamelContext createCamelContext() throws Exception {
        CamelContext camelContext = super.createCamelContext();
        ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory();
        camelContext.addComponent("activemq", jmsComponentAutoAcknowledge(connectionFactory));
        return camelContext;
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from("activemq:queue:in").process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        exchange.getOut().setBody("Bye World");
                    }
                });
            }
        };
    }

}


text:
<?php

namespace Hyper\AdsBundle\Payment\BitPay;

use Hyper\AdsBundle\Payment\OrderInterface;
use Hyper\AdsBundle\Payment\ParamsProviderInterface;
use Hyper\AdsBundle\Payment\Util\OrderHashGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Translation\TranslatorInterface;

class BitPayParamsProvider implements ParamsProviderInterface
{
    /** @var \Symfony\Component\Routing\RouterInterface */
    private $router;

    /** @var \Hyper\AdsBundle\Payment\Util\OrderHashGeneratorInterface */
    private $hashGenerator;

    /** @var \Symfony\Component\Translation\TranslatorInterface */
    private $translator;

    private $transactionSpeed;
    private $fullNotifications;
    private $notificationEmail;

    public function __construct(
        RouterInterface $router,
        OrderHashGeneratorInterface $hashGenerator,
        TranslatorInterface $translator,
        $transactionSpeed,
        $fullNotifications,
        $notificationEmail
    ) {
        $this->router = $router;
        $this->transactionSpeed = $transactionSpeed;
        $this->fullNotifications = !!$fullNotifications;
        $this->notificationEmail = $notificationEmail;
        $this->hashGenerator = $hashGenerator;
        $this->translator = $translator;
    }

    public function getParametersFromOrder(OrderInterface $order)
    {
        $params = array(
            'amount' => round($order->getPaymentInstruction()->getAmount(), 2),
            'currency' => $order->getPaymentInstruction()->getCurrency(),
            'returnUrl' => $this->router->generate(
                'payment_successful',
                array('order' => $order->getId()),
                RouterInterface::ABSOLUTE_URL
            ),
            'notifyUrl' => $this->router->generate(
                "hyper_ads.omnipay.ipn.bitpay",
                array(),
                RouterInterface::ABSOLUTE_URL
            ),
            'transactionSpeed' => $this->transactionSpeed,
            'fullNotifications' => $this->fullNotifications,
            'orderId' => $order->getOrderNumber(),
            'description' => $this->translator->trans(
                'payment.info',
                array('%orderNumber%' => $order->getOrderNumber()),
                'HyperAdsBundle'
            ),
        );

        if (!empty($this->notificationEmail)) {
            $params['notifyEmail'] = $this->notificationEmail;
        }

        $params['transactionId'] = json_encode(
            array(
                'hash' => $this->hashGenerator->hashOrder($order),
                'posData' => $this->getPosData($order),
            )
        );

        return $params;
    }

    private function getPosData(OrderInterface $order)
    {
        return array(
            'order' => $order->getId(),
        );
    }
}


text:
/**
 * 模块入口
 *
 * @author 老雷<leizongmin@gmail.com>
 */

var DEFAULT = require('./default');
var parser = require('./parser');
var FilterXSS = require('./xss');

/**
 * XSS过滤
 *
 * @param {String} html 要过滤的HTML代码
 * @param {Object} options 选项:whiteList, onTag, onTagAttr, onIgnoreTag, onIgnoreTagAttr, safeAttrValue, escapeHtml
 * @return {String}
 */
function filterXSS (html, options) {
  var xss = new FilterXSS(options);
  return xss.process(html);
}

// 输出
exports = module.exports = filterXSS;
exports.FilterXSS = FilterXSS;
for (var i in DEFAULT) exports[i] = DEFAULT[i];
for (var i in parser) exports[i] = parser[i];

// 在AMD下使用
if (typeof define === 'function' && define.amd) {
  define(function () {
    return module.exports;
  });
}

// 在浏览器端使用
if (typeof window !== 'undefined') {
  window.filterXSS = module.exports;
}


text:
import moment from 'moment'
import pick from 'object.pick'
import omit from 'object.omit'
import Message from '../models/Message'
import config from '../../src/config'
import defaultMessage from '../../src/helpers/defaultMessage'
const logger = require('../../src/lib/logger')

function searchParams (roles = [], userId = '') {
  return {
    role: {'$in': roles},
    date_to: {
      $gte: moment().toDate()
    },
    date_from: {
      $lte: moment().toDate()
    },
    hidefor: {
      $ne: userId
    }
  }
}

function search (request, reply) {
  const start = new Date().getTime()
  const query = request.query.query || ''
  const size = request.query.size || 10
  const offset = request.query.offset || 0
  const userId = request.query.userId || false
  const roles = request.query.roles ? request.query.roles.split(',') : false

  let params = searchParams(roles, userId)
  if (!userId) {
    params = omit(params, ['hidefor'])
  }
  if (!roles) {
    params = omit(params, ['role'])
  }

  Message.search(query, null, {
    skip: parseInt(offset),
    conditions: params,
    limit: parseInt(size)
  }, (err, data) => {
    if (err) {
      return reply(err).code(500)
    }
    reply({
      took: new Date().getTime() - start,
      hits: {
        total: data.totalCount,
        hits: data.results.map((item) => {
          return {
            _type: 'message',
            _id: item._id,
            _score: item._relevance,
            _url: `${config.publicUrl}/meldinger/${item._id}`,
            _source: pick(item, ['_id', 'title', 'text', 'user', 'role', 'date_to', 'date_from'])
          }
        })
      }
    })
  })
}

function readOne (request, reply) {
  Message.findOne({_id: request.params.id})
  .then((doc) => {
    reply(doc)
  })
  .catch((err) => {
    reply(err).code(400)
  })
}

function readAll (request, reply) {
  const {roles, offset, limit} = {
    roles: request.query.roles ? request.query.roles.split('|') : request.auth.credentials.role,
    limit: request.query.limit || 20,
    offset: request.query.offset || 0
  }
  const params = searchParams(roles, request.auth.credentials.userId)
  Promise.all([
    /* First fetch all you likes */
    Message.find({...params, likes: request.auth.credentials.userId})
    .sort({'date_from': -1}),
    /* Then fill all other */
    Message.find({...params, likes: {$ne: request.auth.credentials.userId}})
    .skip(parseInt(offset))
    .limit(parseInt(limit))
    .sort({'date_from': -1})
  ]).then((promises) => {
    reply([...promises[0], ...promises[1]])
  })
  .catch((err) => {
    reply(err).code(400)
  })
}

export function createMessage (payload, request) {
  const template = defaultMessage()
  return new Promise((resolve, reject) => {
    const userId = request.auth.credentials.userId
    logger('info', ['messages', 'createMessage', 'user', userId, 'start'])
    new Message({
      ...template,
      ...pick(payload, ['title', 'text', 'user', 'role']),
      date_from: payload.date_from ? moment(payload.date_from).toDate() : template.date_from,
      date_to: payload.date_to ? moment(payload.date_to).toDate() : template.date_to
    })
    .save()
    .then((doc) => {
      logger('info', ['messages', 'createMessage', 'user', userId, 'success', doc._id])
      if (shouldShowMessage(doc)) {
        publishMessage(request, doc)
      }
      resolve(doc)
    })
    .catch((err) => {
      logger('error', ['messages', 'createMessage', 'user', userId, err])
      reject(err)
    })
  })
}

function create (request, reply) {
  const {payload, auth: {credentials}} = request
  createMessage({
    ...payload,
    user: pick(credentials, ['cn', 'mail'])
  }, request)
  .then((doc) => reply(doc))
  .catch((err) => reply(err))
}

function shouldShowMessage (doc) {
  const now = new Date().getTime()
  return (doc.date_from.getTime() < now && doc.date_to.getTime() > now)
}

function publishMessage (request, doc, obj = false) {
  doc.role.forEach((role) => {
    request.server.publish(`/messageupdates/${role}`, obj || doc)
  })
}

function update (request, reply) {
  Message.findOne({_id: request.params.id})
  .then((doc) => {
    doc.title = request.payload.title
    doc.text = request.payload.text
    doc.date_from = moment(request.payload.date_from).toDate()
    doc.date_to = moment(request.payload.date_to).toDate()
    doc.role = request.payload.role
    return doc.save()
  })
  .then((doc) => {
    reply(doc)
    if (shouldShowMessage(doc)) {
      publishMessage(request, doc)
    }
  })
  .catch((err) => {
    reply(err).code(400)
  })
}

function remove (request, reply) {
  const userId = request.auth.credentials.userId
  logger('info', ['messages', 'remove', 'user', userId, 'message', request.params.id, 'start'])
  Message.findOne({_id: request.params.id})
  .then((doc) => {
    return doc.remove()
  })
  .then((doc) => {
    reply(doc)
    if (shouldShowMessage(doc)) {
      publishMessage(request, doc, {deleted: request.params.id})
    }
  })
  .catch((err) => {
    logger('error', ['messages', 'remove', 'user', userId, 'message', request.params.id, error])
    reply(err).code(400)
  })
}

function likeMessage (request, reply) {
  Message.findOne({_id: request.params.id})
  .then((doc) => {
    const likes = [...doc.likes]
    likes.push(request.auth.credentials.userId)
    doc.likes = likes
    return doc.save()
  })
  .then((doc) => {
    reply(doc)
    if (shouldShowMessage(doc)) {
      publishMessage(request, doc)
    }
  })
  .catch((err) => {
    reply(err).code(400)
  })
}

function hideMessage (request, reply) {
  Message.findOne({_id: request.params.id})
  .then((doc) => {
    const hidefor = [...doc.hidefor]
    hidefor.push(request.auth.credentials.userId)
    doc.hidefor = hidefor
    return doc.save()
  })
  .then((doc) => {
    reply(doc)
    if (shouldShowMessage(doc)) {
      publishMessage(request, doc)
    }
  })
  .catch((err) => {
    reply(err).code(400)
  })
}

function unLikeMessage (request, reply) {
  Message.findOne({_id: request.params.id})
  .then((doc) => {
    doc.likes = doc.likes.filter((user) => user !== request.auth.credentials.userId)
    return doc.save()
  })
  .then((doc) => {
    reply(doc)
    if (shouldShowMessage(doc)) {
      publishMessage(request, doc)
    }
  })
  .catch((err) => {
    reply(err).code(400)
  })
}

const Messages = {
  readOne,
  readAll,
  create,
  update,
  remove,
  likeMessage,
  unLikeMessage,
  hideMessage,
  search
}

export default Messages


text:
from airflow.contrib.hooks.aws_hook import AwsHook

class RedshiftHook(AwsHook):
    """
    Interact with AWS Redshift, using the boto3 library
    """
    def get_conn(self):
        return self.get_client_type('redshift')

    # TODO: Wrap create_cluster_snapshot
    def cluster_status(self, cluster_identifier):
        """
        Return status of a cluster

        :param cluster_identifier: unique identifier of a cluster whose properties you are requesting
        :type cluster_identifier: str
        """
        # Use describe clusters
        response = self.get_conn().describe_clusters(ClusterIdentifier=cluster_identifier)
        # Possibly return error if cluster does not exist
        return response['Clusters'][0]['ClusterStatus'] if response['Clusters'] else None

    def delete_cluster(self, cluster_identifier, skip_final_cluster_snapshot=True, final_cluster_snapshot_identifier=''):
        """
        Delete a cluster and optionally create a snapshot

        :param cluster_identifier: unique identifier of a cluster whose properties you are requesting
        :type cluster_identifier: str
        :param skip_final_cluster_snapshot: determines if a final cluster snapshot is made before shut-down
        :type skip_final_cluster_snapshot: bool
        :param final_cluster_snapshot_identifier: name of final cluster snapshot
        :type final_cluster_snapshot_identifier: str
        """
        response = self.get_conn().delete_cluster(
            ClusterIdentifier = cluster_identifier,
            SkipFinalClusterSnapshot = skip_final_cluster_snapshot,
            FinalClusterSnapshotIdentifier = final_cluster_snapshot_identifier
        )
        return response['Cluster'] if response['Cluster'] else None

    def describe_cluster_snapshots(self, cluster_identifier):
        """
        Gets a list of snapshots for a cluster

        :param cluster_identifier: unique identifier of a cluster whose properties you are requesting
        :type cluster_identifier: str
        """
        response = self.get_conn().describe_cluster_snapshots(
            ClusterIdentifier = cluster_identifier
        )
        if 'Snapshots' not in response:
            return None
        snapshots = response['Snapshots']
        snapshots = filter(lambda x: x['Status'], snapshots)
        snapshots.sort(key=lambda x: x['SnapshotCreateTime'], reverse=True)
        return snapshots

    def restore_from_cluster_snapshot(self, cluster_identifier, snapshot_identifier):
        """
        Restores a cluster from it's snapshot

        :param cluster_identifier: unique identifier of a cluster whose properties you are requesting
        :type cluster_identifier: str
        :param snapshot_identifier: unique identifier for a snapshot of a cluster
        :type snapshot_identifier: str
        """
        response = self.get_conn().restore_from_cluster_snapshot(
            ClusterIdentifier = cluster_identifier,
            SnapshotIdentifier = snapshot_identifier
        )
        return response['Cluster'] if response['Cluster'] else None

    def create_cluster_snapshot(self, snapshot_identifier, cluster_identifier):
        """
        Creates a snapshot of a cluster

        :param snapshot_identifier: unique identifier for a snapshot of a cluster
        :type snapshot_identifier: str
        :param cluster_identifier: unique identifier of a cluster whose properties you are requesting
        :type cluster_identifier: str
        """
        response = self.get_conn().create_cluster_snapshot(
            SnapshotIdentifier=snapshot_identifier,
            ClusterIdentifier=cluster_identifier,
        )
        return response['Snapshot'] if response['Snapshot'] else None


text:
if os[:family] == 'debian' || os[:family] == 'ubuntu'
  if os[:release].to_i == 7 || os[:release].to_f == 12.04
    describe file('/etc/apache2-default/conf.d') do
      it { should be_directory }
      its('mode') { should eq 00755 }
      it { should be_owned_by 'root' }
      it { should be_grouped_into 'root' }
    end

    describe file('/etc/apache2-default/conf.d/hello.conf') do
      it { should be_file }
      it { should be_owned_by 'root' }
      it { should be_grouped_into 'root' }
      its('mode') { should eq 00644 }
    end

    describe file('/etc/apache2-foo/conf.d/hello_again.conf') do
      it { should be_file }
      it { should be_owned_by 'root' }
      it { should be_grouped_into 'root' }
      its('mode') { should eq 00644 }
    end
  else
    describe file('/etc/apache2-default/conf-available') do
      it { should be_directory }
      it { should be_owned_by 'root' }
      it { should be_grouped_into 'root' }
      its('mode') { should eq 00755 }
    end

    describe file('/etc/apache2-default/conf-enabled') do
      it { should be_directory }
      it { should be_owned_by 'root' }
      it { should be_grouped_into 'root' }
      its('mode') { should eq 00755 }
    end

    describe file('/etc/apache2-default/conf-available/hello.conf') do
      it { should be_file }
      its('mode') { should eq 00644 }
      it { should be_owned_by 'root' }
      it { should be_grouped_into 'root' }
    end

    describe file('/etc/apache2-default/conf-enabled/hello.conf') do
      it { should be_file }
      it { should be_owned_by 'root' }
      it { should be_grouped_into 'root' }
      it { should be_linked_to '/etc/apache2-default/conf-available/hello.conf' }
    end

    describe file('/etc/apache2-foo/conf-available') do
      it { should be_directory }
      it { should be_owned_by 'root' }
      it { should be_grouped_into 'root' }
      its('mode') { should eq 00755 }
    end

    describe file('/etc/apache2-foo/conf-enabled') do
      it { should be_directory }
      it { should be_owned_by 'root' }
      it { should be_grouped_into 'root' }
      its('mode') { should eq 00755 }
    end

    describe file('/etc/apache2-foo/conf-available/hello_again.conf') do
      it { should be_file }
      it { should be_owned_by 'root' }
      it { should be_grouped_into 'root' }
      its('mode') { should eq 00644 }
    end

    describe file('/etc/apache2-foo/conf-enabled/hello_again.conf') do
      it { should be_file }
      it { should be_owned_by 'root' }
      it { should be_grouped_into 'root' }
      it { should be_linked_to '/etc/apache2-foo/conf-available/hello_again.conf' }
    end
  end
end


text:
title: Hands-on Web Development with React (Video Course)
seo_description: Hands-on web development with React is a video course by Filip Danić. Aimed at newcomers who want to learn React.js
promo_photo: /content/images/2018/react-web-development-course.png
date: 2018-09-28
tags:
---

After nearly 200 hours of work, my first video course is available! _**[Hands-on Web Development with React](https://www.packtpub.com/web-development/hands-web-development-react-video)**_ is available via Packt Publishing and you can actually jump into the course for free [via Mapt.](https://www.packtpub.com/mapt/video/web_development/9781789343915) (Packt's on-demand course platform.)

## The Elevator Pitch

You'll learn how to build a ReactJS web application / SPA from scratch. We're going to build a job board app where:
- Visitors can see job postings and search through them via a global search bar.
- Registered users can add/edit postings (if they're on a `paid plan`) and view stats on their existing/old ones.
- Admin users can edit postings and view global analytics in the form of a nice chart.

Along the way, you'll also learn about `css-in-js`, mocking, functional programming, and pick up some general software engineering wisdom.

The course is structured into 7 sections that span across ~4.5 hours. Each with a particular set of goals and challenges that we'll overcome. You can skip ahead and read [the full list.](#The-Long-List)

_Note: The course is made with React 16 in mind, but works with `15.x.x`. The guide will still be relevant once React 17.0.0 is released._

**Style & Approach:**

- The videos are mostly a mix of talking and live coding, accompanied by slides when discussing theoretical concepts.
- Code files are included with the course.
  - There is also a [git repository]( https://github.com/PacktPublishing/Hands-on-Web-Development-with-React) where each commit is tagged with the video it related to.
- Each video follows a similar pattern:
  - **Step 1:** What's the problem? How are we planning to solve it?
  - **Step 2:** What technical concepts do we need?
  - **Step 3:** Let's code it out and discus along the way!
- The sound is recorded with a solid condenser microphone and pop-filter.
  - An introductory video at the bottom of the course landing page will give you a good idea of the sound quality and my accent. :)
- There's a quiz within and at the end of some of the videos, to test if you've been paying attention.

Note: if you've seen my [YouTube or Twitch videos](https://www.youtube.com/channel/UClctBvKpOUts0_B_kvooo_w) then you should know that the approach in this course is different. The videos are between 4 to 10 minutes long and highly focused. Unlike the streams which last for hours and are fairly _"free form."_

My advice for consuming the content of the course is to watch it in chunks between 2 to 6 minutes and then pause and try writing some code yourself.

## The Long List

**You will:**
- Learn how to bootstrap a React application with Create React App.
- Create React components and manage application state.
  - Forms and event handling.
  - Lists and dynamic item rendering.
  - Loading indicators and placeholders.
  - Other common UI components.
- Understand the why and how behind core React concepts and common patterns.
  - Lifecycle methods.
  - React PropTypes.
  - State lifting and prop drilling.
  - Callback-controlled data flow.
  - Functional (Stateless) components.
- Learn patterns for building reusable ReactJS components.
- Learn how to communicate with a real server, as well as local mocks.
- Use CSS-in-JS with `styled-components`.
- Build a fully-functional, feature-rich SPA with:
  - Dynamic routing via `react-router-dom`,
  - support for multiple roles, and
  - granular access control via feature/permission flags.
- Learn core functional programming concepts and how they apply to working with React.
  - Map, filter, reduce!
  - Pure functions.
  - Immutability.
  - Higher order functions and higher order components.
- Practice Unit and Snapshot Testing with Jest, a JavaScript test runner.
- Figure out how to configure your build and deploy it to production.
- Learn about the basics of React's internals:
  - The virtual DOM.
  - The reconciliation algorithm and diffing process.

## What I Left Out

There are also some things that I've left out and that you might have expected would be in the course. I think it's fair to mention those:

- The React Context API – it's not something you need at a junior/intermediate level. When you need it, you'll be able to read up on it and learn it by yourself.
- Render Props – it's considered an "advanced pattern", but this is mainly to it being a new, shiny tool in a React developer's arsenal. When you need them, you can learn them on your own. They're not that important at this stage.
- Redux – it's common for instructors to bundle Redux into a React course. The two technologies are used widely. However, I feel that Redux is it's own topic and I am against learning it before you have a good grasp of React.
 - Once you understand the pains of state management, you're ready to start exploring Redux on your own. There's also a ton of free resources that would explain it better than I would. [Including one by Dan Abramov, the creator of Redux.](https://egghead.io/courses/getting-started-with-redux)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using ReClassNET.Extensions;
using ReClassNET.Memory;
using ReClassNET.Nodes;

namespace ReClassNET.UI
{
	[ToolboxItem(false)]
	public class MemoryPreviewPopUp : ToolStripDropDown
	{
		private const int ToolTipWidth = 1000 + ToolTipPadding;
		private const int ToolTipPadding = 4;

		/// Panel for the memory preview.
		private class MemoryPreviewPanel : Panel
		{
			private const int MinNodeCount = 10;

			public ViewInfo ViewInfo { get; }

			private readonly List<BaseHexNode> nodes;

			public MemoryPreviewPanel(FontEx font)
			{
				Contract.Requires(font != null);

				DoubleBuffered = true;

				nodes = new List<BaseHexNode>();

				ViewInfo = new ViewInfo
				{
					Font = font,

					Memory = new MemoryBuffer(),

					HotSpots = new List<HotSpot>()
				};

				SetNodeCount(MinNodeCount);

				CalculateSize();
			}

			/// Sets the absolute number of nodes and resizes the underlaying memory buffer.
			/// <param name="count">Number of nodes.</param>
			private void SetNodeCount(int count)
			{
				BaseHexNode CreateNode(int index)
				{
					return new
#if RECLASSNET64
					Hex64Node
#else
					Hex32Node
#endif
					{
						Offset = index * IntPtr.Size
					};
				}

				if (nodes.Count < count)
				{
					nodes.AddRange(Enumerable.Range(nodes.Count, count - nodes.Count).Select(CreateNode));
				}
				else if (nodes.Count > count && count >= MinNodeCount)
				{
					nodes.RemoveRange(count, nodes.Count - count);
				}

				ViewInfo.Memory.Size = nodes.Select(n => n.MemorySize).Sum();
			}

			/// Changes the number of nodes with the provided delta.
			/// <param name="delta">The change delta.</param>
			public void ChangeNodeCount(int delta)
			{
				SetNodeCount(nodes.Count + delta);

				CalculateSize();
			}

			/// Resets the settings of the panel to the defaults.
			public void Reset()
			{
				SetNodeCount(MinNodeCount);

				CalculateSize();
			}

			/// Calculates the size of the panel.
			private void CalculateSize()
			{
				var size = new Size(
					ToolTipWidth,
					nodes.Sum(n => n.CalculateDrawnHeight(ViewInfo)) + ToolTipPadding
				);

				ViewInfo.ClientArea = new Rectangle(ToolTipPadding / 2, ToolTipPadding / 2, size.Width - ToolTipPadding, size.Height - ToolTipPadding);

				Size = MinimumSize = MaximumSize = size;
			}

			protected override void OnPaint(PaintEventArgs e)
			{
				ViewInfo.HotSpots.Clear();

				// Some settings are not usefull for the preview.
				ViewInfo.Settings = Program.Settings.Clone();
				ViewInfo.Settings.ShowNodeAddress = false;

				ViewInfo.Context = e.Graphics;

				using (var brush = new SolidBrush(ViewInfo.Settings.BackgroundColor))
				{
					e.Graphics.FillRectangle(brush, ClientRectangle);
				}
				using (var pen = new Pen(ViewInfo.Settings.BackgroundColor.Invert(), 1))
				{
					e.Graphics.DrawRectangle(pen, new Rectangle(Bounds.X, Bounds.Y, Bounds.Width - 1, Bounds.Height - 1));
				}

				int x = -24;
				int y = 2;
				foreach (var node in nodes)
				{
					y += node.Draw(ViewInfo, x, y).Height;
				}
			}
		}

		private readonly MemoryPreviewPanel panel;

		private IntPtr memoryAddress;

		protected override CreateParams CreateParams
		{
			get
			{
				const int WS_EX_NOACTIVATE = 0x08000000;

				var cp = base.CreateParams;
				cp.ExStyle |= WS_EX_NOACTIVATE;
				return cp;
			}
		}

		public MemoryPreviewPopUp(FontEx font)
		{
			Contract.Requires(font != null);

			AutoSize = false;
			AutoClose = false;
			DoubleBuffered = true;
			ResizeRedraw = true;
			TabStop = false;

			panel = new MemoryPreviewPanel(font)
			{
				Location = Point.Empty
			};

			var host = new ToolStripControlHost(panel);
			Padding = Margin = host.Padding = host.Margin = Padding.Empty;
			MinimumSize = panel.MinimumSize;
			panel.MinimumSize = panel.Size;
			MaximumSize = panel.MaximumSize;
			panel.MaximumSize = panel.Size;
			Size = panel.Size;

			panel.SizeChanged += (s, e) => Size = MinimumSize = MaximumSize = panel.Size;

			Items.Add(host);
		}

		protected override void OnClosed(ToolStripDropDownClosedEventArgs e)
		{
			panel.Reset();

			base.OnClosed(e);
		}

		internal void HandleMouseWheelEvent(MouseEventArgs e)
		{
			if (e.Delta != 0)
			{
				panel.ChangeNodeCount(e.Delta < 0 ? 1 : -1);

				UpdateMemory();

				Invalidate();

				if (e is HandledMouseEventArgs he)
				{
					he.Handled = true;
				}
			}
		}

		/// Initializes the memory buffer.
		/// <param name="process">The process to use.</param>
		/// <param name="address">The address to read from.</param>
		public void InitializeMemory(RemoteProcess process, IntPtr address)
		{
			Contract.Requires(process != null);

			memoryAddress = address;

			var memory = panel.ViewInfo.Memory;
			memory.Process = process;
			memory.Update(address);
		}

		/// Updates the memory buffer to get current data.
		public void UpdateMemory()
		{
			panel.ViewInfo.Memory.Update(memoryAddress);

			panel.Invalidate();
		}
	}
}


text:
@* signupPage Template File *@
@(signupForm: Form[(String, (String, String))])(flash: play.api.mvc.Flash)(implicit session: play.api.mvc.Session)

@import helper._
@import helper.twitterBootstrap._

@main("Signup"){

@form(action = routes.Auth.signupSubmit()){

    <fieldset>
    <legend>Sign Up or Go to Login</legend>

            @inputText(
                signupForm("email"),
                '_label -> "Email",
                '_showConstraints -> false
            )

            @inputPassword(
                signupForm("passwords.first_time"),
                '_label -> "Password",
                '_showConstraints -> false
            )

            @inputPassword(
                signupForm("passwords.second_time"),
                '_label -> "Repeat Password",
                '_showConstraints -> false
            )
        <button class="btn btn-default">Sign Up</button>

    </fieldset>

}

@flash.get("success").map{ message =>

@message

}

@signupForm.globalErrors.map{ error =>

@Messages(error.message)

}

}


text:
package com.google.common.collect;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Collections;

/**
 * GWT emulation of {@link SingletonImmutableMap}.
 *
 * @author Hayward Chan
 */
final class SingletonImmutableMap<K, V> extends ImmutableMap<K, V> {

  // These references are used both by the custom field serializer, and by the
  // GWT compiler to infer the keys and values of the map that needs to be
  // serialized.
  //
  // Although they are non-final, they are package private and the reference is
  // never modified after a map is constructed.
  K singleKey;
  V singleValue;

  SingletonImmutableMap(K key, V value) {
    super(Collections.singletonMap(checkNotNull(key), checkNotNull(value)));
    this.singleKey = key;
    this.singleValue = value;
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
All Classes
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

Almost

ArrayUtil

ArrayUtil.IllPosedException

ArrayUtil.Line3

ArrayUtil.Plane3

ArrayUtil.Rotate3

ArrayVect1

CleanFormatter

CleanHandler

CoordinateTransform

GaussNewtonSolver

GaussNewtonSolverTest

IndexGrouper

IndexGrouper.Grouper

IndexSorter

LinearTransform

LinearTransformWrapper

Localize

LoggerStream

LogMonitor

Monitor

PartialMonitor

Quadratic

QuadraticSolver

ScalarSolver

ScalarSolver.Function

StringUtil

StringUtil.TableBuilder

Transform

TransformQuadratic

Vect

VectConst

VectUtil


text:
<?xml version="1.0"?>
<package>
  <name>crazyflie_controller</name>
  <version>0.0.1</version>
  <description>Controller to fly a Crazyflie in a space with location feedback (such as motion capture).</description>

  <maintainer email="whoenig@usc.edu">Wolfgang Hoenig</maintainer>

  <license>MIT</license>

  <url type="website">http://ros.org/wiki/crazyflie</url>
  <url type="bugtracker">https://github.com/whoenig/crazyflie_ros/issues</url>

  <author email="whoenig@usc.edu">Wolfgang Hoenig</author>

  <buildtool_depend>catkin</buildtool_depend>
</package>


text:
/*
 * Author: Mihailscu Maria-Elena
 * Faculty of Automatic Control and Computer Science,
 * University POLITHENICA of Bucharest
 */

import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.misc.Interval;
import java.util.ArrayList;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.*;

import java.util.ArrayList;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class DokuWikiTablesListener extends DokuWikiTablesGrammarBaseListener {
	DokuWikiTablesGrammarParser parser;
	private String wikihost = "";
	private int rowIndex = -1;
	private int colIndex = -1;
	private int rowNo = 0;
	private int colNo = 0;

	private ArrayList<ArrayList<String>> matrix;

	public DokuWikiTablesListener(DokuWikiTablesGrammarParser parser) {
		this.parser = parser;
		matrix = new ArrayList<ArrayList<String>>();
	}

	public DokuWikiTablesListener(DokuWikiTablesGrammarParser parser, String dokuWikiHost) {
		this.parser = parser;
		this.wikihost = dokuWikiHost;
		matrix = new ArrayList<ArrayList<String>>();
	}

	private int multicolumn(int row, int position) {
		ArrayList<String> rowList = matrix.get(row);
		int multicolumnIndex = 0;
		int i = position + 1;
		while (true) {
			if (i >= colNo)
				break;
			if (! (rowList.get(i).equals("^") || rowList.get(i).equals("|")))
				break;
			i += 1;
			multicolumnIndex += 1;
		}

		return multicolumnIndex;
	}

	private char checkAlign(String s) {
		int trailing = 0, leading = 0;
		int i = 0;
		while(true) {
			if (i >= s.length())
				break;
			if (s.charAt(i) != ' ')
				break;
			leading += 1;
			i += 1;
		}

		i = s.length() - 1;
		while(true) {
			if(i <= 0)
				break;
			if (s.charAt(i) != ' ')
				break;
			trailing += 1;
			i -= 1;
		}

		if (leading > trailing && leading >= 2)
			return 'r';

		if (trailing > leading  && trailing >= 2)
			return 'l';

		if (leading <= 1 && trailing <= 1)
			return 'l';

		return 'c';
	}

	private int multirow(int startFromRow, int column) {
		int multirowIndex = 0;
		int i = startFromRow + 1;
		while(true) {
			if (i >= rowNo)
				break;
			if (!matrix.get(i).get(column).contains(":::"))
				break;
			multirowIndex += 1;
			i += 1;
		}
		return multirowIndex;
	}

	private void printLaTeXMatrix() {
		char align;
		System.out.print("\\begin{tabular}{|");
		for (int i = 0 ; i < colNo; i++)
			System.out.print("l ");
		System.out.println("|}");

		int r = -1, c = -1;
		System.out.println("\\hline");

		for (ArrayList<String> rowList : matrix) {
			r += 1;
			c = -1;
			int toIgnore = 0;
			for (String cell : rowList) {
				c += 1;
				if (toIgnore > 0) {
					toIgnore -= 1;
					continue;
				}
				// see if multicolumn
				int multicolumnIndex = multicolumn(r, c);
				// System.out.println("DEBUG: multicolumn " + multicolumnIndex);
				// see if multirow
				int multirowIndex = multirow(r, c);
				// System.out.println("DEBUG: multirow " + multirowIndex);
				if (c > 0)
					System.out.print("&");

				if (cell.equals("")) {

				}
				else if(multicolumnIndex == 0 && multirowIndex == 0) {
					// print cell
					/*
					if (cell.contains("\\begin{verbatim}") || cell.contains("\\vbox")) {
						if (cell.startsWith("|")){
							System.out.print(cell.replace("|", ""));
						} else {
							System.out.print("\\cellcolor[gray]{0.8}{" + cell.replace("^", "") + "}");
						}
					} else
					*/
					if (cell.startsWith("|")){
						// cell = cell.substring(1, cell.length());
						// align = checkAlign(cell);
						// cell = cell.trim();
						// if (align == 'l') {
						System.out.print(cell.replace("|", ""));
						// } else if (align == 'r') {
						// 	System.out.print("\\multicolumn{1}{r}{" + cell + "}");
						// } else {
						// 	System.out.print("\\multicolumn{1}{c}{" + cell + "}");
						// }
						// System.out.print(cell.replace("|", ""));
					} else {
						System.out.print("\\cellcolor[gray]{0.8}{" + cell.replace("^", "") + "}");
					}

				} else if (multicolumnIndex > 0) {
					toIgnore = multicolumnIndex;
					System.out.print("\\multicolumn{" + (1 + multicolumnIndex) + "}{l}{");
					if (cell.startsWith("|")){
						System.out.print(cell.replace("|", ""));
					}
					else {
						System.out.print("\\cellcolor[gray]{0.8}{" + cell.replace("^", "") + "}");
					}
					System.out.print("} ");

				} else if (multirowIndex > 0) {
					System.out.print("\\multirow{" + (1 + multirowIndex) + "}*{");
					if (cell.startsWith("|")){
						System.out.print(cell.replace("|", ""));
					}
					else {
						System.out.print("\\cellcolor[gray]{0.8}{" + cell.replace("^", "") + "}");
					}
					System.out.print("} ");

					for (int i = r + 1; i < multirowIndex + r + 1; i ++) {
						ArrayList<String> rowListAux = matrix.get(i);
						rowListAux.set(c, "");
					}
				}

			}
			System.out.println("\\\\");
		}
		System.out.println("\\hline");
		System.out.println("\\end{tabular}");
	}

	@Override
	public void enterTable(DokuWikiTablesGrammarParser.TableContext ctx) {
	}

	@Override
	public void exitTable(DokuWikiTablesGrammarParser.TableContext ctx) {
		printLaTeXMatrix();
	}

	@Override
	public void enterRow(DokuWikiTablesGrammarParser.RowContext ctx) {
		rowNo += 1;
		colIndex = -1;
		rowIndex += 1;
		// if (rowNo != 1) {
		// 	System.out.println(" \\\\ \\hline");
		// }
		ArrayList<String> rowList = new ArrayList<String>();
		matrix.add(rowIndex, rowList);

		int start = ctx.start.getStartIndex();
    	int end = ctx.stop.getStopIndex();
     	Interval interval = new Interval(start, end);

     	String row = ctx.start.getInputStream().getText(interval).toString();

     	colNo = Utils.countCharInString(row, '|') + Utils.countCharInString(row, '^') - 1;

     	// if (rowNo == 1) {
     	// 	System.out.print("{|");
     	// 	for (int k = 0; k < colNo; k ++)
     	// 		System.out.print("c|");
     	// 	System.out.println("}");
     	// }
	}

	@Override
	public void exitRow(DokuWikiTablesGrammarParser.RowContext ctx) {

	}

	@Override public void enterCell(DokuWikiTablesGrammarParser.CellContext ctx) {
		colIndex += 1;
		ArrayList<String> rowList = matrix.get(rowIndex);

		int start = ctx.start.getStartIndex();
    	int end = ctx.stop.getStopIndex();
     	Interval interval = new Interval(start, end);

     	String cell = ctx.start.getInputStream().getText(interval).toString();
     	if (cell.startsWith("^"))
			rowList.add(colIndex, "^");
		else
			rowList.add(colIndex, "|");
	}

	@Override
	public void exitCell(DokuWikiTablesGrammarParser.CellContext ctx) {
		// if (colIndex < colNo - 1) {
		// 	// System.out.print("&");

		// 	// ArrayList<String> rowList = matrix.get(rowIndex);
		// 	// String elem = rowList.get(colIndex);
		// 	// elem += "&";
		// 	// rowList.set(colIndex, elem);
		// }
	}

	@Override
	public void enterTable_nowiki(DokuWikiTablesGrammarParser.Table_nowikiContext ctx) {
		if (ctx.NOWIKI_TOKEN() == null)
			return;
		String s = ctx.NOWIKI_TOKEN().toString();
		s = Utils.removeFirstAndLastTag(s);
		s = SpecialChars.replaceLaTeXSpecialChars(s);

		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += s; ///* "\\vbox{"   + "\\begin{verbatim}"  + */ s /* + "\\end{verbatim}"  + "}" */;
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_nowiki2(DokuWikiTablesGrammarParser.Table_nowiki2Context ctx) {
		if (ctx.NOWIKI_TOKEN2() == null)
			return;
		String s = ctx.NOWIKI_TOKEN2().toString();
		s = s.substring(2, s.length() - 2);
		s = SpecialChars.replaceLaTeXSpecialChars(s);

		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += s;//"\\vbox{" /* + "\\begin{verbatim}" */ + s  /* + "\\end{verbatim}" */ + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_code(DokuWikiTablesGrammarParser.Table_codeContext ctx) {
		if (ctx.CODE_TOKEN1() == null)
			return;
		Utils.writeInLogFile("  -> Be aware of code sections inside table");
		String s = ctx.CODE_TOKEN1().toString();
		s = Utils.removeFirstAndLastTag(s);

		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + "\\begin{verbatim}" + s + "\\end{verbatim}" + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_file(DokuWikiTablesGrammarParser.Table_fileContext ctx) {
		if (ctx.FILE_TOKEN() == null)
			return;
		Utils.writeInLogFile("  -> Be aware of code sections inside table");
		String s = ctx.FILE_TOKEN().toString();
		s = Utils.removeFirstAndLastTag(s);

		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + "\\begin{verbatim}" + s + "\\end{verbatim}" + "}";
		rowList.set(colIndex, elem);
	}

//	@Override
//	public void enterTable_latexs(DokuWikiTablesGrammarParser.Table_latexsContext ctx) {
//		String s = ctx.LATEX_TOKEN_S().toString();
//		ArrayList<String> rowList = matrix.get(rowIndex);
//		String elem = rowList.get(colIndex);
//		elem += s;
//		rowList.set(colIndex, elem);
//	}
//
//	@Override
//	public void enterTable_latexss(DokuWikiTablesGrammarParser.Table_latexssContext ctx) {
//		String s = ctx.LATEX_TOKEN_SS().toString();
//		ArrayList<String> rowList = matrix.get(rowIndex);
//		String elem = rowList.get(colIndex);
//		elem += s.substring(1, s.length() - 1);
//		rowList.set(colIndex, elem);
//	}

	@Override
	public void enterTable_latextag(DokuWikiTablesGrammarParser.Table_latextagContext ctx) {

		String s = ctx.LATEX_TOKEN_TAG().toString();
		s = Utils.removeFirstAndLastTag(s);
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += s.trim();
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_displaymath(DokuWikiTablesGrammarParser.Table_latex_displaymathContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");

		String s = ctx.LATEX_TOKEN_DISPLAYMATH().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_eqnarray(DokuWikiTablesGrammarParser.Table_latex_eqnarrayContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");

		String s = ctx.LATEX_TOKEN_EQNARRAY().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_eqnarray_star(DokuWikiTablesGrammarParser.Table_latex_eqnarray_starContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");

		String s = ctx.LATEX_TOKEN_EQNARRAY_STAR().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_equation(DokuWikiTablesGrammarParser.Table_latex_equationContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");

		String s = ctx.LATEX_TOKEN_EQUATION().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_equation_star(DokuWikiTablesGrammarParser.Table_latex_equation_starContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
		String s = ctx.LATEX_TOKEN_EQUATION_STAR().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_align(DokuWikiTablesGrammarParser.Table_latex_alignContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
		String s = ctx.LATEX_TOKEN_ALIGN().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_align_star(DokuWikiTablesGrammarParser.Table_latex_align_starContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
		String s = ctx.LATEX_TOKEN_ALIGN_STAR().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_alignat(DokuWikiTablesGrammarParser.Table_latex_alignatContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
		String s = ctx.LATEX_TOKEN_ALIGNAT().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_alignat_star(DokuWikiTablesGrammarParser.Table_latex_alignat_starContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
		String s = ctx.LATEX_TOKEN_ALIGNAT_STAR().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_flalign(DokuWikiTablesGrammarParser.Table_latex_flalignContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
		String s = ctx.LATEX_TOKEN_FLALIGN().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_flalign_star(DokuWikiTablesGrammarParser.Table_latex_flalign_starContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
		String s = ctx.LATEX_TOKEN_FLALIGN_STAR().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_gather(DokuWikiTablesGrammarParser.Table_latex_gatherContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
		String s = ctx.LATEX_TOKEN_GATHER().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_gather_star(DokuWikiTablesGrammarParser.Table_latex_gather_starContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
		String s = ctx.LATEX_TOKEN_GATHER_STAR().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_multiline(DokuWikiTablesGrammarParser.Table_latex_multilineContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
  		String s = ctx.LATEX_TOKEN_MULTILINE().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_multiline_star(DokuWikiTablesGrammarParser.Table_latex_multiline_starContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
		String s = ctx.LATEX_TOKEN_MULTILINE_STAR().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_latex_math(DokuWikiTablesGrammarParser.Table_latex_mathContext ctx) {
		Utils.writeInLogFile("  -> Be aware of LaTeX sections inside table");
		String s = ctx.LATEX_TOKEN_MATH().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\vbox{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_link(DokuWikiTablesGrammarParser.Table_linkContext ctx) {
		String s = ctx.LINK().toString();
		if (s.length() <= 4)
			return;
		s = s.substring(2, s.length() - 2);
		s = s.trim();

		StringBuilder linkSB = new StringBuilder();

		try {
			InputStream linkIs = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));

			ANTLRInputStream linksInput = new ANTLRInputStream(linkIs);

        	DokuWikiLinksGrammarLexer linksLexer = new DokuWikiLinksGrammarLexer(linksInput);
        	CommonTokenStream linksTokens = new CommonTokenStream(linksLexer);
	        DokuWikiLinksGrammarParser linksParser = new DokuWikiLinksGrammarParser(linksTokens);
	        ParseTree linksTree = linksParser.links_start();

	        ParseTreeWalker linksWalker = new ParseTreeWalker();
	        DokuWikiLinkListener linksExtractor = new DokuWikiLinkListener(linksParser, linkSB);
	        linksWalker.walk(linksExtractor, linksTree);
    	} catch (Exception e) {
    		System.err.println(e);
    	}

		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += linkSB.toString();
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_url1(DokuWikiTablesGrammarParser.Table_url1Context ctx) {
		String s = ctx.URL1().toString();
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\url{" + s + "}";
		rowList.set(colIndex, elem);
	}

	@Override public void enterTable_mail(DokuWikiTablesGrammarParser.Table_mailContext ctx) {
		String mail = ctx.MAIL().toString();
		mail = mail.replace("<", "");
		mail = mail.replace(">", "");

		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\href{mailto:" + mail + "}{" + mail + "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_media(DokuWikiTablesGrammarParser.Table_mediaContext ctx) {
		Utils.writeInLogFile("  -> Be aware of images inside a table."
			+ " Please review image dimensions and image position.\n"
			+ "    -> Please read " + Utils.logImagesFileName + " file.\n"
			+ "    -> Be aware of the fact that all media files are considered to be images. "
			+ "For other media files formats, please change manually the LaTeX code");

		String s = ctx.MEDIA_FILES_TOKEN().toString();
		s = s.substring(2, s.length() - 2);
		String text = "";
		String[] splitText = s.split("[|]");
		int width = -1, height = -1;
		if (splitText.length >= 2)
			text = splitText[1];

		String[] splitDimensions = splitText[0].split("[?]");
		String imageName = splitDimensions[0].trim();

		if (splitDimensions.length >= 2) {
			if (splitDimensions[1].contains("linkonly")) {
			} else {
				String[] splitWH = splitDimensions[1].split("x");
				width = Integer.parseInt(splitWH[0]);
				if (splitWH.length == 2) {
					height = Integer.parseInt(splitWH[1]);
				}
			}
		}
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);

		if (!text.isEmpty())
			elem += "\\caption{" + text + "} ";
		elem += "\\vbox{\\includegraphics";

		if (width > -1) {
			if (height > -1) {
				elem += "[width = " + width + "cm, height = " + height + "cm, keepaspectratio]";
			} else {
				elem += "[width = " + width + "cm, keepaspectratio]";
			}
		}
		elem += "{" + imageName + "}}";

		rowList.set(colIndex, elem);
		try {
			BufferedWriter output = new BufferedWriter(new FileWriter(Utils.logImagesFileName, true));
			output.write(imageName + "\n");
			output.close();
		} catch (Exception e) {

		}

	}

	@Override
	public void enterTable_html(DokuWikiTablesGrammarParser.Table_htmlContext ctx) {
		String s = ctx.HTML_TOKEN().toString();
		Utils.writeInLogFile("  -> HTML section in table\n"
									+ "    -> HTML sections are not converted in LaTeX."
									);
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += s;
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_php(DokuWikiTablesGrammarParser.Table_phpContext ctx) {
		String s = ctx.PHP_TOKEN().toString();
		Utils.writeInLogFile("  -> PHP section as list table\n"
									+ "    -> PHP sections are not converted in LaTeX."
									);
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += s;
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_bold(DokuWikiTablesGrammarParser.Table_boldContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\textbf{";
		rowList.set(colIndex, elem);
	}

	@Override
	public void exitTable_bold(DokuWikiTablesGrammarParser.Table_boldContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_italic(DokuWikiTablesGrammarParser.Table_italicContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\textit{";
		rowList.set(colIndex, elem);

	}

	@Override
	public void exitTable_italic(DokuWikiTablesGrammarParser.Table_italicContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_underline(DokuWikiTablesGrammarParser.Table_underlineContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\underline{";
		rowList.set(colIndex, elem);
	}

	@Override
	public void exitTable_underline(DokuWikiTablesGrammarParser.Table_underlineContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_monospaced(DokuWikiTablesGrammarParser.Table_monospacedContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\texttt{";
		rowList.set(colIndex, elem);
	}

	@Override
	public void exitTable_monospaced(DokuWikiTablesGrammarParser.Table_monospacedContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_superscript(DokuWikiTablesGrammarParser.Table_superscriptContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\textsuperscript{";
		rowList.set(colIndex, elem);

	}

	@Override
	public void exitTable_superscript(DokuWikiTablesGrammarParser.Table_superscriptContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "}";
		rowList.set(colIndex, elem);
	}

	@Override
	public void enterTable_subscript(DokuWikiTablesGrammarParser.Table_subscriptContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "$_{\\text{";
		rowList.set(colIndex, elem);

	}

	@Override
	public void exitTable_subscript(DokuWikiTablesGrammarParser.Table_subscriptContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "}}$";
		rowList.set(colIndex, elem);

	}

	@Override
	public void enterTable_del(DokuWikiTablesGrammarParser.Table_delContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\sout{";
		rowList.set(colIndex, elem);

	}

	@Override
	public void exitTable_del(DokuWikiTablesGrammarParser.Table_delContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "}";
		rowList.set(colIndex, elem);

	}

	@Override
	public void enterTable_footnote(DokuWikiTablesGrammarParser.Table_footnoteContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "\\footnote{";
		rowList.set(colIndex, elem);

	}

	@Override
	public void exitTable_footnote(DokuWikiTablesGrammarParser.Table_footnoteContext ctx) {
		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += "}";
		rowList.set(colIndex, elem);

	}

	@Override
	public void enterTable_unparsed(DokuWikiTablesGrammarParser.Table_unparsedContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
	@Override public void exitTable_unparsed(DokuWikiTablesGrammarParser.Table_unparsedContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
	@Override public void enterRaw_text(DokuWikiTablesGrammarParser.Raw_textContext ctx) {
		String s;
		if(ctx.UNPARSED() != null) {
			s = ctx.UNPARSED().toString();
			if (s.matches("((.|\n)*)" + SpecialChars.regex_keys +"((.|\n)*)")) {
				s = SpecialChars.replaceSpecialChars(s);
			}
			s = SpecialChars.replaceLaTeXSpecialChars(s);

			ArrayList<String> rowList = matrix.get(rowIndex);
			String elem = rowList.get(colIndex);
			elem += s;
			rowList.set(colIndex, elem);

			// System.out.print(s);
			// System.out.print(ctx.UNPARSED());
			if (ctx.ANYCHAR() == null)
				return;
		}

		if (ctx.SPECIAL_CHAR() != null) {
			s = ctx.SPECIAL_CHAR().toString();
			if (s.matches("((.|\n)*)" + SpecialChars.regex_keys +"((.|\n)*)")) {
				s = SpecialChars.replaceSpecialChars(s);
			}
			s = SpecialChars.replaceLaTeXSpecialChars(s);

			ArrayList<String> rowList = matrix.get(rowIndex);
			String elem = rowList.get(colIndex);
			elem += s;
			rowList.set(colIndex, elem);
			// System.out.print(s);
		}

		if (ctx.ANYCHAR() == null)
			return;
		s = ctx.ANYCHAR().toString();
		if (s.matches("((.|\n)*)" + SpecialChars.regex_keys +"((.|\n)*)")) {
			s = SpecialChars.replaceSpecialChars(s);
		}
		s = SpecialChars.replaceLaTeXSpecialChars(s);

		// System.out.print(s);

		ArrayList<String> rowList = matrix.get(rowIndex);
		String elem = rowList.get(colIndex);
		elem += s;
		rowList.set(colIndex, elem);
	}
	/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
	@Override public void exitRaw_text(DokuWikiTablesGrammarParser.Raw_textContext ctx) {

	}

}