text:
namespace
{

double roundDouble(double value, int decimals)
{
    return (std::floor((value * std::pow(10.0, decimals)) + 0.5) / std::pow(10.0, decimals));
}

double internalValueToDisplayValue(double value, double scalingFactor, double valueOffset, int decimals)
{
    return roundDouble(((value * scalingFactor) + valueOffset), decimals);
}

double displayValueToInternalValue(double value, double scalingFactor, double valueOffset, int decimals)
{
    return ((roundDouble(value, decimals) - valueOffset) / scalingFactor);
}

}

namespace ViewModelsFramework
{

QuantityFieldBackend::QuantityFieldBackend(QObject* parent) : EditFieldBackendBase(parent)
{
}

QuantityFieldBackend::QuantityFieldBackend(AbstractViewModel* parent, double& value, int fieldId, const QString& label) :
    EditFieldBackendBase(parent, fieldId, label),
    m_value(value),
    m_minValue(std::numeric_limits<double>::lowest()),
    m_maxValue(std::numeric_limits<double>::max()),
    m_decimals(2),
    m_scalingFactor(1.0),
    m_valueOffset(0.0)
{
    connect(this, SIGNAL(valueChanged()), parent, SLOT(onFieldChanged()));
}

QuantityFieldBackend::~QuantityFieldBackend()
{
}

double QuantityFieldBackend::value() const
{
    return m_value;
}

double QuantityFieldBackend::minValue() const
{
    return m_minValue;
}

double QuantityFieldBackend::maxValue() const
{
    return m_maxValue;
}

double QuantityFieldBackend::displayValue() const
{
    return internalValueToDisplayValue(m_value, m_scalingFactor, m_valueOffset, m_decimals);
}

double QuantityFieldBackend::minDisplayValue() const
{
    return internalValueToDisplayValue(m_minValue, m_scalingFactor, m_valueOffset, m_decimals);
}

double QuantityFieldBackend::maxDisplayValue() const
{
    return internalValueToDisplayValue(m_maxValue, m_scalingFactor, m_valueOffset, m_decimals);
}

int QuantityFieldBackend::decimals() const
{
    return m_decimals;
}

QString QuantityFieldBackend::prefixText() const
{
    return m_prefixText;
}

QString QuantityFieldBackend::suffixText() const
{
    return m_suffixText;
}

double QuantityFieldBackend::scalingFactor() const
{
    return m_scalingFactor;
}

double QuantityFieldBackend::valueOffset() const
{
    return m_valueOffset;
}

bool QuantityFieldBackend::isChangedFromOriginalValue() const
{
    return m_value.isCurrentValueDifferentFromOriginalValue();
}

void QuantityFieldBackend::restoreOriginalValue()
{
    setValue(m_value.originalValue());
}

bool QuantityFieldBackend::isValueInRange() const
{
    return ((m_value >= m_minValue) && (m_value <= m_maxValue));
}

void QuantityFieldBackend::setValue(double value)
{
    if (m_value != value)
    {
        m_value = value;
        emit valueChanged();
    }
}

void QuantityFieldBackend::setMinValue(double value)
{
    if (m_minValue != value)
    {
        m_minValue = value;
        emit minValueChanged();
    }
}

void QuantityFieldBackend::setMaxValue(double value)
{
    if (m_maxValue != value)
    {
        m_maxValue = value;
        emit maxValueChanged();
    }
}

void QuantityFieldBackend::setDisplayValue(double value)
{
    setValue(displayValueToInternalValue(value, m_scalingFactor, m_valueOffset, m_decimals));
}

void QuantityFieldBackend::setValueRange(double minVal, double maxVal)
{
    setMinValue(minVal);
    setMaxValue(maxVal);
}

void QuantityFieldBackend::setDecimals(int value)
{
    if (m_decimals != value)
    {
        m_decimals = value;
        emit decimalsChanged();
    }
}

void QuantityFieldBackend::setPrefixText(const QString& value)
{
    if (m_prefixText != value)
    {
        m_prefixText = value;
        emit prefixTextChanged();
    }
}

void QuantityFieldBackend::setSuffixText(const QString& value)
{
    if (m_suffixText != value)
    {
        m_suffixText = value;
        emit suffixTextChanged();
    }
}

void QuantityFieldBackend::setScalingFactor(double value)
{
    if (m_scalingFactor != value)
    {
        m_scalingFactor = value;
        emit valueChanged();
    }
}

void QuantityFieldBackend::setValueOffset(double value)
{
    if (m_valueOffset != value)
    {
        m_valueOffset = value;
        emit valueChanged();
    }
}

void QuantityFieldBackend::setQuantityParameters(const QString& prefixText, const QString& suffixText, double scalingFactor, double valueOffset, int decimals)
{
    setPrefixText(prefixText);
    setSuffixText(suffixText);
    setScalingFactor(scalingFactor);
    setValueOffset(valueOffset);
    setDecimals(decimals);
}

void QuantityFieldBackend::beginFieldUpdate()
{
    EditFieldBackendBase::beginFieldUpdate();

    m_value.storeCurrentValue();
    m_minValue.storeCurrentValue();
    m_maxValue.storeCurrentValue();
    m_decimals.storeCurrentValue();
    m_prefixText.storeCurrentValue();
    m_suffixText.storeCurrentValue();
    m_scalingFactor.storeCurrentValue();
    m_valueOffset.storeCurrentValue();
}

void QuantityFieldBackend::endFieldUpdate()
{
    EditFieldBackendBase::endFieldUpdate();

    if (m_value.isCurrentValueDifferentFromStoredValue() ||
        m_scalingFactor.isCurrentValueDifferentFromStoredValue() ||
        m_valueOffset.isCurrentValueDifferentFromStoredValue())
    {
        emit valueChanged();
    }

    if (m_minValue.isCurrentValueDifferentFromStoredValue() ||
        m_scalingFactor.isCurrentValueDifferentFromStoredValue() ||
        m_valueOffset.isCurrentValueDifferentFromStoredValue())
    {
        emit minValueChanged();
    }

    if (m_maxValue.isCurrentValueDifferentFromStoredValue() ||
        m_scalingFactor.isCurrentValueDifferentFromStoredValue() ||
        m_valueOffset.isCurrentValueDifferentFromStoredValue())
    {
        emit maxValueChanged();
    }

    if (m_decimals.isCurrentValueDifferentFromStoredValue())
    {
        emit decimalsChanged();
    }

    if (m_prefixText.isCurrentValueDifferentFromStoredValue())
    {
        emit prefixTextChanged();
    }

    if (m_suffixText.isCurrentValueDifferentFromStoredValue())
    {
        emit suffixTextChanged();
    }
}

} // namespace ViewModelsFramework


text:
package components

import (
	str "strings"

	"github.com/knakk/rdf"
)

// --------------------------------------------------------------------------------
// TripleAggregate
// --------------------------------------------------------------------------------

type TripleAggregate struct {
	Subject    rdf.Subject
	SubjectStr string
	Triples    []rdf.Triple
}

func NewTripleAggregate(subj rdf.Subject, triples []rdf.Triple) *TripleAggregate {
	return &TripleAggregate{
		Subject:    subj,
		SubjectStr: subj.String(),
		Triples:    triples,
	}
}

// --------------------------------------------------------------------------------
// WikiPage
// --------------------------------------------------------------------------------

type WikiPage struct {
	Title            string
	Type             int
	Facts            []*Fact
	Categories       []*Category
	SpecificCategory *Category
}

func NewWikiPage(title string, facts []*Fact, categories []*Category, specificCategory *Category, pageType int) *WikiPage {
	return &WikiPage{
		Title:            title,
		Facts:            facts,
		Categories:       categories,
		SpecificCategory: specificCategory,
		Type:             pageType,
	}
}

func (p *WikiPage) AddFact(fact *Fact) {
	p.Facts = append(p.Facts, fact)
}

func (p *WikiPage) AddFactUnique(fact *Fact) {
	factExists := false
	for _, existingFact := range p.Facts {
		if fact.Property == existingFact.Property && fact.Value == existingFact.Value {
			factExists = true
			break
		}
	}
	if !factExists {
		p.AddFact(fact)
	}
}

func (p *WikiPage) AddCategory(category *Category) {
	p.Categories = append(p.Categories, category)
}

func (p *WikiPage) AddCategoryUnique(category *Category) {
	catExists := false
	for _, existingCat := range p.Categories {
		if category.Name == existingCat.Name {
			catExists = true
			break
		}
	}
	if !catExists {
		p.AddCategory(category)
	}
}

// ------------------------------------------------------------
// Helper type: Fact
// ------------------------------------------------------------

type Fact struct {
	Property string
	Value    string
}

func NewFact(property string, value string) *Fact {
	return &Fact{
		Property: property,
		Value:    value,
	}
}

func (f *Fact) asWikiFact() string {
	return "[[" + f.Property + "::" + f.escapeWikiChars(f.Value) + "]]\n"
}

func (f *Fact) escapeWikiChars(inStr string) string {
	outStr := str.Replace(inStr, "[", "(", -1)
	outStr = str.Replace(outStr, "]", ")", -1)
	outStr = str.Replace(outStr, "|", ",", -1)
	outStr = str.Replace(outStr, "=", "-", -1)
	outStr = str.Replace(outStr, "<", "<", -1)
	outStr = str.Replace(outStr, ">", ">", -1)
	return outStr
}

// ------------------------------------------------------------
// Helper type: Category
// ------------------------------------------------------------

type Category struct {
	Name string
}

func NewCategory(name string) *Category {
	return &Category{
		Name: name,
	}
}

func (c *Category) asWikiString() string {
	return "[[Category:" + c.Name + "]]\n"
}

redpajama_set_name: RedPajamaGithub


text:
rst2html.py ptr_multimap_adapter.rst |
    sed 's@compatible-smart-ptr@compatible-smart-ptr@g' > ptr_multimap_adapter.html


text:
package natlab.tame.valueanalysis.aggrvalue;

import natlab.tame.builtin.Builtin;
import natlab.tame.valueanalysis.value.*;

/**
 * provides propagations for builtins called with composite mclasses like
 * struct, function_handle, or cell. Does not provide propagations
 * for MatrixValues, which should be provided by actual MatrixValue factories.
 *
 * When implementing a new matrix value, the corresponding matrix value propagator
 * should not be used directory by the analysis - instead, it should use an
 * AggrValue propagator containing a matrix value propagator.
 *
 * It also means that when implementing new matrix values, this class may have
 * to be updated if the new abstraction affects the way cells, structs and function
 * handles behave.
 */
final public class AggrValuePropagator<D extends MatrixValue<D>> extends ValuePropagator<AggrValue<D>>{
	private MatrixPropagator<D> matrixValuePropagator;

	/**
	 * produce an aggrValuePropagator, given a propagator for the matrix values
	 */
	public AggrValuePropagator(
			MatrixPropagator<D> matrixValuePropagator) {
		super(matrixValuePropagator.getFactory());
		this.matrixValuePropagator = matrixValuePropagator;
	}

	@Override
	//XU add this to support...
	public Res<AggrValue<D>> caseBuiltin(Builtin builtin, Args<AggrValue<D>> args) {
		//TODO - check whether values are only matrizes
		return matrixValuePropagator.call(builtin, args);
	}
}


text:
import Effect from './Effect';

/**
 * Fading effect
 *
 * Supported on: `Drawable`, `Scene`
 *
 * @extends Effect
 */
class Fade extends Effect {
    /**
     * Creates a Fade Effect
     *
     * @param {Object} options
     * @param {Number} options.startValue the start value of the effect.
     * @param {Number} options.endValue the end value of the effect.
     * @param {Boolean} options.loop Set to true to make the effect loop.
     * @param {Display} display Reference to the Display in case a buffer is needed.
     */
    constructor(options, display) {
        super(Object.assign({
            startValue: 0,
            endValue: 1
        }, options), display);

        this.startOpacity = this.startValue !== undefined ? options.startValue : 0;
        this.endOpacity = this.endValue !== undefined ? options.endValue : 1;

        this.diff = this.endValue - this.startValue;
    }

    /**
     * Initializes the effect
     */
    start() {
        this.currentOpacity = 1;

        // start timer and get deferred
        return super.start();
    }

    /**
     *
     * @param {enderingContext} ctx The `source`rendering context.
     * @param {RenderingContext} fxCtx The `destination` context.
     * @param {Drawable} obj The Drawable on which to execute the ffect.
     */
    process(ctx, fxCtx, obj) {
        super.process();

        this.currentOpacity = this.startValue + this.animProgress * this.diff;

        obj.setOpacity(this.currentOpacity);

        return this.ended;
    }
}

export default Fade;


text:
"""
SDoc

Copyright 2016 Set Based IT Consultancy

Licence MIT
"""
# ----------------------------------------------------------------------------------------------------------------------
import re

class SDoc:
    """
    Utility class with functions for generating SDoc code.
    """

    # ------------------------------------------------------------------------------------------------------------------
    @staticmethod
    def escape(text):
        """
        Returns an escaped string that is svae to use in SDoc.

        :param text: The escaped string.

        :rtype: str
        """
        def replace(matchobj):
            """
            Returns the match text prefixed with backslash

            :param matchobj: The match.

            :rtype: str
            """
            return '\\' + matchobj.group(0)

        return re.sub(r'[\\{}]', replace, text)

    # ------------------------------------------------------------------------------------------------------------------
    @staticmethod
    def unescape(text):
        """
        Returns an unescaped SDoc escaped string. I.e. removes back slashes.

        :param text: The SDoc escaped string.

        :rtype: str
        """

        def replace(matchobj):
            """
            Returns the match text without prefixed backslash.

            :param matchobj: The match.

            :rtype: str
            """
            return matchobj.group(0)[1:]

        return re.sub(r'\\.', replace, text)

# ----------------------------------------------------------------------------------------------------------------------


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Modules.js demo page</title>

Hello


text:
<?php

namespace APM\VenteBundle\Controller;

use APM\AchatBundle\Entity\Groupe_offre;
use APM\UserBundle\Entity\Admin;
use APM\UserBundle\Entity\Utilisateur_avm;
use APM\VenteBundle\Entity\Transaction;
use APM\VenteBundle\Entity\Transaction_produit;
use APM\VenteBundle\Form\OffreType;
use Doctrine\Common\Collections\Collection;
use APM\VenteBundle\Entity\Boutique;
use APM\VenteBundle\Entity\Categorie;
use APM\VenteBundle\Entity\Offre;
use APM\VenteBundle\Factory\TradeFactory;
use Doctrine\DBAL\Exception\ConstraintViolationException;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Routing\ClassResourceInterface;
use FOS\RestBundle\View\View;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Post;
use FOS\RestBundle\Controller\Annotations\Put;
use FOS\RestBundle\Controller\Annotations\Delete;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser;

/**
 * Offre controller.
 * @RouteResource("offre", pluralize=false)
 */
class OffreController extends FOSRestController implements ClassResourceInterface
{
    /********************************************AJAX REQUEST********************************************/
    private
        $designation_filter;
    private
        $boutique_filter;
    private
        $code_filter;
    private
        $etat_filter;
    private
        $dateFrom_filter;
    private
        $dateTo_filter;

    /**
     * @ParamConverter("categorie", options={"mapping": {"categorie_id":"id"}})
     * @ParamConverter("user", options={"mapping": {"user_id":"id"}})
     * @ParamConverter("groupe_offre", options={"mapping": {"groupe_id":"id"}})
     * @ParamConverter("transaction", options={"mapping": {"transaction_id":"id"}})
     * Liste les offres de la boutique ou du vendeur
     * @param Request $request
     * @param Boutique $boutique
     * @param Categorie $categorie
     * @param Utilisateur_avm $user
     * @param Groupe_offre|null $groupe_offre
     * @param Transaction|null $transaction
     * @return JsonResponse
     *
     * @Get("/cget/offres", name="s")
     * @Get("/cget/offres/boutique/{id}", name="s_boutique", requirements={"id"="boutique_id"})
     * @Get("/cget/offres/boutique/{id}/categorie/{categorie_id}", name="s_categorie", requirements={"id"="boutique_id", "categorie_id"="\d+"})
     * @Get("/cget/offres/user/{user_id}", name="s_ByAdmin", requirements={"user_id"="\d+"})
     * @Get("/cget/offres/groupe/{groupe_id}", name="s_groupeOffre", requirements={"groupe_offre_id"="\d+"})
     * @Get("/cget/offres/transaction/{transaction_id}", name="s_transaction", requirements={"transaction_id"="\d+"})
     * @Get("/cget/offres/boutique/{id}/transaction/{transaction_id}", name="s_transaction_boutique", requirements={"id"="boutique_id", "transaction_id"="\d+"})
     *
     * @ApiDoc(
     * resource=true,
     * description="Retrieve list of offres.",
     * headers={
     *      { "name"="Authorization", "required"="true", "description"="Authorization token"},
     * },
     * filters={
     *      {"name"="code_filter", "dataType"="string"},
     *      {"name"="designation_filter", "dataType"="integer"},
     *      {"name"="date_from_filter",  "dataType"="dateTime", "pattern"="19-12-2017|ASC"},
     *      {"name"="date_to_filter", "dataType"="dateTime", "pattern"="19-12-2017|DESC"},
     *      {"name"="etat_filter", "dataType"="integer", "pattern"="1,2,3,4,5,6,7,8|SELECT"},
     *      {"name"="length", "dataType"="integer"},
     *      {"name"="start", "dataType"="integer"},
     * },
     * output={
     *   "class"="APM\VenteBundle\Entity\Offre",
     *   "parsers" = {
     *      "Nelmio\ApiDocBundle\Parser\JmsMetadataParser"
     *    },
     *     "groups"={"owner_list"}
     * },
     *
     * statusCodes={
     *     "output" = "A single or a collection of offre",
     *     200="Returned when successful",
     *     403="Returned when the user is not authorized to carry on this operation",
     *     404="Returned when a specified object is not found",
     * },
     *     views={"default","vente"}
     * )
     */
    public function getAction(Request $request, Boutique $boutique = null, Categorie $categorie = null, Utilisateur_avm $user = null, Groupe_offre $groupe_offre = null, Transaction $transaction = null)
    {
        try {
            $vendeur = null;
            $selectedGroup = array("others_list");
            if (null !== $transaction) {
                //security
                $this->listOfrresSecurity($boutique, $transaction);
                $offres = $this->listOffres($transaction);
            } elseif (null !== $boutique) {
                $this->listAndShowSecurity($boutique);
                if ($categorie) {
                    $offres = $categorie->getOffres();
                } else {
                    $offres = $boutique->getOffres();
                }
            } elseif (null !== $groupe_offre) {
                $offres = $groupe_offre->getOffres();
            } else {
                if (null === $user) {
                    $this->listAndShowSecurity();
                    $user = $this->getUser();
                    $selectedGroup = array("owner_list");
                } else {
                    $this->adminSecurity();
                }
                /** @var Collection $offres */
                $offres = $user->getOffres();
            }

            $json = array();
            //filter parameters
            $this->code_filter = $request->query->has('code_filter') ? $request->query->get('code_filter') : "";
            $this->designation_filter = $request->query->has('desc_filter') ? $request->query->get('desc_filter') : "";
            $this->boutique_filter = $request->query->has('boutique_filter') ? $request->query->get('boutique_filter') : "";
            $this->dateFrom_filter = $request->query->has('date_from_filter') ? $request->query->get('date_from_filter') : "";
            $this->dateTo_filter = $request->query->has('date_to_filter') ? $request->query->get('date_to_filter') : "";
            $this->etat_filter = $request->query->has('etat_filter') ? $request->query->get('etat_filter') : "";
            $iDisplayLength = $request->query->has('length') ? intval($request->query->get('length')) : -1;
            $iDisplayStart = $request->query->has('start') ? intval($request->query->get('start')) : 0;
            //-----Source -------
            $iTotalRecords = count($offres);
            $iDisplayLength = $iDisplayLength < 0 ? $iTotalRecords : $iDisplayLength;
            $offres = $this->handleResults($offres, $iTotalRecords, $iDisplayStart, $iDisplayLength);
            $iFilteredRecords = count($offres);
            $data = $this->get('apm_core.data_serialized')->getFormalData($offres, $selectedGroup);
            $json['totalRecords'] = $iTotalRecords;
            $json['filteredRecords'] = $iFilteredRecords; //nbre d'unité
            $json['items'] = $data;
            return new JsonResponse($json, 200);
        } catch (AccessDeniedException $ads) {
            return new JsonResponse([
                "status" => 403,
                "message" => $this->get('translator')->trans("Accès refusé", [], 'FOSUserBundle')
            ], Response::HTTP_FORBIDDEN);
        }

    }

    /**
     * @param Boutique|null $boutique
     * @param Transaction $transaction
     */
    private function listOfrresSecurity($boutique, $transaction)
    {
        $this->denyAccessUnlessGranted('ROLE_USERAVM', null, 'Unable to access this page!');
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
            throw $this->createAccessDeniedException();
        }
        $gerant = null;
        $proprietaire = null;
        $auteur = null;
        $beneficiaire = null;
        $user = $this->getUser();
        if ($boutique) {
            $gerant = $boutique->getGerant();
            $proprietaire = $boutique->getProprietaire();
            if ($beneficiaire) $beneficiaire = $transaction->getBeneficiaire();
        } else {
            $auteur = $transaction->getAuteur();
            $beneficiaire = $transaction->getBeneficiaire();
        }
        if ($user !== $gerant && $user !== $proprietaire && $user !== $auteur && $user !== $beneficiaire) {
            throw $this->createAccessDeniedException();
        }
        //----------------------------------------------------------------------------------------
    }

    /**
     * @param Transaction $transaction
     * @return Collection
     */
    private function listOffres(Transaction $transaction)
    {
        $offres = new ArrayCollection();
        $transaction_produits = $transaction->getTransactionProduits();
        if (null !== $transaction_produits) {
            /** @var Transaction_produit $transaction_produit */
            foreach ($transaction_produits as $transaction_produit) {
                $offre = $transaction_produit->getProduit();
                $offres->add($offre);
            }
        }
        return $offres;
    }

    /**
     * @param Boutique $boutique
     */
    private function listAndShowSecurity($boutique = null)
    {
        //-----------------------------------security-------------------------------------------
        // Unable to access the controller unless you have a USERAVM role
        $this->denyAccessUnlessGranted('ROLE_USERAVM', $user = $this->getUser(), 'Unable to access this page!');
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw $this->createAccessDeniedException();
        }
        if ($boutique) {
            $gerant = $boutique->getGerant();
            $proprietaire = $boutique->getProprietaire();
            if ($user !== $gerant && $user !== $proprietaire) {
                throw $this->createAccessDeniedException();
            }
        }
        //----------------------------------------------------------------------------------------
    }

    private function adminSecurity()
    {
        //-----------------------------------security-------------------------------------------
        $this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY') || !$this->getUser() instanceof Admin) {
            throw $this->createAccessDeniedException();
        }
        //----------------------------------------------------------------------------------------
    }

    /**
     * @param Collection $offres
     * @param $iTotalRecords
     * @param $iDisplayStart
     * @param $iDisplayLength
     * @return array
     */
    private function handleResults($offres, $iTotalRecords, $iDisplayStart, $iDisplayLength)
    {
        //filtering
        if ($offres === null) return array();

        if ($this->code_filter != null) {
            $offres = $offres->filter(function ($e) {//filtrage select
                /** @var Offre $e */
                return $e->getCode() === $this->code_filter;
            });
        }
        if ($this->etat_filter != null) {
            $offres = $offres->filter(function ($e) {//filtrage select
                /** @var Offre $e */
                return $e->getEtat() === intval($this->etat_filter);
            });
        }
        if ($this->dateFrom_filter != null) {
            $offres = $offres->filter(function ($e) {//start date
                /** @var Offre $e */
                $dt1 = (new \DateTime($e->getUpdatedAt()->format('d-m-Y')))->getTimestamp();
                $dt2 = (new \DateTime($this->dateFrom_filter))->getTimestamp();
                return $dt1 - $dt2 >= 0 ? true : false; //start from the given date 'dateFrom_filter'
            });
        }
        if ($this->dateTo_filter != null) {
            $offres = $offres->filter(function ($e) {//end date
                /** @var Offre $e */
                $dt = (new \DateTime($e->getUpdatedAt()->format('d-m-Y')))->getTimestamp();
                $dt2 = (new \DateTime($this->dateTo_filter))->getTimestamp();
                return $dt - $dt2 <= 0 ? true : false;// end from at the given date 'dateTo_filter'
            });
        }
        if ($this->boutique_filter != null) {
            $offres = $offres->filter(function ($e) {//filter with the begining of the entering word
                /** @var Offre $e */
                $str1 = $e->getBoutique()->getDesignation();
                $str2 = $this->boutique_filter;
                $len = strlen($str2);
                return strncasecmp($str1, $str2, $len) === 0 ? true : false;
            });
        }
        if ($this->designation_filter != null) {
            $offres = $offres->filter(function ($e) {//search for occurences in the text
                /** @var Offre $e */
                $subject = $e->getDesignation();
                $pattern = $this->designation_filter;
                return preg_match('/' . $pattern . '/i', $subject) === 1 ? true : false;
            });
        }
        $offres = ($offres !== null) ? $offres->toArray() : [];
        //assortment: descending of date -- du plus recent au plus ancient
        usort(
            $offres, function ($e1, $e2) {
            /**
             * @var Offre $e1
             * @var Offre $e2
             */
            $dt1 = $e1->getUpdatedAt()->getTimestamp();
            $dt2 = $e2->getUpdatedAt()->getTimestamp();
            return $dt1 <= $dt2 ? 1 : -1;
        });
        if ($iDisplayLength < 0) $iDisplayLength = $iTotalRecords;
        //paging; slice and preserve keys' order
        $offres = array_slice($offres, $iDisplayStart, $iDisplayLength, true);

        return $offres;
    }

    /**
     * @ApiDoc(
     * resource=true,
     * resourceDescription="Operations on offre.",
     * description="Create an object of type Offre.",
     * statusCodes={
     *         201="The details are returned when successful",
     *         400="Returned when the data are not valid or an unknown error occurred",
     *         403="Returned when the user is not authorized to carry on the action",
     *         404="Returned when the entity is not found",
     * },
     * headers={
     *      { "name"="Authorization",  "required"=true, "description"="Authorization token"}
     * },
     * authentication= true,
     * authenticationRoles= {
     *          "ROLE_USERAVM"
     *     },
     * input={
     *    "class"="APM\VenteBundle\Form\OffreType",
     *     "parsers" = {
     *          "Nelmio\ApiDocBundle\Parser\FormTypeParser"
     *      }
     * },
     * output={
     *   "class"="APM\VenteBundle\Entity\Offre",
     *   "parsers" = {
     *      "Nelmio\ApiDocBundle\Parser\JmsMetadataParser"
     *    },
     *     "groups"={"owner_offre_details", "owner_list"}
     * },
     * parameters= {
     *      {"name"="imagefile1x", "dataType"="integer", "required"= true, "description"="horizontal start point 01"},
     *      {"name"="imagefile1y", "dataType"="integer", "required"= true, "description"="vertical start point 01"},
     *      {"name"="imagefile1w", "dataType"="integer", "required"= true, "description"="width 01"},
     *      {"name"="imagefile1h", "dataType"="integer", "required"= true, "description"="height 01"},
     *
     *      {"name"="imagefile2x", "dataType"="integer", "required"= true, "description"="horizontal start point 02"},
     *      {"name"="imagefile2y", "dataType"="integer", "required"= true, "description"="vertical start point 02"},
     *      {"name"="imagefile2w", "dataType"="integer", "required"= true, "description"="width 02"},
     *      {"name"="imagefile2h", "dataType"="integer", "required"= true, "description"="height 02"},
     *
     *      {"name"="imagefile3x", "dataType"="integer", "required"= true, "description"="horizontal start point 03"},
     *      {"name"="imagefile3y", "dataType"="integer", "required"= true, "description"="vertical start point 03"},
     *      {"name"="imagefile3w", "dataType"="integer", "required"= true, "description"="width 03"},
     *      {"name"="imagefile3h", "dataType"="integer", "required"= true, "description"="height 03"},
     *
     *      {"name"="imagefile4x", "dataType"="integer", "required"= true, "description"="horizontal start point 04"},
     *      {"name"="imagefile4y", "dataType"="integer", "required"= true, "description"="vertical start point 04"},
     *      {"name"="imagefile4w", "dataType"="integer", "required"= true, "description"="width 04"},
     *      {"name"="imagefile4h", "dataType"="integer", "required"= true, "description"="height 04"},
     *
     *  },
     * views = {"default", "vente" }
     * )
     * @param Request $request
     * @return View|JsonResponse
     * @Post("/new/offre")
     */
    public function newAction(Request $request)
    {
        try {
            $this->createSecurity();
            /** @var Offre $offre */
            $offre = TradeFactory::getTradeProvider('offre');
            $form = $this->createForm('APM\VenteBundle\Form\OffreType', $offre);
            $data = $request->request->has($form->getName()) ? $request->request->get($form->getName()) : $data[$form->getName()] = array();
            $form->submit(array_merge($data, $request->files->get($form->getName())));
            if (!$form->isValid()) {
                return new JsonResponse([
                    "status" => 400,
                    "message" => $this->get('translator')->trans($form->getErrors(true, false), [], 'FOSUserBundle')
                ], Response::HTTP_BAD_REQUEST);
            }
            $this->createSecurity($offre->getBoutique(), $offre->getCategorie());
            $em = $this->getEM();
            $offre->setVendeur($this->getUser());
            $em->persist($offre);
            $em->flush();
            return $this->routeRedirectView("api_vente_show_offre", ['id' => $offre->getId()], Response::HTTP_CREATED);
        } catch (ConstraintViolationException $cve) {
            return new JsonResponse([
                "status" => 400,
                "message" => $this->get('translator')->trans("impossible d'enregistrer, vérifiez vos données", [], 'FOSUserBundle')
            ], Response::HTTP_BAD_REQUEST);
        } catch (AccessDeniedException $ads) {
            return new JsonResponse([
                    "status" => 403,
                    "message" => $this->get('translator')->trans("Access denied", [], 'FOSUserBundle'),
                ]
                , Response::HTTP_FORBIDDEN
            );
        }
    }

    /**
     * @param Categorie $categorie
     * @param Boutique $boutique
     */
    private function createSecurity($boutique = null, $categorie = null)
    {
        //---------------------------------security-----------------------------------------------
        // Unable to access the controller unless you have a USERAVM role
        $this->denyAccessUnlessGranted('ROLE_USERAVM', null, 'Unable to access this page!');
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY') || !$this->getUser() instanceof Utilisateur_avm) {
            throw $this->createAccessDeniedException();
        }
        if ($boutique) {
            $user = $this->getUser();
            $gerant = $boutique->getGerant();
            $proprietaire = $boutique->getProprietaire();
            if ($user !== $gerant && $user !== $proprietaire) {
                throw $this->createAccessDeniedException();
            }
            if ($categorie) {//Inserer l'offre uniquement dans la meme boutique que la categorie
                $currentBoutique = $categorie->getBoutique();
                if ($currentBoutique !== $boutique) {
                    throw $this->createAccessDeniedException();
                }
            }
        }
        //----------------------------------------------------------------------------------------
    }

    private function getEM()
    {
        return $this->get('doctrine.orm.entity_manager');
    }

    /**
     * @ApiDoc(
     * resource=true,
     * description="Retrieve the details of an objet of type Offre.",
     * headers={
     *      { "name"="Authorization", "required"="true", "description"="Authorization token"},
     * },
     * requirements = {
     *      {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="offre id"}
     * },
     * output={
     *   "class"="APM\VenteBundle\Entity\Offre",
     *   "parsers" = {
     *      "Nelmio\ApiDocBundle\Parser\JmsMetadataParser"
     *    },
     *     "groups"={"owner_offre_details", "owner_list"}
     * },
     * statusCodes={
     *     "output" = "A single Object",
     *     200="Returned when successful",
     *     403="Returned when the user is not authorized to perform the action",
     *     404="Returned when the specified resource is not found",
     * },
     *     views={"default", "vente"}
     * )
     * @param Offre $offre
     * @return JsonResponse
     *
     * @Get("/show/offre/{id}")
     */
    public function showAction(Offre $offre)
    {
        $this->listAndShowSecurity();
        $data = $this->get('apm_core.data_serialized')->getFormalData($offre, ["owner_offre_details", "owner_list"]);
        return new JsonResponse($data, 200);
    }

    /**
     * @ApiDoc(
     * resource=true,
     * resourceDescription="Operations on Offre",
     * description="Update an object of type Offre.",
     * statusCodes={
     *         "output"="PUT or POST method can be used",
     *         200="The details are returned only on POST when successful",
     *         400="Returned when the data are not valid or an unknown error occurred",
     *         403="Returned when the user is not authorized to carry on the action",
     *         404="Returned when the entity is not found",
     * },
     * headers={
     *      { "name"="Authorization", "required"="true", "description"="Authorization token"}
     * },
     * authentication= true,
     * authenticationRoles= {
     *          "ROLE_USERAVM"
     *     },
     * input={
     *    "class"="APM\VenteBundle\Form\OffreType",
     *     "parsers" = {
     *          "Nelmio\ApiDocBundle\Parser\FormTypeParser"
     *      }
     * },
     * output={
     *   "class"="APM\VenteBundle\Entity\Offre",
     *   "parsers" = {
     *      "Nelmio\ApiDocBundle\Parser\JmsMetadataParser"
     *    },
     *     "groups"={"owner_offre_details", "owner_list"}
     * },
     * requirements = {
     *      {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="offre Id"}
     * },
     * parameters= {
     *      {"name"="imagefile1x", "dataType"="integer", "required"= true, "description"="horizontal start point 01"},
     *      {"name"="imagefile1y", "dataType"="integer", "required"= true, "description"="vertical start point 01"},
     *      {"name"="imagefile1w", "dataType"="integer", "required"= true, "description"="width 01"},
     *      {"name"="imagefile1h", "dataType"="integer", "required"= true, "description"="height 01"},
     *
     *      {"name"="imagefile2x", "dataType"="integer", "required"= true, "description"="horizontal start point 02"},
     *      {"name"="imagefile2y", "dataType"="integer", "required"= true, "description"="vertical start point 02"},
     *      {"name"="imagefile2w", "dataType"="integer", "required"= true, "description"="width 02"},
     *      {"name"="imagefile2h", "dataType"="integer", "required"= true, "description"="height 02"},
     *
     *      {"name"="imagefile3x", "dataType"="integer", "required"= true, "description"="horizontal start point 03"},
     *      {"name"="imagefile3y", "dataType"="integer", "required"= true, "description"="vertical start point 03"},
     *      {"name"="imagefile3w", "dataType"="integer", "required"= true, "description"="width 03"},
     *      {"name"="imagefile3h", "dataType"="integer", "required"= true, "description"="height 03"},
     *
     *      {"name"="imagefile4x", "dataType"="integer", "required"= true, "description"="horizontal start point 04"},
     *      {"name"="imagefile4y", "dataType"="integer", "required"= true, "description"="vertical start point 04"},
     *      {"name"="imagefile4w", "dataType"="integer", "required"= true, "description"="width 04"},
     *      {"name"="imagefile4h", "dataType"="integer", "required"= true, "description"="height 04"},
     *  },
     *      views = {"default", "vente" }
     * )
     * @param Request $request
     * @param Offre $offre
     * @return View | JsonResponse
     *
     * @Put("/edit/offre/{id}")
     * @Post("/edit/offre/{id}")
     */
    public function editAction(Request $request, Offre $offre)
    {
        try {
            $this->editAndDeleteSecurity($offre);
            $form = $this->createForm('APM\VenteBundle\Form\OffreType', $offre);
            $data = $request->request->has('offre') ? $request->request->get('offre') : $data['offre'] = array();
            $form->submit(array_merge($data, $request->files->all()['offre']), false);
            if (!$form->isValid()) {
                return new JsonResponse([
                    "status" => 400,
                    "message" => $this->get('translator')->trans($form->getErrors(true, false), [], 'FOSUserBundle')
                ], Response::HTTP_BAD_REQUEST);
            }
            $em = $this->getEM();
            $em->flush();
            $response = $request->isMethod('PUT') ? new JsonResponse(['status' => 200], Response::HTTP_OK) : $this->routeRedirectView("api_vente_show_offre", ['id' => $offre->getId()], Response::HTTP_OK);
            return $response;
        } catch (ConstraintViolationException $cve) {
            return new JsonResponse([
                "status" => 400,
                "message" => $this->get('translator')->trans("impossible d'enregistrer, vérifiez vos données", [], 'FOSUserBundle')
            ], Response::HTTP_BAD_REQUEST);
        } catch (AccessDeniedException $ads) {
            return new JsonResponse([
                    "status" => 403,
                    "message" => $this->get('translator')->trans("Access denied", [], 'FOSUserBundle'),
                ]
                , Response::HTTP_FORBIDDEN
            );
        }
    }

    /**
     * @param Offre $offre
     */
    private function editAndDeleteSecurity($offre)
    {
        //---------------------------------security-----------------------------------------------
        // Unable to access the controller unless you have a USERAVM role
        $this->denyAccessUnlessGranted('ROLE_USERAVM', null, 'Unable to access this page!');
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY') || !$this->getUser() instanceof Utilisateur_avm) {
            throw $this->createAccessDeniedException();
        }
        if (null !== $offre) {
            $boutique = $offre->getBoutique();
            $user = $this->getUser();
            $proprietaire = null;
            $gerant = null;
            if (null !== $boutique) {
                $gerant = $boutique->getGerant();
                $proprietaire = $boutique->getProprietaire();
            }
            if ($user !== $offre->getVendeur() && $user !== $gerant && $user !== $proprietaire) {
                throw $this->createAccessDeniedException();
            }
        }
        //----------------------------------------------------------------------------------------

    }

    /**
     * @ApiDoc(
     * resource=true,
     * description="Delete objet of type offre.",
     * headers={
     *      { "name"="Authorization", "required"="true", "description"="Authorization token"},
     * },
     * requirements = {
     *      {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="offre Id"}
     * },
     * parameters = {
     *      {"name"="exec", "required"=true, "dataType"="string", "requirement"="\D+", "description"="needed to check the origin of the request", "format"="exec=go"}
     * },
     * statusCodes={
     *     200="Returned when successful",
     *     400="Returned when the data are not valid or an unknown error occurred",
     *     403="Returned when the user is not authorized to perform the action",
     *     404="Returned when the specified resource is not found",
     * },
     *     views={"default", "vente"}
     * )
     * @param Request $request
     * @param Offre $offre
     * @return View|JsonResponse
     * @Delete("/delete/offre/{id}")
     */
    public function deleteAction(Request $request, Offre $offre)
    {
        try {
            $this->editAndDeleteSecurity($offre);
            if (!$request->request->has('exec') || $request->request->get('exec') !== 'go') {
                return new JsonResponse([
                    "status" => 400,
                    "message" => $this->get('translator')->trans('impossible de supprimer', [], 'FOSUserBundle')
                ], Response::HTTP_BAD_REQUEST);
            }
            $em = $this->getEM();
            $em->remove($offre);
            $em->flush();
            return new JsonResponse(['status' => 200], Response::HTTP_OK);
        } catch (ConstraintViolationException $cve) {
            return new JsonResponse([
                "status" => 400,
                "message" => $this->get('translator')->trans("impossible de supprimer, vérifiez vos données", [], 'FOSUserBundle')
            ], Response::HTTP_FAILED_DEPENDENCY);
        } catch (AccessDeniedException $ads) {
            return new JsonResponse([
                    "status" => 403,
                    "message" => $this->get('translator')->trans("Access denied", [], 'FOSUserBundle'),
                ]
                , Response::HTTP_FORBIDDEN
            );
        }
    }

}


text:
/**
 * This class is generated by jOOQ
 */
package us.fok.lenzenslijper.models.jooq.routines;

/**
 * This class is generated by jOOQ.
 */
@javax.annotation.Generated(value    = { "http://www.jooq.org", "3.3.0" },
                            comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class PostgisTransformGeometry extends org.jooq.impl.AbstractRoutine<java.lang.Object> {

	private static final long serialVersionUID = 199180622;

	/**
	 * The parameter public.postgis_transform_geometry.RETURN_VALUE.
	 */
	public static final org.jooq.Parameter<java.lang.Object> RETURN_VALUE = createParameter("RETURN_VALUE", org.jooq.impl.DefaultDataType.getDefaultDataType("USER-DEFINED"));

	/**
	 * The parameter public.postgis_transform_geometry._1.
	 */
	public static final org.jooq.Parameter<java.lang.Object> _1 = createParameter("_1", org.jooq.impl.DefaultDataType.getDefaultDataType("USER-DEFINED"));

	/**
	 * The parameter public.postgis_transform_geometry._2.
	 */
	public static final org.jooq.Parameter<java.lang.String> _2 = createParameter("_2", org.jooq.impl.SQLDataType.CLOB);

	/**
	 * The parameter public.postgis_transform_geometry._3.
	 */
	public static final org.jooq.Parameter<java.lang.String> _3 = createParameter("_3", org.jooq.impl.SQLDataType.CLOB);

	/**
	 * The parameter public.postgis_transform_geometry._4.
	 */
	public static final org.jooq.Parameter<java.lang.Integer> _4 = createParameter("_4", org.jooq.impl.SQLDataType.INTEGER);

	/**
	 * Create a new routine call instance
	 */
	public PostgisTransformGeometry() {
		super("postgis_transform_geometry", us.fok.lenzenslijper.models.jooq.Public.PUBLIC, org.jooq.impl.DefaultDataType.getDefaultDataType("USER-DEFINED"));

		setReturnParameter(RETURN_VALUE);
		addInParameter(_1);
		addInParameter(_2);
		addInParameter(_3);
		addInParameter(_4);
	}

	/**
	 * Set the _1 parameter IN value to the routine
	 */
	public void set__1(java.lang.Object value) {
		setValue(us.fok.lenzenslijper.models.jooq.routines.PostgisTransformGeometry._1, value);
	}

	/**
	 * Set the _1 parameter to the function to be used with a {@link org.jooq.Select} statement
	 */
	public void set__1(org.jooq.Field<java.lang.Object> field) {
		setField(_1, field);
	}

	/**
	 * Set the _2 parameter IN value to the routine
	 */
	public void set__2(java.lang.String value) {
		setValue(us.fok.lenzenslijper.models.jooq.routines.PostgisTransformGeometry._2, value);
	}

	/**
	 * Set the _2 parameter to the function to be used with a {@link org.jooq.Select} statement
	 */
	public void set__2(org.jooq.Field<java.lang.String> field) {
		setField(_2, field);
	}

	/**
	 * Set the _3 parameter IN value to the routine
	 */
	public void set__3(java.lang.String value) {
		setValue(us.fok.lenzenslijper.models.jooq.routines.PostgisTransformGeometry._3, value);
	}

	/**
	 * Set the _3 parameter to the function to be used with a {@link org.jooq.Select} statement
	 */
	public void set__3(org.jooq.Field<java.lang.String> field) {
		setField(_3, field);
	}

	/**
	 * Set the _4 parameter IN value to the routine
	 */
	public void set__4(java.lang.Integer value) {
		setValue(us.fok.lenzenslijper.models.jooq.routines.PostgisTransformGeometry._4, value);
	}

	/**
	 * Set the _4 parameter to the function to be used with a {@link org.jooq.Select} statement
	 */
	public void set__4(org.jooq.Field<java.lang.Integer> field) {
		setField(_4, field);
	}
}


text:
<?php

namespace Build\Core\Tests\Unit\Repositories;

use Build\Core\Tests\AbstractTestCase;
use Illuminate\Database\Eloquent\Collection;
use Build\Core\Contracts\Repositories\Website;
use Build\Core\Repositories\WebsiteRepository;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Build\Core\Eloquent\Models\Website as WebsiteModel;

class WebsiteRepositoryTest extends AbstractTestCase
{
    use DatabaseMigrations;

    /** @test */
    public function it_can_create_a_new_repository_instance()
    {
        $this->assertInstanceOf(WebsiteRepository::class, app(Website::class));
    }

    /** @test */
    public function it_can_get_all_websites()
    {
        // Create a new website repository instance.
        $repository = app(WebsiteRepository::class);

        // Create 3 websites.
        factory(WebsiteModel::class, 3)->create();

        // Get all websites.
        $websites = $repository->getAllWebsites();

        $this->assertNotNull($websites);
        $this->assertCount(3, $websites);
        $this->assertInstanceOf(Collection::class, $websites);
    }

    /** @test */
    public function it_can_create_a_new_website()
    {
        // Create a new website repository instance.
        $repository = app(WebsiteRepository::class);

        // Create a new website.
        $website = $repository->createWebsite(
            factory(WebsiteModel::class)->make()->toArray()
        );

        $this->assertNotNull($website);
        $this->assertInstanceOf(WebsiteModel::class, $website);
    }

    /** @test */
    public function it_can_update_an_existing_website()
    {
        // Create a new website repository instance.
        $repository = app(WebsiteRepository::class);

        // Create a new website.
        $website = factory(WebsiteModel::class)->create();

        // Update the website.
        $website = $repository->updateWebsite(
            $website, ['name' => 'New Website Name']
        );

        $this->assertNotNull($website);
        $this->assertInstanceOf(WebsiteModel::class, $website);
        $this->assertEquals($website->name, 'New Website Name');
    }
}


text:
/**
 * DocuSign REST API
 * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
 *
 * OpenAPI spec version: v2.1
 * Contact: devcenter@docusign.com
 *
 * NOTE: This class is auto generated. Do not edit the class manually and submit a new issue instead.
 *
 */

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['ApiClient'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // CommonJS-like environments that support module.exports, like Node.
    module.exports = factory(require('../ApiClient'));
  } else {
    // Browser globals (root is window)
    if (!root.Docusign) {
      root.Docusign = {};
    }
    root.Docusign.BrandLogos = factory(root.Docusign.ApiClient);
  }
}(this, function(ApiClient) {
  'use strict';

  /**
   * The BrandLogos model module.
   * @module model/BrandLogos
   */

  /**
   * Constructs a new BrandLogos.
   * @alias module:model/BrandLogos
   * @class
   */
  var exports = function() {
    var _this = this;

  };

  /**
   * Constructs a BrandLogos from a plain JavaScript object, optionally creating a new instance.
   * Copies all relevant properties from data to obj if supplied or a new instance if not.
   * @param {Object} data The plain JavaScript object bearing properties of interest.
   * @param {module:model/BrandLogos} obj Optional instance to populate.
   * @return {module:model/BrandLogos} The populated BrandLogos instance.
   */
  exports.constructFromObject = function(data, obj) {
    if (data) {
      obj = obj || new exports();

      if (data.hasOwnProperty('email')) {
        obj['email'] = ApiClient.convertToType(data['email'], 'String');
      }
      if (data.hasOwnProperty('primary')) {
        obj['primary'] = ApiClient.convertToType(data['primary'], 'String');
      }
      if (data.hasOwnProperty('secondary')) {
        obj['secondary'] = ApiClient.convertToType(data['secondary'], 'String');
      }
    }
    return obj;
  }

  /**
   *
   * @member {String} email
   */
  exports.prototype['email'] = undefined;
  /**
   *
   * @member {String} primary
   */
  exports.prototype['primary'] = undefined;
  /**
   *
   * @member {String} secondary
   */
  exports.prototype['secondary'] = undefined;

  return exports;
}));


text:
package com.github.davidmoten.rx2.internal.flowable;

import static org.junit.Assert.assertTrue;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;

import com.github.davidmoten.rx2.Actions;
import com.github.davidmoten.rx2.exceptions.ThrowingException;
import com.github.davidmoten.rx2.flowable.Transformers;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.Notification;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subscribers.TestSubscriber;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public final class FlowableRepeatingTransformTest {

    private static final Function<List<Integer>, Integer> sum = (new Function<List<Integer>, Integer>() {
        @Override
        public Integer apply(List<Integer> list) throws Exception {
            int sum = 0;
            for (int value : list) {
                sum += value;
            }
            return sum;
        }
    });

    private static final Function<Flowable<Integer>, Flowable<Integer>> reducer = new Function<Flowable<Integer>, Flowable<Integer>>() {

        @Override
        public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
            return f.buffer(2).map(sum);
        }
    };

    private static final Function<Flowable<Integer>, Flowable<Integer>> plusOne = new Function<Flowable<Integer>, Flowable<Integer>>() {

        @Override
        public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
            return f.map(new Function<Integer, Integer>() {

                @Override
                public Integer apply(Integer t) throws Exception {
                    return t + 1;
                }
            });
        }
    };

    private static final Function<Flowable<Integer>, Flowable<Integer>> reducerThrows = new Function<Flowable<Integer>, Flowable<Integer>>() {

        @Override
        public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
            throw new ThrowingException();
        }
    };

    private static final Function<Flowable<Integer>, Flowable<Integer>> reducerThrowsOnThird = new Function<Flowable<Integer>, Flowable<Integer>>() {
        final AtomicInteger count = new AtomicInteger();

        @Override
        public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
            if (count.incrementAndGet() >= 3) {
                throw new ThrowingException();
            } else {
                return reducer.apply(f);
            }
        }
    };

    private static final Function<Flowable<Integer>, Flowable<Integer>> reducerAsync = new Function<Flowable<Integer>, Flowable<Integer>>() {

        @Override
        public Flowable<Integer> apply(Flowable<Integer> f) throws Exception {
            return f.subscribeOn(Schedulers.computation()).buffer(2).map(sum);
        }
    };

    @Test
    public void testEmpty() {
        int result = Flowable.<Integer>empty() //
                .to(Transformers.reduce(reducer, 2)) //
                .single(-1) //
                .blockingGet();
        Assert.assertEquals(-1, result);
    }

    @Test
    public void testOne() {
        check(1, 2);
    }

    @Test
    public void testOneAsync() {
        checkAsync(1, 2);
    }

    @Test
    public void testCompletesFirstLevel() {
        check(2, 2);
    }

    @Test
    public void testCompletesSecondLevel() {
        check(3, 2);
    }

    @Test(timeout = 1000)
    public void testCompletesThirdLevel() {
        check(4, 2);
    }

    @Test
    public void testCompletesThirdLevelWithOneLeftOver() {
        check(5, 2);
    }

    @Test
    public void testCompletesFourLevels() {
        check(8, 2);
    }

    @Test
    public void testMany() {
        for (int n = 5; n <= 100; n++) {
            int m = (int) Math.round(Math.floor(Math.log(n) / Math.log(2))) - 1;
            for (int maxChained = Math.max(3, m); maxChained < 6; maxChained++) {
//                System.out.println("maxChained=" + maxChained + ",n=" + n);
                check(n, maxChained);
            }
        }
    }

    @Test
    @Ignore
    public void testManyAsync() {
        for (int n = 5; n <= 100; n++) {
            int m = (int) Math.round(Math.floor(Math.log(n) / Math.log(2))) - 1;
            for (int maxChained = Math.max(3, m); maxChained < 6; maxChained++) {
//                System.out.println("maxChained=" + maxChained + ",n=" + n);
                checkAsync(n, maxChained);
            }
        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMaxChainedGreaterThanZero() {
        check(10, 0);
    }

    @Test
    public void testReducerThrows() {
        Flowable.range(1, 10) //
                .to(Transformers.reduce(reducerThrows, 2)) //
                .test() //
                .assertNoValues() //
                .assertError(ThrowingException.class);
    }

    @Test
    public void testReducerThrowsOnThirdCall() {
        Flowable.range(1, 128) //
                .to(Transformers.reduce(reducerThrowsOnThird, 2)) //
                .test() //
                .assertNoValues() //
                .assertError(ThrowingException.class);
    }

    @Test
    public void testUpstreamCancelled() {
        AtomicBoolean cancelled = new AtomicBoolean();
        Flowable.<Integer>never() //
                .doOnCancel(Actions.setToTrue(cancelled)) //
                .to(Transformers.reduce(reducer, 2)) //
                .test().cancel();
        assertTrue(cancelled.get());
    }

    @Test
    public void testErrorPreChaining() {
        Flowable.<Integer>error(new ThrowingException()) //
                .to(Transformers.reduce(reducer, 2)) //
                .test() //
                .assertNoValues() //
                .assertError(ThrowingException.class);
    }

    @Test
    @Ignore
    public void testErrorPreChainingCausesCancel() {
        AtomicBoolean cancelled = new AtomicBoolean();
        Flowable.<Integer>error(new ThrowingException()) //
                .doOnCancel(Actions.setToTrue(cancelled)) //
                .to(Transformers.reduce(reducer, 2)) //
                .test() //
                .assertNoValues() //
                .assertError(ThrowingException.class);
        assertTrue(cancelled.get());
    }

    @Test
    public void testErrorPostChaining() {
        Flowable.range(1, 100) //
                .concatWith(Flowable.<Integer>error(new ThrowingException())) //
                .to(Transformers.reduce(reducer, 2)) //
                .test() //
                .assertNoValues() //
                .assertError(ThrowingException.class);
    }

    @Test
    public void testMaxIterationsOne() {
        Function<Observable<Integer>, Observable<?>> tester = new Function<Observable<Integer>, Observable<?>>() {
            @Override
            public Observable<?> apply(Observable<Integer> o) throws Exception {
                return o.concatWith(Observable.<Integer>never());
            }
        };
        Flowable.just(1, 5) //
                .to(Transformers.repeat(plusOne, 3, 1, tester)) //
                .test() //
                .assertValues(2, 6) //
                .assertComplete();
    }

    @Test(timeout = 20000)
    public void testMaxIterationsTwoMaxChainedThree() {
        Flowable.just(1, 5) //
                .to(Transformers.reduce(plusOne, 3, 2)) //
                .test() //
                .assertValues(3, 7) //
                .assertComplete();
    }

    @Test(timeout = 20000)
    public void testMaxIterations() {
        Flowable.range(1, 2) //
                .to(Transformers.reduce(plusOne, 2, 3)) //
                .test() //
                .assertValues(4, 5) //
                .assertComplete();
    }

    @Test
    public void testRequestOverflow() {
        PublishSubject<Integer> subject = PublishSubject.create();

        TestSubscriber<Integer> sub = subject.toFlowable(BackpressureStrategy.BUFFER) //
                .to(Transformers.reduce(reducer, 2, 5)) //
                .test(Long.MAX_VALUE - 2) //
                .requestMore(Long.MAX_VALUE - 2);
        subject.onNext(1);
        subject.onNext(2);
        subject.onComplete();
        sub.assertValues(3);
    }

    @Test
    public void testDematerialize() {
        Flowable.just(Notification.createOnNext(1)).dematerialize().count().blockingGet();
        Flowable.empty().dematerialize().count().blockingGet();
    }

    @Test
    public void testBackpressure() {
        Flowable.range(1, 4) //
                .to(Transformers.reduce(plusOne, 2, 3)) //
                .test(0) //
                .assertNoValues() //
                .requestMore(1) //
                .assertValue(4) //
                .requestMore(1) //
                .assertValues(4, 5) //
                .requestMore(2) //
                .assertValues(4, 5, 6, 7) //
                .assertComplete();
    }

    @Test
    public void testBackpressureOnErrorNoRequests() {
        Flowable.<Integer>error(new ThrowingException())//
                .to(Transformers.reduce(plusOne, 2, 3)) //
                .test(0) //
                .assertNoValues() //
                .assertError(ThrowingException.class);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMaxIterationsZeroThrowsIAE() {
        @SuppressWarnings("unchecked")
        Function<Observable<Integer>, Observable<?>> tester = Mockito.mock(Function.class);
        Transformers.<Integer>repeat(plusOne, 2, 0, tester);
    }

    @Test
    public void testStackOverflowDoesNotHappen() {
        Flowable.range(1, 3) //
        .to(Transformers.reduce(plusOne, 2, 10000)) //
        .test();
    }

    private static void check(int n, int maxChained) {
        int result = Flowable.range(1, n) //
                .to(Transformers.reduce(reducer, maxChained)) //
                .single(-1) //
                .blockingGet();
        Assert.assertEquals(sum(n), result);
    }

    private static void checkAsync(int n, int maxChained) {
        int result = Flowable.range(1, n) //
                .to(Transformers.reduce(reducerAsync, maxChained)) //
                .single(-1) //
                .blockingGet();
        Assert.assertEquals(sum(n), result);
    }

    private static int sum(int n) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }

    public static void main(String[] args) {
        Flowable.just(1, 2, 3) //
                .to(Transformers.reduce(plusOne, 2, Long.MAX_VALUE)) //
                .test();
    }

}


text:
package net.kaczmarzyk.spring.data.jpa.utils;

public class JoinPathUtils {

	public static boolean pathToJoinContainsAlias(String pathToJoinOn) {
		return pathToJoinOn.contains(".");
	}

	public static String[] pathToJoinSplittedByDot(String pathToFetch) {
		String[] pathSplittedByDot = pathToFetch.split("\\.");

		if (pathSplittedByDot.length != 2) {
			throw new IllegalArgumentException(
					"Expected path to join with single alias in the pattern: 'alias.attribute' (without an apostrophe) where: " +
							"alias is a alias of another join (of which annotation should be before annotation of actual join)," +
							"attribute - name of the attribute for the target of the join."
			);
		}

		if(pathSplittedByDot[0].isEmpty()) {
			throw new IllegalArgumentException("Expected path to join with single alias in the pattern: 'alias.attribute'. An alias has to be not empty value!");
		}

		return pathSplittedByDot;
	}

}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Struktur2 extends CI_Controller {

	public function index()
	{
		$this->load->view('templates/header.php');
		$this->load->view('templates/nav2.php');
		$this->load->view('struktur2');
		$this->load->view('templates/footer2.php');
	}
}


text:
.. toctree::
   :hidden:

   cmake/index
   python/index

.. _qibuild-design:

qiBuild design
==============

qiBuild source code is divide into two loosely-coupled components.

qiBuild CMake framework
-----------------------

The CMake framework is composed of two parts:

* A bunch of files containing nice wrappers for CMake functions,
  aim to simplify authoring of CMakeLists files, which
  constitutes the :ref:`qibuild-cmake-api`

* A set of `-config.cmake` files, written because upstream
  CMake modules files are missing or not correct.
  You can learn about about this config files by following
  the :ref:`writing-a-config-cmake` tutorial.

But of course, the main feature of the qiBuild CMake
framework is to allow you to easily manage dependencies
between projects.

For a more detailed description of how this works,
please read the :ref:`qibuild-cmake-design` section.

qiBuild command line tools
--------------------------

First note that the qibuild command line tools are absolutely
not necessary use the qiBuild CMake framework.

The qibuild tools are all written in Python.

The :ref:`porting-to-qibuild` guide never uses the qibuild command
line, for instance.

The coupling between the Python command line tools and the CMake
framework is very loose.

qibuild command line only generates small bits of CMake code:

* A `dependencies.cmake` in the build directory, which is
  only useful if your project depends on library not found on
  your system, or if the qibuild CMake framework is not
  installed on your system.
  (And this file is simply NOT included if it does not exist)

* A CMake toolchain file when using toolchains. (more on this later)

For a more detailed description of the qibuild features
and how the are implemented, please read the :ref:`qibuild-python-design` section.


text:
[TOC]

# Packages

## babel

Multilingual support for Plain TeX or LaTeX.

This package manages culturally determined typographical (and other)
rules for a wide range of languages. A document may select a single
language to be supported, or it may select several, in which case the
document may switch from one language to another in a variety of ways.

Babel uses contributed configuration files that provide the detail of
what has to be done for each language. Included is also a set of ini
files for about 200 languages.

Many language styles work with pdfLATEX, as well as with XELATEX and
LuaLATEX, out of the box. A few even work with plain formats.

```
\usepackage[english]{babel}
```

## csquotes

Context sensitive quotation facilities.

This package provides advanced facilities for inline and display
quotations. It is designed for a wide range of tasks ranging from the
most simple applications to the more complex demands of formal
quotations. The facilities include commands, environments, and
userdefinable 'smart quotes' which dynamically adjust to their
context. Quotation marks are switched automatically if quotations are
nested and they can be adjusted to the current language if the babel
package is available. There are additional facilities designed to cope
with the more specific demands of academic writing, especially in the
humanities and the social sciences. All quote styles as well as the
optional active quotes are freely configurable.

```
\usepackage[autostyle, english = american]{csquotes}
```

## [nag](http://www.ctan.org/pkg/nag)

Warns when you accidentally use deprecated LaTeX constructs from
**l2tabu**. Place below line before the `\documentclass`:

`\RequirePackage[l2tabu, orthodox]{nag}`

## [microtype](http://www.ctan.org/pkg/microtype)

It plays with eversoslightly shrinking and stretching of the fonts and
with the extent to which text protrudes into the margins in a way that
yields results that look better, that have fewer instances of
hyphenation, and fewer overfull *hboxes*.

`\usepackage[stretch=10]{microtype}`

## [hyperref](http://tug.org/applications/hyperref/)

Extensive support for hypertext in LATEX.

The hyperref package is used to handle crossreferencing commands in
LATEX to produce hypertext links in the document. The package provides
backends for the \special set defined for HyperTEX DVI processors; for
embedded pdfmark commands for processing by Acrobat Distiller (dvips and
Y&Y's dvipsone); for Y&Y's dviwindo; for PDF control within pdfTEX and
dvipdfm; for TEX4ht; and for VTEX's pdf and HTML backends.

The package is distributed with the backref and nameref packages,
which make use of the facilities of hyperref.

## [geometry](http://www.ctan.org/pkg/geometry)

Flexible and complete interface to document dimensions.

## [amsmath](http://ctan.org/pkg/amsmath)

AMS mathematical facilities for LATEX.

The principal package in the AMSLATEX distribution. It adapts for use in
LATEX most of the mathematical features found in AMSTEX; it is highly
recommended as an adjunct to serious mathematical typesetting in LATEX.

When amsmath is loaded, AMSLATEX packages amsbsy (for bold symbols),
amsopn (for operator names) and amstext (for text embedded in
mathematics) are also loaded.

amsmath is part of the LATEX required distribution; however, several
contributed packages add still further to its appeal; examples are
empheq, which provides functions for decorating and highlighting
mathematics, and ntheorem, for specifying theorem (and similar)
definitions.

## amsthm

Typesetting theorems (AMS style).

The package facilitates the kind of theorem setup typically needed in
American Mathematical Society publications. The package offers the
theorem setup of the AMS document classes (amsart, amsbook, etc.)
encapsulated in LATEX package form so that it can be used with other
document classes.

Amsthm is part of the (required) AMSLATEX distribution, so should be
present in any LATEX distribution.

## amsfonts

TEX fonts from the American Mathematical Society.

An extended set of fonts for use in mathematics, including: extra
mathematical symbols; blackboard bold letters (uppercase only); fraktur
letters; subscript sizes of bold math italic and bold Greek letters;
subscript sizes of large symbols such as sum and product; added sizes of
the Computer Modern small caps font; cyrillic fonts (from the University
of Washington); Euler mathematical fonts.  All fonts are provided as
Adobe Type 1 files, and all except the Euler fonts are provided as
METAFONT source.

The distribution also includes the canonical Type 1 versions of the
Computer Modern family of fonts.

Basic LATEX support for the symbol fonts is provided by amsfonts.sty,
with names of individual symbols defined in amssymb.sty. The Euler fonts
are supported by separate packages; details can be found in the
documentation.

## mathtools

Mathematical tools to use with amsmath.

It will load amsmath if it's not loaded.

Mathtools provides a series of packages designed to enhance the
appearance of documents containing a lot of mathematics. The main
backbone is amsmath, so those unfamiliar with this required part of the
LATEX system will probably not find the packages very useful.

Mathtools provides many useful tools for mathematical typesetting. It is
based on amsmath and fixes various deficiencies of amsmath and standard
LATEX. It provides:

Extensible symbols, such as brackets, arrows, harpoons, etc.; Various
symbols such as \coloneqq (:=); Easy creation of new tag forms; Showing
equation numbers only for referenced equations; Extensible arrows,
harpoons and hookarrows; Starred versions of the amsmath matrix
environments for specifying the column alignment; More building blocks:
multlined, caseslike environments, new gathered environments; Maths
versions of \makebox, \llap, \rlap etc.; Cramped math styles; and
more...

## cancel

Place lines through maths formulae.

A package to draw diagonal lines ("cancelling" a term) and arrows with
limits (cancelling a term "to a value") through parts of maths formulae.

## [urlbst](http://nxg.me.uk/dist/urlbst/)

Web support for BibTEX.

## [booktabs](http://www.ctan.org/pkg/booktabs)

Publication quality tables in LATEX.

## [array](http://www.ctan.org/pkg/array)

Extending the array and tabular environments.

## [memoir](http://www.ctan.org/pkg/memoir)

Typeset fiction, nonfiction and mathematical books

## [komascript](http://www.ctan.org/pkg/komascript)

A bundle of versatile classes and packages.

## [pgfTikZ](http://sourceforge.net/projects/pgf/)

Create PostScript and PDF graphics in TEX.

TikZ and PGF are TeX packages for creating graphics programmatically.
TikZ is build on top of PGF and allows you to create sophisticated
graphics in a rather intuitive and easy manner.

PGF is a macro package for creating graphics. It is platform and
format independent and works together with the most important TEX backend
drivers, including pdfTEX and dvips. It comes with a user-friendly syntax
layer called TikZ.

Its usage is similar to pstricks and the standard picture
environment. PGF works with plain (pdf)TEX, (pdf)LATEX, and
ConTEXt. Unlike pstricks, it can produce either PostScript or PDF
output.

## graphicx

Enhanced support for graphics.

The package builds upon the graphics package, providing a keyvalue
interface for optional arguments to the \includegraphics command. This
interface provides facilities that go far beyond what the graphics
package offers on its own.

For extended documentation, see epslatex.

The package is part of the latexgraphics bundle, which is one of the
collections in the LATEX 'required' set of packages.

## enumitem

Control layout of itemize, enumerate, description.

This package provides user control over the layout of the three basic
list environments: enumerate, itemize and description. It supersedes
both enumerate and mdwlist (providing wellstructured replacements for
all their funtionality), and in addition provides functions to compute
the layout of labels, and to 'clone' the standard environments, to
create new environments with counters of their own.

- conflict with paralist package

## fancyhdr

Extensive control of page headers and footers in LATEX2ε.

The package provides extensive facilities, both for constructing headers
and footers, and for controlling their use (for example, at times when
LATEX would automatically change the heading style in use).

## mdframed

Framed environments that can split at page boundaries.

The package develops the facilities of framed in providing breakable
framed and coloured boxes.

The user may instruct the package to perform its operations using
default LATEX commands, PStricks or TikZ.

## longtable

## [listing](http://www.ctan.org/texarchive/macros/latex/contrib/listings/)

## [verbatim]()

# Bibliography

## Backend bibliography processor

### BibTeX

- https://en.wikipedia.org/wiki/BibTeX

BibTeX is reference management software for formatting lists of
references. BibTeX was created by Oren Patashnik and Leslie Lamport in
1985. It is written in WEB/Pascal.
- bib2x tool: convert .bib file to .x file
    + http://www.xandi.eu/bib2x/download.html
- parsing tools
    + biblib: https://github.com/aclements/biblib
    + bibtexparser: https://github.com/sciunto-org/python-bibtexparser
- jabref: creating, managing bibtex and conversion
- zotero: managing bibliographies

#### Usage

- https://www.overleaf.com/blog/532-creating-and-managing-bibliographies-with-bibtex-on-overleaf

```IEEE
\documentclass[conference]{IEEEtran}
...
\usepackage{cite}    % \cite{ref-name}
...

%% Bibliography
\newpage
\bibliographystyle{IEEEtran}
\bibliography{main}
```

#### Basic structure

Input:

An `.aux` file produced by LaTeX on an earlier run.  A `.bst` file (the
style file), which specifies the general referencelist style and
specifies how to format individual entries, and which is written by a
style designer [..] in a specialpurpose language [..].  A `.bib` file(s)
create a database of all referencelist entries the user might ever hope
to use.

BibTeX chooses from the `.bib` file(s) only those entries specified by
the `.aux` file (that is, those given by LaTeX's `\cite` or `\nocite`
commands), and creates as **output** a `.bbl` file containing these
entries together with the formatting commands specified by the `.bst`
file [..]. LaTeX will use the `.bbl` file, perhaps edited by the user,
to produce the reference list.

`bib + aux(\cite) > bbl + bib > ref list`

### [Biber](http://biblatexbiber.sourceforge.net/)

[manual](http://mirrors.ctan.org/biblio/biber/documentation/biber.pdf)

## Packages

`\cite{cite_key}`
`\cite[p.~215]{citation01}`
`\cite{citation01,citation02,citation03}`
`\nocite{citation01}` : ref appear in bibliography but not where it is ref in the main text.

### [natbib](http://ctan.org/pkg/natbib)

[ref sheet](http://merkel.zoneo.net/Latex/natbib.php)

`\usepackage[options]{natbib}`

Natbib Options

`\bibliographystyle{plainnat}`

Styles compatible with Natbib

### [biblatex](http://www.ctan.org/pkg/biblatex)

# Basic Tutorial

## Structure of a LaTeX file

```latex
%Preamble part
\documentclass{article}

%Document content part
\begin{document}
....
\end{document}
```

Using the symbol `%` to comment some texts.

## The preamble of a document

Everything before the line `\begin{document}`
You define
    + type of document
        * `\documentclas[12pt, letterpaper]{article}`
    + language
    + the packages that you want to use
        * `\usepackage[utf8]{inputenc}`
    + Adding a title, author, and date
        * `\title{First document}`
        * `\author{Son Tran}`
        * `\thanks{funded by ...}`
        * `\date{February 2019}`
        * You can print this information by using `\maketitle`command
        between `\begin{document}` and `\end{document}`

## Bold, italics, and underlining

`\textbf{...}`
`\textit{...}`
`\underline{...}`

## Adding images

```
\documentclass{article}
\usepackage{graphicx}
\graphicspath{ {images/} }

\begin{document}
The universe is immense and it seems to be homogeneous,
in a large scale, everywhere we look at.

% Here universe is the name of the file containing the image without the
% extension. The file name of the image should not contain white spaces
% nor multiple dots
\includegraphics{universe}

There's a picture of a galaxy above
\end{document}
```

## Captions, labels, and references

```
\begin{figure}[h]
\centering
\includegraphics[width=0.25\textwidth]{mesh}
\caption{a nice plot}
\label{fig:mesh1}
\end{figure}

As you can see in the figure \ref{fig:mesh1}, the
function grows near 0. Also, in the page \pageref{fig:mesh1}
is the same example.
```

There are three important commands in the example:
    + `\caption{a nice plot}`: As you may expect this command sets the
    caption for the figure. If you create a list of figures this
    caption will be used there. You can place it above or below the
    figure.
    + `\label{fig:mesh1}`: If you need to refer the image within your
    document, set a label with this command. The label will number the
    image, and combined with the next command will allow you to
    reference it.
    + `\ref{fig:mesh1}`: This code will be substituted by the number
    corresponding to the referenced figure.
    When placing images in a LATEX document, we should always put them
    inside a figure environment or similar so that LATEX will position the
    image in a way that fits in with the rest of your text.

## Creating lists

### Unordered lists

```
\begin{itemize}
\item The individual entries are indicated with a black dot, a socalled bullet.
\item The text in the entries may be of any length.
\end{itemize}
```

### Ordered lists

```
\begin{enumerate}
\item This is the first entry in our list
\item The list numbers increase with each entry we add
\end{enumerate}
```

## Adding math

Two modes to write mathematical expressions:
    + The inline mode
        * use one of these delimiters: \( ... \), $ ... $ or
        \begin{math} ... \end{math}
    + The display mode
        * numbered
        * unnumbered
        * To print your equations in display mode use one of these
        delimiters: \[ ... \], \begin{displaymath} ...
        \end{displaymath} or \begin{equation} ... \end{equation}. $$
        ... $$ is discouraged as it can give inconsistent spacing, and
        may not work well with some math packages.

        ```
        % Inline
        In physics, the massenergy equivalence is stated
        by the equation $E=mc^2$, discovered in 1905 by Albert Einstein.

        % Display
        The massenergy equivalence is described by the famous equation

        \[E=mc^2\]

        discovered in 1905 by Albert Einstein.
        In natural units ($c = 1$), the formula expresses the identity

        \begin{equation}
        E=m
        \end{equation}
        ```

        Using `amsmath` package for more flexibility.

## Basic Formatting

### Lengths in LaTeX

#### Units

| Abbreviation | Value                                                                                |
|--------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| pt           | a point is approximately 1/72.27 inch, that means about 0.0138 inch or 0.3515 mm (exactly point is defined as 1/864 of American printer's foot that is 249/250 of English foot) |
| mm           | a millimeter                                                                                |
| cm           | a centimeter                                                                                |
| in           | inch                                                                                |
| ex           | roughly the height of an 'x' (lowercase) in the current font (it depends on the font used)                                                                                |
| em           | roughly the width of an 'M' (uppercase) in the current font (it depends on the font used)                                                                                |
| mu           | math unit equal to 1/18 em, where em is taken from the math symbols family                                                                                |

#### Lengths

Lengths are units of distance relative to some document elements.
Lengths can be changed by the command:

`\setlength{\lengthname}{value_in_specified_unit}`

For example, in a twocolumn document the column separation can be set
to 1 inch by:

`\setlength{\columnsep}{1in}`

| Length          | Description                                                             |
|-----------------|-------------------------------------------------------------------------|
| \baselineskip   | Vertical distance between lines in a paragraph                          |
| \columnsep      | Distance between columns                                                |
| \columnwidth    | The width of a column                                                   |
| \evensidemargin | Margin of even pages, commonly used in twosided documents such as books |
| \linewidth      | Width of the line in the current environment.                           |
| \oddsidemargin  | Margin of odd pages, commonly used in twosided documents such as books  |
| \paperwidth     | Width of the page                                                       |
| \paperheight    | Height of the page                                                      |
| \parindent      | Paragraph indentation                                                   |
| \parskip        | Vertical space between paragraphs                                       |
| \tabcolsep      | Separation between columns in a table (tabular environment)             |
| \textheight     | Height of the text area in the page                                     |
| \textwidth      | Width of the text area in the page                                      |
| \topmargin      | Length of the top margin                                                |

Default lengths can not only be set to any desired value, they can
also be used as units to set the dimensions of other LATEX elements.
For instance, you can set an image to have a width of one quarter the
total text width.

```
\includegraphics[width=0.25\textwidth]{lionlogo}
[...]
```

### Abstract

```
\begin{document}

\begin{abstract}
This is a simple paragraph at the beginning of the
document. A brief introduction about the main subject.
\end{abstract}
\end{document}
```

### Paragraphs and newlines

A new line without starting a new paragraph: add a break line
    + `\\`
    + `\newline`
    A new paragraph:
    + "Enter" twice (double blank line)
    + `\par` command

### Paragraphs indentation

By default, LATEX does not indent the first paragraph of a section or a
chapter. The size of the subsequent paragraph indents is determined by
\parindent

```
\setlength{\parindent}{4em}

\begin{document}
This is the text in first paragraph. This is the text in first
paragraph. This is the text in first paragraph. \par
This is the text in second paragraph. This is the text in second
paragraph. This is the text in second paragraph.

This is another paragraph, contains some text to test the paragraph
interlining, paragraph indentation and some other features. Also,
is easy to see how new paragraphs are defined by simply entering a
double blank space.
...
\end{document}
```

The default length of this parameter is set by the document class used.
It is possible to change the indent size. In the example, the first
lines of each paragraph are indented 4em (an "em" equals the length of
the "m" in the current font), this is accomplished by the command
\setlength{\parindent}{4em}. It's recommended to put this command in the
preamble of the document, but it can be set anywhere else.

If you want to create a nonindented paragraph, like the second one in
the example, put the command \noindent at the beginning of it. If you
want the whole document not to be indented, set the indentation length
to zero with \setlength{\parindent}{0pt}.

On the other side, if you want to indent a paragraph that is not
indented you can use \indent right above it. It should be noted that
this command will only have an effect when \parindent is set to zero.

### Paragraph spacing

The length parameter that characterises the paragraph spacing is
\parskip, this determines the space between a paragraph and the
preceding text.

```
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\setlength{\parindent}{4em}
\setlength{\parskip}{1em}

\begin{document}
This is the text in first paragraph. This is the text in first
paragraph. This is the text in first paragraph. \par
This is the text in second paragraph...

\end{document}
```

### Line spacing

There are three commands that control the line spacing, below an example
redefining the length of \baselinestretch

```
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\setlength{\parindent}{4em}
\setlength{\parskip}{1em}
\renewcommand{\baselinestretch}{1.5}

\begin{document}
This is the text in first paragraph. This is the text in first
paragraph. This is the text in first paragraph. \par
This is the text in second paragraph...
\end{document}
```

In the example above, \renewcommand{\baselinestretch}{1.5} scales the
default interline space to 1.5 its default value. Of course that number
can be set to any value.

As mentioned before, there are other two LATEX lengths that may change
the line spacing:

\baselineskip
    + Is a length determining the minimum space between the bottom of
    two successive lines in a paragraph; it may be changed (in the
    preamble) by \setlength{\baselineskip}{value}. Where value is set
    using any of the LaTeX units.
    \linespread{value}
    + where value determine line spacing. This value is somewhat
    confusing, because:

    Value   Line spacing
    1.0 single spacing
    1.3 oneandahalf spacing
    1.6 double spacing

### Text alignment

Text alignment can be manually controlled by several commands.

| Alignment       | Environment | Switch command | ragged2e environment | ragged2e switch command |
|-----------------|-------------|----------------|----------------------|-------------------------|
| Left            | flushleft   | \raggedright   | FlushLeft            | \RaggedRight            |
| Right           | flushright  | \raggedleft    | FlushRight           | \RaggedLeft             |
| Centre          | center      | \centering     | Center               | \Centering              |
| Fully justified |             |                | justify              | \justify                |

## Chapters and Sections

Commands to organize a document vary depending on the document type, the
simplest form of organization is the sectioning, available in all
formats.

```
\chapter{First Chapter}

\section{Introduction}

This is the first section.

Lorem  ipsum  dolor  sit  amet,  consectetuer  adipiscing
elit.   Etiam  lobortisfacilisis sem.  Nullam nec mi et
neque pharetra sollicitudin.  Praesent imperdietmi nec ante.
Donec ullamcorper, felis non sodales...

\section{Second Section}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem.  Nullam nec mi et neque pharetra
sollicitudin.  Praesent imperdiet mi necante...

\subsection{First Subsection}
Praesent imperdietmi nec ante. Donec ullamcorper, felis non sodales...

\section*{Unnumbered Section}
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem
```

The command \section{} marks the beginning of a new section, inside the
braces is set the title. Section numbering is automatic and can be
disabled by including a * in the section command as \section*{}. We can
also have \subsection{}s, and indeed \subsubsection{}s. The basic levels
of depth are listed below:

1  \part{part}
0   \chapter{chapter}
1   \section{section}
2   \subsection{subsection}
3   \subsubsection{subsubsection}
4   \paragraph{paragraph}
5   \subparagraph{subparagraph}

Note that \part and \chapter are only available in report and book
document classes.

## Creating Tables

Using tool: `https://www.tablesgenerator.com/`

Simple Tables without border

```
\begin{center}
\begin{tabular}{ c c c }
cell1 & cell2 & cell3 \\
cell4 & cell5 & cell6 \\
cell7 & cell8 & cell9
\end{tabular}
\end{center}
```

Tables with borders

```
\begin{center}
\begin{tabular}{ |c|c|c| }
\hline
cell1 & cell2 & cell3 \\
cell4 & cell5 & cell6 \\
cell7 & cell8 & cell9 \\
\hline
\end{tabular}
\end{center}
```

## Adding a Table of Contents

`\tableofcontents`

```
\documentclass{article}
\usepackage[utf8]{inputenc}

\title{Sections and Chapters}
\author{Gubert Farnsworth}
\date{ }

\begin{document}

\maketitle

\tableofcontents

\section{Introduction}

This is the first section.

Lorem  ipsum  dolor  sit  amet,  consectetuer  adipiscing
elit.   Etiam  lobortisfacilisis sem.  Nullam nec mi et
neque pharetra sollicitudin.  Praesent imperdietmi nec ante.
Donec ullamcorper, felis non sodales...

\addcontentsline{toc}{section}{Unnumbered Section}
\section*{Unnumbered Section}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem.  Nullam nec mi et neque pharetra
sollicitudin.  Praesent imperdiet mi necante...

\section{Second Section}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem.  Nullam nec mi et neque pharetra
sollicitudin.  Praesent imperdiet mi necante...

\end{document}
```

# Mac OS  MacTeX

http://www.tug.org/mactex/

## Installing packages

For packages found on CTAN: use the TeX Live Utility found in your
/Applications/TeX folder. This application can keep all of your TeX
packages up to date.
Place the relevant files in `~/Library/texmf/tex/latex`. TeX will find
them.
Enter `tlmgr install *packagename*` in the terminal

# Writing mathematical document with amsmath

Usage guide: http://texdoc.net/texmfdist/doc/latex/amsmath/amsldoc.pdf

# Drawing electrical circuits

- https://www.overleaf.com/learn/latex/LaTeX_Graphics_using_TikZ:_A_Tutorial_for_Beginners_(Part_4)%E2%80%94Circuit_Diagrams_Using_Circuitikz
- https://www.latextutorial.com/tutorials/circuitikz/
    + https://github.com/circuitikz/circuitikz/issues/101

# LaTeX and Vim

## Introduction

- https://castel.dev/post/lecture-notes-1/
- https://castel.dev/post/lecture-notes-2/
- Tools
    + Vim + vimtex + ultisnips + vim-snippets + Inkscape + TikZ
    + vimtex
        * compiling and preview
        * forward and backward search
    + ultisnips + vim-snippets
        * increase typing speed
    + Inkscape: drawing and export to pdf+LaTeX
    + TikZ
- vimtex Usage: through mappings
    + https://github.com/lervag/vimtex/wiki/Usage
    + https://github.com/lervag/vimtex#features
    + forward search:
        * Put the cursor at the place you want to see it in the pdf file
        * Using mapping forward search: `<localleader>lv` (`\lv`)
    + backward search:
        * Skim:
            - `Shift + Command + Click` on the pdf file to jump to the
            corresponding text.
- vimtex's workflow:
    + Open a .tex file
    + Checking that the vimtex is running or not: `\lg`
    + Toggling the continuous compiling if it isn't running: `\ll`
    + Edit the file using vimtex features
        * Motions:
            - Section boundaries: `[[`, `]]`, `[]`, `][`
            - Environment boundaries: `[m`, `[M`, `]m`, `]M`
            - Comment boundaries: `[*`, `]*`
            - Matching delimiters: `%`
        * Text objects
            - Commands: `ic`, `ac`
            - Delimiters: `id`, `ad`
            - LaTeX environments: `ie`, `ae`
            - Inline Math blocks: `i$`, `a$`
            - Sections: `iP`, `aP`
        * Delete the surrounding command, environment, delimiter
            - `dsc`, `dse`, `dsd`, `ds$`
        * Change the surrounding command, environment, delimiter
            - `csc`, `cse`, `csd`, `cs$`
        * Toggle starred command or environment: `tsc`, `tse`
        * Close the current environment/delimiter in insert mode by ]]
        * Insert a new command: `<F7>`
        * Show all insert mode mapping in math mode: `\lm`
            - In math type the leader "backtick" and the mapping
            - `q` to quit the list
        * Toggle table of contents: `\lT`
    + After writing the file is compiled automatically
        * If errors occur, it will show the list of errors
        * Reading the errors to know what's wrong
        * Usually the first error caused by the line right above the
        error
    + Typing `\lv` to do the forward search
    + Typing `\lk` to stop the continuous compiling for the current file
        * `\lK` stop for all files
    + `\lc`: clean, `\lC` full clean

## Ultisnips

```basic-snippet
snippet "b(egin)?" "begin{} / end{}" br
snippet abs "abstract environment" b
snippet tab "tabular / array environment" b
snippet "gentbl(\d+)x(\d+)" "Generate table of *width* by *height*" r
snippet "tr(\d+)" "Add table row of dimension ..." r
snippet table "Table environment" b
snippet fig "Figure environment" b
snippet enum "Enumerate" b
snippet item "Itemize" b
snippet desc "Description" b
snippet it "Individual item" b
snippet part "Part" b
snippet cha "Chapter" b
snippet sec "Section"
snippet sec* "Section*"
snippet sub "Subsection"
snippet sub* "Subsection*"
snippet ssub "Subsubsection"
snippet ssub* "Subsubsection*"
snippet par "Paragraph"
snippet subp "Subparagraph"
snippet ac "Acroynm normal" b
snippet acl "Acroynm expanded" b
snippet ni "Non-indented paragraph" b
snippet pac "Package" b
snippet lp "Long parenthesis"
snippet "mint(ed)?( (\S+))?" "Minted code typeset" br
```

```custom-snippets
snippet mk "Inline Math" wA
snippet dm "Display Math" wA

# Expand when type a character followed by a digit
snippet '([A-Za-z])(\d)' "Auto Subscript" wrA

# Expand when type a character followed by `_` and two digits
snippet '([A-Za-z])_(\d\d)' "Auto Subscript2" wrA

snippet '([A-Za-z])\^(\d+)\s' "Auto Superscript" wrA

# Expand a character followed by `_` and other characters by tab
snippet '([A-Za-z])_([A-Za-z]+)' "Subscript" r

# Expand vector by typing "vec_name., or vec_name,."
snippet "(\\?\w+)(,\.|\.,)" "Vector postfix" riA

# The bar on top by typing tab
snippet "bar" "bar" ri
snippet "([a-zA-Z])bar" "bar" ri

snippet compl "Complement" i
```

# Tips and Tricks

## Convert LaTeX to other file types and vice versa

- pandoc
    + `pandoc -s file1.tex -o file2.txt`
- detex: tex to txt
    + `detex file1.tex > file2.txt`

## Block/Multiline comments

Using verbartim package
    + `\userpackage{verbatim}`
    + `\begin{comment`
    + `<comment here>`
    + `\end{comment}`

## Add text in math mode

\text{}
https://tex.stackexchange.com/questions/3415/whatisthecorrectwayofembeddingtextintomathmode#3418

## Align multiline equation with indent equal signs

```
\documentclass{article}

\usepackage{amsmath}

\begin{document}

\begin{align*}
\mathcal{L}^{1}\left\{f(d)\right\} &= \mathcal{L}^{1}\left\{f_1(\delta).f_2(\delta)\right\} \\
&= \exp(mt) \star \left\{\frac{l}{2\sqrt{\pi t^3}} \exp(l^2/{4t})\right\} \\
&= F_1 * F_2
\end{align*}

\end{document}
```

## Create posters using LaTeX

https://tex.stackexchange.com/questions/341/howtocreatepostersusinglatex
    + beamerposter
    + fancytikzposter
    + baposter
    templates
    + https://www.latextemplates.com/cat/conferenceposters
    + https://www.overleaf.com/gallery/tagged/poster

## [Latex templates](https://github.com/bamos/latextemplates)

## [Popular packages in latex](https://tex.stackexchange.com/questions/553/whatpackagesdopeopleloadbydefaultinlatex)

## [Problems with Vietnamese](http://vntex.sourceforge.net/vntexse4.html)

## Set up for includegraphic

Use variable environment **TEXINPUTS** to set up path to directory
contain figures. Eg. **TEXINPUTS=E:/Software/Report/Figures**
Use package graphicx to include figures.

## [Integrating Local Additions](http://docs.miktex.org/manual/localadditions.html)

Use to install offline, manual package at local.

## Miktex packages

Use package manager to install packages, change repositories to have
best speed.

# Alternatives

https://tex.stackexchange.com/questions/120271/alternativestolatex

# References


text:
exports.up = function(knex, Promise) {
  return Promise.all([
    knex.schema.createTableIfNotExists('Snippets', function(table){
      table.string('id').primary()
      table.string('code').notNullable()
      table.string('name', 45).notNullable()
    }),
    knex.schema.createTableIfNotExists('Comments', function(table){
      table.string('id').primary()
      table.string('comment').notNullable()
      table.string('snippet_id')
      table.foreign('snippet_id').references('Snippets.id')
    })
  ])
};

exports.down = function(knex, Promise) {
    return Promise.all([
    knex.schema.dropTableIfExists('Snippets'),
    knex.schema.dropTableIfExists('Comments')
  ])
};