text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.googlecode.cernunnos</groupId>
    <artifactId>cernunnos-parent</artifactId>
    <version>1.4.1-SNAPSHOT</version>

    <packaging>pom</packaging>
    <name>Cernunnos - Parent</name>
    <inceptionYear>2007</inceptionYear>
    <description>
        Cernunnos is a Java technology for developing domain-agnostic behaviors
        and mixing them in meaningful (yet arbitrary) ways.
    </description>
    <url>http://cernunnos.googlecode.com/</url>
    <licenses>
        <license>
            <name>Apache 2</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
            <comments>A business-friendly OSS license</comments>
        </license>
    </licenses>

    <issueManagement>
        <system>Google Code</system>
        <url>http://code.google.com/p/cernunnos/issues</url>
    </issueManagement>

    <scm>
        <connection>scm:git:git://github.com/drewwills/cernunnos.git</connection>
        <developerConnection>scm:git:git@github.com:drewwills/cernunnos.git</developerConnection>
        <url>https://github.com/drewwills/cernunnos</url>
        <tag>HEAD</tag>
    </scm>

    <modules>
        <module>cernunnos-archetypes</module>
        <module>cernunnos-core</module>
        <module>cernunnos-cmd-tool</module>
    </modules>

    <properties>
        <commons-dbcp.version>1.2.2</commons-dbcp.version>
        <commons-fileupload.version>1.2.1</commons-fileupload.version>
        <commons-io.version>1.4</commons-io.version>
        <commons-jexl.version>1.1</commons-jexl.version>
        <commons-lang.version>2.4</commons-lang.version>
        <commons-logging.version>1.1.1</commons-logging.version>
        <commons-pool.version>1.4</commons-pool.version>
        <cvsclient.version>20060125</cvsclient.version>
        <dom4j.version>1.6.1</dom4j.version>
        <groovy.version>1.5.6</groovy.version>
        <groovy-engine.version>1.1</groovy-engine.version>
        <mail.version>1.4.1</mail.version>
        <jaxen.version>1.1.1</jaxen.version>
        <json-lib.version>2.2.3</json-lib.version>
        <junit.version>4.5</junit.version>
        <log4j.version>1.2.15</log4j.version>
        <nekohtml.version>1.9.6.2</nekohtml.version>
        <portlet-api.version>1.0</portlet-api.version>
        <rhino.version>1.7R1</rhino.version>
        <rhino-engine.version>1.1</rhino-engine.version>
        <script-api.version>1.0</script-api.version>
        <servlet-api.version>2.4</servlet-api.version>
        <spring.version>4.3.11.RELEASE</spring.version>
        <spring-ldap.version>1.2.1</spring-ldap.version>
        <xercesImpl.version>2.8.1</xercesImpl.version>
        <xml-apis.version>1.0.b2</xml-apis.version>
        <xom.version>1.1</xom.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>commons-dbcp</groupId>
                <artifactId>commons-dbcp</artifactId>
                <version>${commons-dbcp.version}</version>
            </dependency>
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>${commons-fileupload.version}</version>
            </dependency>
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>${commons-io.version}</version>
            </dependency>
            <dependency>
                <groupId>commons-jexl</groupId>
                <artifactId>commons-jexl</artifactId>
                <version>${commons-jexl.version}</version>
            </dependency>
            <dependency>
                <groupId>commons-lang</groupId>
                <artifactId>commons-lang</artifactId>
                <version>${commons-lang.version}</version>
            </dependency>
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>${commons-logging.version}</version>
                <exclusions>
                    <exclusion>
                        <groupId>avalon-framework</groupId>
                        <artifactId>avalon-framework</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>logkit</groupId>
                        <artifactId>logkit</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>commons-pool</groupId>
                <artifactId>commons-pool</artifactId>
                <version>${commons-pool.version}</version>
            </dependency>
            <dependency>
                <groupId>dom4j</groupId>
                <artifactId>dom4j</artifactId>
                <version>${dom4j.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
                <version>${mail.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.portlet</groupId>
                <artifactId>portlet-api</artifactId>
                <version>${portlet-api.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.script</groupId>
                <artifactId>groovy-engine</artifactId>
                <classifier>jdk14</classifier>
                <version>${groovy-engine.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.script</groupId>
                <artifactId>js-engine</artifactId>
                <classifier>jdk14</classifier>
                <version>${rhino-engine.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.script</groupId>
                <artifactId>script-api</artifactId>
                <version>${script-api.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>${servlet-api.version}</version>
            </dependency>
            <dependency>
                <groupId>jaxen</groupId>
                <artifactId>jaxen</artifactId>
                <version>${jaxen.version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <dependency>
                <groupId>nekohtml</groupId>
                <artifactId>nekohtml</artifactId>
                <version>${nekohtml.version}</version>
            </dependency>
            <dependency>
                <groupId>net.sf.json-lib</groupId>
                <artifactId>json-lib</artifactId>
                <classifier>jdk15</classifier>
                <version>${json-lib.version}</version>
            </dependency>
            <dependency>
                <groupId>org.codehaus.groovy</groupId>
                <artifactId>groovy-all</artifactId>
                <version>${groovy.version}</version>
            </dependency>
            <dependency>
                <groupId>org.netbeans.lib</groupId>
                <artifactId>cvsclient</artifactId>
                <version>${cvsclient.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.ldap</groupId>
                <artifactId>spring-ldap</artifactId>
                <version>${spring-ldap.version}</version>
            </dependency>
            <dependency>
                <groupId>rhino</groupId>
                <artifactId>js</artifactId>
                <version>${rhino.version}</version>
            </dependency>
            <dependency>
                <groupId>xerces</groupId>
                <artifactId>xercesImpl</artifactId>
                <version>${xercesImpl.version}</version>
            </dependency>
            <dependency>
                <groupId>xml-apis</groupId>
                <artifactId>xml-apis</artifactId>
                <version>${xml-apis.version}</version>
            </dependency>
            <dependency>
                <groupId>xom</groupId>
                <artifactId>xom</artifactId>
                <version>${xom.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <mailingLists>
        <mailingList>
            <name>Cernunnos Discussion List</name>
            <subscribe>http://groups.google.com/group/cernunnos-discussion/subscribe</subscribe>
            <unsubscribe />
            <post />
            <archive />
            <otherArchives>
                <otherArchive />
            </otherArchives>
        </mailingList>
    </mailingLists>

    <developers>
        <developer>
            <name>Andrew Gherna</name>
            <id>argherna</id>
            <organization>University of Illinois</organization>
        </developer>
        <developer>
            <name>Andrew Petro</name>
            <id>microcline</id>
            <email>aptero AT unicon.net</email>
            <organization>UNICON</organization>
        </developer>
        <developer>
            <name>Chris Doyle</name>
            <id>cdoyle</id>
            <email>cdoyle AT jhu.edu</email>
            <organization>Johns Hopkins University</organization>
        </developer>
        <developer>
            <name>Drew Wills</name>
            <id>wills.drew</id>
            <email>awills AT unicon.net</email>
            <organization>UNICON</organization>
        </developer>
        <developer>
            <name>Eric Dalquist</name>
            <id>eric.dalquist@gmail.com</id>
            <organization>University of Wisconsin, Madison</organization>
        </developer>
        <developer>
            <name>Jen Bourey</name>
            <id>jennifer.bourey</id>
            <email>jennifer.bourey AT yale.edu</email>
            <organization>Yale</organization>
        </developer>
        <developer>
            <name>Susan Bramhall</name>
            <id>susan.bramhall</id>
            <email>susan.bramhall AT google.com</email>
            <organization>Yale</organization>
        </developer>
    </developers>

    <distributionManagement>
        <repository>
            <id>sonatype-nexus-staging</id>
            <name>Nexus Release Repository</name>
            <url>http://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
        <snapshotRepository>
            <id>sonatype-nexus-snapshots</id>
            <name>Sonatype Nexus Snapshots</name>
            <url>http://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <!--
        <repository>
            <id>jasig.maven</id>
            <name>Jasig Maven 2 Repository</name>
            <url>http://developer.jasig.org/repo/content/repositories/m2</url>
        </repository>
        <snapshotRepository>
            <id>jasig.maven</id>
            <name>Jasig Maven 2 Repository (Snapshots and Test Builds)</name>
            <url>http://developer.jasig.org/repo/content/repositories/m2-snapshot</url>
        </snapshotRepository>
        -->
    </distributionManagement>

    <repositories>
        <repository>
            <id>jasig-3rd-party</id>
            <name>Jasig 3rd Party Repository</name>
            <url>http://developer.jasig.org/repo/content/repositories/3rd-party</url>
        </repository>
        <repository>
            <id>jasig-m2</id>
            <name>Jasig Maven2 Repository</name>
            <url>http://developer.jasig.org/repo/content/repositories/m2</url>
        </repository>
        <repository>
            <id>jasig-m2-snapshot</id>
            <name>Jasig Maven2 Repository</name>
            <url>http://developer.jasig.org/repo/content/repositories/m2-snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>

    <profiles>
        <profile>
            <id>release-sign-artifacts</id>
            <activation>
                <property>
                    <name>performRelease</name>
                    <value>true</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <inherited>true</inherited>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.0</version>
                <configuration>
                    <tagBase>https://cernunnos.googlecode.com/svn/tags</tagBase>
                    <mavenExecutorId>forked-path</mavenExecutorId>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                        <configuration>
                            <additionalparam>-Xdoclint:none</additionalparam>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Auction App</title>

redpajama_set_name: RedPajamaGithub


text:
package strings;

public class Concatenation {

	public static void main(String[] args) {
		String mango = "mango";
		String s = "NBA" + mango + "team" + 90;
		System.out.println(s);
	}

}

/**Output:
NBAmangoteam90
*/


text:
package http

import (
	"net/http"

	"go-common/app/job/main/favorite/conf"
	"go-common/app/job/main/favorite/service"
	"go-common/library/log"
	bm "go-common/library/net/http/blademaster"
)

var favSvc *service.Service

// Init init http
func Init(c *conf.Config, s *service.Service) {
	favSvc = s
	// init external router
	engineOut := bm.DefaultServer(c.BM)
	outerRouter(engineOut)
	// init Outer serve
	if err := engineOut.Start(); err != nil {
		log.Error("bm.DefaultServer error(%v)", err)
		panic(err)
	}
}

// outerRouter init outer router api path.
func outerRouter(e *bm.Engine) {
	e.Ping(ping)
}

// ping check server ok.
func ping(c *bm.Context) {
	if err := favSvc.Ping(c); err != nil {
		log.Error("favorite http service ping error(%v)", err)
		c.AbortWithStatus(http.StatusServiceUnavailable)
	}
}


text:
title: Authoring Github Pages articles locally
date: 2016-02-08 16:00:00 -08:00
layout: post
---

### Less waiting, more writing
We don't want to spend all of our time pushing commits to github, so lets run a local instance of github-pages and get busy writing articles instead.

To simplify this, I've created [test-pages](https://github.com/modulusx/test-pages) that contains a Vagrantfile and Ansible playbook that will stand up and provision your own box. Assuming you have Vagrant and Ansible, it's as simple as:
{% highlight git %}
git clone https://github.com/modulusx/test-pages.git
cd test-pages
export GHP_REPO=https://github.com/YOUR_USERNAME/YOUR_USERNAME.github.io.git
vagrant up
{% endhighlight %}

Now just edit your source code in test-pages/repo until [your site](http://localhost:8000) looks good. Commit and push and you're done!


text:
from django.contrib.auth import get_user_model
from django.test import TestCase

from projects import models

User = get_user_model()

class ActionlistProjectTests(TestCase):
    def test_create_action_project_on_user_creation(self):
        user = User.objects.create(username='alice', password='alice')
        ps = models.Project.objects.filter(user=user)

        self.assertEqual(ps.count(), 1)
        self.assertEqual(ps[0].name, models.ACTION_PROJECT_NAME)


text:
package org.frustra.filament.injection.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ProxyMethod {
	String value();
}


text:
<?php

namespace AppBundle\Service;

use AppBundle\Entity\Operation;
use Doctrine\ORM\EntityManager;
use League\Csv\Reader;
use Money\Converter;
use Money\Currencies\ISOCurrencies;
use Money\Currency;
use Money\Exchange\FixedExchange;
use Money\Exchange\ReversedCurrenciesExchange;
use Money\Formatter\DecimalMoneyFormatter;
use Money\Money;
use Money\Parser\DecimalMoneyParser;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class CommissionCalculator
{
    const CASH_IN = "cash_in";
    const CASH_OUT = "cash_out";

    /**
     * @var \Iterator
     */
    private $rowIterator;

    /**
     * @var ValidatorInterface
     */
    private $validator;

    /**
     * @var Converter
     */
    private $exc;

    /**
     * @var Converter
     */
    private $reExc;

    /**
     * CommissionCalculator constructor.
     *
     * @param ValidatorInterface $validator
     * @param EntityManager      $em
     */
    public function __construct(
        ValidatorInterface $validator,
        EntityManager $em
    ) {
        $this->validator = $validator;
        $this->em        = $em;

        $exchange = new FixedExchange([
            'EUR' => [
                'EUR' => 1,
                'USD' => 1.1497,
                'JPY' => 129.53,
            ],
        ]);

        $reExchange = new ReversedCurrenciesExchange($exchange);

        $this->exc   = new Converter(new ISOCurrencies(), $exchange);
        $this->reExc = new Converter(new ISOCurrencies(), $reExchange);
    }

    /**
     * @param $fileName
     *
     * @return \Iterator
     */
    public function setCSVData($fileName)
    {
        //load the CSV document from a file path

        $reader = Reader::createFromPath($fileName);
        //$reader->setHeaderOffset(0);
        //$reader->setDelimiter(',');

        $this->rowIterator = $reader->fetch([
            $this,
            'checkDataIntegrity',
        ]); // callback

        return $this->rowIterator;
    }

    /**
     * @return array
     */
    public function getCalculatedData()
    {
        $result = [];
        foreach ($this->rowIterator as $row) {
            // print_r($row);
            // 2016-01-05, 1, natural, cash_in, 200.00, EUR
            if (isset($row[3]) && $row[3] == self::CASH_IN) {
                $result[] = $this->commissionDeposit(
                    $row[0], $row[1], $row[4], $row[5]
                );
            } elseif (isset($row[3]) && $row[3] == self::CASH_OUT) {
                $result[] = $this->commissionWithdraw(
                    $row[0], $row[1], $row[2], $row[4], $row[5]
                );
            }
        }

        return $result;
    }

    /**
     * @description Komisinis mokestis - 0.03% nuo sumos, ne daugiau 5.00 EUR.
     *
     * @param string $amount
     * @param string $currency
     * @param int    $userId
     * @param string $date
     *
     * @return Money
     */
    public function commissionDeposit(
        $date = "1990-01-01",
        $userId = 1,
        $amount = "0",
        $currency = 'EUR'
    ) {
        $currencies  = new ISOCurrencies();
        $moneyParser = new DecimalMoneyParser($currencies);

        $amount       = $moneyParser->parse($amount, $currency);
        $amountInEuro = $this->reExc->convert($amount, new Currency('EUR'));

        $commissionAmount       = $amount->multiply(0.0003, Money::ROUND_UP);
        $commissionInEuroAmount = $amountInEuro->multiply(0.0003,
            Money::ROUND_UP);

        $moneyFormatter = new DecimalMoneyFormatter($currencies);

        if ($commissionInEuroAmount->lessThan(Money::EUR("500"))) {
            return $moneyFormatter->format($commissionAmount);
        }

        return $moneyFormatter->format($this->reExc->convert(Money::EUR(500),
            new Currency($currency), Money::ROUND_UP));
    }

    /**
     * @param string $date
     * @param int    $userId
     * @param string $type
     *
     * @param string $amount
     * @param string $currency
     *
     * @return Money
     */
    public function commissionWithdraw(
        $date = "1990-01-01",
        $userId = 1,
        $type = 'natural',
        $amount = "0",
        $currency = 'EUR'
    ) {

        $currencies     = new ISOCurrencies();
        $moneyParser    = new DecimalMoneyParser($currencies);
        $moneyFormatter = new DecimalMoneyFormatter($currencies);

        $amount       = $moneyParser->parse($amount, $currency);
        $amountInEuro = $this->reExc->convert($amount, new Currency('EUR'));

        $commissionAmount       = $amount->multiply(0.003, Money::ROUND_UP);
        $commissionInEuroAmount = $amountInEuro->multiply(0.003,
            Money::ROUND_UP);

        if ($type === 'natural') {

            $operation = new Operation();
            $operation->setUserId($userId);
            $operation->setAmount($moneyFormatter->format($amountInEuro));
            $operation->setDate(new \DateTime($date));

            $this->em->persist($operation);
            $this->em->flush();

            /**
             * Suma, OP skaičius per savaitę (nuo pirmadienio iki sekmadienio).
             */
            $query = (
            'SELECT
                  count(id) as total,
                  strftime(\'%W\', date) AS w,
                  strftime(\'%Y\', date) AS yearcheck,
                  user_id,
                  (SUM(amount) - 1000.00) as sum
                 FROM
                  operation
                 WHERE
                  user_id = :userId
                  AND
                  w = strftime(\'%W\', :date)
                  AND
                  yearcheck = strftime(\'%Y\', :date)
                 GROUP BY w, user_id
                 LIMIT 1
            ');

            $params['date']   = $date;
            $params['userId'] = $userId;

            $stmt = $this->em->getConnection()->prepare($query);
            $stmt->execute($params);
            $ops = $stmt->fetch();

            $weekOverLimitSumEur = $moneyParser->parse($ops['sum'], "EUR");

            //print_r($ops);

            // Jei suma viršijama - komisinis skaičiuojamas tik nuo viršytos sumos
            // (t.y. vis dar galioja 1000 EUR be komiso).
            if ($weekOverLimitSumEur->greaterThan($moneyParser->parse("0",
                "EUR"))
            ) {
                if ($ops['total'] > 3) {
                    $commissionAmount = $amountInEuro->multiply(0.003,
                        Money::ROUND_UP);
                } else {
                    $commissionAmount = $weekOverLimitSumEur->multiply(0.003,
                        Money::ROUND_UP);
                }

                return $moneyFormatter->format($this->reExc->convert($commissionAmount,
                    new Currency($currency)));

            } else {
                // 1000.00 EUR per savaitę (nuo pirmadienio iki sekmadienio)
                // galima išsiimti nemokamai.
                return $moneyFormatter->format(
                    $moneyParser->parse("0.00", $currency)
                );
            }

        } else {
            // legal | Komisinis mokestis - 0.3% nuo sumos, bet ne mažiau nei 0.50 EUR.

            if ($commissionInEuroAmount->greaterThan(Money::EUR("50"))) {
                return $moneyFormatter->format($commissionAmount);
            }

            return $moneyFormatter->format($this->reExc->convert(Money::EUR(50),
                new Currency($currency), Money::ROUND_UP));
        }
    }

    /**
     * Validate data and return it or insert error message at exact column
     *
     * @param $row
     *
     * @return array
     */
    public function checkDataIntegrity($row)
    {
        // 2016-01-05,1,natural,cash_in,200.00,EUR
        $dateConstraint          = new Assert\Date();
        $dateConstraint->message = 'Invalid date at [0]';

        $intConstraint          = new Assert\Type("integer");
        $intConstraint->message = 'Invalid integer at [1]';

        $userTypeConstraint          = new Assert\Choice(["natural", "legal"]);
        $userTypeConstraint->message = 'Invalid user type at [2]';

        $opTypeConstraint          = new Assert\Choice([
            self::CASH_IN,
            self::CASH_OUT,
        ]);
        $opTypeConstraint->message = 'Invalid operation type at [3]';

        $amountConstraint          = new Assert\Type("numeric");
        $amountConstraint->message = 'Invalid amount at [4]';

        $currencyConstraint          = new Assert\Choice(["EUR", "USD", "JPY"]);
        $currencyConstraint->message = 'Invalid currency type at [5]';

        // use the validator to validate the value
        $errorList = [];
        $validator = $this->validator;

        $errorList[] = $validator->validate($row[0], $dateConstraint);
        $errorList[] = $validator->validate(intval($row[1]), $intConstraint);
        $errorList[] = $validator->validate($row[2], $userTypeConstraint);
        $errorList[] = $validator->validate($row[3], $opTypeConstraint);
        $errorList[] = $validator->validate($row[4], $amountConstraint);
        $errorList[] = $validator->validate($row[5], $currencyConstraint);

        $errorMessages = [];
        $pos           = 0;
        foreach ($errorList as $error) {
            if (0 !== count($error)) {
                $errorMessages[$pos++] = $error[0]->getMessage();
            }
        }

        return empty($errorMessages) ? $row : $errorMessages;
    }

}


text:
package com.forsrc.base.service;

import com.forsrc.base.dao.BaseHibernateDao;
import com.forsrc.exception.DaoException;
import com.forsrc.exception.ServiceException;
import org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * The interface Base service.
 *
 * @param <E>  the type parameter
 * @param <PK> the type parameter
 */
@Service
@Transactional
public interface BaseService<E, PK extends Serializable> {
    /**
     * List list.
     *
     * @param start the start
     * @param size  the size
     * @return the list
     * @throws ServiceException the service exception
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<E> list(int start, int size) throws ServiceException;

    /**
     * Get e.
     *
     * @param pk the pk
     * @return the e
     * @throws ServiceException the service exception
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public E get(PK pk) throws ServiceException;

    /**
     * Load e.
     *
     * @param pk the pk
     * @return the e
     * @throws ServiceException the service exception
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public E load(PK pk) throws ServiceException;

    /**
     * Save e.
     *
     * @param user the user
     * @return the e
     * @throws ServiceException the service exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = DaoException.class)
    public E save(E user) throws ServiceException;

    /**
     * Update e.
     *
     * @param user the user
     * @return the e
     * @throws ServiceException                           the service exception
     * @throws HibernateOptimisticLockingFailureException the hibernate optimistic locking failure exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = DaoException.class)
    public E update(E user) throws ServiceException, HibernateOptimisticLockingFailureException;

    /**
     * Merge e.
     *
     * @param user the user
     * @return the e
     * @throws ServiceException                           the service exception
     * @throws HibernateOptimisticLockingFailureException the hibernate optimistic locking failure exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = DaoException.class)
    public E merge(E user) throws ServiceException, HibernateOptimisticLockingFailureException;

    /**
     * Delete.
     *
     * @param e the e
     * @throws ServiceException the service exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = DaoException.class)
    public void delete(E e) throws ServiceException;

    /**
     * Clean.
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = DaoException.class)
    public void clean();

    /**
     * Flush.
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = DaoException.class)
    public void flush();

    /**
     * Gets base hibernate dao.
     *
     * @return the base hibernate dao
     */
    public BaseHibernateDao<E, PK> getBaseHibernateDao();

    //public void setBaseHibernateDao(BaseHibernateDao<E, PK> baseHibernateDao);

}


text:
package org.jkiss.dbeaver.model.impl.data;

import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.data.DBDDisplayFormat;
import org.jkiss.dbeaver.model.data.DBDValueDefaultGenerator;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.exec.DBCSession;
import org.jkiss.dbeaver.model.struct.DBSTypedObject;

import java.util.Date;

/**
 * Date/time value handler
 */
public abstract class DateTimeValueHandler extends BaseValueHandler implements DBDValueDefaultGenerator {

    protected static final Log log = Log.getLog(DateTimeValueHandler.class);

    @NotNull
    @Override
    public Class<Date> getValueObjectType(@NotNull DBSTypedObject attribute)
    {
        return Date.class;
    }

    @Override
    public Object getValueFromObject(@NotNull DBCSession session, @NotNull DBSTypedObject type, Object object, boolean copy) throws DBCException
    {
        if (object == null) {
            return null;
        } else if (object instanceof Date) {
            return (copy ? ((Date)object).clone() : object);
        } else {
            return object;
        }
    }

    @NotNull
    @Override
    public String getValueDisplayString(@NotNull DBSTypedObject column, Object value, @NotNull DBDDisplayFormat format) {
        return super.getValueDisplayString(column, value, format);
    }

    ////////////////////////////////////////////////////////
    // Default generator

    @Override
    public String getDefaultValueLabel() {
        return "Current Time";
    }

    @Override
    public Object generateDefaultValue(DBSTypedObject type) {
        try {
            return getValueFromObject(null, type, new Date(), false);
        } catch (DBCException e) {
            log.debug("Error getting current time stamp", e);
            return null;
        }
    }

}


text:
<!doctype html>

 <html class="no-js loading" <?php language_attributes(); ?>>
<?php global $smof_data; ?>

<meta charset="<?php bloginfo('charset'); ?>" />
<title><?php wp_title('—', true, 'right'); bloginfo('name'); ?></title>
<meta name="description" content="<?php if(!empty($smof_data['meta-desc'])) { ?><?php echo $smof_data['meta-desc']; ?><?php } else bloginfo('description'); ?>" />
<meta name="keywords" content="<?php if(!empty($smof_data['meta-key'])) { ?><?php echo $smof_data['meta-key']; ?><?php } ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta property="og:title" content="<?php bloginfo('name'); ?>" />
<meta property="og:description" content="<?php if(!empty($smof_data['meta-desc'])) { ?><?php echo $smof_data['meta-desc']; ?><?php } else bloginfo('description'); ?>" />
<?php if(!empty($smof_data['custom_site_image'])) { ?><meta property="og:image" content="<?php echo $smof_data['custom_site_image']; ?>" /><?php } ?>
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
  <link rel="shortcut icon" href="img/favicon.ico">
  <link rel="apple-touch-icon" href="img/apple-touch-icon.png">
  <link rel="apple-touch-icon" sizes="72x72" href="img/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="114x114" href="img/apple-touch-icon-114x114.png">
<?php if(!empty($smof_data['custom_apple_touch_icon_1'])) { ?><link rel="apple-touch-icon" href="<?php echo $smof_data['custom_apple_touch_icon_1']; ?>"><?php } ?>
<?php if(!empty($smof_data['custom_apple_touch_icon_2'])) { ?><link rel="apple-touch-icon" sizes="72x72" href="<?php echo $smof_data['custom_apple_touch_icon_2']; ?>"><?php } ?>
<?php if(!empty($smof_data['custom_apple_touch_icon_3'])) { ?><link rel="apple-touch-icon" sizes="114x114" href="<?php echo $smof_data['custom_apple_touch_icon_3']; ?>"><?php } ?>
<?php if(!empty($smof_data['custom_favicon'])) { ?>
<link rel="shortcut icon" href="<?php echo $smof_data['custom_favicon']; ?>" />
<?php } else { ?>
<link rel="shortcut icon" href="<?php echo get_template_directory_uri(); ?>/favicon.png" />
<?php } ?>
<?php if(!empty($smof_data['custom_site_image'])) { ?><link rel="image_src" href="<?php echo $smof_data['custom_site_image']; ?>" /><?php } ?>
<?php if (!empty($smof_data['tracking_header'])) echo $smof_data['tracking_header']; ?>
<?php if (!empty($smof_data['custom_css']) ) { ?><?php } ?>
<?php if ( is_singular() ) wp_enqueue_script( 'comment-reply' ); ?>
<?php wp_head(); ?>

<body <?php body_class(); ?>>

          <?php
          if(empty($smof_data['custom_logo'])) {
           echo do_shortcode($smof_data['logo_text']);
         } else {?>

          <?php $thumb_image_url2 = aq_resize( $smof_data['custom_logo'], '', 110, false ); ?>
          <img src="<?php echo $thumb_image_url2; ?>" class="logo_pic_small" alt="<?php bloginfo( 'name' ); ?>"/>
          <?php } ?>

        MAIN MENU

    <?php
        wp_nav_menu(array(
          'container' => false,
          'theme_location' => 'main_menu',
          'depth'           => 1,
          'items_wrap' => '
%3$s
'
        )); ?>

            <a href="<?php echo esc_url( home_url( '/' ) ); ?>">

        <?php if(!empty($smof_data['custom_logo']) && current_user_can('manage_options')) {
            $thumb_image_url = aq_resize( $smof_data['custom_logo'], '', 110, false );
          ?>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home" title="<?php if(!empty($smof_data['meta-desc'])) { ?><?php echo esc_attr($smof_data['meta-desc']); ?><?php } else { echo esc_attr( get_bloginfo( 'description', 'display' )); } ?>"><img src="<?php echo $thumb_image_url; ?>" class="logo_pic" style="top:34px;" alt="<?php bloginfo( 'name' ); ?>"/>

          <?php }
          elseif(!empty($smof_data['custom_logo']) && !current_user_can('manage_options')) {
             $thumb_image_url = aq_resize( $smof_data['custom_logo'], '', 110, false );
            ?>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home" title="<?php if(!empty($smof_data['meta-desc'])) { ?><?php echo esc_attr($smof_data['meta-desc']); ?><?php } else { echo esc_attr( get_bloginfo( 'description', 'display' )); } ?>"><img src="<?php echo $thumb_image_url; ?>" class="logo_pic" alt="<?php bloginfo( 'name' ); ?>"/>

        <?php } else { ?>

<?php echo do_shortcode($smof_data['logo_text']); ?>

<?php echo do_shortcode($smof_data['logo_tagline_text']); ?>

        <?php } ?>

     <?php
        wp_nav_menu(array(
          'container' => false,
          'theme_location' => 'main_menu',
          'depth'           => 1,
          'items_wrap' => '
%3$s
'
        )); ?>


text:
A lot of code borrowed/inspired by django-datetime-widget

Add 'b3datepicker' to installed apps.

# Static
```
{% load b3datepicker_tags %}
{% b3datepicker_css %}
{% b3datepicker_js %}
{{form.media}}
```

By default loads the following version css and js:
```
BOOTSTRAP_DATEPICKER_VERSION = '1.6.4'
B3DATEPICKER_JS = '//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js'
B3DATEPICKER_CSS = '//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker3.min.css'
```
If you just want to use a more recent version available on cdnjs just add BOOTSTRAP_DATEPICKER_VERSION = '1.whatever'

# Available options

Pretty much all the options except the function based ones from:

https://bootstrap-datepicker.readthedocs.io/en/stable/options.html

You can add options to the widget via:
```
widget=DateWidget(
            usel10n=True,
            options={
                'endDate': '0d',
            }
        )
```

If you dont want to show a calendar icon from the component markup:

https://bootstrap-datepicker.readthedocs.io/en/stable/markup.html
```
widget=DateWidget(
            usel10n=True,
            options={
                'endDate': '0d',
            },
            component_view=False
        )
```


text:
The cmake build mode is experimental and not officially supported,
the community is asked to maintain and support this mode through PRs.

Set up build environment (from top-level librdkafka directory):

    $ cmake -H. -B_cmake_build

On MacOSX and OpenSSL from Homebrew you might need to do:

    $ cmake -H. -B_cmake_build -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl

Build the library:

    $ cmake --build _cmake_build

If you want to build static library:

    $ cmake --build _cmake_build -DRDKAFKA_BUILD_STATIC=1

Run (local) tests:

    $ (cd _cmake_build && ctest -VV -R RdKafkaTestBrokerLess)

Install library:

    $ cmake --build _cmake_build --target install

If you use librdkafka as submodule in cmake project and want static link of librdkafka:

      set(RDKAFKA_BUILD_STATIC ON CACHE BOOL "")
      add_subdirectory(librdkafka)
      target_link_libraries(your_library_or_executable rdkafka)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.storage.blob.perf.core;

import com.azure.storage.blob.perf.BlobPerfStressOptions;

import java.util.UUID;

public abstract class AbstractUploadTest<TOptions extends BlobPerfStressOptions> extends BlobTestBase<TOptions> {

    /**
     * This ctor makes sure that each upload tests targets different blob.
     * @param options options
     */
    public AbstractUploadTest(TOptions options) {
        super(options, BLOB_NAME_PREFIX + UUID.randomUUID());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// ReSharper disable InconsistentNaming

namespace Grabacr07.KanColleWrapper.Models.Raw
{
	public class kcsapi_remodel_slotlist_detail
	{
		public int api_req_buildkit { get; set; }
		public int api_req_remodelkit { get; set; }
		public int api_certain_buildkit { get; set; }
		public int api_certain_remodelkit { get; set; }
		public int api_req_slot_id { get; set; }
		public int api_req_slot_num { get; set; }
		public int api_change_flag { get; set; }
	}
}


text:
<?php
/**
 *
 * This file is part of the Aura project for PHP.
 *
 * @package Aura.Http
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\Http\Exception;

use Aura\Http\Exception;

/**
 *
 * The response from an HTTP request was empty.
 *
 * @package Aura.Http
 *
 */
class EmptyResponse extends Exception
{
}


text:
var NAMESPACE = 'packages/local-test:nemo64:translator/test/namespace';
var LANGUAGE_FOREIGN = new Translator.LanguageArray('de_DE');
var LANGUAGE_DEFAULT = new Translator.LanguageArray();

if (Meteor.isClient) {
  Tinytest.add("Translator - Namespace - correct path", function (test) {
    var namespace = new Translator.Namespace(NAMESPACE);
    var filename = namespace._filenameForLocale('de_DE');
    var expect = NAMESPACE + '.de_DE.json';
    test.equal(filename, expect, "the language and format should be appended");
  });
}

testAsyncMulti("Translator - Namespace - check existence of an existing key", [
  function (test, expect) {
    var namespace = new Translator.Namespace(NAMESPACE);
    var expect = expect(true);
    Deps.autorun(function (dep) {
      var result = namespace.has('a_key', LANGUAGE_FOREIGN);
      if (! namespace.isLoading()) {
        expect(result);
      }
    });
  }
]);

testAsyncMulti("Translator - Namespace - check existence of a none existing key", [
  function (test, expect) {
    var namespace = new Translator.Namespace(NAMESPACE);
    var expect = expect(false);
    Deps.autorun(function (dep) {
      var result = namespace.has('not_a_key', LANGUAGE_FOREIGN);
      if (! namespace.isLoading()) {
        expect(result);
      }
    });
  }
]);

testAsyncMulti("Translator - Namespace - access existing key", [
  function (test, expect) {
    var namespace = new Translator.Namespace(NAMESPACE);
    var expect = expect("Hallo Test");
    Deps.autorun(function (dep) {
      var result = namespace.get('a_key', LANGUAGE_FOREIGN);
      if (! namespace.isLoading()) {
        expect(result.value);
      }
    });
  }
]);

testAsyncMulti("Translator - Namespace - access none existing key", [
  function (test, expect) {
    var namespace = new Translator.Namespace(NAMESPACE);
    var expect = expect(undefined);
    Deps.autorun(function (dep) {
      var result = namespace.get('not_a_key', LANGUAGE_FOREIGN);
      if (! namespace.isLoading()) {
        expect(result.value);
      }
    });
  }
]);

testAsyncMulti("Translator - Namespace - access key though fallback", [
  function (test, expect) {
    var namespace = new Translator.Namespace(NAMESPACE);
    var language = new Translator.LanguageArray(['it', 'en_US', 'de_DE']);
    var expect = expect("Hallo Test");
    Deps.autorun(function (dep) {
      var result = namespace.get('a_key', LANGUAGE_FOREIGN);
      if (! namespace.isLoading()) {
        expect(result.value);
      }
    });
  }
]);

Tinytest.add("Translator - Namespace - none existing namespace", function (test) {
  try {
    var namespace = new Translator.Namespace("none existing namespace");
    test.isTrue(false);
  } catch (e) {
    test.instanceOf(e, Error);
  }
});


text:
<?php

namespace Gnugat\Redaktilo\Search\Php;

/**
 * @deprecated 1.7 No replacement
 */
class TokenBuilder
{
    /**
     * @param mixed $rawToken
     * @param int   $lineNumber
     *
     * @return Token
     */
    public function makeFromRaw($rawToken, $lineNumber = 0)
    {
        trigger_error(__CLASS__.' is no longer supported and will be removed in version 2', \E_USER_DEPRECATED);
        if (!is_array($rawToken)) {
            return new Token(null, $rawToken, $lineNumber);
        }

        return new Token($rawToken[0], $rawToken[1], $rawToken[2] - 1);
    }

    /** @return Token */
    public function makeFunction()
    {
        trigger_error(__CLASS__.' is no longer supported and will be removed in version 2', \E_USER_DEPRECATED);

        return new Token(T_FUNCTION, 'function');
    }

    /** @return Token */
    public function makeMethod()
    {
        trigger_error(__CLASS__.' is no longer supported and will be removed in version 2', \E_USER_DEPRECATED);

        return $this->makeFunction();
    }

    /** @return Token */
    public function makeClass()
    {
        trigger_error(__CLASS__.' is no longer supported and will be removed in version 2', \E_USER_DEPRECATED);

        return new Token(T_CLASS, 'class');
    }

    /**
     * @param string $whitespace
     *
     * @return Token
     */
    public function makeWhitespace($whitespace)
    {
        trigger_error(__CLASS__.' is no longer supported and will be removed in version 2', \E_USER_DEPRECATED);

        return new Token(T_WHITESPACE, $whitespace);
    }

    /**
     *
     * @param string $string
     *
     * @return Token
     */
    public function makeString($string)
    {
        trigger_error(__CLASS__.' is no longer supported and will be removed in version 2', \E_USER_DEPRECATED);

        return new Token(T_STRING, $string);
    }

    /**
     * @param array $rawTokens
     *
     * @return Token[]
     */
    public function buildFromRaw(array $rawTokens)
    {
        trigger_error(__CLASS__.' is no longer supported and will be removed in version 2', \E_USER_DEPRECATED);
        $lineNumber = 0;
        $tokens = array();
        foreach ($rawTokens as $rawToken) {
            $token = $this->makeFromRaw($rawToken, $lineNumber);
            if ($token->hasNumber()) {
                $lineNumber = $token->getLineNumber() + substr_count($token->getValue(), "\n");
            }
            $tokens[] = $token;
        }

        return $tokens;
    }

    /**
     * @param string $className
     *
     * @return Token[]
     */
    public function buildClass($className)
    {
        trigger_error(__CLASS__.' is no longer supported and will be removed in version 2', \E_USER_DEPRECATED);
        $class = $this->makeClass();
        $whitespace = $this->makeWhitespace(null);
        $string = $this->makeString($className);

        return array($class, $whitespace, $string);
    }

    /**
     * @param string $functionName
     *
     * @return Token[]
     */
    public function buildFunction($functionName)
    {
        trigger_error(__CLASS__.' is no longer supported and will be removed in version 2', \E_USER_DEPRECATED);
        $function = $this->makeFunction();
        $whitespace = $this->makeWhitespace(null);
        $string = $this->makeString($functionName);

        return array($function, $whitespace, $string);
    }

    /**
     * @param string $methodName
     *
     * @return Token[]
     */
    public function buildMethod($methodName)
    {
        trigger_error(__CLASS__.' is no longer supported and will be removed in version 2', \E_USER_DEPRECATED);

        return $this->buildFunction($methodName);
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.reldb.rel</groupId>
        <artifactId>rel</artifactId>
        <version>3.017</version>
    </parent>

    <artifactId>swtNative</artifactId>
    <name>swtNative</name>
    <packaging>pom</packaging>

    <properties>
        <swt.native.version>3.121.0</swt.native.version>
    </properties>

    <modules>
        <module>swt_linux</module>
        <module>swt_macos</module>
        <module>swt_win</module>
    </modules>
</project>


text:
<!DOCTYPE html>

        <title>CIGP</title>

        <link rel="stylesheet" href="css/cigp.css" />
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

Canvas Irregular Grid Painter

This tool is based heavily on the work done by Zlosk on Irregular Grid Painter.

Zlosk's IGP contains a number of features that are not implemented yet here such as freehand drawing and the ability to export to a 3d image file format.  It is an excellent tool which many folks have used over the past decade.

I intend to add most of the missing features in the near future.  If there is a particular feature you need please comment below and I will try to prioritize it.

This version is a ground-up rewrite which uses the html5 canvas element so that it can run entirely in browser.  The primary advantages to this approach are that it is platform independent, and the user does not need to install anything.

For more information, please reference the FAQ (coming soon).

The source code is available on github under the MIT license at Canvas IGP.

This tool currently only works in Chrome and Firefox.

                    Please choose a pattern:
                    <select id="patternSelector"></select>

                    Canvas width:
                    <input type="number" value="800" id="canvasWidth"/>

                    Canvas height:
                    <input type="number" value="600" id="canvasHeight"/>

                    Color:
                    <input type="color" value="#000000" id="colorPicker"/>
                    <input type="button" id="colorButton" value="Set"/>

                    Select File:
                    <input type="file" id="sourceFile"/>

After selecting a file, the canvas will resize and then begin drawing in your patterned image.  If your image begins with a large white space, it may initially appear that nothing is happening.

            <button id="saveImageButton">Save Patterned Image</button>
            <button id="subtileCountButton">View Subtile Count By Color</button>

                    <canvas width="50" height="100" id="canvas">
                        Canvas
                    </canvas>

Right click the image in this dialog and "Save Image As..." to save.

Or if you are using Chrome you have to select "Copy Image" and then paste it into an image editing program to save.


text:
package abi43_0_0.expo.modules.interfaces.sensors.services;

import abi43_0_0.expo.modules.interfaces.sensors.SensorServiceInterface;

public interface GyroscopeServiceInterface extends SensorServiceInterface {
}


text:
function [A,b]=affinemap(pfrom,pto)
%  [A,b]=affinemap(pfrom,pto)
%
%  calculate an affine transform (A matrix and b vector) to map n
%  vertices from one space to the other using least square solutions
%
%  author: Qianqian Fang <fangq at nmr.mgh.harvard.edu>
%  date: 12/12/2008
%
% parameters:
%      pfrom: nx3 matrix, each row is a 3d point in original space
%      pto: nx3 matrix, each row is a 3d point in the mapped space
%
% outputs:
%      A: 3x3 matrix, the calculated affine A matrix
%      b: 3x1 vector, the calculated affine b vector
%
% the solution will satisfy the following equation: A*pfrom'+b=pto
%
% Please find more information at http://iso2mesh.sf.net/cgi-bin/index.cgi?metch
%
% this function is part of "metch" toobox, see COPYING for license

bsubmat=eye(3);
ptnum=size(pfrom,1);
if(size(pto,1)~=ptnum)
        error('two inputs should have the same size');
end
amat=zeros(ptnum*3,9);
for i=1:ptnum
        amat(i*3-2:i*3,:)=kron(bsubmat,pfrom(i,:));
end
amat=[amat,repmat(bsubmat,ptnum,1)];

bvec=pto';
bvec=bvec(:);

x=amat\bvec;
A=reshape(x(1:9),3,3)';
b=x(end-2:end);


text:
FROM blacklabelops/jobber
MAINTAINER Steffen Bleul <sbl@blacklabelops.com>

ENV JAVA_DISTRIBUTION=server-jre \
    JAVA_MAJOR_VERSION=8 \
    JAVA_UPDATE_VERSION=92 \
    JAVA_BUILD_NUMBER=14 \
    ROTATOR_HOME=/opt/backuprotator \
    GLIBC_VERSION=2.23-r1 \
    LANG=en_US.UTF-8

ENV JAVA_VERSION=1.${JAVA_MAJOR_VERSION}.0_${JAVA_UPDATE_VERSION}
ENV JAVA_HOME=/opt/java/${JAVA_DISTRIBUTION}${JAVA_VERSION}
ENV PATH=$PATH:$JAVA_HOME/bin

RUN apk add --update \
      ca-certificates \
      unzip \
      wget && \
    # Install latest glibc
    wget --directory-prefix=/tmp https://github.com/andyshinn/alpine-pkg-glibc/releases/download/${GLIBC_VERSION}/glibc-${GLIBC_VERSION}.apk && \
    apk add --allow-untrusted /tmp/glibc-${GLIBC_VERSION}.apk && \
    wget --directory-prefix=/tmp https://github.com/andyshinn/alpine-pkg-glibc/releases/download/${GLIBC_VERSION}/glibc-bin-${GLIBC_VERSION}.apk && \
    apk add --allow-untrusted /tmp/glibc-bin-${GLIBC_VERSION}.apk && \
    wget --directory-prefix=/tmp https://github.com/andyshinn/alpine-pkg-glibc/releases/download/${GLIBC_VERSION}/glibc-i18n-${GLIBC_VERSION}.apk && \
    apk --allow-untrusted add /tmp/glibc-i18n-${GLIBC_VERSION}.apk && \
    /usr/glibc-compat/bin/localedef -i en_US -f UTF-8 en_US.UTF-8 && \
    # Install oracle java
    export JAVA_TARBALL=${JAVA_DISTRIBUTION}-${JAVA_MAJOR_VERSION}u${JAVA_UPDATE_VERSION}-linux-x64.tar.gz && \
    wget --directory-prefix=/tmp \
         --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" \
         http://download.oracle.com/otn-pub/java/jdk/${JAVA_MAJOR_VERSION}u${JAVA_UPDATE_VERSION}-b${JAVA_BUILD_NUMBER}/${JAVA_TARBALL} && \
    mkdir -p /opt/java && \
    tar -xzf /tmp/${JAVA_TARBALL} -C /opt/java/ && \
    if  [ "${JAVA_DISTRIBUTION}" = "server-jre" ]; \
      then mv /opt/java/jdk${JAVA_VERSION} ${JAVA_HOME} ; \
    fi && \
    ln -s ${JAVA_HOME}/bin/java /usr/bin/java && \
    # Remove obsolete packages
    apk del \
      unzip \
      wget && \
    # Clean caches and tmps
    rm -rf /var/cache/apk/* && \
    rm -rf /tmp/* && \
    rm -rf /var/log/*

COPY build/libs/backuprotator-all-0.1.0.jar /opt/backuprotator/backrotator-all.jar
COPY build/resources/main /opt/backuprotator
WORKDIR /opt/backuprotator


text:
3210 Project 1
==============

Leap Frog random number generator kernel module!

Install Module
--------------

On factor-3210:

    make
    scp lfprng.ko factor007:~

On factor007

    sudo su
    insmod lfprng.ko

Remove Module
-------------

    rmmod lfprng

Misc
----

In `read_proc_lfprng` (the callback for when a user reads), the if block gets
executed as long as thread_count is not set (-1), and that's where the number
generation should go, since its only executed once. There's no check currently
if there are not enough numbers, but that should be quite easy to check for.

In `write_proc_lfprng` the user input is converted to an integer and
`user_seed` is set to that.


text:
module Pageflow
  module NavigationBarHelper
    def navigation_bar_css_class(entry, options = {})
      [
        options[:class],
        entry.home_button.enabled? ? 'with_home_button' : nil,
        entry.overview_button.enabled? ? 'with_overview_button' : nil
      ].compact.join(' ')
    end
  end
end


text:
'use strict';

/**
 * Data Lake Store filesystem error containing a specific WebHDFS exception.
 *
 */
class AdlsError {
  /**
   * Create a AdlsError.
   * @property {object} [remoteException] the object representing the actual
   * WebHDFS exception being returned.
   * @property {string} [remoteException.javaClassName] the full class package
   * name for the exception thrown, such as
   * 'java.lang.IllegalArgumentException'.
   * @property {string} [remoteException.message] the message associated with
   * the exception that was thrown, such as 'Invalid value for webhdfs
   * parameter "permission":...'.
   * @property {string} [remoteException.exception] Polymorphic Discriminator
   */
  constructor() {
  }

  /**
   * Defines the metadata of AdlsError
   *
   * @returns {object} metadata of AdlsError
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'AdlsError',
      type: {
        name: 'Composite',
        className: 'AdlsError',
        modelProperties: {
          remoteException: {
            required: false,
            readOnly: true,
            serializedName: 'remoteException',
            type: {
              name: 'Composite',
              polymorphicDiscriminator: {
                serializedName: 'exception',
                clientName: 'exception'
              },
              uberParent: 'AdlsRemoteException',
              className: 'AdlsRemoteException'
            }
          }
        }
      }
    };
  }
}

module.exports = AdlsError;


text:
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;

-- Index
--ALTER TABLE `KBOOpenData_meta` ADD UNIQUE INDEX  `metaUnique` (Variable);


text:
/* See LICENSE for licensing information */

/**
 * \file circuitmux.c
 * \brief Circuit mux/cell selection abstraction
 *
 * A circuitmux is responsible for MUltipleXing all of the
 * circuits that are writing on a single channel. It keeps track of which of
 * these circuits has something to write (aka, "active" circuits), and which
 * one should write next.  A circuitmux corresponds 1:1 with a channel.
 *
 * There can be different implementations of the circuitmux's rules (which
 * decide which circuit is next to write).
 *
 * A circuitmux exposes three distinct
 * interfaces to other components:
 *
 * To channels, which each have a circuitmux_t, the supported operations
 * (invoked from relay.c) are:
 *
 *   circuitmux_get_first_active_circuit():
 *
 *     Pick one of the circuitmux's active circuits to send cells from.
 *
 *   circuitmux_notify_xmit_cells():
 *
 *     Notify the circuitmux that cells have been sent on a circuit.
 *
 * To circuits, the exposed operations are:
 *
 *   circuitmux_attach_circuit():
 *
 *     Attach a circuit to the circuitmux; this will allocate any policy-
 *     specific data wanted for this circuit and add it to the active
 *     circuits list if it has queued cells.
 *
 *   circuitmux_detach_circuit():
 *
 *     Detach a circuit from the circuitmux, freeing associated structures.
 *
 *   circuitmux_clear_num_cells():
 *
 *     Clear the circuitmux's cell counter for this circuit.
 *
 *   circuitmux_set_num_cells():
 *
 *     Set the circuitmux's cell counter for this circuit. One of
 *     circuitmuc_clear_num_cells() or circuitmux_set_num_cells() MUST be
 *     called when the number of cells queued on a circuit changes.
 *
 * See circuitmux.h for the circuitmux_policy_t data structure, which contains
 * a table of function pointers implementing a circuit selection policy, and
 * circuitmux_ewma.c for an example of a circuitmux policy.  Circuitmux
 * policies can be manipulated with:
 *
 *   circuitmux_get_policy():
 *
 *     Return the current policy for a circuitmux_t, if any.
 *
 *   circuitmux_clear_policy():
 *
 *     Remove a policy installed on a circuitmux_t, freeing all associated
 *     data.  The circuitmux will revert to the built-in round-robin behavior.
 *
 *   circuitmux_set_policy():
 *
 *     Install a policy on a circuitmux_t; the appropriate callbacks will be
 *     made to attach all existing circuits to the new policy.
 **/

#define CIRCUITMUX_PRIVATE

#include "core/or/or.h"
#include "core/or/channel.h"
#include "core/or/circuitlist.h"
#include "core/or/circuitmux.h"
#include "core/or/relay.h"

#include "core/or/or_circuit_st.h"

#include "lib/crypt_ops/crypto_util.h"

/*
 * Private typedefs for circuitmux.c
 */

/*
 * Hash table entry (yeah, calling it chanid_circid_muxinfo_s seems to
 * break the hash table code).
 */
typedef struct chanid_circid_muxinfo_t chanid_circid_muxinfo_t;

/*
 * Anything the mux wants to store per-circuit in the map; right now just
 * a count of queued cells.
 */

typedef struct circuit_muxinfo_t circuit_muxinfo_t;

/*
 * This struct holds whatever we want to store per attached circuit on a
 * circuitmux_t; right now, just the count of queued cells and the direction.
 */

struct circuit_muxinfo_t {
  /* Count of cells on this circuit at last update */
  unsigned int cell_count;
  /* Direction of flow */
  cell_direction_t direction;
  /* Policy-specific data */
  circuitmux_policy_circ_data_t *policy_data;
  /* Mark bit for consistency checker */
  unsigned int mark:1;
};

/*
 * A map from channel ID and circuit ID to a circuit_muxinfo_t for that
 * circuit.
 */

struct chanid_circid_muxinfo_t {
  HT_ENTRY(chanid_circid_muxinfo_t) node;
  uint64_t chan_id;
  circid_t circ_id;
  circuit_muxinfo_t muxinfo;
};

/*
 * Static function declarations
 */

static inline int
chanid_circid_entries_eq(chanid_circid_muxinfo_t *a,
                         chanid_circid_muxinfo_t *b);
static inline unsigned int
chanid_circid_entry_hash(chanid_circid_muxinfo_t *a);
static chanid_circid_muxinfo_t *
circuitmux_find_map_entry(circuitmux_t *cmux, circuit_t *circ);
static void
circuitmux_make_circuit_active(circuitmux_t *cmux, circuit_t *circ);
static void
circuitmux_make_circuit_inactive(circuitmux_t *cmux, circuit_t *circ);

/* Static global variables */

/** Count the destroy balance to debug destroy queue logic */
static int64_t global_destroy_ctr = 0;

/* Function definitions */

/**
 * Helper for chanid_circid_cell_count_map_t hash table: compare the channel
 * ID and circuit ID for a and b, and return less than, equal to, or greater
 * than zero appropriately.
 */

static inline int
chanid_circid_entries_eq(chanid_circid_muxinfo_t *a,
                         chanid_circid_muxinfo_t *b)
{
    return a->chan_id == b->chan_id && a->circ_id == b->circ_id;
}

/**
 * Helper: return a hash based on circuit ID and channel ID in a.
 */

static inline unsigned int
chanid_circid_entry_hash(chanid_circid_muxinfo_t *a)
{
    return (((unsigned int)(a->circ_id) << 8) ^
            ((unsigned int)((a->chan_id >> 32) & 0xffffffff)) ^
            ((unsigned int)(a->chan_id & 0xffffffff)));
}

/* Emit a bunch of hash table stuff */
HT_PROTOTYPE(chanid_circid_muxinfo_map, chanid_circid_muxinfo_t, node,
             chanid_circid_entry_hash, chanid_circid_entries_eq)
HT_GENERATE2(chanid_circid_muxinfo_map, chanid_circid_muxinfo_t, node,
             chanid_circid_entry_hash, chanid_circid_entries_eq, 0.6,
             tor_reallocarray_, tor_free_)

/*
 * Circuitmux alloc/free functions
 */

/**
 * Allocate a new circuitmux_t
 */

circuitmux_t *
circuitmux_alloc(void)
{
  circuitmux_t *rv = NULL;

  rv = tor_malloc_zero(sizeof(*rv));
  rv->chanid_circid_map = tor_malloc_zero(sizeof(*( rv->chanid_circid_map)));
  HT_INIT(chanid_circid_muxinfo_map, rv->chanid_circid_map);
  destroy_cell_queue_init(&rv->destroy_cell_queue);

  return rv;
}

/**
 * Detach all circuits from a circuitmux (use before circuitmux_free())
 *
 * If detached_out is non-NULL, add every detached circuit_t to
 * detached_out.
 */

void
circuitmux_detach_all_circuits(circuitmux_t *cmux, smartlist_t *detached_out)
{
  chanid_circid_muxinfo_t **i = NULL, *to_remove;
  channel_t *chan = NULL;
  circuit_t *circ = NULL;

  tor_assert(cmux);

  i = HT_START(chanid_circid_muxinfo_map, cmux->chanid_circid_map);
  while (i) {
    to_remove = *i;

    if (! to_remove) {
      log_warn(LD_BUG, "Somehow, an HT iterator gave us a NULL pointer.");
      break;
    } else {
      /* Find a channel and circuit */
      chan = channel_find_by_global_id(to_remove->chan_id);
      if (chan) {
        circ =
          circuit_get_by_circid_channel_even_if_marked(to_remove->circ_id,
                                                       chan);
        if (circ) {
          /* Clear the circuit's mux for this direction */
          if (to_remove->muxinfo.direction == CELL_DIRECTION_OUT) {
            /*
             * Update active_circuits et al.; this does policy notifies, so
             * comes before freeing policy data
             */

            if (to_remove->muxinfo.cell_count > 0) {
              circuitmux_make_circuit_inactive(cmux, circ);
            }

            if (detached_out)
              smartlist_add(detached_out, circ);
          } else if (circ->magic == OR_CIRCUIT_MAGIC) {
            /*
             * Update active_circuits et al.; this does policy notifies, so
             * comes before freeing policy data
             */

            if (to_remove->muxinfo.cell_count > 0) {
              circuitmux_make_circuit_inactive(cmux, circ);
            }

            if (detached_out)
              smartlist_add(detached_out, circ);
          } else {
            /* Complain and move on */
            log_warn(LD_CIRC,
                     "Circuit %u/channel %"PRIu64 " had direction == "
                     "CELL_DIRECTION_IN, but isn't an or_circuit_t",
                     (unsigned)to_remove->circ_id,
                     (to_remove->chan_id));
          }

          /* Free policy-specific data if we have it */
          if (to_remove->muxinfo.policy_data) {
            /*
             * If we have policy data, assert that we have the means to
             * free it
             */
            tor_assert(cmux->policy);
            tor_assert(cmux->policy->free_circ_data);
            /* Call free_circ_data() */
            cmux->policy->free_circ_data(cmux,
                                         cmux->policy_data,
                                         circ,
                                         to_remove->muxinfo.policy_data);
            to_remove->muxinfo.policy_data = NULL;
          }
        } else {
          /* Complain and move on */
          log_warn(LD_CIRC,
                   "Couldn't find circuit %u (for channel %"PRIu64 ")",
                   (unsigned)to_remove->circ_id,
                   (to_remove->chan_id));
        }
      } else {
        /* Complain and move on */
        log_warn(LD_CIRC,
                 "Couldn't find channel %"PRIu64 " (for circuit id %u)",
                 (to_remove->chan_id),
                 (unsigned)to_remove->circ_id);
      }

      /* Assert that we don't have un-freed policy data for this circuit */
      tor_assert(to_remove->muxinfo.policy_data == NULL);
    }

    i = HT_NEXT_RMV(chanid_circid_muxinfo_map, cmux->chanid_circid_map, i);

    /* Free it */
    tor_free(to_remove);
  }

  cmux->n_circuits = 0;
  cmux->n_active_circuits = 0;
  cmux->n_cells = 0;
}

/** Reclaim all circuit IDs currently marked as unusable on chan because
 * of pending destroy cells in cmux.
 *
 * This function must be called AFTER circuits are unlinked from the (channel,
 * circuid-id) map with circuit_unlink_all_from_channel(), but before calling
 * circuitmux_free().
 */
void
circuitmux_mark_destroyed_circids_usable(circuitmux_t *cmux, channel_t *chan)
{
  destroy_cell_t *cell;
  TOR_SIMPLEQ_FOREACH(cell, &cmux->destroy_cell_queue.head, next) {
    channel_mark_circid_usable(chan, cell->circid);
  }
}

/**
 * Free a circuitmux_t; the circuits must be detached first with
 * circuitmux_detach_all_circuits().
 */

void
circuitmux_free_(circuitmux_t *cmux)
{
  if (!cmux) return;

  tor_assert(cmux->n_circuits == 0);
  tor_assert(cmux->n_active_circuits == 0);

  /*
   * Free policy-specific data if we have any; we don't
   * need to do circuitmux_set_policy(cmux, NULL) to cover
   * the circuits because they would have been handled in
   * circuitmux_detach_all_circuits() before this was
   * called.
   */
  if (cmux->policy && cmux->policy->free_cmux_data) {
    if (cmux->policy_data) {
      cmux->policy->free_cmux_data(cmux, cmux->policy_data);
      cmux->policy_data = NULL;
    }
  } else tor_assert(cmux->policy_data == NULL);

  if (cmux->chanid_circid_map) {
    HT_CLEAR(chanid_circid_muxinfo_map, cmux->chanid_circid_map);
    tor_free(cmux->chanid_circid_map);
  }

  /*
   * We're throwing away some destroys; log the counter and
   * adjust the global counter by the queue size.
   */
  if (cmux->destroy_cell_queue.n > 0) {
    cmux->destroy_ctr -= cmux->destroy_cell_queue.n;
    global_destroy_ctr -= cmux->destroy_cell_queue.n;
    log_debug(LD_CIRC,
              "Freeing cmux at %p with %u queued destroys; the last cmux "
              "destroy balance was %"PRId64", global is %"PRId64,
              cmux, cmux->destroy_cell_queue.n,
              (cmux->destroy_ctr),
              (global_destroy_ctr));
  } else {
    log_debug(LD_CIRC,
              "Freeing cmux at %p with no queued destroys, the cmux destroy "
              "balance was %"PRId64", global is %"PRId64,
              cmux,
              (cmux->destroy_ctr),
              (global_destroy_ctr));
  }

  destroy_cell_queue_clear(&cmux->destroy_cell_queue);

  tor_free(cmux);
}

/*
 * Circuitmux policy control functions
 */

/**
 * Remove any policy installed on cmux; all policy data will be freed and
 * cmux behavior will revert to the built-in round-robin active_circuits
 * mechanism.
 */

void
circuitmux_clear_policy(circuitmux_t *cmux)
{
  tor_assert(cmux);

  /* Internally, this is just setting policy to NULL */
  circuitmux_set_policy(cmux, NULL);
}

/**
 * Return the policy currently installed on a circuitmux_t
 */

MOCK_IMPL(const circuitmux_policy_t *,
circuitmux_get_policy, (circuitmux_t *cmux))
{
  tor_assert(cmux);

  return cmux->policy;
}

/**
 * Set policy; allocate for new policy, detach all circuits from old policy
 * if any, attach them to new policy, and free old policy data.
 */

void
circuitmux_set_policy(circuitmux_t *cmux,
                      const circuitmux_policy_t *pol)
{
  const circuitmux_policy_t *old_pol = NULL, *new_pol = NULL;
  circuitmux_policy_data_t *old_pol_data = NULL, *new_pol_data = NULL;
  chanid_circid_muxinfo_t **i = NULL;
  channel_t *chan = NULL;
  uint64_t last_chan_id_searched = 0;
  circuit_t *circ = NULL;

  tor_assert(cmux);

  /* Set up variables */
  old_pol = cmux->policy;
  old_pol_data = cmux->policy_data;
  new_pol = pol;

  /* Check if this is the trivial case */
  if (old_pol == new_pol) return;

  /* Allocate data for new policy, if any */
  if (new_pol && new_pol->alloc_cmux_data) {
    /*
     * If alloc_cmux_data is not null, then we expect to get some policy
     * data.  Assert that we also have free_cmux_data so we can free it
     * when the time comes, and allocate it.
     */
    tor_assert(new_pol->free_cmux_data);
    new_pol_data = new_pol->alloc_cmux_data(cmux);
    tor_assert(new_pol_data);
  }

  /* Install new policy and new policy data on cmux */
  cmux->policy = new_pol;
  cmux->policy_data = new_pol_data;

  /* Iterate over all circuits, attaching/detaching each one */
  i = HT_START(chanid_circid_muxinfo_map, cmux->chanid_circid_map);
  while (i) {
    /* Assert that this entry isn't NULL */
    tor_assert(*i);

    /*
     * Get the channel; since normal case is all circuits on the mux share a
     * channel, we cache last_chan_id_searched
     */
    if (!chan || last_chan_id_searched != (*i)->chan_id) {
      chan = channel_find_by_global_id((*i)->chan_id);
      last_chan_id_searched = (*i)->chan_id;
    }
    tor_assert(chan);

    /* Get the circuit */
    circ = circuit_get_by_circid_channel_even_if_marked((*i)->circ_id, chan);
    tor_assert(circ);

    /* Need to tell old policy it becomes inactive (i.e., it is active) ? */
    if (old_pol && old_pol->notify_circ_inactive &&
        (*i)->muxinfo.cell_count > 0) {
      old_pol->notify_circ_inactive(cmux, old_pol_data, circ,
                                    (*i)->muxinfo.policy_data);
    }

    /* Need to free old policy data? */
    if ((*i)->muxinfo.policy_data) {
      /* Assert that we have the means to free it if we have policy data */
      tor_assert(old_pol);
      tor_assert(old_pol->free_circ_data);
      /* Free it */
      old_pol->free_circ_data(cmux, old_pol_data, circ,
                             (*i)->muxinfo.policy_data);
      (*i)->muxinfo.policy_data = NULL;
    }

    /* Need to allocate new policy data? */
    if (new_pol && new_pol->alloc_circ_data) {
      /*
       * If alloc_circ_data is not null, we expect to get some per-circuit
       * policy data.  Assert that we also have free_circ_data so we can
       * free it when the time comes, and allocate it.
       */
      tor_assert(new_pol->free_circ_data);
      (*i)->muxinfo.policy_data =
        new_pol->alloc_circ_data(cmux, new_pol_data, circ,
                                 (*i)->muxinfo.direction,
                                 (*i)->muxinfo.cell_count);
    }

    /* Need to make active on new policy? */
    if (new_pol && new_pol->notify_circ_active &&
        (*i)->muxinfo.cell_count > 0) {
      new_pol->notify_circ_active(cmux, new_pol_data, circ,
                                  (*i)->muxinfo.policy_data);
    }

    /* Advance to next circuit map entry */
    i = HT_NEXT(chanid_circid_muxinfo_map, cmux->chanid_circid_map, i);
  }

  /* Free data for old policy, if any */
  if (old_pol_data) {
    /*
     * If we had old policy data, we should have an old policy and a free
     * function for it.
     */
    tor_assert(old_pol);
    tor_assert(old_pol->free_cmux_data);
    old_pol->free_cmux_data(cmux, old_pol_data);
    old_pol_data = NULL;
  }
}

/*
 * Circuitmux/circuit attachment status inquiry functions
 */

/**
 * Query the direction of an attached circuit
 */

cell_direction_t
circuitmux_attached_circuit_direction(circuitmux_t *cmux, circuit_t *circ)
{
  chanid_circid_muxinfo_t *hashent = NULL;

  /* Try to find a map entry */
  hashent = circuitmux_find_map_entry(cmux, circ);

  /*
   * This function should only be called on attached circuits; assert that
   * we had a map entry.
   */
  tor_assert(hashent);

  /* Return the direction from the map entry */
  return hashent->muxinfo.direction;
}

/**
 * Find an entry in the cmux's map for this circuit or return NULL if there
 * is none.
 */

static chanid_circid_muxinfo_t *
circuitmux_find_map_entry(circuitmux_t *cmux, circuit_t *circ)
{
  chanid_circid_muxinfo_t search, *hashent = NULL;

  /* Sanity-check parameters */
  tor_assert(cmux);
  tor_assert(cmux->chanid_circid_map);
  tor_assert(circ);

  /* Check if we have n_chan */
  if (circ->n_chan) {
    /* Okay, let's see if it's attached for n_chan/n_circ_id */
    search.chan_id = circ->n_chan->global_identifier;
    search.circ_id = circ->n_circ_id;

    /* Query */
    hashent = HT_FIND(chanid_circid_muxinfo_map, cmux->chanid_circid_map,
                      &search);
  }

  /* Found something? */
  if (hashent) {
    /*
     * Assert that the direction makes sense for a hashent we found by
     * n_chan/n_circ_id before we return it.
     */
    tor_assert(hashent->muxinfo.direction == CELL_DIRECTION_OUT);
  } else {
    /* Not there, have we got a p_chan/p_circ_id to try? */
    if (circ->magic == OR_CIRCUIT_MAGIC) {
      search.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
      /* Check for p_chan */
      if (TO_OR_CIRCUIT(circ)->p_chan) {
        search.chan_id = TO_OR_CIRCUIT(circ)->p_chan->global_identifier;
        /* Okay, search for that */
        hashent = HT_FIND(chanid_circid_muxinfo_map, cmux->chanid_circid_map,
                          &search);
        /* Find anything? */
        if (hashent) {
          /* Assert that the direction makes sense before we return it */
          tor_assert(hashent->muxinfo.direction == CELL_DIRECTION_IN);
        }
      }
    }
  }

  /* Okay, hashent is it if it was there */
  return hashent;
}

/**
 * Query whether a circuit is attached to a circuitmux
 */

int
circuitmux_is_circuit_attached(circuitmux_t *cmux, circuit_t *circ)
{
  chanid_circid_muxinfo_t *hashent = NULL;

  /* Look if it's in the circuit map */
  hashent = circuitmux_find_map_entry(cmux, circ);

  return (hashent != NULL);
}

/**
 * Query whether a circuit is active on a circuitmux
 */

int
circuitmux_is_circuit_active(circuitmux_t *cmux, circuit_t *circ)
{
  chanid_circid_muxinfo_t *hashent = NULL;
  int is_active = 0;

  tor_assert(cmux);
  tor_assert(circ);

  /* Look if it's in the circuit map */
  hashent = circuitmux_find_map_entry(cmux, circ);
  if (hashent) {
    /* Check the number of cells on this circuit */
    is_active = (hashent->muxinfo.cell_count > 0);
  }
  /* else not attached, so not active */

  return is_active;
}

/**
 * Query number of available cells for a circuit on a circuitmux
 */

unsigned int
circuitmux_num_cells_for_circuit(circuitmux_t *cmux, circuit_t *circ)
{
  chanid_circid_muxinfo_t *hashent = NULL;
  unsigned int n_cells = 0;

  tor_assert(cmux);
  tor_assert(circ);

  /* Look if it's in the circuit map */
  hashent = circuitmux_find_map_entry(cmux, circ);
  if (hashent) {
    /* Just get the cell count for this circuit */
    n_cells = hashent->muxinfo.cell_count;
  }
  /* else not attached, so 0 cells */

  return n_cells;
}

/**
 * Query total number of available cells on a circuitmux
 */

MOCK_IMPL(unsigned int,
circuitmux_num_cells, (circuitmux_t *cmux))
{
  tor_assert(cmux);

  return cmux->n_cells + cmux->destroy_cell_queue.n;
}

/**
 * Query total number of circuits active on a circuitmux
 */

unsigned int
circuitmux_num_active_circuits(circuitmux_t *cmux)
{
  tor_assert(cmux);

  return cmux->n_active_circuits;
}

/**
 * Query total number of circuits attached to a circuitmux
 */

unsigned int
circuitmux_num_circuits(circuitmux_t *cmux)
{
  tor_assert(cmux);

  return cmux->n_circuits;
}

/*
 * Functions for circuit code to call to update circuit status
 */

/**
 * Attach a circuit to a circuitmux, for the specified direction.
 */

MOCK_IMPL(void,
circuitmux_attach_circuit,(circuitmux_t *cmux, circuit_t *circ,
                           cell_direction_t direction))
{
  channel_t *chan = NULL;
  uint64_t channel_id;
  circid_t circ_id;
  chanid_circid_muxinfo_t search, *hashent = NULL;
  unsigned int cell_count;

  tor_assert(cmux);
  tor_assert(circ);
  tor_assert(direction == CELL_DIRECTION_IN ||
             direction == CELL_DIRECTION_OUT);

  /*
   * Figure out which channel we're using, and get the circuit's current
   * cell count and circuit ID; assert that the circuit is not already
   * attached to another mux.
   */
  if (direction == CELL_DIRECTION_OUT) {
    /* It's n_chan */
    chan = circ->n_chan;
    cell_count = circ->n_chan_cells.n;
    circ_id = circ->n_circ_id;
  } else {
    /* We want p_chan */
    chan = TO_OR_CIRCUIT(circ)->p_chan;
    cell_count = TO_OR_CIRCUIT(circ)->p_chan_cells.n;
    circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  }
  /* Assert that we did get a channel */
  tor_assert(chan);
  /* Assert that the circuit ID is sensible */
  tor_assert(circ_id != 0);

  /* Get the channel ID */
  channel_id = chan->global_identifier;

  /* See if we already have this one */
  search.chan_id = channel_id;
  search.circ_id = circ_id;
  hashent = HT_FIND(chanid_circid_muxinfo_map, cmux->chanid_circid_map,
                    &search);

  if (hashent) {
    /*
     * This circuit was already attached to this cmux; make sure the
     * directions match and update the cell count and active circuit count.
     */
    log_info(LD_CIRC,
             "Circuit %u on channel %"PRIu64 " was already attached to "
             "(trying to attach to %p)",
             (unsigned)circ_id, (channel_id),
             cmux);

    /*
     * The mux pointer on this circuit and the direction in result should
     * match; otherwise assert.
     */
    tor_assert(hashent->muxinfo.direction == direction);

    /*
     * Looks okay; just update the cell count and active circuits if we must
     */
    if (hashent->muxinfo.cell_count > 0 && cell_count == 0) {
      --(cmux->n_active_circuits);
      circuitmux_make_circuit_inactive(cmux, circ);
    } else if (hashent->muxinfo.cell_count == 0 && cell_count > 0) {
      ++(cmux->n_active_circuits);
      circuitmux_make_circuit_active(cmux, circ);
    }
    cmux->n_cells -= hashent->muxinfo.cell_count;
    cmux->n_cells += cell_count;
    hashent->muxinfo.cell_count = cell_count;
  } else {
    /*
     * New circuit; add an entry and update the circuit/active circuit
     * counts.
     */
    log_debug(LD_CIRC,
             "Attaching circuit %u on channel %"PRIu64 " to cmux %p",
              (unsigned)circ_id, (channel_id), cmux);

    /* Insert it in the map */
    hashent = tor_malloc_zero(sizeof(*hashent));
    hashent->chan_id = channel_id;
    hashent->circ_id = circ_id;
    hashent->muxinfo.cell_count = cell_count;
    hashent->muxinfo.direction = direction;
    /* Allocate policy specific circuit data if we need it */
    if (cmux->policy->alloc_circ_data) {
      /* Assert that we have the means to free policy-specific data */
      tor_assert(cmux->policy->free_circ_data);
      /* Allocate it */
      hashent->muxinfo.policy_data =
        cmux->policy->alloc_circ_data(cmux,
                                      cmux->policy_data,
                                      circ,
                                      direction,
                                      cell_count);
      /* If we wanted policy data, it's an error  not to get any */
      tor_assert(hashent->muxinfo.policy_data);
    }
    HT_INSERT(chanid_circid_muxinfo_map, cmux->chanid_circid_map,
              hashent);

    /* Update counters */
    ++(cmux->n_circuits);
    if (cell_count > 0) {
      ++(cmux->n_active_circuits);
      circuitmux_make_circuit_active(cmux, circ);
    }
    cmux->n_cells += cell_count;
  }
}

/**
 * Detach a circuit from a circuitmux and update all counters as needed;
 * no-op if not attached.
 */

MOCK_IMPL(void,
circuitmux_detach_circuit,(circuitmux_t *cmux, circuit_t *circ))
{
  chanid_circid_muxinfo_t search, *hashent = NULL;
  /*
   * Use this to keep track of whether we found it for n_chan or
   * p_chan for consistency checking.
   *
   * The 0 initializer is not a valid cell_direction_t value.
   * We assert that it has been replaced with a valid value before it is used.
   */
  cell_direction_t last_searched_direction = 0;

  tor_assert(cmux);
  tor_assert(cmux->chanid_circid_map);
  tor_assert(circ);

  /* See if we have it for n_chan/n_circ_id */
  if (circ->n_chan) {
    search.chan_id = circ->n_chan->global_identifier;
    search.circ_id = circ->n_circ_id;
    hashent = HT_FIND(chanid_circid_muxinfo_map, cmux->chanid_circid_map,
                        &search);
    last_searched_direction = CELL_DIRECTION_OUT;
  }

  /* Got one? If not, see if it's an or_circuit_t and try p_chan/p_circ_id */
  if (!hashent) {
    if (circ->magic == OR_CIRCUIT_MAGIC) {
      search.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
      if (TO_OR_CIRCUIT(circ)->p_chan) {
        search.chan_id = TO_OR_CIRCUIT(circ)->p_chan->global_identifier;
        hashent = HT_FIND(chanid_circid_muxinfo_map,
                            cmux->chanid_circid_map,
                            &search);
        last_searched_direction = CELL_DIRECTION_IN;
      }
    }
  }

  tor_assert(last_searched_direction == CELL_DIRECTION_OUT
             || last_searched_direction == CELL_DIRECTION_IN);

  /*
   * If hashent isn't NULL, we have a circuit to detach; don't remove it from
   * the map until later of circuitmux_make_circuit_inactive() breaks.
   */
  if (hashent) {
    /* Update counters */
    --(cmux->n_circuits);
    if (hashent->muxinfo.cell_count > 0) {
      --(cmux->n_active_circuits);
      /* This does policy notifies, so comes before freeing policy data */
      circuitmux_make_circuit_inactive(cmux, circ);
    }
    cmux->n_cells -= hashent->muxinfo.cell_count;

    /* Free policy-specific data if we have it */
    if (hashent->muxinfo.policy_data) {
      /* If we have policy data, assert that we have the means to free it */
      tor_assert(cmux->policy);
      tor_assert(cmux->policy->free_circ_data);
      /* Call free_circ_data() */
      cmux->policy->free_circ_data(cmux,
                                   cmux->policy_data,
                                   circ,
                                   hashent->muxinfo.policy_data);
      hashent->muxinfo.policy_data = NULL;
    }

    /* Consistency check: the direction must match the direction searched */
    tor_assert(last_searched_direction == hashent->muxinfo.direction);

    /* Now remove it from the map */
    HT_REMOVE(chanid_circid_muxinfo_map, cmux->chanid_circid_map, hashent);

    /* Wipe and free the hash entry */
    // This isn't sensitive, but we want to be sure to know if we're accessing
    // this accidentally.
    memwipe(hashent, 0xef, sizeof(*hashent));
    tor_free(hashent);
  }
}

/**
 * Make a circuit active; update active list and policy-specific info, but
 * we don't mess with the counters or hash table here.
 */

static void
circuitmux_make_circuit_active(circuitmux_t *cmux, circuit_t *circ)
{
  tor_assert(cmux);
  tor_assert(cmux->policy);
  tor_assert(circ);

  /* Policy-specific notification */
  if (cmux->policy->notify_circ_active) {
    /* Okay, we need to check the circuit for policy data now */
    chanid_circid_muxinfo_t *hashent = circuitmux_find_map_entry(cmux, circ);
    /* We should have found something */
    tor_assert(hashent);
    /* Notify */
    cmux->policy->notify_circ_active(cmux, cmux->policy_data,
                                     circ, hashent->muxinfo.policy_data);
  }
}

/**
 * Make a circuit inactive; update active list and policy-specific info, but
 * we don't mess with the counters or hash table here.
 */

static void
circuitmux_make_circuit_inactive(circuitmux_t *cmux, circuit_t *circ)
{
  tor_assert(cmux);
  tor_assert(cmux->policy);
  tor_assert(circ);

  /* Policy-specific notification */
  if (cmux->policy->notify_circ_inactive) {
    /* Okay, we need to check the circuit for policy data now */
    chanid_circid_muxinfo_t *hashent = circuitmux_find_map_entry(cmux, circ);
    /* We should have found something */
    tor_assert(hashent);
    /* Notify */
    cmux->policy->notify_circ_inactive(cmux, cmux->policy_data,
                                       circ, hashent->muxinfo.policy_data);
  }
}

/**
 * Clear the cell counter for a circuit on a circuitmux
 */

void
circuitmux_clear_num_cells(circuitmux_t *cmux, circuit_t *circ)
{
  /* This is the same as setting the cell count to zero */
  circuitmux_set_num_cells(cmux, circ, 0);
}

/**
 * Set the cell counter for a circuit on a circuitmux
 */

void
circuitmux_set_num_cells(circuitmux_t *cmux, circuit_t *circ,
                         unsigned int n_cells)
{
  chanid_circid_muxinfo_t *hashent = NULL;

  tor_assert(cmux);
  tor_assert(circ);

  /* Search for this circuit's entry */
  hashent = circuitmux_find_map_entry(cmux, circ);
  /* Assert that we found one */
  tor_assert(hashent);

  /* Update cmux cell counter */
  cmux->n_cells -= hashent->muxinfo.cell_count;
  cmux->n_cells += n_cells;

  /* Do we need to notify a cmux policy? */
  if (cmux->policy->notify_set_n_cells) {
    /* Call notify_set_n_cells */
    cmux->policy->notify_set_n_cells(cmux,
                                     cmux->policy_data,
                                     circ,
                                     hashent->muxinfo.policy_data,
                                     n_cells);
  }

  /*
   * Update cmux active circuit counter: is the old cell count > 0 and the
   * new cell count == 0 ?
   */
  if (hashent->muxinfo.cell_count > 0 && n_cells == 0) {
    --(cmux->n_active_circuits);
    hashent->muxinfo.cell_count = n_cells;
    circuitmux_make_circuit_inactive(cmux, circ);
  /* Is the old cell count == 0 and the new cell count > 0 ? */
  } else if (hashent->muxinfo.cell_count == 0 && n_cells > 0) {
    ++(cmux->n_active_circuits);
    hashent->muxinfo.cell_count = n_cells;
    circuitmux_make_circuit_active(cmux, circ);
  } else {
    hashent->muxinfo.cell_count = n_cells;
  }
}

/*
 * Functions for channel code to call to get a circuit to transmit from or
 * notify that cells have been transmitted.
 */

/**
 * Pick a circuit to send from, using the active circuits list or a
 * circuitmux policy if one is available.  This is called from channel.c.
 *
 * If we would rather send a destroy cell, return NULL and set
 * *destroy_queue_out to the destroy queue.
 *
 * If we have nothing to send, set *destroy_queue_out to NULL and
 * return NULL.
 */

circuit_t *
circuitmux_get_first_active_circuit(circuitmux_t *cmux,
                                    destroy_cell_queue_t **destroy_queue_out)
{
  circuit_t *circ = NULL;

  tor_assert(cmux);
  tor_assert(cmux->policy);
  /* This callback is mandatory. */
  tor_assert(cmux->policy->pick_active_circuit);
  tor_assert(destroy_queue_out);

  *destroy_queue_out = NULL;

  if (cmux->destroy_cell_queue.n &&
        (!cmux->last_cell_was_destroy || cmux->n_active_circuits == 0)) {
    /* We have destroy cells to send, and either we just sent a relay cell,
     * or we have no relay cells to send. */

    /* XXXX We should let the cmux policy have some say in this eventually. */
    /* XXXX Alternating is not a terribly brilliant approach here. */
    *destroy_queue_out = &cmux->destroy_cell_queue;

    cmux->last_cell_was_destroy = 1;
  } else if (cmux->n_active_circuits > 0) {
    /* We also must have a cell available for this to be the case */
    tor_assert(cmux->n_cells > 0);
    /* Do we have a policy-provided circuit selector? */
    circ = cmux->policy->pick_active_circuit(cmux, cmux->policy_data);
    cmux->last_cell_was_destroy = 0;
  } else {
    tor_assert(cmux->n_cells == 0);
    tor_assert(cmux->destroy_cell_queue.n == 0);
  }

  return circ;
}

/**
 * Notify the circuitmux that cells have been sent on a circuit; this
 * is called from channel.c.
 */

void
circuitmux_notify_xmit_cells(circuitmux_t *cmux, circuit_t *circ,
                             unsigned int n_cells)
{
  chanid_circid_muxinfo_t *hashent = NULL;
  int becomes_inactive = 0;

  tor_assert(cmux);
  tor_assert(circ);

  if (n_cells == 0) return;

  /*
   * To handle this, we have to:
   *
   * 1.) Adjust the circuit's cell counter in the cmux hash table
   * 2.) Move the circuit to the tail of the active_circuits linked list
   *     for this cmux, or make the circuit inactive if the cell count
   *     went to zero.
   * 3.) Call cmux->policy->notify_xmit_cells(), if any
   */

  /* Find the hash entry */
  hashent = circuitmux_find_map_entry(cmux, circ);
  /* Assert that we found one */
  tor_assert(hashent);

  /* Adjust the cell counter and assert that we had that many cells to send */
  tor_assert(n_cells <= hashent->muxinfo.cell_count);
  hashent->muxinfo.cell_count -= n_cells;
  /* Do we need to make the circuit inactive? */
  if (hashent->muxinfo.cell_count == 0) becomes_inactive = 1;
  /* Adjust the mux cell counter */
  cmux->n_cells -= n_cells;

  /*
   * We call notify_xmit_cells() before making the circuit inactive if needed,
   * so the policy can always count on this coming in on an active circuit.
   */
  if (cmux->policy->notify_xmit_cells) {
    cmux->policy->notify_xmit_cells(cmux, cmux->policy_data, circ,
                                    hashent->muxinfo.policy_data,
                                    n_cells);
  }

  /*
   * Now make the circuit inactive if needed; this will call the policy's
   * notify_circ_inactive() if present.
   */
  if (becomes_inactive) {
    --(cmux->n_active_circuits);
    circuitmux_make_circuit_inactive(cmux, circ);
  }
}

/**
 * Notify the circuitmux that a destroy was sent, so we can update
 * the counter.
 */

void
circuitmux_notify_xmit_destroy(circuitmux_t *cmux)
{
  tor_assert(cmux);

  --(cmux->destroy_ctr);
  --(global_destroy_ctr);
  log_debug(LD_CIRC,
            "Cmux at %p sent a destroy, cmux counter is now %"PRId64", "
            "global counter is now %"PRId64,
            cmux,
            (cmux->destroy_ctr),
            (global_destroy_ctr));
}

/*DOCDOC */
void
circuitmux_append_destroy_cell(channel_t *chan,
                               circuitmux_t *cmux,
                               circid_t circ_id,
                               uint8_t reason)
{
  destroy_cell_queue_append(&cmux->destroy_cell_queue, circ_id, reason);

  /* Destroy entering the queue, update counters */
  ++(cmux->destroy_ctr);
  ++global_destroy_ctr;
  log_debug(LD_CIRC,
            "Cmux at %p queued a destroy for circ %u, cmux counter is now "
            "%"PRId64", global counter is now %"PRId64,
            cmux, circ_id,
            (cmux->destroy_ctr),
            (global_destroy_ctr));

  /* XXXX Duplicate code from append_cell_to_circuit_queue */
  if (!channel_has_queued_writes(chan)) {
    /* There is no data at all waiting to be sent on the outbuf.  Add a
     * cell, so that we can notice when it gets flushed, flushed_some can
     * get called, and we can start putting more data onto the buffer then.
     */
    log_debug(LD_GENERAL, "Primed a buffer.");
    channel_flush_from_first_active_circuit(chan, 1);
  }
}

/*DOCDOC; for debugging 12184.  This runs slowly. */
int64_t
circuitmux_count_queued_destroy_cells(const channel_t *chan,
                                      const circuitmux_t *cmux)
{
  int64_t n_destroy_cells = cmux->destroy_ctr;
  int64_t destroy_queue_size = cmux->destroy_cell_queue.n;

  int64_t manual_total = 0;
  int64_t manual_total_in_map = 0;
  destroy_cell_t *cell;

  TOR_SIMPLEQ_FOREACH(cell, &cmux->destroy_cell_queue.head, next) {
    circid_t id;
    ++manual_total;

    id = cell->circid;
    if (circuit_id_in_use_on_channel(id, (channel_t*)chan))
      ++manual_total_in_map;
  }

  if (n_destroy_cells != destroy_queue_size ||
      n_destroy_cells != manual_total ||
      n_destroy_cells != manual_total_in_map) {
    log_warn(LD_BUG, "  Discrepancy in counts for queued destroy cells on "
             "circuitmux. n=%"PRId64". queue_size=%"PRId64". "
             "manual_total=%"PRId64". manual_total_in_map=%"PRId64".",
             (n_destroy_cells),
             (destroy_queue_size),
             (manual_total),
             (manual_total_in_map));
  }

  return n_destroy_cells;
}

/**
 * Compare cmuxes to see which is more preferred; return < 0 if
 * cmux_1 has higher priority (i.e., cmux_1 < cmux_2 in the scheduler's
 * sort order), > 0 if cmux_2 has higher priority, or 0 if they are
 * equally preferred.
 *
 * If the cmuxes have different cmux policies or the policy does not
 * support the cmp_cmux method, return 0.
 */

MOCK_IMPL(int,
circuitmux_compare_muxes, (circuitmux_t *cmux_1, circuitmux_t *cmux_2))
{
  const circuitmux_policy_t *policy;

  tor_assert(cmux_1);
  tor_assert(cmux_2);

  if (cmux_1 == cmux_2) {
    /* Equivalent because they're the same cmux */
    return 0;
  }

  if (cmux_1->policy && cmux_2->policy) {
    if (cmux_1->policy == cmux_2->policy) {
      policy = cmux_1->policy;

      if (policy->cmp_cmux) {
        /* Okay, we can compare! */
        return policy->cmp_cmux(cmux_1, cmux_1->policy_data,
                                cmux_2, cmux_2->policy_data);
      } else {
        /*
         * Equivalent because the policy doesn't know how to compare between
         * muxes.
         */
        return 0;
      }
    } else {
      /* Equivalent because they have different policies */
      return 0;
    }
  } else {
    /* Equivalent because one or both are missing a policy */
    return 0;
  }
}