text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Event
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Repository\EventRepository")
 */
class Event {

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */

    private $name;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $location;

    /**
     * @ORM\Column(type="date")
     */
    private $date;

    /**
     * @ORM\Column(type="time")
     */
    private $time;

    /**
     * @ORM\Column(type="smallint", name="max_slot")
     */
    private $maxOccupancy;

    /**
     * @ORM\Column(type="smallint", name="free_slot")
     */
    private $freeOccupancy;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Set location
     *
     * @param string $location
     * @return Event
     */
    public function setLocation($location) {
        $this->location = $location;

        return $this;
    }

    /**
     * Get location
     *
     * @return string
     */
    public function getLocation() {
        return $this->location;
    }

    /**
     * Set date
     *
     * @param \DateTime $date
     * @return Event
     */
    public function setDate($date) {
        $this->date = $date;

        return $this;
    }

    /**
     * Get date
     *
     * @return \DateTime
     */
    public function getDate() {
        return $this->date;
    }

    /**
     * Set time
     *
     * @param \DateTime $time
     * @return Event
     */
    public function setTime($time) {
        $this->time = $time;

        return $this;
    }

    /**
     * Get time
     *
     * @return \DateTime
     */
    public function getTime() {
        return $this->time;
    }

    /**
     * Set maxOccupancy
     *
     * @param integer $maxOccupancy
     * @return Event
     */
    public function setMaxOccupancy($maxOccupancy) {
        $this->maxOccupancy = $maxOccupancy;

        return $this;
    }

    /**
     * Get maxOccupancy
     *
     * @return integer
     */
    public function getMaxOccupancy() {
        return $this->maxOccupancy;
    }

    /**
     * Set freeOccupancy
     *
     * @param integer $freeOccupancy
     * @return Event
     */
    public function setFreeOccupancy($freeOccupancy)
    {
        $this->freeOccupancy = $freeOccupancy;

        return $this;
    }

    /**
     * Get freeOccupancy
     *
     * @return integer
     */
    public function getFreeOccupancy()
    {
        return $this->freeOccupancy;
    }
    function getName() {
        return $this->name;
    }

    function setName($name) {
        $this->name = $name;
    }

}


text:
var JSC          = require("jscheck");
var assert       = require("chai").assert;
var _            = require("lodash");
var devBuild     = require("../seamless-immutable.development.js");
var prodBuild    = require("../seamless-immutable.production.min.js");
var getTestUtils = require("./TestUtils.js");

[
  {id: "dev",  name: "Development build", implementation: devBuild},
  {id: "prod", name: "Production build",  implementation: prodBuild}
].forEach(function(config) {
  var Immutable = config.implementation;
  var TestUtils = getTestUtils(Immutable);

  describe(config.name, function () {
    describe("Immutable", function () {

      it("makes an Immutable Array when passed a mutable array", function () {
        TestUtils.check(100, [JSC.array()], function (mutable) {
          var immutable = Immutable(mutable);

          assert.deepEqual(immutable, mutable);
          assert.isTrue(Immutable.isImmutable(immutable));
          assert.isFalse(Immutable.isImmutable(mutable));
        });
      });

      it("makes an Immutable Object when passed a mutable object", function () {
        TestUtils.check(100, [JSC.object()], function (mutable) {
          var immutable = Immutable(mutable);

          assert.typeOf(immutable, "object");
          assert.isTrue(Immutable.isImmutable(immutable));
          assert.isFalse(Immutable.isImmutable(mutable));
        });
      });

      it("makes a deeply Immutable Object when passed a complex mutable object", function () {
        var complexObjFactory = JSC.array([JSC.integer(), JSC.object()]);
        TestUtils.check(100, [complexObjFactory], function (mutable) {
          var immutable = Immutable(mutable);

          assert.deepEqual(immutable, mutable);
          assert.isTrue(Immutable.isImmutable(immutable));
          assert.isTrue(Immutable.isImmutable(immutable[1]))
        })
      })

      it("doesn't fail when a function is defined on Array.prototype", function() {
        Array.prototype.veryEvilFunction = function() {};
        Immutable([]);
        delete Array.prototype.veryEvilFunction;
      });

      it("returns an object with the given optional prototype", function() {
        function TestClass(o) { _.extend(this, o); };
        var data = new TestClass({a: 1, b: 2});

        var immutable = Immutable(data, {prototype: TestClass.prototype});

        assert.deepEqual(immutable, data);
        TestUtils.assertHasPrototype(immutable, TestClass.prototype);
      });

      // These are already immutable, and should pass through Immutable() untouched.
      _.each({
        "string": JSC.string(),
        "number": JSC.number(),
        "boolean": JSC.boolean(),
        "null": JSC.literal(null),
        "undefined": JSC.literal(undefined)
      }, function (specifier, type) {
        it("simply returns its argument when passed a value of type " + type, function () {
          TestUtils.check(100, [specifier], function (value) {
            assert.strictEqual(Immutable(value), value);

            // should still pass through with a faulty prototype option
            assert.strictEqual(Immutable(value, {prototype: Object.prototype}), value);
          });
        });
      });
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

        <meta charset="UTF-8"/>
        <link rel="stylesheet" href="style.css" type="text/css"/>
        <title>Physical Viewpoint</title>

The Physical viewpoint contains equipment (one or more physical machines, tools, or instruments) that can create, use, store, move, or transform materials, how the equipment is connected via the distribution network, and what other active elements are assigned to the equipment.

Stakeholders:

Infrastructure architects, operational managers

Concerns:

Relationships and dependencies of the physical environment and how this relates to IT infrastructure

Purpose:

Designing

Scope:

Multiple layer/Multiple aspect


text:
package db
import (
	"database/sql"
	"log"
	"errors"
)
type DbUtil struct {
	writeDB *sql.DB
	readDB  *sql.DB
}
func NewDBUtil() *DbUtil {
	sessionW, err := NewSessionMysqlWriteDB()
	if err != nil {
		log.Panicf("Ocorreu um erro ao tentar abrir conexão com o dbWrite . %v", err)
	}

	err = sessionW.Ping()
	if err != nil {
		log.Panicf("Ocorreu um erro ao tentar verificar conexão dbWrite . %v", err)
	}

	sessionR, err := NewSessionMysqlReadDB()
	if err != nil {
		log.Panicf("Ocorreu um erro ao tentar abrir conexão com o dbRead . %v", err)
	}

	err = sessionR.Ping()
	if err != nil {
		log.Panicf("Ocorreu um erro ao tentar verificar conexão dbRead . %v", err)
	}
	return &DbUtil{sessionW, sessionR}
}

func (e *DbUtil) DeletePorAlias(alias string) error {
	var stmt *sql.Stmt
	stmt, err := e.writeDB.Prepare(`DELETE FROM url_encurtada where alias = ? `)
	if err != nil {
		log.Printf("Error na sequence. %v", err)
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec(alias)
	if err != nil {
		log.Printf("dbWrite error ao deletar. %v", err)
		return errors.New("dbWrite error ao deletar")
	}

	return nil
}

func (e *DbUtil) DeleteAll() error {
	var stmt *sql.Stmt
	stmt, err := e.writeDB.Prepare(`DELETE FROM url_encurtada`)
	if err != nil {
		log.Printf("Error na sequence. %v", err)
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec()
	if err != nil {
		log.Printf("dbWrite error ao deletar. %v", err)
		return errors.New("dbWrite error ao deletar")
	}

	return nil
}

func (e *DbUtil) Close() {
	if e.writeDB != nil {
		e.writeDB.Close()
		e.writeDB = nil
	}

	if e.readDB != nil {
		e.readDB.Close()
		e.readDB = nil
	}
}


text:
/* */
"format cjs";
/* Copyright (c) 2011 by The Authors.
 * Published under the LGPL 2.1 license.
 * See /license-notice.txt for the full text of the license notice.
 * See /license.txt for the full text of the license.
 */

/**
 * A Key is a unique identifier for a node in a tree. It contains a lower-left
 * point and a level number. The level number is the power of two for the size
 * of the node envelope
 */
(function() {

  /**
   * @requires jsts/index/bintree/Interval.js
   * @requires jsts/index/DoubleBits.js
   */

  var DoubleBits = jsts.index.DoubleBits;
  var Interval = jsts.index.bintree.Interval;

  /**
   * Constructs a new Key
   *
   * @constructor
   * @param {jsts.index.bintree.Interval}
   *          interval the interval to compute the key from.
   */
  var Key = function(interval) {
    this.pt = 0.0;
    this.level = 0;

    this.computeKey(interval);
  };

  /**
   * Computes the level for an interval
   *
   * @param {jsts.index.bintree.Interval}
   *          interval the interval.
   * @results {Number} the calculated level
   */
  Key.computeLevel = function(interval) {
    var dx = interval.getWidth(), level;

    level = DoubleBits.exponent(dx) + 1;
    return level;
  };

  /**
   * Returns the point
   *
   * @return {Number} point.
   */
  Key.prototype.getPoint = function() {
    return this.pt;
  };

  /**
   * Returns the level
   *
   * @return {Number} level.
   */
  Key.prototype.getLevel = function() {
    return this.level;
  };

  /**
   * Returns the interval
   *
   * @return {jsts.index.bintree.Interval}
   */
  Key.prototype.getInterval = function() {
    return this.interval;
  };

  /**
   * Calculates the key
   *
   * @param {jsts.index.bintree.Interval}
   *          itemInterval the interval.
   */
  Key.prototype.computeKey = function(itemInterval) {
    this.level = Key.computeLevel(itemInterval);
    this.interval = new Interval();
    this.computeInterval(this.level, itemInterval);
    // MD - would be nice to have a non-iterative form of this algorithm
    while (!this.interval.contains(itemInterval)) {
      this.level += 1;
      this.computeInterval(this.level, itemInterval);
    }
  };

  /**
   * Computes the interval
   *
   * @param {Number}
   *          level the level.
   * @param {jsts.index.bintree.Interval}
   *          itemInterval an interval.
   */
  Key.prototype.computeInterval = function(level, itemInterval) {
    var size = DoubleBits.powerOf2(level);

    this.pt = Math.floor(itemInterval.getMin() / size) * size;
    this.interval.init(this.pt, this.pt + size);
  };

  jsts.index.bintree.Key = Key;
})();


text:
<?php

namespace Sonata\AdminBundle\Tests\Fixtures\Filter;

use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\AdminBundle\Filter\Filter;

class FooFilter extends Filter
{
    public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $value)
    {
    }

    public function apply($query, $value)
    {
    }

    public function getDefaultOptions()
    {
        return array(
            'foo' => 'bar',
        );
    }

    public function getRenderSettings()
    {
    }
}


text:
package org.sistemafinanciero.service.ts;

import javax.ejb.Remote;

import org.sistemafinanciero.entity.Giro;

@Remote
public interface GiroServiceTS extends AbstractServiceTS<Giro> {

}


text:
declare module ReactRouter {
  interface RouteProp {
    component?: any
    components?: any
    onEnter?: any
  }

  export var Router: any
  export var IndexRoute: any
  export var browserHistory: any
}


text:
__author__ = 'GoNe'

from util import ltp

if __name__ == '__main__':
    line = "元芳你怎么看"
    words = ltp.word_segment(line)
    tags = ltp.postag(words)
    arcs = ltp.parse(words, tags)
    for word, tag, arc in zip(words, tags, arcs):
        print word, tag, arc.head, arc.relation


text:
LEISTUNGEN

Mein Beratungsspektrum teilt sich in vier Bereiche auf.

Software Engineering

Die Kunst tragfähige Softwarelösungen zu bauen, erfordert ein hohes Maß an Qualität. Ich habe langjährige Erfahrungen in Entwicklung und Test von anspruchsvollen und hochskalierbaren Web-Anwendungen.

Scrum & Kanban

Die agile Herangehensweise im komplexen Umfeld des Software-Projektmanagements hat sich immer wieder bewährt. Ich bin zertifizierter Scrum Master und habe viele Prozessumstellungen erfolgreich begleitet.

Development & Operations

Development und Operations rücken in den letzten Jahren, aus gutem Grund, immer näher aneinander. Bei zunehmender Komplexität ist es immer wichtiger beide Seiten zu kennen. Ich helfen Ihnen Continuous Delivery oder Integration in Ihren Prozess einzubinden.

Data Engineering

Big Data und Machine Learning beeinflussen immer mehr Bereiche unseres Lebens. Aus großen Datenmengen können neue Erkenntnisse gewonnen werden. Es gibt unzählige Anwendungsfälle, bei deren Umsetzung ich Sie gerne unterstütze.


text:
"""Create country sub-division redirect pages.

Check if they are in the form Something, State, and if so, create a redirect
from Something, ST.

Specific arguments:
-start:xxx Specify the place in the alphabet to start searching
-force: Don't ask whether to create pages, just create them.

PRE-REQUISITE : Need to install python-pycountry library.
* Follow the instructions at: https://www.versioneye.com/python/pycountry/0.16
* Install with pip: pip install pycountry
"""
#
# (C) Andre Engels, 2004
# (C) Pywikibot team, 2004-2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals

__version__ = '$Id$'
#

import re
import sys
import pywikibot
from pywikibot import i18n

try:
    import pycountry
except ImportError:
    pywikibot.error('This script requires the python-pycountry module')
    pywikibot.error('See: https://pypi.python.org/pypi/pycountry')
    pywikibot.exception()
    sys.exit(1)

msg = {
    'en': 'Creating state abbreviation redirect',
    'ar': u'إنشاء تحويلة اختصار الولاية',
    'fa': u'ایجاد تغییرمسیر برای نام اختصاری ایالت',
    'he': u'יוצר הפניה מראשי התיבות של המדינה',
}

class StatesRedirectBot(pywikibot.Bot):

    """Bot class used for implementation of re-direction norms."""

    def __init__(self, start, force):
        """Constructor.

        Parameters:
            @param start:xxx Specify the place in the alphabet to start
            searching.
            @param force: Don't ask whether to create pages, just create
            them.
        """
        site = pywikibot.Site()
        generator = site.allpages(start=start)
        super(StatesRedirectBot, self).__init__(generator=generator)

        self.force = force

        # Created abbrev from pycountry data base
        self.abbrev = {}
        for subd in pycountry.subdivisions:
            # Used subd.code[3:] to extract the exact code for
            # subdivisional states(ignoring the country code).
            self.abbrev[subd.name] = subd.code[3:]

    def treat(self, page):
        """Re-directing process.

        Check if pages are in the given form Something, State, and
        if so, create a redirect from Something, ST..
        """
        for sn in self.abbrev:
            R = re.compile(r', %s$' % sn)
            if R.search(page.title()):
                pl = pywikibot.Page(self.site, page.title().replace(sn,
                                    self.abbrev[sn]))
                # A bit hacking here - the real work is done in the
                # 'except pywikibot.NoPage' part rather than the 'try'.

                try:
                    pl.get(get_redirect=True)
                    goal = pl.getRedirectTarget().title()
                    if pywikibot.Page(self.site, goal).exists():
                        pywikibot.output(
                            u"Not creating %s - redirect already exists."
                            % goal)
                    else:
                        pywikibot.warning(
                            u"%s already exists but redirects elsewhere!"
                            % goal)
                except pywikibot.IsNotRedirectPage:
                    pywikibot.warning(
                        u"Page %s already exists and is not a redirect "
                        u"Please check page!"
                        % pl.title())
                except pywikibot.NoPage:
                    change = ''
                    if page.isRedirectPage():
                        p2 = page.getRedirectTarget()
                        pywikibot.output(
                            u'Note: goal page is redirect.\nCreating redirect '
                            u'to "%s" to avoid double redirect.' % p2.title())
                    else:
                        p2 = page
                    if self.force:
                        change = 'y'
                    else:
                        change = pywikibot.input_choice(
                            u'Create redirect %s?' % pl.title(),
                            (('yes', 'y'), ('no', 'n')))
                    if change == 'y':
                        pl.set_redirect_target(
                            p2, create=True,
                            summary=i18n.translate(self.site, msg))

def main(*args):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    local_args = pywikibot.handle_args(args)
    start = None
    force = False

    # Parse command line arguments
    for arg in local_args:
        if arg.startswith('-start:'):
            start = arg[7:]
        elif arg == '-force':
            force = True
        else:
            pywikibot.warning(
                u'argument "%s" not understood; ignoring.' % arg)

    bot = StatesRedirectBot(start, force)
    bot.run()

if __name__ == "__main__":
    main()


text:
package com.mpush.common.druid;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

import com.mpush.tools.config.CC;
import org.apache.log4j.Logger;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

/**
 * 要实现单例模式,保证全局只有一个数据库连接池
 *
 * @author hongjun
 * @date 2017-09-09
 */
public class DBPoolConnection {
    static Logger log = Logger.getLogger(DBPoolConnection.class);
    private static DBPoolConnection dbPoolConnection = null;
    private static DruidDataSource druidDataSource = null;

    static {
//        Properties properties = loadPropertiesFile("classes/db_server.properties");
        Properties properties = new Properties();
        properties.put("driverClassName", CC.mp.druid.driverClassName);
        properties.put("url", CC.mp.druid.url);
        properties.put("username", CC.mp.druid.username);
        properties.put("password", CC.mp.druid.password);
        properties.put("maxActive", CC.mp.druid.maxActive);

        try {
            druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); //DruidDataSrouce工厂模式
        } catch (Exception e) {
            log.error("获取配置失败");
        }
    }

    /**
     * 数据库连接池单例
     *
     * @return
     */
    public static synchronized DBPoolConnection getInstance() {
        if (null == dbPoolConnection) {
            dbPoolConnection = new DBPoolConnection();
        }
        return dbPoolConnection;
    }

    /**
     * 返回druid数据库连接
     *
     * @return
     * @throws SQLException
     */
    public DruidPooledConnection getConnection() throws SQLException {
        return druidDataSource.getConnection();
    }

    /**
     * @param string 配置文件名
     * @return Properties对象
     */
    private static Properties loadPropertiesFile(String fullFile) {
        String webRootPath = null;
        if (null == fullFile || fullFile.equals("")) {
            throw new IllegalArgumentException("Properties file path can not be null" + fullFile);
        }
        webRootPath = DBPoolConnection.class.getClassLoader().getResource("").getPath();
        webRootPath = new File(webRootPath).getParent();
        InputStream inputStream = null;
        Properties p = null;
        try {
            inputStream = new FileInputStream(new File(webRootPath + File.separator + fullFile));
            p = new Properties();
            p.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return p;
    }

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>strand::on_work_finished</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../strand.html" title="strand">
<link rel="prev" href="inner_executor_type.html" title="strand::inner_executor_type">
<link rel="next" href="on_work_started.html" title="strand::on_work_started">

strand::on_work_finished

Inform the strand that some work is no longer outstanding.

void on_work_finished();

          The strand delegates this call to its underlying executor.

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
'use strict';
/* jshint quotmark: false */

angular.module('myIonicStarter.config', [])

.constant('config', {
  "env": "development",
  "baseUrl": "http://localhost:3000/api"
});


text:
To enable Add-ins in your test instance of a Blackbaud solution, the add-in needs to be associated with an application. The first step in this process is to register your application with SKY API.

From My Applications, click Register app.

Enter the name, description, and logo of your application, as well as your organization's name.

In the Application website URL field, enter where users can learn more about your application online.

Specify the URIs to use to redirect users back to your application during the authorization process.
        Note: The URIs must be absolute and use HTTPS. However, we do support http://localhost:port or http://127.0.0.1:port for local development.

<bb-alert bb-alert-type="warning">Important!   When your application requests authorization to access a Blackbaud user's data, it includes a redirect_uri parameter in its query string.  To authorize your application, this value must match exactly against one of the URIs you provide, including any trailing slashes. For more information, see common authorization issues.</bb-alert>

Click Save.


text:
package jettest

import (
	"bytes"
	"fmt"
	"strings"
	"testing"

	"github.com/CloudyKit/jet/v6"
)

func RunWithSet(t *testing.T, set *jet.Set, variables jet.VarMap, context interface{}, testName, testExpected string) {
	tt, err := set.GetTemplate(testName)
	if err != nil {
		t.Errorf("Error parsing templates for test %s: %v", testName, err)
		return
	}
	RunWithTemplate(t, tt, variables, context, testExpected)
}

func RunWithTemplate(t *testing.T, tt *jet.Template, variables jet.VarMap, context interface{}, testExpected string) {
	if testing.RunTests(func(pat, str string) (bool, error) {
		return true, nil
	}, []testing.InternalTest{
		{
			Name: fmt.Sprintf("\tJetTest(%s)", tt.Name),
			F: func(t *testing.T) {
				var buf bytes.Buffer
				err := tt.Execute(&buf, variables, context)
				if err != nil {
					t.Errorf("Eval error: %q executing %s", err.Error(), tt.Name)
					return
				}
				result := strings.Replace(buf.String(), "\r\n", "\n", -1)
				if result != testExpected {
					t.Errorf("Result error expected %q got %q on %s", testExpected, result, tt.Name)
				}
			},
		},
	}) == false {
		t.Fail()
	}
}


text:
<?xml version="1.0"?>

<alvisnlp-doc author="" date="" target="fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.trie.OBOProjector">

  <synopsis>

Projects OBO terms and synonyms on sections.

  </synopsis>

  <module-doc>
    <description>

<this/> reads <param name="source"/> SKOS terminologies or OWL ontologies and searches for class and concept labels in sections.

The parameters <param name="allowJoined"/>, <param name="allUpperCaseInsensitive"/>, <param name="caseInsensitive"/>, <param name="ignoreDiacritics"/>, <param name="joinDash"/>, <param name="matchStartCaseInsensitive"/>, <param name="skipConsecutiveWhitespaces"/>, <param name="skipWhitespace"/> and <param name="wordStartCaseInsensitive"/> control the matching between the section and the entry keys.

The <param name="subject"/> parameter specifies which text of the section should be matched. There are two options:

the entries are matched on the contents of the section, <param name="subject"/> can also control if matches boundaries coincide with word delimiters;

the entries are matched on the feature value of annotations of a given layer separated by a whitespace, in this way entries can be searched against word lemmas for instance.

<this/> creates an annotation for each matched entry and adds these annotations to the layer named <param name="targetLayerName"/>. The created annotations will have the feature <param name="uriFeatureName"/> containing the URI of the matched class or concept. <this/> may also map property object values into features specified by <param name="labelFeatures"/>.

    </description>

    <param-doc name="source">

Path to the source SKOS/OWL files.

    </param-doc>

    <param-doc name="labelFeatures">

Mapping from feature names to property URIs. This parameter indicates the properties of the entry to record in features.

    </param-doc>

    <param-doc name="labelURIs">

RDF properties whose object values that represent entry keys.

    </param-doc>

    <param-doc name="resourceTypeURIs">

Type of RDF resources that represent an entry.

    </param-doc>

    <param-doc name="uriFeatureName">

Feature where to store the entry URI.

    </param-doc>

    <param-doc name="prefixes">

Specify URI prefixes to be used in <param name="resourceTypeURIs"/>, <param name="labelURIs"/>, and <param name="labelFeatures"/>

    </param-doc>

    <param-doc name="rdfFormat">

Specify the RDF serialization format (xml, rdfxml, xmlrdf, turtle, ttl, n3, ntriples, ntriple, nt, jsonld, rdfjson, jsonrdf, json, trig, nquads, nq, nthrift, csv, tsv, trix).

    </param-doc>

    <param-doc name="language">

Specify the language of labels to project. If this parameter is not set then labels of any language are projected. Labels without a language qualifier are always projected regardless of the value of this parameter.

    </param-doc>

	<include-doc>fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.trie.TrieProjectorParamsDoc</include-doc>
  </module-doc>
</alvisnlp-doc>


text:
local cassandra = require "cassandra"
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local DaoError = require "kong.dao.error"
local utils = require "kong.tools.utils"
local uuid = require "lua_uuid"

-- Load everything we need from the spec_helper
local env = spec_helper.get_env() -- test environment
local faker = env.faker
local dao_factory = env.dao_factory
local configuration = env.configuration

-- An utility function to apply tests on core collections.
local function describe_core_collections(tests_cb)
  for type, dao in pairs({ api = dao_factory.apis,
                           consumer = dao_factory.consumers }) do
    local collection = type == "plugin" and "plugins" or type.."s"
    describe(collection, function()
      tests_cb(type, collection)
    end)
  end
end

-- An utility function to test if an object is a DaoError.
-- Naming is due to luassert extensibility's restrictions
local function daoError(state, arguments)
  local stub_err = DaoError("", "")
  return getmetatable(stub_err) == getmetatable(arguments[1])
end

local say = require("say")
say:set("assertion.daoError.positive", "Expected %s\nto be a DaoError")
say:set("assertion.daoError.negative", "Expected %s\nto not be a DaoError")
assert:register("assertion", "daoError", daoError, "assertion.daoError.positive", "assertion.daoError.negative")

describe("Cassandra", function()
  -- Create a parallel session to verify the dao's behaviour
  local session
  setup(function()
    spec_helper.prepare_db()

    local err
    session, err = cassandra.spawn_session {
      shm = "factory_specs",
      keyspace = configuration.dao_config.keyspace,
      contact_points = configuration.dao_config.contact_points
    }
    assert.falsy(err)
  end)

  teardown(function()
    if session ~= nil then
      session:shutdown()
    end
  end)

  describe("Base DAO", function()
    describe("insert()", function()
      setup(function()
        spec_helper.drop_db()
      end)
      teardown(function()
        spec_helper.drop_db()
      end)
      it("should throw an error if called with invalid parameters", function()
        assert.has_error(function()
          dao_factory.apis:insert()
        end, "Cannot insert a nil element")

        assert.has_error(function()
          dao_factory.apis:insert("")
        end, "Entity to insert must be a table")
      end)
      it("should insert in DB and let the schema validation add generated values", function()
        -- API
        local api_t = faker:fake_entity("api")
        local api, err = dao_factory.apis:insert(api_t)
        assert.falsy(err)
        assert.truthy(api.id)
        assert.truthy(api.created_at)
        local rows, err = session:execute("SELECT * FROM apis WHERE id = ?", {cassandra.uuid(api.id)})
        assert.falsy(err)
        assert.True(#rows == 1)
        assert.equal(api.id, rows[1].id)

        -- API
        api, err = dao_factory.apis:insert {
          request_host = "test.com",
          upstream_url = "http://mockbin.com"
        }
        assert.falsy(err)
        assert.truthy(api.name)
        assert.equal("test.com", api.name)

        -- Consumer
        local consumer_t = faker:fake_entity("consumer")
        local consumer, err = dao_factory.consumers:insert(consumer_t)
        assert.falsy(err)
        assert.truthy(consumer.id)
        assert.truthy(consumer.created_at)
        rows, err = session:execute("SELECT * FROM consumers WHERE id = ?", {cassandra.uuid(consumer.id)})
        assert.falsy(err)
        assert.True(#rows == 1)
        assert.equal(consumer.id, rows[1].id)

        -- Plugin configuration
        local plugin_t = {name = "key-auth", api_id = api.id}
        local plugin, err = dao_factory.plugins:insert(plugin_t)
        assert.falsy(err)
        assert.truthy(plugin)
        local plugins, err = session:execute("SELECT * FROM plugins")
        assert.falsy(err)
        assert.True(#plugins > 0)
        assert.equal(plugin.id, plugins[1].id)
      end)
      it("should let the schema validation return errors and not insert", function()
        -- Without an api_id, it's a schema error
        local plugin_t = faker:fake_entity("plugin")
        local plugin, err = dao_factory.plugins:insert(plugin_t)
        assert.falsy(plugin)
        assert.truthy(err)
        assert.is_daoError(err)
        assert.True(err.schema)
        assert.equal("api_id is required", err.message.api_id)
      end)
      it("should ensure fields with `unique` are unique", function()
        local api_t = faker:fake_entity("api")

        -- Success
        local _, err = dao_factory.apis:insert(api_t)
        assert.falsy(err)

        -- Failure
        local api, err = dao_factory.apis:insert(api_t)
        assert.truthy(err)
        assert.is_daoError(err)
        assert.True(err.unique)
        assert.equal("name already exists with value '"..api_t.name.."'", err.message.name)
        assert.falsy(api)
      end)
      it("should ensure fields with `foreign` are existing", function()
        -- Plugin configuration
        local plugin_t = faker:fake_entity("plugin")
        plugin_t.api_id = uuid()

        local plugin, err = dao_factory.plugins:insert(plugin_t)
        assert.falsy(plugin)
        assert.truthy(err)
        assert.is_daoError(err)
        assert.True(err.foreign)
        assert.equal("api_id "..plugin_t.api_id.." does not exist", err.message.api_id)
      end)
      it("should do insert checks for entities with `self_check`", function()
        local api, err = dao_factory.apis:insert(faker:fake_entity("api"))
        assert.falsy(err)
        assert.truthy(api.id)

        local plugin_t = faker:fake_entity("plugin")
        plugin_t.api_id = api.id

        -- Success: plugin doesn't exist yet
        local plugin, err = dao_factory.plugins:insert(plugin_t)
        assert.falsy(err)
        assert.truthy(plugin)

        -- Failure: the same plugin is already inserted
        local plugin, err = dao_factory.plugins:insert(plugin_t)
        assert.falsy(plugin)
        assert.truthy(err)
        assert.is_daoError(err)
        assert.True(err.unique)
        assert.equal("Plugin configuration already exists", err.message)
      end)
    end) -- describe insert()

    describe("count_by_keys()", function()
      setup(function()
        spec_helper.drop_db()

        local err = select(2, session:execute("INSERT INTO apis(id, name) VALUES(uuid(), 'foo')"))
        assert.falsy(err)

        for i = 1, 99 do
          err = select(2, session:execute("INSERT INTO apis(id, name) VALUES(uuid(), 'bar')"))
          assert.falsy(err)
        end
      end)
      teardown(function()
        spec_helper.drop_db()
      end)
      it("should return the count of rows in a table", function()
        local count, err = dao_factory.apis:count_by_keys()
        assert.falsy(err)
        assert.equal(100, count)
      end)
      it("should return the count of rows in a table with filter columns", function()
        local count, err = dao_factory.apis:count_by_keys({name = "bar"})
        assert.falsy(err)
        assert.equal(99, count)

        count, err = dao_factory.apis:count_by_keys({name = "test"})
        assert.falsy(err)
        assert.equal(0, count)

        count, err = dao_factory.apis:count_by_keys({name = ""})
        assert.falsy(err)
        assert.equal(0, count)
      end)
      it("should return the count of rows in a table from a given paging_state", function()
        local rows, err = session:execute("SELECT * FROM apis", nil, {page_size = 50})
        assert.falsy(err)

        local paging_state = rows.meta.paging_state
        assert.truthy(paging_state)

        local count, err = dao_factory.apis:count_by_keys(nil, paging_state)
        assert.falsy(err)
        assert.equal(50, count)
      end)
      it("should return a filtered value to know if the query was filtered", function()
        local _, err, filtered = dao_factory.apis:count_by_keys()
        assert.falsy(err)
        assert.False(filtered)

        _, err, filtered = dao_factory.apis:count_by_keys({name = "bar"})
        assert.falsy(err)
        assert.False(filtered)

        _, err, filtered = dao_factory.apis:count_by_keys({name = "bar", request_host = ""})
        assert.falsy(err)
        assert.True(filtered)
      end)
      it("should return errors when query is refused by Cassandra", function()
        local count, err = dao_factory.apis:count_by_keys({upstream_url = ""})
        assert.truthy(err)
        assert.falsy(count)
        assert.is_daoError(err)
      end)
    end)

    describe("update()", function()
      setup(function()
        spec_helper.drop_db()
      end)
      teardown(function()
        spec_helper.drop_db()
      end)
      it("should error if called with invalid arguments", function()
        assert.has_error(function()
          dao_factory.apis:update()
        end, "Cannot update a nil element")

        assert.has_error(function()
          dao_factory.apis:update("")
        end, "Entity to update must be a table")
      end)
      it("should return nil and no error if no entity was found to update in DB", function()
        local api_t = faker:fake_entity("api")
        api_t.id = uuid()

        -- No entity to update
        local entity, err = dao_factory.apis:update(api_t)
        assert.equal(nil, entity)
        assert.falsy(err)
      end)
      it("should consider no entity to be found if an empty table is given to it", function()
        local api, err = dao_factory.apis:update {}
        assert.falsy(err)
        assert.falsy(api)
      end)
      it("should update an entity's non primary fields", function()
        local UUID = uuid()

        -- API
        local api_t = {
          id = UUID,
          name = "mockbin"
        }
        local _, err = session:execute("INSERT INTO apis(id, name) VALUES(?, ?)", {cassandra.uuid(api_t.id), api_t.name})
        assert.falsy(err)

        api_t.name = api_t.name.."-updated"

        local api, err = dao_factory.apis:update(api_t)
        assert.falsy(err)
        assert.truthy(api)
        assert.equal("mockbin-updated", api.name)

        local rows, err = session:execute("SELECT * FROM apis WHERE id = ?", {cassandra.uuid(api.id)})
        assert.falsy(err)
        assert.equal(1, #rows)
        assert.equal(api_t.id, rows[1].id)
        assert.equal(api_t.name, rows[1].name)
        assert.equal(api_t.request_host, rows[1].request_host)
        assert.equal(api_t.upstream_url, rows[1].upstream_url)

        -- Consumer
        local consumer_t = {
          id = UUID,
          username = "john"
        }
        _, err = session:execute("INSERT INTO consumers(id, username) VALUES(?, ?)", {
          cassandra.uuid(consumer_t.id),
          consumer_t.username
        })
        assert.falsy(err)

        consumer_t.username = consumer_t.username.."-updated"

        local consumer, err = dao_factory.consumers:update(consumer_t)
        assert.falsy(err)
        assert.truthy(consumer)
        assert.equal("john-updated", consumer.username)

        rows, err = session:execute("SELECT * FROM consumers WHERE id = ?", {cassandra.uuid(consumer_t.id)})
        assert.falsy(err)
        assert.equal(1, #rows)
        assert.equal(consumer_t.name, rows[1].name)

        -- Plugin Configuration
        local plugin_t = {
          id = UUID,
          api_id = UUID,
          name = "key-auth",
          enabled = true
        }
        _, err = session:execute("INSERT INTO plugins(id, api_id, name, enabled) VALUES(?, ?, ?, ?)", {
          cassandra.uuid(plugin_t.id),
          cassandra.uuid(plugin_t.api_id),
          plugin_t.name,
          plugin_t.enabled
        })
        assert.falsy(err)

        plugin_t.enabled = false

        local plugin, err = dao_factory.plugins:update(plugin_t)
        assert.falsy(err)
        assert.truthy(plugin)
        assert.False(plugin.enabled)

        rows, err = session:execute("SELECT * FROM plugins WHERE id = ?", {cassandra.uuid(plugin_t.id)})
        assert.falsy(err)
        assert.equal(1, #rows)
        assert.False(rows[1].enabled)
      end)
      describe("with `where_t` argument", function()
        local UUID = uuid()
        before_each(function()
          local _, err = session:execute("INSERT INTO apis(id, name, request_host, upstream_url) VALUES(?, ?, ?, ?)", {
            cassandra.uuid(UUID),
            "to-update",
            "to-update.com",
            "http://mockbin.com"
          })
          assert.falsy(err)

          _, err = session:execute("INSERT INTO apis(id, name) VALUES(uuid(), 'to-not-update')")
          assert.falsy(err)
          _, err = session:execute("INSERT INTO apis(id, name) VALUES(uuid(), 'to-not-update')")
          assert.falsy(err)
        end)
        after_each(function()
          spec_helper.drop_db()
        end)
        it("should be possible to pass a `where_t` with primary key as an argument", function()
          local res, err = dao_factory.apis:update({name = "updated"}, false, {id = UUID})
          assert.falsy(err)
          assert.truthy(res)

          local rows, err = session:execute("SELECT * FROM apis WHERE id = ?", {cassandra.uuid(UUID)})
          assert.falsy(err)
          assert.truthy(rows[1])
          assert.equal("updated", rows[1].name)
        end)
        it("should be possible to pass a `where_t` with non primary fields as an argument", function()
          local res, err = dao_factory.apis:update({name = "updated"}, false, {name = "to-update"})
          assert.falsy(err)
          assert.truthy(res)

          local rows, err = session:execute("SELECT * FROM apis WHERE id = ?", {cassandra.uuid(UUID)})
          assert.falsy(err)
          assert.truthy(rows[1])
          assert.equal("updated", rows[1].name)
        end)
        it("should not perform an update if more than one entity was found from the `where_t` argument", function()
          local res, err = dao_factory.apis:update({name = "updated"}, false, {name = "to-not-update"})
          assert.falsy(err)
          assert.falsy(res)

          local rows, err = session:execute("SELECT * FROM apis WHERE name = ?", {"to-not-update"})
          assert.falsy(err)
          assert.equal(2, #rows)
        end)
      end)

      describe("edge-cases with an entity", function()
        local api_t
        before_each(function()
          api_t = {
            id = uuid(),
            name = "mockbin",
            created_at = 1450519058000,
            upstream_url = "http://mockbin.com",
            request_path = "/request_path",
            request_host = "host.com"
          }
          local _, err = session:execute("INSERT INTO apis(id, created_at, name, upstream_url, request_path, request_host) VALUES(?, ?, ?, ?, ?, ?)", {
            cassandra.uuid(api_t.id),
            cassandra.timestamp(api_t.created_at),
            api_t.name,
            api_t.upstream_url,
            api_t.request_path,
            api_t.request_host
          })
          assert.falsy(err)
        end)
        after_each(function()
          session:execute("TRUNCATE apis")
        end)
        it("should return the complete updated entity when the argument entity is partial", function()
          api_t.name = "updated"
          -- Only passing a subset of the entity to update()
          local api, err = dao_factory.apis:update {
            id = api_t.id,
            name = api_t.name
          }
          assert.falsy(err)
          assert.truthy(api)
          assert.same(api_t, api)
        end)
        it("should ensure fields with `unique` are unique", function()
          local UUID_bis = uuid()

          local _, err = session:execute("INSERT INTO apis(id, request_host) VALUES(?, ?)", {
            cassandra.uuid(UUID_bis),
            "host2.com"
          })
          assert.falsy(err)

          local api, err = dao_factory.apis:update {
            id = UUID_bis,
            request_host = api_t.request_host
          }
          assert.truthy(err)
          assert.falsy(api)
          assert.is_daoError(err)
          assert.True(err.unique)
          assert.equal("request_host already exists with value 'host.com'", err.message.request_host)

          local rows, err = session:execute("SELECT * FROM apis WHERE id = ?", {cassandra.uuid(UUID_bis)})
          assert.falsy(err)
          assert.equal("host2.com", rows[1].request_host)
        end)
        it("should return an error if trying to update `immutable` fields", function()
          local rows, err = session:execute("SELECT * FROM apis")
          assert.falsy(err)
          assert.equal(api_t.created_at, rows[1].created_at)

          local api, err = dao_factory.apis:update {
            id = api_t.id,
            created_at = 123
          }
          assert.truthy(err)
          assert.falsy(api)
          assert.is_daoError(err)
          assert.True(err.schema)
          assert.equal("created_at cannot be updated", err.message.created_at)

          rows, err = session:execute("SELECT * FROM apis")
          assert.falsy(err)
          assert.equal(api_t.created_at, rows[1].created_at)
        end)
        describe("full update", function()
          it("should set a column to CQL `null` if a field is not specified", function()
            -- Verify the column is set
            local rows, err = session:execute("SELECT * FROM apis WHERE id = ?", {cassandra.uuid(api_t.id)})
            assert.falsy(err)
            assert.equal(1, #rows)
            assert.equal("/request_path", rows[1].request_path)

            -- Update
            api_t.request_path = nil
            local api, err = dao_factory.apis:update(api_t, true)
            assert.falsy(err)
            assert.truthy(api)
            assert.falsy(api.request_path)

            rows, err = dao_factory.apis:find_by_keys {id = api_t.id}
            assert.falsy(err)
            assert.truthy(rows)
            assert.falsy(rows[1].request_path)

            -- Check update
            rows, err = session:execute("SELECT * FROM apis WHERE id = ?", {cassandra.uuid(api_t.id)})
            assert.falsy(err)
            assert.falsy(rows[1].request_path)
          end)
          it("should still check the validity of the schema", function()
            -- Update with invalid value
            api_t.upstream_url = nil
            local api, err = dao_factory.apis:update(api_t, true)
            assert.truthy(err)
            assert.falsy(api)
            assert.equal("upstream_url is required", err.message.upstream_url)

            -- Check update failed
            local rows, err = session:execute("SELECT * FROM apis WHERE id = ?", {cassandra.uuid(api_t.id)})
            assert.falsy(err)
            assert.equal("http://mockbin.com", rows[1].upstream_url)
          end)
          it("should still select defaults when entity is incomplete", function()
            local plugin, err = dao_factory.plugins:insert {
              name = "key-auth",
              api_id = api_t.id,
              config = {hide_credentials = true}
            }
            assert.falsy(err)
            assert.same({"apikey"}, plugin.config.key_names)
            assert.True(plugin.config.hide_credentials)

            plugin, err = dao_factory.plugins:update({
              name = "key-auth",
              id = plugin.id,
              api_id = api_t.id
            }, true)
            assert.falsy(err)
            assert.same({"apikey"}, plugin.config.key_names)
            assert.False(plugin.config.hide_credentials)
          end)
          it("should return an error if trying to update `immutable` fields", function()
            api_t.created_at = 123
            api_t.name = "updated"
            local api, err = dao_factory.apis:update(api_t, true)
            assert.truthy(err)
            assert.falsy(api)
            assert.is_daoError(err)
            assert.True(err.schema)
            assert.equal("created_at cannot be updated", err.message.created_at)
          end)
        end)
      end)
    end) -- describe update()

    describe("find_by_keys()", function()
      setup(function()
        spec_helper.drop_db()

        local err = select(2, session:execute("INSERT INTO apis(id, request_host, upstream_url) VALUES(uuid(), 'foo.com', 'http://foo.com')"))
        assert.falsy(err)

        for i = 1, 99 do
          err = select(2, session:execute("INSERT INTO apis(id, request_host, upstream_url) VALUES(uuid(), 'foo.com', 'http://bar.com')"))
          assert.falsy(err)
        end
      end)
      teardown(function()
        spec_helper.drop_db()
      end)
      it("should error if called with invalid parameters", function()
        assert.has_error(function()
          dao_factory.apis:find_by_keys("")
        end, "where_t must be a table")
      end)
      it("should handle empty search fields", function()
        local apis, err = dao_factory.apis:find_by_keys({})
        assert.falsy(err)
        assert.truthy(apis)
        assert.True(#apis > 0)
      end)
      it("should handle nil search fields", function()
        local apis, err = dao_factory.apis:find_by_keys(nil)
        assert.falsy(err)
        assert.truthy(apis)
        assert.True(#apis > 0)
      end)
      it("should query an entity from the given fields and return if filtering was needed", function()
        -- No filtering needed
        local apis, err, needs_filtering = dao_factory.apis:find_by_keys {
          request_host = 'foo.com',
        }
        assert.falsy(err)
        assert.equal(100, #apis)
        assert.False(needs_filtering)

        -- Filtering needed
        apis, err, needs_filtering = dao_factory.apis:find_by_keys {
          request_host = 'foo.com',
          upstream_url = 'http://foo.com'
        }
        assert.falsy(err)
        assert.equal(1, #apis)
        assert.True(needs_filtering)
      end)
    end) -- describe find_by_keys()

    describe("find()", function()
      setup(function()
        spec_helper.drop_db()
        spec_helper.seed_db(10)
      end)
      teardown(function()
        spec_helper.drop_db()
      end)
      describe_core_collections(function(type, collection)
        it("should find entities", function()
          local entities, err = session:execute("SELECT * FROM "..collection)
          assert.falsy(err)
          assert.truthy(entities)
          assert.True(#entities > 0)

          local results, err = dao_factory[collection]:find()
          assert.falsy(err)
          assert.truthy(results)
          assert.same(#entities, #results)
        end)

        it("should allow pagination", function()
          -- 1st page
          local rows_1, err = dao_factory[collection]:find(2)
          assert.falsy(err)
          assert.truthy(rows_1)
          assert.same(2, #rows_1)
          assert.truthy(rows_1.next_page)

          -- 2nd page
          local rows_2, err = dao_factory[collection]:find(2, rows_1.next_page)
          assert.falsy(err)
          assert.truthy(rows_2)
          assert.same(2, #rows_2)
        end)
      end)
    end) -- describe find()

    describe("find_by_primary_key()", function()
      local api_t = {
        id = uuid(),
        name = "mockbin"
      }
      setup(function()
        spec_helper.drop_db()
        local err = select(2, session:execute("INSERT INTO apis(id, name) VALUES(?, ?)", {
          cassandra.uuid(api_t.id),
          api_t.name
        }))
        assert.falsy(err)
      end)
      teardown(function()
        spec_helper.drop_db()
      end)
      it("should error if called with invalid parameters", function()
        assert.has_error(function()
          dao_factory.apis:find_by_primary_key("")
        end, "where_t must be a table")
      end)
      it("should return nil (not found) if where_t is empty", function()
        local res, err = dao_factory.apis:find_by_primary_key {}
        assert.falsy(err)
        assert.falsy(res)
      end)
      it("should find one entity by its primary key", function()
        local api, err = dao_factory.apis:find_by_primary_key {id = api_t.id}
        assert.falsy(err)
        assert.truthy(api)
        assert.same(api_t, api)
      end)
      it("should handle an invalid uuid value", function()
        local api, err = dao_factory.apis:find_by_primary_key {id = "abcd"}
        assert.falsy(api)
        assert.True(err.invalid_type)
        assert.equal("abcd is an invalid uuid", err.message.id)
      end)

      describe("plugins", function()
        local plugin_t = {
          id = uuid(),
          name = "key-auth",
          api_id = api_t.id,
          config = [[{"key_names": ["test_key"]}]]
        }
        setup(function()
          local err = select(2, session:execute("INSERT INTO plugins(id, api_id, name, config) VALUES(?, ?, ?, ?)", {
            cassandra.uuid(plugin_t.id),
            cassandra.uuid(plugin_t.api_id),
            plugin_t.name,
            plugin_t.config
          }))
          assert.falsy(err)
        end)
        it("should unmarshall the `config` field", function()
          local plugin, err = dao_factory.plugins:find_by_primary_key {
            id = plugin_t.id,
            name = plugin_t.name
          }
          assert.falsy(err)
          assert.truthy(plugin)
          assert.equal("table", type(plugin.config))
        end)
      end)
    end) -- describe find_by_primary_key()

    describe("delete()", function()
      setup(function()
        spec_helper.drop_db()
        local _, err = session:execute("INSERT INTO plugins(id, name) VALUES(uuid(), 'some-plugin')")
        assert.falsy(err)
        _, err = session:execute("INSERT INTO consumers(id, username) VALUES(uuid(), 'to-delete')")
        assert.falsy(err)
        _, err = session:execute("INSERT INTO consumers(id, username) VALUES(uuid(), 'to-not-delete')")
        assert.falsy(err)
        _, err = session:execute("INSERT INTO consumers(id, username) VALUES(uuid(), 'to-not-delete')")
        assert.falsy(err)
      end)
      teardown(function()
        spec_helper.drop_db()
      end)
      it("should error if called with invalid parameters", function()
        assert.has_error(function()
          dao_factory.plugins:delete("")
        end, "where_t must be a table")
      end)
      it("should return false if entity to delete wasn't found", function()
        local ok, err = dao_factory.plugins:delete {id = uuid()}
        assert.falsy(err)
        assert.False(ok)
      end)
      it("should delete an entity when given its primary key", function()
        local rows, err = session:execute("SELECT * FROM plugins")
        assert.falsy(err)
        assert.truthy(rows)
        assert.True(#rows > 0)

        local ok, err = dao_factory.plugins:delete(rows[1])
        assert.falsy(err)
        assert.True(ok)
      end)
      it("should delete an entity when it can be found without its primay key", function()
        local ok, err = dao_factory.consumers:delete(nil, {
          username = "to-delete"
        })
        assert.falsy(err)
        assert.True(ok)
      end)
      it("should not delete an entity which can be found without primary key when there are multiple results", function()
        local ok, err = dao_factory.consumers:delete(nil, {
          username = "to-not-delete"
        })
        assert.falsy(err)
        assert.False(ok)

        local rows, err = session:execute("SELECT * FROM consumers WHERE username = 'to-not-delete'")
        assert.falsy(err)
        assert.equal(2, #rows)
      end)
    end)

    --
    -- APIs additional behaviour
    --

    describe("APIs", function()
      setup(function()
        spec_helper.drop_db()
        for i = 1, 100 do
          local err = select(2, session:execute("INSERT INTO apis(id, name) VALUES(uuid(), 'mockbin')"))
          assert.falsy(err)
        end
      end)
      teardown(function()
        spec_helper.drop_db()
      end)

      describe(":find_all()", function()
        it("should retrieve all APIs", function()
          local apis, err = dao_factory.apis:find_all()
          assert.falsy(err)
          assert.truthy(apis)
          assert.equal(100, #apis)
        end)
      end)
    end)

    --
    -- Nodes tests
    --

    describe("Nodes", function()

      setup(function()
        spec_helper.drop_db()
        spec_helper.seed_db(100)
      end)

      describe(":insert()", function()
        local node, err = dao_factory.nodes:insert({
          cluster_listening_address = "wot.hello.com:1111",
          name = "wot"
        })
        assert.falsy(err)
        assert.truthy(node)
        assert.equal("wot.hello.com:1111", node.cluster_listening_address)
      end)

      describe(":find_by_keys() and :delete()", function()
        local nodes, err = dao_factory.nodes:find_by_keys({
          cluster_listening_address = "wot.hello.com:1111"
        })

        assert.falsy(err)
        assert.truthy(nodes)
        assert.equal(1, #nodes)

        local ok, err = dao_factory.nodes:delete({
          name = table.remove(nodes, 1).name
        })

        assert.True(ok)
        assert.falsy(err)
      end)

      describe(":find_all()", function()
        local nodes, err = dao_factory.nodes:find_all()
        assert.falsy(err)
        assert.truthy(nodes)
        assert.equal(100, #nodes)
      end)

    end)

    --
    -- Plugins configuration additional behaviour
    --

    describe("plugins", function()
      setup(function()
        spec_helper.drop_db()
        faker:insert_from_table {
          api = {
            {name = "tests-distinct-1", request_host = "foo.com", upstream_url = "http://mockbin.com"},
            {name = "tests-distinct-2", request_host = "bar.com", upstream_url = "http://mockbin.com"}
          },
          plugin = {
            {name = "key-auth", config = {key_names = {"apikey"}, hide_credentials = true}, __api = 1},
            {name = "rate-limiting", config = { minute = 6}, __api = 1},
            {name = "rate-limiting", config = { minute = 6}, __api = 2},
            {name = "file-log", config = { path = "/tmp/spec.log" }, __api = 1}
          }
        }
      end)
      teardown(function()
        spec_helper.drop_db()
      end)
      describe("find_distinct()", function()
        it("should find distinct plugins configurations", function()
          local res, err = dao_factory.plugins:find_distinct()
          assert.falsy(err)
          assert.truthy(res)

          assert.equal(3, #res)
          assert.truthy(utils.table_contains(res, "key-auth"))
          assert.truthy(utils.table_contains(res, "rate-limiting"))
          assert.truthy(utils.table_contains(res, "file-log"))
        end)
      end)

      describe("insert()", function()
        local api_id
        local inserted_plugin
        it("should insert a plugin and set the consumer_id to a 'null' uuid if none is specified", function()
          -- Since we want to specifically select plugins configurations which have _no_ consumer_id sometimes, we cannot rely on using
          -- NULL (and thus, not inserting the consumer_id column for the row). To fix this, we use a predefined, nullified uuid...

          -- Create an API
          local api_t = faker:fake_entity("api")
          local api, err = dao_factory.apis:insert(api_t)
          assert.falsy(err)

          local plugin_t = faker:fake_entity("plugin")
          plugin_t.api_id = api.id

          local plugin, err = dao_factory.plugins:insert(plugin_t)
          assert.falsy(err)
          assert.truthy(plugin)
          assert.falsy(plugin.consumer_id)

          -- for next test
          api_id = api.id
          inserted_plugin = plugin
          inserted_plugin.consumer_id = nil
        end)
        it("should insert a plugin with an default config if none is specified", function()
          local api_t = faker:fake_entity("api")
          local api, err = dao_factory.apis:insert(api_t)
          assert.falsy(err)
          assert.truthy(api)

          local plugin, err = dao_factory.plugins:insert {
            name = "request-transformer",
            api_id = api.id
          }

          assert.falsy(err)
          assert.truthy(plugin)
          assert.falsy(plugin.consumer_id)
          assert.equal("request-transformer", plugin.name)
          assert.same({
            add = {
              body = {},
              headers = {},
              querystring = {}
            },
            append = {
              body = {},
              headers = {},
              querystring = {}
            },
            remove = {
              body = {},
              headers = {},
              querystring = {}
            },
            replace = {
              body = {},
              headers = {},
              querystring = {}
            }
          }, plugin.config)
        end)
        it("should select a plugin configuration by 'null' uuid consumer_id and remove the column", function()
          -- Now we should be able to select this plugin
          local rows, err = dao_factory.plugins:find_by_keys {
            api_id = api_id,
            consumer_id = constants.DATABASE_NULL_ID
          }
          assert.falsy(err)
          assert.truthy(rows[1])
          assert.same(inserted_plugin, rows[1])
          assert.falsy(rows[1].consumer_id)
        end)
      end)
    end) -- describe plugins configurations
  end) -- describe Base DAO
end) -- describe Cassandra


text:
using NetFusion.RabbitMQ.Subscriber.Internal;

namespace NetFusion.RabbitMQ.Subscriber
{
    /// <summary>
    /// Used to specify that a command message handler should be
    /// bound to a work-queue on the default exchange.
    /// </summary>
    public class WorkQueueAttribute : SubscriberQueueAttribute
    {
        public WorkQueueAttribute(string busName, string queueName)
            : base(busName, queueName, new WorkQueueStrategy())
        {

        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>

        <record id="base.res_partner_6" model="res.partner">
            <field name="website_published">True</field>
        </record>

        <record id="event.event_0" model="event.event">
            <field name="website_published">True</field>
            <field name="twitter_hashtag">openerp</field>
            <field name="description"><![CDATA[

5 Intensive Days

to learn .JS development

Course Summary

This course is dedicated to developers who need to grasp knowledge of the business applications development process. This course is for new developers or for IT professionals eager to learn more about technical aspects.

What you will learn?

Day 1

Introduction to Javascript

Hello World

Variables & Operators

Dive into Strings

Functions

Loops

Arrays

You will be able to develop simple dynamic components in HTML pages.

Day 2

Odoo Web Client

Introduction to JQuery

Advanced JQuery

Underscore

Introduction to QWeb

Controlers and Views

Bootstrap CSS

Calling the ORM

You will be able to create dynamic page interacting with the ORM.

Day 3

Building a Full Application

Modules

Python Objects

Report Engine

Workflows

Training Center Module

Integrated Help

How to Debug

You will be able to develop a full application with backend and user interface.

Requirements

Objectives:

Having attended this course, participants should be able to:

Understand the development concepts and architecture;

Install and administer your own server;

Develop a new module for a particular application.

Our prices include:

drinks and lunch;

training material.

Requirements:

Bring your own laptop.

Participants are expected to have some knowledge in programming. A basic knowledge of the Python programming is recommended.

Participants preferably have a functional knowledge of our software (see Functional Training).

To get more information, visit the Odoo Official Website.

Read Great Contents

What do people say about this course?

I did not expect such a great learning experience. I feel like I can develop anything now.

John Doe, CEO

This course help me build my first application within a month. Definetly worth its price.

John Doe, CEO

]]></field>        </record>

        <record id="base.res_partner_5" model="res.partner">
            <field name="website_published">True</field>
        </record>
        <record id="event.event_1" model="event.event">
            <field name="website_published">True</field>
            <field name="twitter_hashtag">openerp</field>
            <field name="description"><![CDATA[

5 Intensive Days

to learn technical aspects

Course Summary

This course is dedicated to developers who need to grasp knowledge of the business applications development process. This course is for new developers or for IT professionals eager to learn more about technical aspects.

What you will learn?

Day 1

Introduction to Javascript

Hello World

Variables & Operators

Dive into Strings

Functions

Loops

Arrays

You will be able to develop simple dynamic components in HTML pages.

Day 2

Odoo Web Client

Introduction to JQuery

Advanced JQuery

Underscore

Introduction to QWeb

Controlers and Views

Bootstrap CSS

Calling the ORM

You will be able to create dynamic page interacting with the ORM.

Day 3

Building a Full Application

Modules

Python Objects

Report Engine

Workflows

Training Center Module

Integrated Help

How to Debug

You will be able to develop a full application with backend and user interface.

Requirements

Objectives:

Having attended this course, participants should be able to:

Understand the development concepts and architecture;

Install and administer your own server;

Develop a new module for a particular application.

Our prices include:

drinks and lunch;

training material.

Requirements:

Bring your own laptop.

Participants are expected to have some knowledge in programming. A basic knowledge of the Python programming is recommended.

Participants preferably have a functional knowledge of our software (see Functional Training).

To get more information, visit the Odoo Official Website.

Read Great Contents

What do people say about this course?

I did not expect such a great learning experience. I feel like I can develop anything now.

John Doe, CEO

This course help me build my first application within a month. Definetly worth its price.

John Doe, CEO

]]></field>
        </record>

        <record id="base.res_partner_14" model="res.partner">
            <field name="website_published">True</field>
        </record>
        <record id="event.event_2" model="event.event">
            <field name="website_published">True</field>
            <field name="twitter_hashtag">openerp</field>
        </record>

        <record id="base.res_partner_2" model="res.partner">
            <field name="website_published">True</field>
        </record>
        <record id="base.res_partner_address_4" model="res.partner">
            <field name="website_published">True</field>
        </record>
        <record id="event.event_3" model="event.event">
            <field name="website_published">True</field>
            <field name="twitter_hashtag">openerp</field>
            <field name="description"><![CDATA[

5 Intensive Days

to learn business applications development

Course Summary

This course is dedicated to developers who need to grasp knowledge of the business applications development process. This course is for new developers or for IT professionals eager to learn more about technical aspects.

What you will learn?

Day 1

Introduction to Javascript

Hello World

Variables & Operators

Dive into Strings

Functions

Loops

Arrays

You will be able to develop simple dynamic components in HTML pages.

Day 2

Odoo Web Client

Introduction to JQuery

Advanced JQuery

Underscore

Introduction to QWeb

Controlers and Views

Bootstrap CSS

Calling the ORM

You will be able to create dynamic page interacting with the ORM.

Day 3

Building a Full Application

Modules

Python Objects

Report Engine

Workflows

Training Center Module

Integrated Help

How to Debug

You will be able to develop a full application with backend and user interface.

Requirements

Objectives:

Having attended this course, participants should be able to:

Understand the development concepts and architecture;

Install and administer your own server;

Develop a new module for a particular application.

Our prices include:

drinks and lunch;

training material.

Requirements:

Bring your own laptop.

Participants are expected to have some knowledge in programming. A basic knowledge of the Python programming is recommended.

Participants preferably have a functional knowledge of our software (see Functional Training).

To get more information, visit the Odoo Official Website.

Read Great Contents

What do people say about this course?

I did not expect such a great learning experience. I feel like I can develop anything now.

John Doe, CEO

This course help me build my first application within a month. Definetly worth its price.

John Doe, CEO

]]></field>
        </record>

    </data>
</openerp>