text:
"""Tests for TransformedDistribution."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
from scipy import stats

from tensorflow.contrib import distributions
from tensorflow.contrib import linalg
from tensorflow.contrib.distributions.python.ops import bijectors
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test

bs = bijectors
ds = distributions
la = linalg

class DummyMatrixTransform(bs.Bijector):
  """Tractable matrix transformation.

  This is a non-sensical bijector that has forward/inverse_min_event_ndims=2.
  The main use is to check that transformed distribution calculations are done
  appropriately.
  """

  def __init__(self):
    super(DummyMatrixTransform, self).__init__(
        forward_min_event_ndims=2,
        is_constant_jacobian=False,
        validate_args=False,
        name="dummy")

  def _forward(self, x):
    return x

  def _inverse(self, y):
    return y

  # Note: These jacobians don't make sense.
  def _forward_log_det_jacobian(self, x):
    return -linalg_ops.matrix_determinant(x)

  def _inverse_log_det_jacobian(self, x):
    return linalg_ops.matrix_determinant(x)

class TransformedDistributionTest(test.TestCase):

  def _cls(self):
    return ds.TransformedDistribution

  def _make_unimplemented(self, name):
    def _unimplemented(self, *args):  # pylint: disable=unused-argument
      raise NotImplementedError("{} not implemented".format(name))
    return _unimplemented

  def testTransformedDistribution(self):
    g = ops.Graph()
    with g.as_default():
      mu = 3.0
      sigma = 2.0
      # Note: the Jacobian callable only works for this example; more generally
      # you may or may not need a reduce_sum.
      log_normal = self._cls()(
          distribution=ds.Normal(loc=mu, scale=sigma),
          bijector=bs.Exp())
      sp_dist = stats.lognorm(s=sigma, scale=np.exp(mu))

      # sample
      sample = log_normal.sample(100000, seed=235)
      self.assertAllEqual([], log_normal.event_shape)
      with self.test_session(graph=g):
        self.assertAllEqual([], log_normal.event_shape_tensor().eval())
        self.assertAllClose(
            sp_dist.mean(), np.mean(sample.eval()), atol=0.0, rtol=0.05)

      # pdf, log_pdf, cdf, etc...
      # The mean of the lognormal is around 148.
      test_vals = np.linspace(0.1, 1000., num=20).astype(np.float32)
      for func in [[log_normal.log_prob, sp_dist.logpdf],
                   [log_normal.prob, sp_dist.pdf],
                   [log_normal.log_cdf, sp_dist.logcdf],
                   [log_normal.cdf, sp_dist.cdf],
                   [log_normal.survival_function, sp_dist.sf],
                   [log_normal.log_survival_function, sp_dist.logsf]]:
        actual = func[0](test_vals)
        expected = func[1](test_vals)
        with self.test_session(graph=g):
          self.assertAllClose(expected, actual.eval(), atol=0, rtol=0.01)

  def testNonInjectiveTransformedDistribution(self):
    g = ops.Graph()
    with g.as_default():
      mu = 1.
      sigma = 2.0
      abs_normal = self._cls()(
          distribution=ds.Normal(loc=mu, scale=sigma),
          bijector=bs.AbsoluteValue())
      sp_normal = stats.norm(mu, sigma)

      # sample
      sample = abs_normal.sample(100000, seed=235)
      self.assertAllEqual([], abs_normal.event_shape)
      with self.test_session(graph=g):
        sample_ = sample.eval()
        self.assertAllEqual([], abs_normal.event_shape_tensor().eval())

        # Abs > 0, duh!
        np.testing.assert_array_less(0, sample_)

        # Let X ~ Normal(mu, sigma), Y := |X|, then
        # P[Y < 0.77] = P[-0.77 < X < 0.77]
        self.assertAllClose(
            sp_normal.cdf(0.77) - sp_normal.cdf(-0.77),
            (sample_ < 0.77).mean(), rtol=0.01)

        # p_Y(y) = p_X(-y) + p_X(y),
        self.assertAllClose(
            sp_normal.pdf(1.13) + sp_normal.pdf(-1.13),
            abs_normal.prob(1.13).eval())

        # Log[p_Y(y)] = Log[p_X(-y) + p_X(y)]
        self.assertAllClose(
            np.log(sp_normal.pdf(2.13) + sp_normal.pdf(-2.13)),
            abs_normal.log_prob(2.13).eval())

  def testQuantile(self):
    with self.test_session() as sess:
      logit_normal = self._cls()(
          distribution=ds.Normal(loc=0., scale=1.),
          bijector=bs.Sigmoid(),
          validate_args=True)
      grid = [0., 0.25, 0.5, 0.75, 1.]
      q = logit_normal.quantile(grid)
      cdf = logit_normal.cdf(q)
      cdf_ = sess.run(cdf)
      self.assertAllClose(grid, cdf_, rtol=1e-6, atol=0.)

  def testCachedSamples(self):
    exp_forward_only = bs.Exp()
    exp_forward_only._inverse = self._make_unimplemented(
        "inverse")
    exp_forward_only._inverse_event_shape_tensor = self._make_unimplemented(
        "inverse_event_shape_tensor ")
    exp_forward_only._inverse_event_shape = self._make_unimplemented(
        "inverse_event_shape ")
    exp_forward_only._inverse_log_det_jacobian = self._make_unimplemented(
        "inverse_log_det_jacobian ")

    with self.test_session() as sess:
      mu = 3.0
      sigma = 0.02
      log_normal = self._cls()(
          distribution=ds.Normal(loc=mu, scale=sigma),
          bijector=exp_forward_only)

      sample = log_normal.sample([2, 3], seed=42)
      sample_val, log_pdf_val = sess.run([sample, log_normal.log_prob(sample)])
      expected_log_pdf = stats.lognorm.logpdf(
          sample_val, s=sigma, scale=np.exp(mu))
      self.assertAllClose(expected_log_pdf, log_pdf_val, rtol=1e-4, atol=0.)

  def testCachedSamplesInvert(self):
    exp_inverse_only = bs.Exp()
    exp_inverse_only._forward = self._make_unimplemented(
        "forward")
    exp_inverse_only._forward_event_shape_tensor = self._make_unimplemented(
        "forward_event_shape_tensor ")
    exp_inverse_only._forward_event_shape = self._make_unimplemented(
        "forward_event_shape ")
    exp_inverse_only._forward_log_det_jacobian = self._make_unimplemented(
        "forward_log_det_jacobian ")

    log_forward_only = bs.Invert(exp_inverse_only)

    with self.test_session() as sess:
      # The log bijector isn't defined over the whole real line, so we make
      # sigma sufficiently small so that the draws are positive.
      mu = 2.
      sigma = 1e-2
      exp_normal = self._cls()(
          distribution=ds.Normal(loc=mu, scale=sigma),
          bijector=log_forward_only)

      sample = exp_normal.sample([2, 3], seed=42)
      sample_val, log_pdf_val = sess.run([sample, exp_normal.log_prob(sample)])
      expected_log_pdf = sample_val + stats.norm.logpdf(
          np.exp(sample_val), loc=mu, scale=sigma)
      self.assertAllClose(expected_log_pdf, log_pdf_val, atol=0.)

  def testShapeChangingBijector(self):
    with self.test_session():
      softmax = bs.SoftmaxCentered()
      standard_normal = ds.Normal(loc=0., scale=1.)
      multi_logit_normal = self._cls()(
          distribution=standard_normal,
          bijector=softmax,
          event_shape=[1])
      x = [[[-np.log(3.)], [0.]],
           [[np.log(3)], [np.log(5)]]]
      y = softmax.forward(x).eval()
      expected_log_pdf = (
          np.squeeze(stats.norm(loc=0., scale=1.).logpdf(x)) -
          np.sum(np.log(y), axis=-1))
      self.assertAllClose(expected_log_pdf,
                          multi_logit_normal.log_prob(y).eval())
      self.assertAllClose(
          [1, 2, 3, 2],
          array_ops.shape(multi_logit_normal.sample([1, 2, 3])).eval())
      self.assertAllEqual([2], multi_logit_normal.event_shape)
      self.assertAllEqual([2], multi_logit_normal.event_shape_tensor().eval())

  def testCastLogDetJacobian(self):
    """Test log_prob when Jacobian and log_prob dtypes do not match."""

    with self.test_session():
      # Create an identity bijector whose jacobians have dtype int32
      int_identity = bs.Inline(
          forward_fn=array_ops.identity,
          inverse_fn=array_ops.identity,
          inverse_log_det_jacobian_fn=(
              lambda y: math_ops.cast(0, dtypes.int32)),
          forward_log_det_jacobian_fn=(
              lambda x: math_ops.cast(0, dtypes.int32)),
          forward_min_event_ndims=0,
          is_constant_jacobian=True)
      normal = self._cls()(
          distribution=ds.Normal(loc=0., scale=1.),
          bijector=int_identity,
          validate_args=True)

      y = normal.sample()
      normal.log_prob(y).eval()
      normal.prob(y).eval()
      normal.entropy().eval()

  def testEntropy(self):
    with self.test_session():
      shift = np.array([[-1, 0, 1], [-1, -2, -3]], dtype=np.float32)
      diag = np.array([[1, 2, 3], [2, 3, 2]], dtype=np.float32)
      actual_mvn_entropy = np.concatenate([
          [stats.multivariate_normal(shift[i], np.diag(diag[i]**2)).entropy()]
          for i in range(len(diag))])
      fake_mvn = self._cls()(
          ds.MultivariateNormalDiag(
              loc=array_ops.zeros_like(shift),
              scale_diag=array_ops.ones_like(diag),
              validate_args=True),
          bs.AffineLinearOperator(
              shift,
              scale=la.LinearOperatorDiag(diag, is_non_singular=True),
              validate_args=True),
          validate_args=True)
      self.assertAllClose(actual_mvn_entropy,
                          fake_mvn.entropy().eval())

  def testScalarBatchScalarEventIdentityScale(self):
    with self.test_session() as sess:
      exp2 = self._cls()(
          ds.Exponential(rate=0.25),
          bijector=ds.bijectors.AffineScalar(scale=2.)
      )
      log_prob = exp2.log_prob(1.)
      log_prob_ = sess.run(log_prob)
      base_log_prob = -0.5 * 0.25 + np.log(0.25)
      ildj = np.log(2.)
      self.assertAllClose(base_log_prob - ildj, log_prob_, rtol=1e-6, atol=0.)

class ScalarToMultiTest(test.TestCase):

  def _cls(self):
    return ds.TransformedDistribution

  def setUp(self):
    self._shift = np.array([-1, 0, 1], dtype=np.float32)
    self._tril = np.array([[[1., 0, 0],
                            [2, 1, 0],
                            [3, 2, 1]],
                           [[2, 0, 0],
                            [3, 2, 0],
                            [4, 3, 2]]],
                          dtype=np.float32)

  def _testMVN(self,
               base_distribution_class,
               base_distribution_kwargs,
               batch_shape=(),
               event_shape=(),
               not_implemented_message=None):
    with self.test_session() as sess:
      # Overriding shapes must be compatible w/bijector; most bijectors are
      # batch_shape agnostic and only care about event_ndims.
      # In the case of `Affine`, if we got it wrong then it would fire an
      # exception due to incompatible dimensions.
      batch_shape_pl = array_ops.placeholder(
          dtypes.int32, name="dynamic_batch_shape")
      event_shape_pl = array_ops.placeholder(
          dtypes.int32, name="dynamic_event_shape")
      feed_dict = {batch_shape_pl: np.array(batch_shape, dtype=np.int32),
                   event_shape_pl: np.array(event_shape, dtype=np.int32)}
      fake_mvn_dynamic = self._cls()(
          distribution=base_distribution_class(validate_args=True,
                                               **base_distribution_kwargs),
          bijector=bs.Affine(shift=self._shift, scale_tril=self._tril),
          batch_shape=batch_shape_pl,
          event_shape=event_shape_pl,
          validate_args=True)

      fake_mvn_static = self._cls()(
          distribution=base_distribution_class(validate_args=True,
                                               **base_distribution_kwargs),
          bijector=bs.Affine(shift=self._shift, scale_tril=self._tril),
          batch_shape=batch_shape,
          event_shape=event_shape,
          validate_args=True)

      actual_mean = np.tile(self._shift, [2, 1])  # Affine elided this tile.
      actual_cov = np.matmul(self._tril, np.transpose(self._tril, [0, 2, 1]))

      def actual_mvn_log_prob(x):
        return np.concatenate([
            [stats.multivariate_normal(
                actual_mean[i], actual_cov[i]).logpdf(x[:, i, :])]
            for i in range(len(actual_cov))]).T

      actual_mvn_entropy = np.concatenate([
          [stats.multivariate_normal(
              actual_mean[i], actual_cov[i]).entropy()]
          for i in range(len(actual_cov))])

      self.assertAllEqual([3], fake_mvn_static.event_shape)
      self.assertAllEqual([2], fake_mvn_static.batch_shape)

      self.assertAllEqual(tensor_shape.TensorShape(None),
                          fake_mvn_dynamic.event_shape)
      self.assertAllEqual(tensor_shape.TensorShape(None),
                          fake_mvn_dynamic.batch_shape)

      x = fake_mvn_static.sample(5, seed=0).eval()
      for unsupported_fn in (fake_mvn_static.log_cdf,
                             fake_mvn_static.cdf,
                             fake_mvn_static.survival_function,
                             fake_mvn_static.log_survival_function):
        with self.assertRaisesRegexp(NotImplementedError,
                                     not_implemented_message):
          unsupported_fn(x)

      num_samples = 5e3
      for fake_mvn, feed_dict in ((fake_mvn_static, {}),
                                  (fake_mvn_dynamic, feed_dict)):
        # Ensure sample works by checking first, second moments.
        y = fake_mvn.sample(int(num_samples), seed=0)
        x = y[0:5, ...]
        sample_mean = math_ops.reduce_mean(y, 0)
        centered_y = array_ops.transpose(y - sample_mean, [1, 2, 0])
        sample_cov = math_ops.matmul(
            centered_y, centered_y, transpose_b=True) / num_samples
        [
            sample_mean_,
            sample_cov_,
            x_,
            fake_event_shape_,
            fake_batch_shape_,
            fake_log_prob_,
            fake_prob_,
            fake_entropy_,
        ] = sess.run([
            sample_mean,
            sample_cov,
            x,
            fake_mvn.event_shape_tensor(),
            fake_mvn.batch_shape_tensor(),
            fake_mvn.log_prob(x),
            fake_mvn.prob(x),
            fake_mvn.entropy(),
        ], feed_dict=feed_dict)

        self.assertAllClose(actual_mean, sample_mean_, atol=0.1, rtol=0.1)
        self.assertAllClose(actual_cov, sample_cov_, atol=0., rtol=0.1)

        # Ensure all other functions work as intended.
        self.assertAllEqual([5, 2, 3], x_.shape)
        self.assertAllEqual([3], fake_event_shape_)
        self.assertAllEqual([2], fake_batch_shape_)
        self.assertAllClose(actual_mvn_log_prob(x_), fake_log_prob_,
                            atol=0., rtol=1e-6)
        self.assertAllClose(np.exp(actual_mvn_log_prob(x_)), fake_prob_,
                            atol=0., rtol=1e-5)
        self.assertAllClose(actual_mvn_entropy, fake_entropy_,
                            atol=0., rtol=1e-6)

  def testScalarBatchScalarEvent(self):
    self._testMVN(
        base_distribution_class=ds.Normal,
        base_distribution_kwargs={"loc": 0., "scale": 1.},
        batch_shape=[2],
        event_shape=[3],
        not_implemented_message="not implemented when overriding event_shape")

  def testScalarBatchNonScalarEvent(self):
    self._testMVN(
        base_distribution_class=ds.MultivariateNormalDiag,
        base_distribution_kwargs={"loc": [0., 0., 0.],
                                  "scale_diag": [1., 1, 1]},
        batch_shape=[2],
        not_implemented_message="not implemented")

    with self.test_session():
      # Can't override event_shape for scalar batch, non-scalar event.
      with self.assertRaisesRegexp(ValueError, "base distribution not scalar"):
        self._cls()(
            distribution=ds.MultivariateNormalDiag(loc=[0.], scale_diag=[1.]),
            bijector=bs.Affine(shift=self._shift, scale_tril=self._tril),
            batch_shape=[2],
            event_shape=[3],
            validate_args=True)

  def testNonScalarBatchScalarEvent(self):
    self._testMVN(
        base_distribution_class=ds.Normal,
        base_distribution_kwargs={"loc": [0., 0], "scale": [1., 1]},
        event_shape=[3],
        not_implemented_message="not implemented when overriding event_shape")

    with self.test_session():
      # Can't override batch_shape for non-scalar batch, scalar event.
      with self.assertRaisesRegexp(ValueError, "base distribution not scalar"):
        self._cls()(
            distribution=ds.Normal(loc=[0.], scale=[1.]),
            bijector=bs.Affine(shift=self._shift, scale_tril=self._tril),
            batch_shape=[2],
            event_shape=[3],
            validate_args=True)

  def testNonScalarBatchNonScalarEvent(self):
    with self.test_session():
      # Can't override event_shape and/or batch_shape for non_scalar batch,
      # non-scalar event.
      with self.assertRaisesRegexp(ValueError, "base distribution not scalar"):
        self._cls()(
            distribution=ds.MultivariateNormalDiag(loc=[[0.]],
                                                   scale_diag=[[1.]]),
            bijector=bs.Affine(shift=self._shift, scale_tril=self._tril),
            batch_shape=[2],
            event_shape=[3],
            validate_args=True)

  def testMatrixEvent(self):
    with self.test_session() as sess:
      batch_shape = [2]
      event_shape = [2, 3, 3]
      batch_shape_pl = array_ops.placeholder(
          dtypes.int32, name="dynamic_batch_shape")
      event_shape_pl = array_ops.placeholder(
          dtypes.int32, name="dynamic_event_shape")
      feed_dict = {batch_shape_pl: np.array(batch_shape, dtype=np.int32),
                   event_shape_pl: np.array(event_shape, dtype=np.int32)}

      scale = 2.
      loc = 0.
      fake_mvn_dynamic = self._cls()(
          distribution=ds.Normal(
              loc=loc,
              scale=scale),
          bijector=DummyMatrixTransform(),
          batch_shape=batch_shape_pl,
          event_shape=event_shape_pl,
          validate_args=True)

      fake_mvn_static = self._cls()(
          distribution=ds.Normal(
              loc=loc,
              scale=scale),
          bijector=DummyMatrixTransform(),
          batch_shape=batch_shape,
          event_shape=event_shape,
          validate_args=True)

      def actual_mvn_log_prob(x):
        # This distribution is the normal PDF, reduced over the
        # last 3 dimensions + a jacobian term which corresponds
        # to the determinant of x.
        return (np.sum(
            stats.norm(loc, scale).logpdf(x), axis=(-1, -2, -3)) +
                np.sum(np.linalg.det(x), axis=-1))

      self.assertAllEqual([2, 3, 3], fake_mvn_static.event_shape)
      self.assertAllEqual([2], fake_mvn_static.batch_shape)

      self.assertAllEqual(tensor_shape.TensorShape(None),
                          fake_mvn_dynamic.event_shape)
      self.assertAllEqual(tensor_shape.TensorShape(None),
                          fake_mvn_dynamic.batch_shape)

      num_samples = 5e3
      for fake_mvn, feed_dict in ((fake_mvn_static, {}),
                                  (fake_mvn_dynamic, feed_dict)):
        # Ensure sample works by checking first, second moments.
        y = fake_mvn.sample(int(num_samples), seed=0)
        x = y[0:5, ...]
        [
            x_,
            fake_event_shape_,
            fake_batch_shape_,
            fake_log_prob_,
            fake_prob_,
        ] = sess.run([
            x,
            fake_mvn.event_shape_tensor(),
            fake_mvn.batch_shape_tensor(),
            fake_mvn.log_prob(x),
            fake_mvn.prob(x),
        ], feed_dict=feed_dict)

        # Ensure all other functions work as intended.
        self.assertAllEqual([5, 2, 2, 3, 3], x_.shape)
        self.assertAllEqual([2, 3, 3], fake_event_shape_)
        self.assertAllEqual([2], fake_batch_shape_)
        self.assertAllClose(actual_mvn_log_prob(x_), fake_log_prob_,
                            atol=0., rtol=1e-6)
        self.assertAllClose(np.exp(actual_mvn_log_prob(x_)), fake_prob_,
                            atol=0., rtol=1e-5)

if __name__ == "__main__":
  test.main()


text:
package org.apache.flink.graph.drivers.input;

import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.drivers.parameter.LongParameter;
import org.apache.flink.types.LongValue;
import org.apache.flink.types.NullValue;

import static org.apache.flink.graph.generator.HypercubeGraph.MINIMUM_DIMENSIONS;

/** Generate a {@link org.apache.flink.graph.generator.HypercubeGraph}. */
public class HypercubeGraph extends GeneratedGraph {

    private LongParameter dimensions =
            new LongParameter(this, "dimensions")
                    .setMinimumValue(MINIMUM_DIMENSIONS)
                    .setMaximumValue(63);

    @Override
    public String getIdentity() {
        return getName() + " (" + dimensions + ")";
    }

    @Override
    protected long vertexCount() {
        return 1L << dimensions.getValue();
    }

    @Override
    public Graph<LongValue, NullValue, NullValue> create(ExecutionEnvironment env) {
        return new org.apache.flink.graph.generator.HypercubeGraph(env, dimensions.getValue())
                .setParallelism(parallelism.getValue().intValue())
                .generate();
    }
}

redpajama_set_name: RedPajamaGithub


text:
//******************************************************************************************************
//  CBReportEventTable.cs - Gbtc
//
//  Copyright © 2020, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
//  not use this file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  08/14/2020 - C. Lackner
//       Generated original version of source code.
//
//******************************************************************************************************

using System;
using System.ComponentModel.DataAnnotations;
using System.Data;
using GSF.Data;
using GSF.Data.Model;

namespace openXDA.Model
{
    public class CBReportEventTable
    {
        [PrimaryKey(true)]
        public int ID { get; set; }

        public int CapBankID { get; set; }

        public int EventID { get; set; }

        [StringLength(200)]
        public string Phase { get; set; }

        [StringLength(500)]
        public string Status { get; set; }

        public int? DataErrorID { get; set; }

        [StringLength(500)]
        public string Operation { get; set; }

        public double? DeltaQ { get; set; }

        public double? MVAsc { get; set; }

        public bool? IsRes { get; set; }

        [FieldDataType(DbType.DateTime2, DatabaseType.SQLServer)]
        public DateTime Time { get; set; }

    }
}


text:
/*** patch en attendant le multiligual ***/
.english {
display:none;
}

#ricontent ul li.english {
display:none;
}


text:
package cmd

import (
	"fmt"

	"strings"

	"errors"

	"github.com/lexty/yandex-dns-cli-manager/api"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// addCmd represents the add command
var addCmd = &cobra.Command{
	Use:   "add",
	Short: "Add a new DNS record",
	Run: func(cmd *cobra.Command, args []string) {
		resp, err := api.AddRecord(&rec, viper.GetString("domain"), viper.GetString("admin-token"))

		if err != nil {
			throwError(err)
		}

		switch viper.GetString("format") {
		case formatJson:
			fmt.Print(resp.Json)
		case formatList:
			setProps()
			fmt.Print("Record successfully created\n\n")
			printList(filterRecords([]api.Record{resp.Record}, []string{"*"}), strings.Join([]string{propId, propType, propContent, propSubdomain, propPriority, propTTL, propFQDN}, ","))
		default:
			throwError(errors.New(fmt.Sprintf(`Unknown output format "%s".`, viper.GetString("format"))))
		}
	},
}

func init() {
	RootCmd.AddCommand(addCmd)

	addCmd.Flags().StringP("format", "f", "", fmt.Sprintf("format output (%s|%s)", formatList, formatJson))
	viper.BindPFlag("format", addCmd.Flags().Lookup("format"))
	viper.SetDefault("format", formatList)

	addCmd.Flags().StringVarP(&rec.RecordType, "type", "t", "", fmt.Sprintf("type of record (available: %s)", strings.Join([]string{typeA, typeAAAA, typeCNAME, typeSRV, typeTXT, typeSOA, typeMX, typeNS}, ", ")))
	addCmd.Flags().StringVarP(&rec.AdminMail, "admin-mail", "m", "", "email-address of the domain's administrator")
	addCmd.Flags().StringVarP(&rec.Content, "content", "c", "", "content of the DNS record")
	//addCmd.Flags().StringVarP(rec.Priority.(*string), "priority", "p", "", "priority of the DNS record")
	addCmd.Flags().IntVarP(&rec.Weight, "weight", "w", 0, "weight of the SRV-record relative to other SRV-records for the same domain with the same priority")
	addCmd.Flags().IntVarP(&rec.Port, "port", "P", 0, "TCP or UDP port of the host that is hosting the service")
	addCmd.Flags().StringVarP(&rec.Target, "target", "T", "", "the canonical name of the host providing the service")
	addCmd.Flags().StringVarP(&rec.Subdomain, "subdomain", "s", "", "Name of the subdomain")
	addCmd.Flags().IntVarP(&rec.TTL, "ttl", "l", 0, "the lifetime of the DNS record in seconds")
}


text:
/**
 * \file
 * \brief Basic/raw interface for serial driver.
 */

/*
 * Copyright (c) 2007, 2008, 2012 ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, CAB F.78, Universitaetstrasse 6, CH-8092 Zurich,
 * Attn: Systems Group.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <barrelfish/barrelfish.h>
#include <barrelfish/nameservice_client.h>
#include <if/serial_defs.h>

#include "serial.h"
#include "serial_debug.h"

#define SERVICE_SUFFIX "raw"

struct bs_state {
    struct serial_common *serial;
    struct term_server *server;

    /// input buffers, double-buffered for safety with async IDC sends
    struct serial_buffer inbuf[2];
    int ninbuf;

    /// current consumer of input
    struct serial_binding *terminal;
};

static void tx_handler(void *arg)
{
    struct bs_state * bs = arg;
    struct serial_binding *b = bs->terminal;
    errval_t err;

    // free previously-sent buffer, if there is one
    if (bs->inbuf[!bs->ninbuf].buf != NULL) {
        free(bs->inbuf[!bs->ninbuf].buf);
        bs->inbuf[!bs->ninbuf].buf = NULL;
    }

    // do we have something to send? if not, bail out
    if (bs->inbuf[bs->ninbuf].buf == NULL) {
        return;
    }

    // try to send
    err = b->tx_vtbl.input(b, MKCONT(tx_handler,b), bs->inbuf[bs->ninbuf].buf,
                           bs->inbuf[bs->ninbuf].len);
    if (err_is_ok(err)) {
        // swing buffer pointer
        bs->ninbuf = !bs->ninbuf;
        assert(bs->inbuf[bs->ninbuf].buf == NULL);
    } else if (err_is_fail(err)) {
        DEBUG_ERR(err, "error sending serial input to terminal");
    }
}

static void basic_serial_input(void *st, char *data, size_t length)
{
    struct bs_state *bs = st;
    struct serial_buffer *in = &bs->inbuf[bs->ninbuf];

    if (in->buf == NULL) { // allocate a buffer
        in->buf = malloc(length);
        assert(in->buf != NULL);
        memcpy(in->buf, data, length);
        in->len = length;
    } else { // append new data to existing buffer
        in->buf = realloc(in->buf, in->len + length);
        assert(in->buf != NULL);
        memcpy(in->buf + in->len, data, length);
        in->len += length;
    }

    // try to send something, if we're not already doing so
    if (bs->terminal != NULL && bs->inbuf[!bs->ninbuf].buf == NULL) {
        tx_handler(bs);
    }
}

static void output_handler(struct serial_binding *b, const char *c, size_t len)
{
    struct bs_state *bs = b->st;
    bs->serial->output(bs->serial, c, len);
}

static void associate_stdin_handler(struct serial_binding *b)
{
    SERIAL_DEBUG("associate_stdin called on basic interface\n");
    struct bs_state *bs = b->st;

    bs->terminal = b;
    serial_set_new_input_consumer(bs->serial, basic_serial_input, bs);
    // try to send something, if we have it ready
    if (bs->inbuf[bs->ninbuf].buf != NULL) {
        tx_handler(bs);
    }
}

static struct serial_rx_vtbl serial_rx_vtbl = {
    .output = output_handler,
    .associate_stdin = associate_stdin_handler,
};

static errval_t connect_cb(void *st, struct serial_binding *b)
{
    struct bs_state *bs = st;
    SERIAL_DEBUG("Client connected to basic interface.\n");

    b->st = bs;
    b->rx_vtbl = serial_rx_vtbl;
    bs->terminal = b;
    serial_set_new_input_consumer(bs->serial, basic_serial_input, bs);
    // try to send something, if we have it ready
    if (bs->inbuf[bs->ninbuf].buf != NULL) {
        tx_handler(bs);
    }

    return SYS_ERR_OK;
}

static void export_cb(void *st, errval_t err, iref_t iref)
{
    struct bs_state *bs = st;
    size_t size = 0;
    char *service_name = NULL;

    if (err_is_fail(err)) {
        USER_PANIC_ERR(err, "Exporting basic interface failed.\n");
    }

    // build service name as driver_name.SERVICE_SUFFIX
    size = snprintf(NULL, 0, "%s.%s", bs->serial->driver_name, SERVICE_SUFFIX);
    service_name = (char *) malloc(size + 1);
    if (service_name == NULL) {
        USER_PANIC("Error allocating memory.");
    }
    snprintf(service_name, size + 1, "%s.%s", bs->serial->driver_name, SERVICE_SUFFIX);

    SERIAL_DEBUG("About to register basic interface '%s' at nameservice.\n",
                 service_name);

    // register basic serial driver service at nameservice
    err = nameservice_register(service_name, iref);
    if (err_is_fail(err)) {
        USER_PANIC_ERR(err, "Registering basic interface at "
                       "nameserver failed.");
    }

    free(service_name);
}

void start_basic_service(struct serial_common *serial)
{
    errval_t err;
    struct bs_state *bs = malloc(sizeof(struct bs_state));
    bs->serial = serial;
    err = serial_export(bs, export_cb, connect_cb,
                        get_default_waitset(), IDC_EXPORT_FLAGS_DEFAULT);
    if (err_is_fail(err)) {
        USER_PANIC_ERR(err, "Preparing basic interface for export failed.");
    }

    SERIAL_DEBUG("Exporting basic interface.\n");
}


text:
using namespace PaintsNow;
using namespace PaintsNow::NsSnowyStream;
using namespace PaintsNow::ShaderMacro;

StandardTransform::StandardTransform() {
	shaderTextBody = UnifyShaderCode(
		vec4 position = vec4(0, 0, 0, 1);
		position.xyz = vertexPosition.xyz;
		worldPosition = mult_vec(modelViewMatrix, position.xyzw);
		rasterPosition = mult_vec(projectionMatrix, worldPosition.xyzw);

		vec3 normal = vec3(0, 0, 1);
		if (enableVertexNormal) {
			normal = mult_vec(normalMatrix, vertexNormal.xyz);
		}

		worldNormal.xyz = normal.xyz;

		vec4 color = vec4(1, 1, 1, 1);
		if (enableVertexColor) {
			color = vertexColor;
		}

		baseColor = color;
	);
}

TObject<IReflect>& StandardTransform::operator () (IReflect& reflect) {
	ReflectClass(StandardTransform)[Interface(IShader)];

	if (reflect.IsReflectAttrib()) {
		ReflectAttrib(modelViewMatrix);
		ReflectAttrib(projectionMatrix);
		ReflectAttrib(normalMatrix);
		ReflectAttrib(rasterPosition);
		ReflectAttrib(vertexPosition);
		ReflectAttrib(vertexNormal);
		ReflectAttrib(vertexColor);
		ReflectAttrib(worldPosition);
		ReflectAttrib(worldNormal);
		ReflectAttrib(baseColor);

		ReflectAttrib(enableVertexNormal);
		ReflectAttrib(enableVertexColor);
	}

	return *this;
}


text:
Input::
//// [/user/username/projects/myProject/pkg1/dist/index.d.ts]
export * from './types';

//// [/user/username/projects/myProject/pkg1/dist/types.d.ts]
export declare type A = {
    id: string;
};
export declare type B = {
    id: number;
};
export declare type IdType = A | B;
export declare class MetadataAccessor<T, D extends IdType = IdType> {
    readonly key: string;
    private constructor();
    toString(): string;
    static create<T, D extends IdType = IdType>(key: string): MetadataAccessor<T, D>;
}

//// [/user/username/projects/myProject/pkg1/package.json]
{"name":"@raymondfeng/pkg1","version":"1.0.0","main":"dist/index.js","typings":"dist/index.d.ts"}

//// [/user/username/projects/myproject/pkg2/dist/index.d.ts]
export * from './types';

//// [/user/username/projects/myproject/pkg2/dist/types.d.ts]
export {MetadataAccessor} from '@raymondfeng/pkg1';

//// [/user/username/projects/myproject/pkg2/package.json]
{"name":"@raymondfeng/pkg2","version":"1.0.0","main":"dist/index.js","typings":"dist/index.d.ts"}

//// [/user/username/projects/myproject/pkg3/src/index.ts]
export * from './keys';

//// [/user/username/projects/myproject/pkg3/src/keys.ts]
import {MetadataAccessor} from "@raymondfeng/pkg2";
export const ADMIN = MetadataAccessor.create<boolean>('1');

//// [/user/username/projects/myproject/pkg3/tsconfig.json]
{"compilerOptions":{"outDir":"dist","rootDir":"src","target":"es5","module":"commonjs","strict":true,"esModuleInterop":true,"declaration":true}}

//// [/user/username/projects/myProject/pkg2/node_modules/@raymondfeng/pkg1] symlink(/user/username/projects/myProject/pkg1)
//// [/user/username/projects/myproject/pkg3/node_modules/@raymondfeng/pkg2] symlink(/user/username/projects/myproject/pkg2)
//// [/a/lib/lib.d.ts]
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> { length: number; [n: number]: T; }

/a/lib/tsc.js -p pkg3 --explainFiles
Output::
pkg3/src/keys.ts:2:14 - error TS2742: The inferred type of 'ADMIN' cannot be named without a reference to '../../pkg2/node_modules/@raymondfeng/pkg1/dist'. This is likely not portable. A type annotation is necessary.

2 export const ADMIN = MetadataAccessor.create<boolean>('1');
               ~~~~~

../../../../a/lib/lib.d.ts
  Default library for target 'es5'
pkg1/dist/types.d.ts
  Imported via './types' from file 'pkg1/dist/index.d.ts'
pkg1/dist/index.d.ts
  Imported via '@raymondfeng/pkg1' from file 'pkg2/dist/types.d.ts' with packageId '@raymondfeng/pkg1/dist/index.d.ts@1.0.0'
pkg2/dist/types.d.ts
  Imported via './types' from file 'pkg2/dist/index.d.ts'
pkg2/dist/index.d.ts
  Imported via "@raymondfeng/pkg2" from file 'pkg3/src/keys.ts' with packageId '@raymondfeng/pkg2/dist/index.d.ts@1.0.0'
pkg3/src/keys.ts
  Imported via './keys' from file 'pkg3/src/index.ts'
  Matched by include pattern '**/*' in 'pkg3/tsconfig.json'
pkg3/src/index.ts
  Matched by include pattern '**/*' in 'pkg3/tsconfig.json'

Found 1 error.

Program root files: ["/user/username/projects/myproject/pkg3/src/index.ts","/user/username/projects/myproject/pkg3/src/keys.ts"]
Program options: {"outDir":"/user/username/projects/myproject/pkg3/dist","rootDir":"/user/username/projects/myproject/pkg3/src","target":1,"module":1,"strict":true,"esModuleInterop":true,"declaration":true,"project":"/user/username/projects/myproject/pkg3","explainFiles":true,"configFilePath":"/user/username/projects/myproject/pkg3/tsconfig.json"}
Program structureReused: Not
Program files::
/a/lib/lib.d.ts
/user/username/projects/myProject/pkg1/dist/types.d.ts
/user/username/projects/myProject/pkg1/dist/index.d.ts
/user/username/projects/myproject/pkg2/dist/types.d.ts
/user/username/projects/myproject/pkg2/dist/index.d.ts
/user/username/projects/myproject/pkg3/src/keys.ts
/user/username/projects/myproject/pkg3/src/index.ts

WatchedFiles::

FsWatches::

FsWatchesRecursive::

exitCode:: ExitStatus.DiagnosticsPresent_OutputsSkipped

//// [/user/username/projects/myproject/pkg3/dist/keys.js]
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ADMIN = void 0;
var pkg2_1 = require("@raymondfeng/pkg2");
exports.ADMIN = pkg2_1.MetadataAccessor.create('1');

//// [/user/username/projects/myproject/pkg3/dist/index.js]
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./keys"), exports);

//// [/user/username/projects/myproject/pkg3/dist/index.d.ts]
export * from './keys';


text:
package engineio

import (
	"fmt"
)

type XHR struct {
	Polling
}

func (xhr *XHR) InitXHR(req *Request) {
	xhr.InitPolling(req)

	xhr.Polling.doWrite = func(req *Request, data []byte) {
		debug(fmt.Sprintf("xhr writing \"%s\"", string(data)))
		contentType := "text/plains; charset=UTF-8"
		if data[0] < 20 {
			contentType = "application/octet-stream"
		}
		contentLength := fmt.Sprintf("%d", len(data))
		res := req.res
		res.Header().Set("Content-Type", contentType)
		res.Header().Set("Content-Length", contentLength)

		// TODO: Prevent XSS warning on IE.

		xhr.headers(req)
		res.WriteHeader(200)
		res.Write(data)
	}

	xhr.Polling.headers = func(req *Request) {
		httpreq := req.httpReq
		res := req.res

		origin := httpreq.Header.Get("Origin")

		if len(origin) > 0 {
			res.Header().Set("Access-Control-Allow-Credentials", "true")
			res.Header().Set("Access-Control-Allow-Origin", origin)
		} else {
			res.Header().Set("Access-Control-Allow-Origin", "*")
		}

		xhr.Emit("headers", res.Header())
	}
}

func (xhr *XHR) onRequest(req *Request) {
	if "OPTIONS" == req.httpReq.Method {
		debug("xhr Method == OPTIONS")
		res := req.res
		xhr.headers(req)
		res.Header().Set("Access-Control-Allow-Headers", "Content-Type")
		res.WriteHeader(200)
		res.Write(nil)
	} else {
		xhr.Polling.onRequest(req)
	}
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.14-5-28
description: >
    Array.prototype.indexOf - side effects produced by step 1 are
    visible when an exception occurs
---*/

        var stepFiveOccurs = false;
        var fromIndex = {
            valueOf: function () {
                stepFiveOccurs = true;
                return 0;
            }
        };
assert.throws(TypeError, function() {
            Array.prototype.indexOf.call(undefined, undefined, fromIndex);
});
assert.sameValue(stepFiveOccurs, false, 'stepFiveOccurs');


text:
package org.apache.olingo.commons.core.edm.annotation;

import org.apache.olingo.commons.api.edm.annotation.EdmAnnotationExpression;
import org.apache.olingo.commons.api.edm.annotation.EdmPropertyValue;

public class EdmPropertyValueImpl
extends AbstractEdmAnnotatableDynamicAnnotationExpression implements EdmPropertyValue {

  private final String property;

  private final EdmAnnotationExpression value;

  public EdmPropertyValueImpl(final String property, final EdmAnnotationExpression value) {
    this.property = property;
    this.value = value;
  }

  @Override
  public String getProperty() {
    return property;
  }

  @Override
  public EdmAnnotationExpression getValue() {
    return value;
  }

}


text:
var _dec, _dec2, _dec3, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _descriptor9, _descriptor10, _descriptor11;

function _initDefineProp(target, property, descriptor, context) {
  if (!descriptor) return;
  Object.defineProperty(target, property, {
    enumerable: descriptor.enumerable,
    configurable: descriptor.configurable,
    writable: descriptor.writable,
    value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
  });
}

function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
  var desc = {};
  Object['ke' + 'ys'](descriptor).forEach(function (key) {
    desc[key] = descriptor[key];
  });
  desc.enumerable = !!desc.enumerable;
  desc.configurable = !!desc.configurable;

  if ('value' in desc || desc.initializer) {
    desc.writable = true;
  }

  desc = decorators.slice().reverse().reduce(function (desc, decorator) {
    return decorator(target, property, desc) || desc;
  }, desc);

  if (context && desc.initializer !== void 0) {
    desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
    desc.initializer = undefined;
  }

  if (desc.initializer === void 0) {
    Object['define' + 'Property'](target, property, desc);
    desc = null;
  }

  return desc;
}

function _initializerWarningHelper(descriptor, context) {
  throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}

import { customElement, bindable, computedFrom } from 'aurelia-framework';
import { resolvedView } from 'aurelia-view-manager';
import { Metadata } from '../aurelia-form';

export let EntityForm = (_dec = resolvedView('spoonx/form', 'entity-form'), _dec2 = customElement('entity-form'), _dec3 = computedFrom('entity'), _dec(_class = _dec2(_class = (_class2 = class EntityForm {
  constructor() {
    _initDefineProp(this, 'form', _descriptor, this);

    _initDefineProp(this, 'entity', _descriptor2, this);

    _initDefineProp(this, 'behavior', _descriptor3, this);

    _initDefineProp(this, 'classes', _descriptor4, this);

    _initDefineProp(this, 'elementClasses', _descriptor5, this);

    _initDefineProp(this, 'labelClasses', _descriptor6, this);

    _initDefineProp(this, 'skip', _descriptor7, this);

    _initDefineProp(this, 'validated', _descriptor8, this);

    _initDefineProp(this, 'buttonOptions', _descriptor9, this);

    _initDefineProp(this, 'buttonLabel', _descriptor10, this);

    _initDefineProp(this, 'buttonEnabled', _descriptor11, this);
  }

  get elements() {
    let entityMeta = {};

    if (typeof this.entity.getMeta === 'function') {
      entityMeta = this.entity.getMeta().metadata;
    }

    let types = entityMeta.types || {};
    let associations = entityMeta.associations || {};
    let fields = Metadata.forTarget(this.entity).fetch('fields', {});

    return Object.keys(this.entity).map(name => {
      let field = fields[name] || {};
      let association = associations[name];
      let options = field.options || {};
      let element = types[name] || 'input';

      if (association) {
        element = 'association';
        options.resource = association.entity;
        options.multiple = association.type === 'collection';
      }

      if (field.element) {
        element = field.element;
      }

      return {
        element: element,
        field: name,
        meta: field,
        options: options
      };
    }).sort((left, right) => {
      let leftPosition = left.meta.position || 0;
      let rightPosition = right.meta.position || 0;

      if (leftPosition < rightPosition) {
        return -1;
      }

      if (leftPosition > rightPosition) {
        return 1;
      }

      return 0;
    });
  }

  isVisible(fieldName) {
    return this.skip.indexOf(fieldName) === -1;
  }

  submit() {
    this.form.submit();
  }
}, (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'form', [bindable], {
  enumerable: true,
  initializer: null
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'entity', [bindable], {
  enumerable: true,
  initializer: null
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'behavior', [bindable], {
  enumerable: true,
  initializer: null
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, 'classes', [bindable], {
  enumerable: true,
  initializer: null
}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, 'elementClasses', [bindable], {
  enumerable: true,
  initializer: null
}), _descriptor6 = _applyDecoratedDescriptor(_class2.prototype, 'labelClasses', [bindable], {
  enumerable: true,
  initializer: null
}), _descriptor7 = _applyDecoratedDescriptor(_class2.prototype, 'skip', [bindable], {
  enumerable: true,
  initializer: function () {
    return [];
  }
}), _descriptor8 = _applyDecoratedDescriptor(_class2.prototype, 'validated', [bindable], {
  enumerable: true,
  initializer: function () {
    return true;
  }
}), _descriptor9 = _applyDecoratedDescriptor(_class2.prototype, 'buttonOptions', [bindable], {
  enumerable: true,
  initializer: null
}), _descriptor10 = _applyDecoratedDescriptor(_class2.prototype, 'buttonLabel', [bindable], {
  enumerable: true,
  initializer: null
}), _descriptor11 = _applyDecoratedDescriptor(_class2.prototype, 'buttonEnabled', [bindable], {
  enumerable: true,
  initializer: null
}), _applyDecoratedDescriptor(_class2.prototype, 'elements', [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, 'elements'), _class2.prototype)), _class2)) || _class) || _class);


text:
namespace ui {

namespace {

// Check that the sequence behaves sanely when it contains no elements.
TEST(LayerAnimationSequenceTest, NoElement) {
  LayerAnimationSequence sequence;
  EXPECT_EQ(sequence.duration(), base::TimeDelta());
  EXPECT_TRUE(sequence.properties().size() == 0);
  LayerAnimationElement::AnimatableProperties properties;
  EXPECT_FALSE(sequence.HasCommonProperty(properties));
}

// Check that the sequences progresses the delegate as expected when it contains
// a single element.
TEST(LayerAnimationSequenceTest, SingleElement) {
  LayerAnimationSequence sequence;
  TestLayerAnimationDelegate delegate;
  float start = 0.0f;
  float middle = 0.5f;
  float target = 1.0f;
  base::TimeDelta delta = base::TimeDelta::FromSeconds(1);
  sequence.AddElement(
      LayerAnimationElement::CreateOpacityElement(target, delta));

  for (int i = 0; i < 2; ++i) {
    delegate.SetOpacityFromAnimation(start);
    sequence.Progress(base::TimeDelta::FromMilliseconds(0), &delegate);
    EXPECT_FLOAT_EQ(start, delegate.GetOpacityForAnimation());
    sequence.Progress(base::TimeDelta::FromMilliseconds(500), &delegate);
    EXPECT_FLOAT_EQ(middle, delegate.GetOpacityForAnimation());
    sequence.Progress(base::TimeDelta::FromMilliseconds(1000), &delegate);
    EXPECT_FLOAT_EQ(target, delegate.GetOpacityForAnimation());
  }

  EXPECT_TRUE(sequence.properties().size() == 1);
  EXPECT_TRUE(sequence.properties().find(LayerAnimationElement::OPACITY) !=
              sequence.properties().end());
  EXPECT_EQ(delta, sequence.duration());
}

// Check that the sequences progresses the delegate as expected when it contains
// multiple elements. Note, see the layer animator tests for cyclic sequences.
TEST(LayerAnimationSequenceTest, MultipleElement) {
  LayerAnimationSequence sequence;
  TestLayerAnimationDelegate delegate;
  float start_opacity = 0.0f;
  float middle_opacity = 0.5f;
  float target_opacity = 1.0f;
  base::TimeDelta delta = base::TimeDelta::FromSeconds(1);
  sequence.AddElement(
      LayerAnimationElement::CreateOpacityElement(target_opacity, delta));

  // Pause bounds for a second.
  LayerAnimationElement::AnimatableProperties properties;
  properties.insert(LayerAnimationElement::BOUNDS);

  sequence.AddElement(
      LayerAnimationElement::CreatePauseElement(properties, delta));

  Transform start_transform, target_transform, middle_transform;
  start_transform.SetRotate(-90);
  target_transform.SetRotate(90);

  sequence.AddElement(
      LayerAnimationElement::CreateTransformElement(target_transform, delta));

  for (int i = 0; i < 2; ++i) {
    delegate.SetOpacityFromAnimation(start_opacity);
    delegate.SetTransformFromAnimation(start_transform);

    sequence.Progress(base::TimeDelta::FromMilliseconds(0), &delegate);
    EXPECT_FLOAT_EQ(start_opacity, delegate.GetOpacityForAnimation());
    sequence.Progress(base::TimeDelta::FromMilliseconds(500), &delegate);
    EXPECT_FLOAT_EQ(middle_opacity, delegate.GetOpacityForAnimation());
    sequence.Progress(base::TimeDelta::FromMilliseconds(1000), &delegate);
    EXPECT_FLOAT_EQ(target_opacity, delegate.GetOpacityForAnimation());
    TestLayerAnimationDelegate copy = delegate;

    // In the middle of the pause -- nothing should have changed.
    sequence.Progress(base::TimeDelta::FromMilliseconds(1500), &delegate);
    CheckApproximatelyEqual(delegate.GetBoundsForAnimation(),
                            copy.GetBoundsForAnimation());
    CheckApproximatelyEqual(delegate.GetTransformForAnimation(),
                            copy.GetTransformForAnimation());
    EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(),
                    copy.GetOpacityForAnimation());

    sequence.Progress(base::TimeDelta::FromMilliseconds(2000), &delegate);
    CheckApproximatelyEqual(start_transform,
                            delegate.GetTransformForAnimation());
    sequence.Progress(base::TimeDelta::FromMilliseconds(2500), &delegate);
    CheckApproximatelyEqual(middle_transform,
                            delegate.GetTransformForAnimation());
    sequence.Progress(base::TimeDelta::FromMilliseconds(3000), &delegate);
    CheckApproximatelyEqual(target_transform,
                            delegate.GetTransformForAnimation());
  }

  EXPECT_TRUE(sequence.properties().size() == 3);
  EXPECT_TRUE(sequence.properties().find(LayerAnimationElement::OPACITY) !=
              sequence.properties().end());
  EXPECT_TRUE(sequence.properties().find(LayerAnimationElement::TRANSFORM) !=
              sequence.properties().end());
  EXPECT_TRUE(sequence.properties().find(LayerAnimationElement::BOUNDS) !=
              sequence.properties().end());
  EXPECT_EQ(delta + delta + delta, sequence.duration());
}

// Check that a sequence can still be aborted if it has cycled many times.
TEST(LayerAnimationSequenceTest, AbortingCyclicSequence) {
  LayerAnimationSequence sequence;
  TestLayerAnimationDelegate delegate;
  float start_opacity = 0.0f;
  float target_opacity = 1.0f;
  base::TimeDelta delta = base::TimeDelta::FromSeconds(1);
  sequence.AddElement(
      LayerAnimationElement::CreateOpacityElement(target_opacity, delta));

  sequence.AddElement(
      LayerAnimationElement::CreateOpacityElement(start_opacity, delta));

  sequence.set_is_cyclic(true);

  delegate.SetOpacityFromAnimation(start_opacity);

  sequence.Progress(base::TimeDelta::FromMilliseconds(101000), &delegate);
  EXPECT_FLOAT_EQ(target_opacity, delegate.GetOpacityForAnimation());
  sequence.Abort();

  // Should be able to reuse the sequence after aborting.
  delegate.SetOpacityFromAnimation(start_opacity);
  sequence.Progress(base::TimeDelta::FromMilliseconds(100000), &delegate);
  EXPECT_FLOAT_EQ(start_opacity, delegate.GetOpacityForAnimation());
}

// Check that a sequence can be 'fast-forwarded' to the end and the target set.
// Also check that this has no effect if the sequence is cyclic.
TEST(LayerAnimationSequenceTest, SetTarget) {
  LayerAnimationSequence sequence;
  TestLayerAnimationDelegate delegate;
  float start_opacity = 0.0f;
  float target_opacity = 1.0f;
  base::TimeDelta delta = base::TimeDelta::FromSeconds(1);
  sequence.AddElement(
      LayerAnimationElement::CreateOpacityElement(target_opacity, delta));

  LayerAnimationElement::TargetValue target_value(&delegate);
  target_value.opacity = start_opacity;
  sequence.GetTargetValue(&target_value);
  EXPECT_FLOAT_EQ(target_opacity, target_value.opacity);

  sequence.set_is_cyclic(true);
  target_value.opacity = start_opacity;
  sequence.GetTargetValue(&target_value);
  EXPECT_FLOAT_EQ(start_opacity, target_value.opacity);
}

TEST(LayerAnimationSequenceTest, AddObserver) {
  base::TimeDelta delta = base::TimeDelta::FromSeconds(1);
  LayerAnimationSequence sequence;
  sequence.AddElement(
      LayerAnimationElement::CreateOpacityElement(1.0f, delta));
  for (int i = 0; i < 2; ++i) {
    TestLayerAnimationObserver observer;
    TestLayerAnimationDelegate delegate;
    sequence.AddObserver(&observer);
    EXPECT_TRUE(!observer.last_ended_sequence());
    sequence.Progress(delta, &delegate);
    EXPECT_EQ(observer.last_ended_sequence(), &sequence);
    sequence.RemoveObserver(&observer);
  }
}

} // namespace

} // namespace ui


text:
using DG.Tweening;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class ColorBreath : MonoBehaviour
{
  [SerializeField]
  private Color _toColor;

  [SerializeField]
  private float _speed;

  private Color _fromColor;

  private Text _text;

  private void Start()
  {
    _text = GetComponent<Text>();
    _text.DOColor(_toColor, _speed).SetLoops(-1, LoopType.Yoyo);
  }

  private void OnEnable()
  {
    _text.DOTogglePause();
  }

  private void OnDisable()
  {
    _text.DOTogglePause();
  }
}


text:
registrar_usuario::registrar_usuario(GUI *guiP, QVector<Pais *> paisesP, QWidget *parent):
    QDialog(parent), ui(new Ui::registrar_usuario), gui(guiP), paises(paisesP)
{
    ui->setupUi(this);
    QPixmap pix("/home/fer/Pegaso/Heros64.png");
    ui->label_logo->setPixmap(pix);
    ui->lineEdit_6->setEnabled(true);

    for (int i = 0; i < paises.size(); ++i) {
       ui->comboBox_5->addItem(paises[i]->getNombre());
    }
    ui->comboBox_8->setCurrentIndex(-1);
    ui->comboBox_5->setCurrentIndex(-1);
    ui->comboBox_6->setCurrentIndex(-1);

}

registrar_usuario::~registrar_usuario()
{
    delete ui;
}

void registrar_usuario::on_pushButton_2_clicked()
{
     this->close();
}

void registrar_usuario::on_pushButton_clicked()
{
    QStringList errores;
    QString c1 = ui->lineEdit_2->text();
    QString c2 = ui->lineEdit_3->text();

    if(c1 != c2){

        errores.append("Su contraseña no coincide, por favor coloquela nuevamente.");
        ui->lineEdit_2->clear();
        ui->lineEdit_3->clear();
    }

    QString correo = ui->lineEdit_6->text();
    QString nombre = ui->lineEdit_9->text();
    QString apellido = ui->lineEdit_10->text();
    QString tipoDocumento = ui->comboBox_7->currentText();
    QString documento = ui->lineEdit_8->text();
    QString pais = ui->comboBox_5->currentText();
    QString provincia = ui->comboBox_8->currentText();
    QString localidad = ui->comboBox_6->currentText();
    bool terminos = ui->checkBox->isChecked();

    if(terminos != 1){
        errores.append("Por favor lea y acepte los Terminos de servicio para continuar.");
    }

    if(errores.size() == 0){
        QByteArray passwordHash = QCryptographicHash::hash(QByteArray::fromStdString(ui->lineEdit_2->text().toStdString()),QCryptographicHash::Sha256);
        DtoUsuario * data = new DtoUsuario(correo,nombre,apellido,tipoDocumento,documento,pais,provincia,localidad,passwordHash);

        QString error = gui->handleRegistrarUsuario(data);
        QMessageBox* msg = new QMessageBox(this);
        QPixmap icono(":/images/Heros-amarillo-64.png");
        msg->setIconPixmap(icono);
        msg->setModal(true);
        msg->setText(error);
        msg->show();
    }
    else
    {
        QString errorStr = errores[0];
        for (int i = 1; i < errores.size(); ++i) {
           errorStr += "\n" + errores[i] ;
        }
        QMessageBox* msg = new QMessageBox(this);
        msg->setModal(true);
        QPixmap icono(":/images/Heros-amarillo-64.png");
        msg->setIconPixmap(icono);
        msg->setText(errorStr);
        msg->show();
    }
}

void registrar_usuario::on_comboBox_5_currentIndexChanged(int index)
{
    ui->comboBox_8->clear();
    if( index != -1){
        provincias = gui->getProvincias(paises[index]);

        for (int i = 0; i < provincias.size(); ++i) {
            ui->comboBox_8->addItem(provincias[i]->getNombre());
        }
    }
}

void registrar_usuario::on_comboBox_8_currentIndexChanged(int index)
{
    ui->comboBox_6->clear();
    if( index != -1){
        localidades = gui->getLocalidades(provincias[index]);

        for (int i = 0; i < localidades.size(); ++i) {
           ui->comboBox_6->addItem(localidades[index]->getNombre());
        }
    }
}


text:
using ExtendedXmlSerializer.Core.Sources;

namespace ExtendedXmlSerializer.ContentModel.Members
{
	interface IMemberAccessors : IParameterizedSource<IMember, IMemberAccess> {}
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Promise = require("bluebird");
const IndicatorNotFoundError_1 = require("./error/IndicatorNotFoundError");
const Indicator_1 = require("./Indicator");
class Xray {
    constructor() {
        this.running = false;
        this.firstRun = true;
        this.defaultIndicatorTimeout = 1000;
        this.interval = 1000;
        this.indicators = new Map();
    }
    setInterval(interval) {
        if (interval <= 0) {
            throw new Error("'interval' parameter have to be larger than 0");
        }
        this.interval = interval;
        return this;
    }
    setDefaultIndicatorTimeout(timeout) {
        if (timeout < 0) {
            throw new Error("'timeout' parameter have to be larger than 0");
        }
        this.defaultIndicatorTimeout = timeout;
        return this;
    }
    setEventEmitter(eventEmitter) {
        this.eventEmitter = eventEmitter;
        return this;
    }
    /**
     * Check if has named indicator or not
     *
     * @param {string} name
     *
     * @returns {boolean}
     */
    has(name) {
        return this.indicators.has(name);
    }
    /**
     * Add new indicator
     *
     * @param {string} name
     * @param {Indicator} indicator
     * @param {IndicatorOptions} options
     *
     * @returns {Xray}
     */
    add(name, indicator, options) {
        options = options || {};
        this.indicators.set(name, {
            indicator,
            name,
            options,
            response: {
                lastCheck: null,
                status: Indicator_1.IndicatorStatus.UNKNOWN,
            },
        });
        return this;
    }
    /**
     * Try to remove existing indicator
     *
     * @param {string} name
     *
     * @returns {boolean}
     */
    remove(name) {
        if (this.has(name)) {
            this.indicators.delete(name);
            return true;
        }
        return false;
    }
    /**
     * Start continuous indicator check
     *
     * @return {void}
     */
    start() {
        if (!this.running) {
            this.running = true;
            this.run();
        }
    }
    status(arg1) {
        arg1 = arg1 || {};
        // status(name: string): IndicatorResponse
        if (typeof arg1 === "string") {
            const indicator = this.indicators.get(arg1);
            if (!indicator) {
                throw new IndicatorNotFoundError_1.IndicatorNotFoundError(arg1);
            }
            return indicator.response;
        }
        // status(): IndicatorStatus
        // status({detailed}: { detailed: true }): Map<string, IndicatorResponse>
        if (arg1.detailed) {
            const result = new Map();
            this.indicators.forEach((value, name) => {
                result.set(name, value.response);
            });
            return result;
        }
        let result = Indicator_1.IndicatorStatus.UP;
        this.indicators.forEach(({ response }) => {
            if (response.status === Indicator_1.IndicatorStatus.UNKNOWN) {
                result = Indicator_1.IndicatorStatus.UNKNOWN;
            }
            else if (response.status === Indicator_1.IndicatorStatus.DOWN && result !== Indicator_1.IndicatorStatus.UNKNOWN) {
                result = Indicator_1.IndicatorStatus.DOWN;
            }
        });
        return result;
    }
    /**
     * Call registered indicators
     *
     * @returns {Promise<Map<string, IndicatorResponse>>}
     */
    check() {
        if (this.indicators.size === 0) {
            return Promise.resolve(new Map());
        }
        return Promise
            .all(Array.from(this.indicators.keys()).map((name) => {
            return Promise.all([name, this.callIndicator(name)]);
        }))
            .then((indicatorResponses) => {
            const result = new Map();
            indicatorResponses.forEach(([name, indicatorResponse]) => {
                result.set(name, indicatorResponse);
            });
            return result;
        });
    }
    /**
     * Recursive method to checking the indicators
     *
     * @return {void}
     */
    run() {
        this.timeoutId = undefined;
        let promise = this.check()
            .catch(() => {
            // TODO should we log the error???
        });
        if (this.firstRun) {
            this.firstRun = false;
            promise = promise.then(() => {
                // We can safely call status method, because
                this.emit("xray.started", this.status());
            });
        }
        promise.then(() => {
            if (this.running) {
                // Need to bind run method to its context to avoid overwriting methods context
                this.timeoutId = setTimeout(this.run.bind(this), this.interval);
            }
        });
    }
    /**
     * Call named indicator and store it's response
     *
     * @param {string} name
     *
     * @returns {Promise<IndicatorResponse>}
     */
    callIndicator(name) {
        const indicator = this.indicators.get(name);
        if (!indicator) {
            // This error should never throw, but for TS type safety need to place here
            throw new IndicatorNotFoundError_1.IndicatorNotFoundError(name);
        }
        // We wrap indicator's promise into new one to protect indicator's promise context
        // For example: We set timeout to new promise not for indicator's promise
        let promise = Promise.resolve()
            .then(() => {
            return indicator.indicator();
        })
            .then((response) => {
            indicator.response = {
                lastCheck: Date.now(),
                response,
                status: Indicator_1.IndicatorStatus.UP,
            };
            this.emit("xray.indicator.success", name, response);
            return response;
        })
            .catch((error) => {
            indicator.response = {
                error,
                lastCheck: Date.now(),
                status: Indicator_1.IndicatorStatus.DOWN,
            };
            this.emit("xray.indicator.error", error, name);
            throw error;
        });
        promise = promise.timeout(indicator.options.timeout || this.defaultIndicatorTimeout);
        return promise;
    }
    emit(event, ...args) {
        if (this.eventEmitter) {
            this.eventEmitter.emit(event, ...args);
        }
    }
}
exports.Xray = Xray;
//# sourceMappingURL=Xray.js.map


text:
import argparse
import re
import sys
import urllib3
import urllib

#
# This class is used to parse collectd log notifications. It returns 0,1,2
#   - 0 - no failures
#   - 1 - only warnings
#   - 2 - failures
#
# In the case that warnings or failures exist, it will also print the information
# about those failures and warning to stdout
#
class NotificationParser:
    # go through all events in a file of a given type, and just keep a record
    # of the last event for each type.
    def parse(self, filename):
        data_hash = {}
        with open(filename, 'r') as f:
            for line in f:
                try:
                    spl_line = line.split(', ')
                    m     = re.search('Notification: severity = (OKAY|WARNING|FAILURE)', spl_line.pop(0))
                    if m:
                        n     = spl_line[1].split(' = ')
                        level = m.group(1)
                        name  = n[1]
                        local_data = {}
                        for l in spl_line:
                            # assumes that message is the last field, so it we have
                            # encountered it, then all remaining text should be
                            # considered part of the message
                            if 'message' in local_data:
                                local_data['message']+=l
                            else:
                                data = l.split(' = ', 2)
                                local_data[data[0]] = data[1]
                        data_hash[name] = [level, local_data['message']]
                except:
                    print "Line: %s, lead to an unexpected exception, skipping" % line
                    pass
        f.close()
        return data_hash

    def update_service_status(self, status, service_name, note=''):
        http = urllib3.PoolManager()
        note = urllib.quote(note)
        url = "http://localhost:8500/v1/agent/check/%s/service:metric_thresholds_%s?note=%s" % (status, service_name, note)
        r = http.request('GET', url)

    def send_alerts(self, data):
        for k, v in data.iteritems():
            if v[0] == 'OKAY':
                resp = self.update_service_status('pass', k, v[1])
            elif v[0] == 'WARNING':
                resp = self.update_service_status('warn', k, v[1])
            elif v[0] == 'FAILURE':
                resp = self.update_service_status('fail', k, v[1])

if __name__ == '__main__':
    argparser = argparse.ArgumentParser()
    argparser.add_argument('--filename', help='Notification file to parse')
    args = argparser.parse_args()
    notification_parser = NotificationParser()
    data = notification_parser.parse(args.filename)
    notification_parser.send_alerts(data)


text:
#define ALLEGRO_NO_COMPATIBILITY

#include "allegro5/allegro.h"

#ifdef ALLEGRO_HAVE_LINUX_INPUT_H

ALLEGRO_DEBUG_CHANNEL("lmseev");

#include "allegro5/internal/aintern.h"
#include "allegro5/internal/aintern_mouse.h"
#include "allegro5/platform/aintunix.h"
#include "allegro5/platform/aintlnx.h"

#ifdef ALLEGRO_RASPBERRYPI
#include "allegro5/internal/aintern_system.h"
#include "allegro5/internal/aintern_display.h"
#include "allegro5/internal/aintern_vector.h"
#endif

#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <linux/input.h>

#define PREFIX_I                "al-evdev INFO: "
#define PREFIX_W                "al-evdev WARNING: "
#define PREFIX_E                "al-evdev ERROR: "

typedef struct AL_MOUSE_EVDEV
{
   ALLEGRO_MOUSE parent;
   int fd;
   ALLEGRO_MOUSE_STATE state;
} AL_MOUSE_EVDEV;

/* the one and only mouse object */
static AL_MOUSE_EVDEV the_mouse;

/* forward declarations */
static void process_new_data(void *unused);
static void process_event(struct input_event *event);
static void handle_button_event(unsigned int button, bool is_down);
static void handle_axis_event(int dx, int dy, int dz);
static void generate_mouse_event(unsigned int type,
                                 int x, int y, int z,
                                 int dx, int dy, int dz,
                                 unsigned int button);
bool _al_evdev_set_mouse_range(int x1, int y1, int x2, int y2);

/*
 * Tools data
 */

/* Tool mode
 * This mode is the behavior the user sees, it is not the way the device
 * reports the position.
 * Tools that send relative informations can only be in relative mode,
 * tools that send absolute informations can be either in absolute mode or in
 * relative mode */
typedef enum {
   MODE_RELATIVE,
   MODE_ABSOLUTE
} MODE;

typedef struct TOOL {
   int tool_id; /* One of the BTN_TOOL_... from linux/input.h */
   MODE mode;   /* Relative or absolute */
} TOOL;

static TOOL tools[] = {
   { BTN_TOOL_MOUSE,    MODE_RELATIVE },
   { BTN_TOOL_PEN,      MODE_ABSOLUTE },
   { BTN_TOOL_RUBBER,   MODE_ABSOLUTE },
   { BTN_TOOL_BRUSH,    MODE_ABSOLUTE },
   { BTN_TOOL_PENCIL,   MODE_ABSOLUTE },
   { BTN_TOOL_AIRBRUSH, MODE_ABSOLUTE },
   { BTN_TOOL_FINGER,   MODE_ABSOLUTE },
   { BTN_TOOL_LENS,     MODE_ABSOLUTE },

   { -1, MODE_ABSOLUTE } /* No tool */
};

/* Default tool, in case the device does not send a tool id */
static TOOL *default_tool = tools + 0;

static TOOL *no_tool = tools + (sizeof(tools)/sizeof(tools[0]) - 1);

static TOOL *current_tool;

/* find_tool:
 *  Returns the tool with id 'tool_id' which is one of the BTN_TOOL_... defined
 *  in linux/input.h. Returns 'default_tool' if not found.
 */
static TOOL *find_tool(int tool_id)
{
   TOOL *t;
   for (t=tools; t!=no_tool; t++) {
      if (t->tool_id == tool_id)
         return t;
   }
   return default_tool;
}

/*
 * Pointer axis
 */
typedef struct AXIS {
   int in_min;      /* For absolute mode */
   int in_max;      /* For absolute mode */
   int out_min;     /* For absolute mode */
   int out_max;     /* For absolute mode */

   float speed;     /* For set_mouse_speed */
   int mickeys;     /* For get_mouse_mickeys */
   float scale;     /* Scale factor, because tablet mice generate more movement
                       than common mice */

   int in_abs;      /* Current absolute position, used for absolute input,
                       whether the output is absolute or relative */
   int out_abs;     /* Position on the screen */
} AXIS;

#define IN_RANGE(axis)  ( (axis).in_max-(axis).in_min+1 )
#define OUT_RANGE(axis)  ( (axis).out_max-(axis).out_min+1 )

/* in_to_screen:
 *  maps an input absolute position to a screen position
 */
static int in_to_screen(const AXIS *axis, int v)
{
   return (((v-axis->in_min) * OUT_RANGE(*axis)) / IN_RANGE(*axis)) + axis->out_min;
}

/* rel_event:
 *  returns the new screen position, given the input relative one.
 *  The tool mode is always relative
 */
static int rel_event(AXIS *axis, int v)
{
   /* When input only send relative events, the mode is always relative */
   int ret = axis->out_abs + v*axis->speed;
   axis->mickeys += v;
   axis->in_abs += v;
   return ret;
}

/* abs_event:
 *  returns the new screen position, given the input absolute one,
 *  and depending on the tool mode
 */
static int abs_event(AXIS *axis, MODE mode, int v)
{
   if (mode == MODE_ABSOLUTE) {
      axis->mickeys = 0; /* No mickeys in absolute mode */
      axis->in_abs = v;
      return in_to_screen(axis, v);
   }
   else { /* Input is absolute, but tool is relative */
      int value = (v-axis->in_abs)*axis->scale;
      axis->mickeys += value;
      axis->in_abs = v;
      return axis->out_abs + value*axis->speed;
   }
}

/* get_axis_value:
 *  returns the input absolute position
 */
static void get_axis_value(int fd, AXIS *axis, int type)
{
  int abs[5];
  int ret = ioctl(fd, EVIOCGABS(type), abs);
  if (ret>=0) {
    axis->in_abs = abs[0];
  }
}

/* has_event:
 *  returns true if the device generates the event
 */
static int has_event(int fd, unsigned short type, unsigned short code)
{
   const unsigned int len = sizeof(unsigned long)*8;
   const unsigned int max = _ALLEGRO_MAX(EV_MAX, _ALLEGRO_MAX(KEY_MAX, _ALLEGRO_MAX(REL_MAX, _ALLEGRO_MAX(ABS_MAX, _ALLEGRO_MAX(LED_MAX, _ALLEGRO_MAX(SND_MAX, FF_MAX))))));
   unsigned long bits[(max+len-1)/len];
   if (ioctl(fd, EVIOCGBIT(type, max), bits)) {
     return (bits[code/len] >> (code%len)) & 1;
   }
   return 0;
}

/* get_num_buttons:
 *  return the number of buttons
 */
static int get_num_buttons(int fd)
{
   if (has_event(fd, EV_KEY, BTN_MIDDLE))
      return 3;
   if (has_event(fd, EV_KEY, BTN_RIGHT))
      return 2;
   if (has_event(fd, EV_KEY, BTN_MOUSE))
      return 1;
   return 0; /* Not a mouse */
}

/* The three axis: horizontal, vertical and wheel */
static AXIS x_axis;
static AXIS y_axis;
static AXIS z_axis;

/*
 * Initialization functions
 */

/* init_axis:
 *  initialize an AXIS structure, from the device and the config file
 */
static void init_axis(int fd, AXIS *axis, const char *name, const char *section, int type)
{
#if 0
   char tmp1[256]; /* config string */
   char tmp2[256]; /* format string */
   char tmp3[256]; /* Converted 'name' */
#endif
   int abs[5]; /* values given by the input */
   int config_speed;

   (void)name;
   (void)section;

   config_speed = 1;
   axis->scale = 1;

   /* Ask the input */
   if (ioctl(fd, EVIOCGABS(type), abs)>=0) {
      if (axis->in_min==0)
         axis->in_min=abs[1];
      if (axis->in_max==0)
         axis->in_max=abs[2];
      axis->in_abs = abs[0];
      axis->scale = 320.0*config_speed/IN_RANGE(*axis);
   }
   if (axis->in_min>axis->in_max) {
      axis->in_min = axis->in_max = 0;
      axis->scale = 1;
   }

   axis->out_min = INT_MIN;
   axis->out_max = INT_MAX;

   axis->speed = 1;
   axis->mickeys = 0;
}

/* init_tablet:
 *  initialize the tools and axis
 */
static void init_tablet(int fd)
{
   int default_abs = default_tool->mode==MODE_ABSOLUTE;

   if (default_abs) {
      default_tool->mode = MODE_ABSOLUTE;
   }
   else {
      default_tool->mode = MODE_RELATIVE;
   }

   init_axis(fd, &x_axis, "x", "mouse", ABS_X);
   init_axis(fd, &y_axis, "y", "mouse", ABS_Y);
   init_axis(fd, &z_axis, "z", "mouse", ABS_Z);
}

/*
 * Process input functions
 */

/* process_key: [fdwatch thread]
 *  process events of type key (button clicks and vicinity events are currently
 *  supported)
 */
static void process_key(const struct input_event *event)
{
   switch (event->code) {
      /* Buttons click
       * if event->value is 1 the button has just been pressed
       * if event->value is 0 the button has just been released */
      case BTN_LEFT: /* Mouse */
      case BTN_TOUCH: /* Stylus */
         handle_button_event(1, event->value);
         break;

      case BTN_RIGHT: /* Mouse */
      case BTN_STYLUS: /* Stylus */
         handle_button_event(2, event->value);
         break;

      case BTN_MIDDLE: /* Mouse */
      case BTN_STYLUS2: /* Stylus */
         handle_button_event(3, event->value);
         break;

      /* Vicinity events
       * if event->value is 1, the tool enters the tablet vicinity
       * if event->value is 0, the tool leaves the tablet vicinity */
      case BTN_TOOL_MOUSE:
      case BTN_TOOL_PEN:
      case BTN_TOOL_RUBBER:
      case BTN_TOOL_BRUSH:
      case BTN_TOOL_PENCIL:
      case BTN_TOOL_AIRBRUSH:
      case BTN_TOOL_FINGER:
      case BTN_TOOL_LENS:
         if (event->value) {
            current_tool = find_tool(event->code);
            get_axis_value(the_mouse.fd, &x_axis, ABS_X);
            get_axis_value(the_mouse.fd, &y_axis, ABS_Y);
            get_axis_value(the_mouse.fd, &z_axis, ABS_Z);
#ifdef ABS_WHEEL  /* absent in 2.2.x */
            get_axis_value(the_mouse.fd, &z_axis, ABS_WHEEL);
#endif
         }
         else {
            current_tool = no_tool;
         }
         break;
   }
}

/* [fdwatch thread] */
static void handle_button_event(unsigned int button, bool is_down)
{
   unsigned int event_type;

   if (is_down) {
      the_mouse.state.buttons |= (1 << (button-1));
      event_type = ALLEGRO_EVENT_MOUSE_BUTTON_DOWN;
   }
   else {
      the_mouse.state.buttons &=~ (1 << (button-1));
      event_type = ALLEGRO_EVENT_MOUSE_BUTTON_UP;
   }

   generate_mouse_event(
      event_type,
      the_mouse.state.x, the_mouse.state.y, the_mouse.state.z,
      0, 0, 0,
      button);
}

/* process_rel: [fdwatch thread]
 *  process relative events (x, y and z movement are currently supported)
 */
static void process_rel(const struct input_event *event)
{
   /* The device can send a report when there's no tool */
   if (current_tool!=no_tool) {
      switch (event->code) {
         case REL_X:
            x_axis.out_abs = rel_event(&x_axis, event->value);
            handle_axis_event(x_axis.mickeys, 0, 0);
            x_axis.mickeys = 0;
            break;

         case REL_Y:
            y_axis.out_abs = rel_event(&y_axis, event->value);
            handle_axis_event(0, y_axis.mickeys, 0);
            y_axis.mickeys = 0;
            break;

#ifdef REL_WHEEL  /* absent in 2.2.x */
         case REL_WHEEL:
#endif
         case REL_Z:
            z_axis.out_abs = rel_event(&z_axis, event->value);
            handle_axis_event(0, 0, z_axis.mickeys);
            z_axis.mickeys = 0;
            break;
      }
   }
}

/* process_abs: [fdwatch thread]
 *  process absolute events (x, y and z movement are currently supported)
 *  TODO: missing handle_axis_event calls
 */
static void process_abs(const struct input_event *event)
{
   /* The device can send a report when there's no tool */
   if (current_tool!=no_tool) {
      switch (event->code) {
         case ABS_X:
            x_axis.out_abs = abs_event(&x_axis, current_tool->mode, event->value);
            break;

         case ABS_Y:
            y_axis.out_abs = abs_event(&y_axis, current_tool->mode, event->value);
            break;

#ifdef ABS_WHEEL  /* absent in 2.2.x */
         case ABS_WHEEL:
#endif
         case ABS_Z:
            z_axis.out_abs = abs_event(&z_axis, current_tool->mode, event->value);
            break;
      }
   }
}

/* [fdwatch thread] */
static void handle_axis_event(int dx, int dy, int dz)
{
   if (current_tool != no_tool) {
      x_axis.out_abs = _ALLEGRO_CLAMP(x_axis.out_min, x_axis.out_abs, x_axis.out_max);
      y_axis.out_abs = _ALLEGRO_CLAMP(y_axis.out_min, y_axis.out_abs, y_axis.out_max);
      /* There's no range for z */

      the_mouse.state.x = x_axis.out_abs;
      the_mouse.state.y = y_axis.out_abs;
      the_mouse.state.z = z_axis.out_abs * al_get_mouse_wheel_precision();

      dz *= al_get_mouse_wheel_precision();

      generate_mouse_event(
         ALLEGRO_EVENT_MOUSE_AXES,
         the_mouse.state.x, the_mouse.state.y, the_mouse.state.z,
         dx, dy, dz,
         0);
   }
}

/* open_mouse_device:
 *  Open the specified device file and check that it is a mouse device.
 *  Returns the file descriptor if successful or a negative number on error.
 */
static int open_mouse_device (const char *device_file)
{
   int fd;

   fd = open (device_file, O_RDONLY | O_NONBLOCK);
   if (fd >= 0) {
      ALLEGRO_DEBUG("Opened device %s\n", device_file);
      /* The device is a mouse if it has a BTN_MOUSE */
      if (has_event(fd, EV_KEY, BTN_MOUSE)) {
	 ALLEGRO_DEBUG("Device %s was a mouse.\n", device_file);
      }
      else {
	 ALLEGRO_DEBUG("Device %s was not mouse, closing.\n", device_file);
	 close(fd);
	 fd = -1;
      }
   }

   return fd;
}

/* mouse_init:
 *  Here we open the mouse device, initialise anything that needs it,
 *  and chain to the framework init routine.
 */
static bool mouse_init (void)
{
/*
   char tmp1[128], tmp2[128];
   const char *udevice;
*/

   /* Set the current tool */
   current_tool = default_tool;

   /* try several /dev/input/event<n>
    * devices. */
   const char *device_name[] = { "/dev/input/event0",
                                 "/dev/input/event1",
                                 "/dev/input/event2",
                                 "/dev/input/event3",
                                 NULL };
   int i;

   ALLEGRO_DEBUG("Trying /dev/input/event[0-3] devices\n");

   for (i=0; device_name[i]; i++) {
      the_mouse.fd = open_mouse_device (device_name[i]);
      if (the_mouse.fd >= 0)
	    break;
   }

   if (!device_name[i]) {
	 return false;
   }

   /* Init the tablet data */
   init_tablet(the_mouse.fd);

   /* Initialise the mouse object for use as an event source. */
   _al_event_source_init(&the_mouse.parent.es);

   /* Start watching for data on the fd. */
   _al_unix_start_watching_fd(the_mouse.fd, process_new_data, &the_mouse);

#ifdef ALLEGRO_RASPBERRYPI
   ALLEGRO_SYSTEM *s = al_get_system_driver();
   if (s && s->displays._size > 0) {
      ALLEGRO_DISPLAY *d = _al_vector_ref(&s->displays, 0);
      if (d) {
         _al_evdev_set_mouse_range(0, 0, d->w-1, d->h-1);
      }
   }
#endif

   return true;
}

/* mouse_exit:
 *  Chain to the framework, then uninitialise things.
 */
static void mouse_exit (void)
{
   _al_unix_stop_watching_fd(the_mouse.fd);

   _al_event_source_free(&the_mouse.parent.es);

   close(the_mouse.fd);

   /* This may help catch bugs in the user program, since the pointer
    * we return to the user is always the same.
    */
   memset(&the_mouse, 0, sizeof the_mouse);
   the_mouse.fd = -1;
}

/* mouse_get_mouse:
 *  Returns the address of a ALLEGRO_MOUSE structure representing the mouse.
 */
static ALLEGRO_MOUSE *mouse_get_mouse(void)
{
   return (ALLEGRO_MOUSE *)&the_mouse;
}

/* mouse_get_mouse_num_buttons:
 *  Return the number of buttons on the mouse.
 */
static unsigned int mouse_get_mouse_num_buttons(void)
{
   ASSERT(the_mouse.fd >= 0);

   return get_num_buttons(the_mouse.fd);
}

/* mouse_get_mouse_num_axes:
 *  Return the number of axes on the mouse.
 */
static unsigned int mouse_get_mouse_num_axes(void)
{
   ASSERT(the_mouse.fd >= 0);

   /* XXX get the right number later */
   return 3;
}

/* mouse_set_mouse_xy:
 *
 */
static bool mouse_set_mouse_xy(ALLEGRO_DISPLAY *display, int x, int y)
{
   (void)display;

   _al_event_source_lock(&the_mouse.parent.es);
   {
      int dx, dy;

      x_axis.out_abs = _ALLEGRO_CLAMP(x_axis.out_min, x, x_axis.out_max);
      y_axis.out_abs = _ALLEGRO_CLAMP(y_axis.out_min, y, y_axis.out_max);
      x_axis.mickeys = 0;
      y_axis.mickeys = 0;

      dx = x_axis.out_abs - the_mouse.state.x;
      dy = y_axis.out_abs - the_mouse.state.y;

      if ((dx != 0) && (dy != 0)) {
         the_mouse.state.x = x_axis.out_abs;
         the_mouse.state.y = y_axis.out_abs;

         generate_mouse_event(
            ALLEGRO_EVENT_MOUSE_AXES,
            the_mouse.state.x, the_mouse.state.y, the_mouse.state.z,
            dx, dy, 0,
            0);
      }
   }
   _al_event_source_unlock(&the_mouse.parent.es);

   return true;
}

/* mouse_set_mouse_axis:
 *
 *   Number of mickeys to cross the screen horizontally: speed * 320.
 */
static bool mouse_set_mouse_axis(int which, int z)
{
   if (which != 2) {
      return false;
   }

   _al_event_source_lock(&the_mouse.parent.es);
   {
      int dz;

      z_axis.out_abs = z;

      dz = z_axis.out_abs - the_mouse.state.z;

      if (dz != 0) {
         the_mouse.state.z = z_axis.out_abs;

         generate_mouse_event(
            ALLEGRO_EVENT_MOUSE_AXES,
            the_mouse.state.x, the_mouse.state.y, the_mouse.state.z,
            0, 0, dz,
            0);
      }
   }
   _al_event_source_unlock(&the_mouse.parent.es);

   return true;
}

/* mouse_set_mouse_range:
 *
 */
bool _al_evdev_set_mouse_range(int x1, int y1, int x2, int y2)
{
   _al_event_source_lock(&the_mouse.parent.es);
   {
      int dx, dy;

      x_axis.out_min = x1;
      y_axis.out_min = y1;
      x_axis.out_max = x2;
      y_axis.out_max = y2;

      x_axis.out_abs = _ALLEGRO_CLAMP(x_axis.out_min, x_axis.out_abs, x_axis.out_max);
      y_axis.out_abs = _ALLEGRO_CLAMP(y_axis.out_min, y_axis.out_abs, y_axis.out_max);

      dx = x_axis.out_abs - the_mouse.state.x;
      dy = y_axis.out_abs - the_mouse.state.y;

      if ((dx != 0) && (dy != 0)) {
         the_mouse.state.x = x_axis.out_abs;
         the_mouse.state.y = y_axis.out_abs;

         generate_mouse_event(
            ALLEGRO_EVENT_MOUSE_AXES,
            the_mouse.state.x, the_mouse.state.y, the_mouse.state.z,
            dx, dy, 0,
            0);
      }
   }
   _al_event_source_unlock(&the_mouse.parent.es);

   return true;
}

/* mouse_get_state:
 *  Copy the current mouse state into RET_STATE, with any necessary locking.
 */
static void mouse_get_state(ALLEGRO_MOUSE_STATE *ret_state)
{
   _al_event_source_lock(&the_mouse.parent.es);
   {
      *ret_state = the_mouse.state;
   }
   _al_event_source_unlock(&the_mouse.parent.es);
}

/* process_new_data: [fdwatch thread]
 *  Process new data arriving in the keyboard's fd.
 */
static void process_new_data(void *data)
{
   ASSERT((AL_MOUSE_EVDEV *)data == &the_mouse);

   _al_event_source_lock(&the_mouse.parent.es);
   {
      struct input_event events[32];
      int bytes, nr, i;

      while ((bytes = read(the_mouse.fd, &events, sizeof events)) > 0) {
         nr = bytes / sizeof(events[0]);
         for (i = 0; i < nr; i++) {
            process_event(&events[i]);
         }
      }
   }
   _al_event_source_unlock(&the_mouse.parent.es);
}

/* [fdwatch thread] */
static void process_event(struct input_event *event)
{
   switch (event->type) {
      case EV_KEY:
         process_key(event);
         break;
      case EV_REL:
         process_rel(event);
         break;
      case EV_ABS:
         process_abs(event);
         break;
   }
}

/* [fdwatch thread] */
static void generate_mouse_event(unsigned int type,
                                 int x, int y, int z,
                                 int dx, int dy, int dz,
                                 unsigned int button)
{
   ALLEGRO_EVENT event;

   if (!_al_event_source_needs_to_generate_event(&the_mouse.parent.es))
      return;

   event.mouse.type = type;
   event.mouse.timestamp = al_get_time();
   event.mouse.display = NULL;
   event.mouse.x = x;
   event.mouse.y = y;
   event.mouse.z = z;
   event.mouse.dx = dx;
   event.mouse.dy = dy;
   event.mouse.dz = dz;
   event.mouse.button = button;
   event.mouse.pressure = 0.0; /* TODO */
   _al_event_source_emit_event(&the_mouse.parent.es, &event);
}

/* the driver vtable */
ALLEGRO_MOUSE_DRIVER _al_mousedrv_linux_evdev =
{
   AL_MOUSEDRV_LINUX_EVDEV,
   "",
   "",
   "Linux EVDEV mouse (and tablet)",
   mouse_init,
   mouse_exit,
   mouse_get_mouse,
   mouse_get_mouse_num_buttons,
   mouse_get_mouse_num_axes,
   mouse_set_mouse_xy,
   mouse_set_mouse_axis,
   mouse_get_state
};

#endif /* ALLEGRO_HAVE_LINUX_INPUT_H */

/*
 * Local Variables:
 * c-basic-offset: 3
 * indent-tabs-mode: nil
 * End:
 */