text:
/*
* Bartosz Dobrzycki, 16 Dec 2013
*
* The following example demonstrates how to solve
* Revolute-Prismatic-Revolute (RPR) robotic manipulator forward kinematics
* problem using quaternions, please see the attached image: manipulatorRPR.pdf
*
* NOTE: Assertions and some parts of the functionality have been removed
* from the code for clarity (e.g -= operator or Magnitude() for Vector3 etc.).
* The code represents the bare minimum implementation-wise to solve the problem.
*
* Please see the attached 'QuaternionRotationOperator.pdf' paper that demonstrates
* how to derive an efficient algorithm (used here) that rotates input vector with a quaternion,
* utilizing the special rule for quaternion multiplication.
*/

// Linux compilation:
// g++ main.cpp -lGL -lglut -lGLU -o a.out

#ifdef _WIN32
    #include <gl\glut.h>
#elif _WIN64
    #include <gl\glut.h>
#elif __linux
    #include <GL/glut.h>
#endif

#include <cmath>
#include <vector>
#include <iostream>
#include <algorithm>  // std::min

namespace MathTools
{
  // Define constant values.
  const double PI = 3.14159265358979323846264338;
  const double PI_OVER_TWO = 1.57079632679489661923132169;
  const double PI_OVER_FOUR = 0.78539816339744830961566084;
  const double ONE_EIGHTY_OVER_PI = 57.29577951308232087679815481;

  // Function converts angle in radians to angle in degrees.
  inline double Rad2Deg(double rad) { return rad * ONE_EIGHTY_OVER_PI; }
}
//////////////////////////////////////////////////////////////////////////
class Quaternion;
//////////////////////////////////////////////////////////////////////
// Three dimensional vector class.
class Vector3
{
friend
  class Quaternion; // Allows Quaternion class to access the private
                    // members of Vector3 class.
private:
  double x, y, z;   // Holds vector x, y, z components.

public:
  // Explicit default ctor.
  explicit Vector3(double _x = 0.0, double _y = 0.0, double _z = 0.0)
    :x(_x), y(_y), z(_z)
  {}

  // Getter functions for vector components.
  inline double GetX() const { return x; }
  inline double GetY() const { return y; }
  inline double GetZ() const { return z; }

  // Setter function that sets vector x, y, z components.
  void SetXYZ(double _x, double _y, double _z)
  {
    x = _x; y = _y; z = _z;
  }

  inline const Vector3 operator+(const Vector3& w) const
  {
    return Vector3(x + w.x, y + w.y, z + w.z);
  }

  Vector3& operator+=(const Vector3& w)
  {
    x += w.x; y += w.y; z += w.z;
    return *this;
  }

  inline const Vector3 operator-(const Vector3& w) const
  {
    return Vector3(x - w.x, y - w.y, z - w.z);
  }

  // Vector multiplication by a scalar operator.
  inline const Vector3 operator*(double a) const
  {
    return Vector3(x * a, y * a, z * a);
  }

  // Vector scalar product operator.
  inline const double operator*(const Vector3& v) const
  {
    return x * v.x + y * v.y + z * v.z;
  }

  // Vector cross product operator.
  inline const Vector3 operator%(const Vector3& v) const
  {
    return Vector3(y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x);
  }
};
//////////////////////////////////////////////////////////////////////
// In this implementation Quaternion is represented by a real part r and
// three dimensional vector part v.
class Quaternion
{
private:
  double r;  //< Holds real part of the quaternion.
  Vector3 v; //< Holds vector part of the quaternion.

public:
  // Default ctor creates identity quaternion.
  Quaternion()
    : r(1.0), v(0.0, 0.0, 0.0)
  {}

  // Explicit ctor creates quaternion from real and vector parts.
  explicit Quaternion(double _r, const Vector3& _v)
    : r(_r), v(_v)
  {}

  // Function returns the real part of the quaternion.
  inline double GetRealPart() const { return r; }

  // Function returns the vector part of the quaternion.
  inline Vector3 GetVectorPart() const { return v; }

  // Function creates quaternion form unit axis and angle (in radians).
  inline void FromAxisAngle(const Vector3& axis, double angle)
  {
    angle /= 2.0;
    r = cos(angle);
    v = axis * sin(angle);
  }

  // Function returns angle in radians.
  inline double GetAngle() const
  {
    // Make sure acos() function parameter is in [-1.0, 1.0] range.
    const double realClamped =
      (r > 0.0) ? std::min(r, 1.0) : std::max(r, -1.0);
    return 2.0 * acos(realClamped);
  }

  // Set quaternion with new real and vector parts.
  inline void Set(double _r, const Vector3& _v)
  {
    r = _r;
    v = _v;
  }

  // Multiplication operator which follows exact mathematical definition but
  // becomes inefficient due to excessive usage of dot and cross product vector operators.
  // s = qp = qrpr - q · p + qrp + prq + q × p
  inline const Quaternion operator^(const Quaternion& p) const
  {
    return Quaternion(
      r*p.r - v*p.v,                   //< qrpr - q · p
      Vector3(p.v*r + v*p.r + v%p.v)); //< qrp + prq + q × p
  }

  // Multiplication operator in its unwrapped and efficient implementation.
  const Quaternion operator*(const Quaternion& p) const
  {
    return Quaternion(
      r*p.r - v.x*p.v.x-v.y*p.v.y - v.z*p.v.z,
      Vector3(r*p.v.x + p.r*v.x + v.y*p.v.z - v.z*p.v.y,
              r*p.v.y - v.x*p.v.z + p.r*v.y + v.z*p.v.x,
              r*p.v.z + v.x*p.v.y - v.y*p.v.x + p.r*v.z));
  }

  // Complex conjugate postfix operator.
  inline const Quaternion operator~() const
  {
    return Quaternion(r, v*(-1.0));
  }

  // Function makes this quaternion a unit length quaternion.
  void Normalise()
  {
    const double length = sqrt(r*r + v.x*v.x + v.y*v.y + v.z*v.z);
    if (length)
    {
      r /= length;
      v = v * (1.0 / length);
    }
  }

  // Function rotates input vector w with a quaternion i.e. it explicitly applies
  // quaternion rotation operator to that vector.
  // It returns new, rotated vector, extracted from the pure quaternion.
  // Implementation strictly follows mathematical definition, but it is computationally inefficient.
  inline const Vector3 Rotate(const Vector3& w) const
  {
    // Assuming e has unit length here.
    const Quaternion& e = *this;
    return (e*(Quaternion(0.0, w)*(~e))).v;
  }

  // Function rotates input vector with a quaternion in most efficient way.
  // Please see attached 'QuaternionRotationOperator.pdf' paper to see
  // how to derive the efficient formula.
  // w' = e(0+w)e* = (2*r*r - 1)w + 2r(v × w) + 2(v · w)v
  inline const Vector3 RotateFast(const Vector3& w) const
  {
    // Assuming e has unit length here.
    const double exrMult = 2.0 * r;
    const double rMult = exrMult * r - 1.0;
    const double eMult = 2.0 * (v.x*w.x + v.y*w.y + v.z*w.z);
    return Vector3(
      rMult*w.x + exrMult*(v.y*w.z - v.z*w.y) + eMult*v.x,
      rMult*w.y + exrMult*(v.z*w.x - v.x*w.z) + eMult*v.y,
      rMult*w.z + exrMult*(v.x*w.y - v.y*w.x) + eMult*v.z);
  }
};
//////////////////////////////////////////////////////////////////////
// Color line for debug drawing.
class GLLine
{
private:
  GLfloat from[3];
  GLfloat to[3];
  GLfloat color[3];

public:
  explicit GLLine(
    const Vector3& from,
    const Vector3& to,
    const Vector3& color)
  {
    GLLine* const line = this;
    line->from[0] = GLfloat(from.GetX());
    line->from[1] = GLfloat(from.GetY());
    line->from[2] = GLfloat(from.GetZ());

    line->to[0] = GLfloat(to.GetX());
    line->to[1] = GLfloat(to.GetY());
    line->to[2] = GLfloat(to.GetZ());

    line->color[0] = GLfloat(color.GetX());
    line->color[1] = GLfloat(color.GetY());
    line->color[2] = GLfloat(color.GetZ());
  }

  void Draw() const
  {
    glColor3f(color[0], color[1], color[2]);
    glBegin(GL_LINES);
    glVertex3f(from[0], from[1], from[2]);
    glVertex3f(to[0], to[1], to[2]);
    glEnd();
  }
};
//////////////////////////////////////////////////////////////////////
// Define constant values.
const double timeDelta = 0.01;
const Vector3 zero(0.0, 0.0, 0.0);

// Global reference frame G axes.
const Vector3 xAxis (1.0, 0.0, 0.0);
const Vector3 yAxis (0.0, 1.0, 0.0);
const Vector3 zAxis (0.0, 0.0, 1.0);

// Colors.
const Vector3 red(1.0, 0.0, 0.0);
const Vector3 green(0.0, 1.0, 0.0);
const Vector3 blue(0.0, 0.0, 1.0);
const Vector3 orange(1.0, 0.5, 0.0);
const Vector3 white(1.0, 1.0, 1.0);

// Buffer for storing lines for drawing.
std::vector<GLLine> lines;
// Line buffer constant iterator.
typedef std::vector<GLLine>::const_iterator GLLineConstIter;

//////////////////////////////////////////////////////////////////////
// Simulation step function.
void SimStep (double timeDelta)
{
  static double time = 0.0;
  time += timeDelta;

  // Manipulator setup;
  // please see the attached manipulatorRPR.pdf diagram.

  // B2rP is the position of the tip of the manipulator P
  // expressed in local reference frame B2.
  const Vector3 B2rP(0.0, 2.0, 0.0);

  // Reference frame B2 can rotate about its local x2 axis,
  // relatively to B1 frame.
  // This models a single degree of freedom revolute joint,
  // that can rotate in range: <Pi/4, -Pi/4>.
  const double phi2 = (MathTools::PI_OVER_FOUR) * sin(time);  //< Rotation angle.
  const Vector3 u2(1.0, 0.0, 0.0);  //< Rotation axis (local x2).
  // Quaternion representing a rotation of B2 frame relatively to B1 frame.
  Quaternion B1eB2;
  B1eB2.FromAxisAngle(u2, phi2);

  // Prismatic joint.
  // Position of B2 frame expressed in local B1 frame.
  const Vector3 B1dB2(0.0, 4.0*std::abs(sin(time)), 0.0);

  // Reference frame B1 can rotate about global Z axis,
  // relatively to the global reference frame G.
  // This models a single degree of freedom revolute joint,
  // that can rotate in range: <Pi, -Pi>.
  const double phi1 = MathTools::PI * sin(time);
  const Vector3 u1(0.0, 0.0, 1.0);  //< Rotation axis (Global Z).
  // Quaternion representing a rotation of B1 frame
  // relatively to the global reference frame G.
  Quaternion GeB1;
  GeB1.FromAxisAngle(u1, phi1);

  // Position of frame B1 relatively to the global reference frame G.
  const Vector3 GdB1(0.0, 0.0, 2.0);

  // Calculate rotation of B2 frame relatively to global reference frame G.
  const Quaternion GeB2 = GeB1 * B1eB2;

  ////////////////////////////////////////////////////////////////////
  // Solve the FK utilizing the quaternion special product only.
  // This is strict mathematically, but inefficient.
  /*const Vector3 GrP =
    (GeB2*(Quaternion(0.0, B2rP)*(~GeB2))).GetVectorPart() +
    (GeB1*(Quaternion(0.0, B1dB2)*(~GeB1))).GetVectorPart() +
    GdB1;*/

  ////////////////////////////////////////////////////////////////////
  // Solve the FK utilizing the quaternion special product only,
  // this time use more human friendly multiplication formula, defined
  // as ^ operator.
  // This is strict mathematically, but inefficient.
  /*const Vector3 GrP =
    (GeB2^(Quaternion(0.0, B2rP)^(~GeB2))).GetVectorPart() +
    (GeB1^(Quaternion(0.0, B1dB2)^(~GeB1))).GetVectorPart() +
    GdB1;*/

  ////////////////////////////////////////////////////////////////////
  // Solve the FK in the most efficient way.
  const Vector3 GrP = GeB2.RotateFast(B2rP) + GeB1.RotateFast(B1dB2) + GdB1;

  ////////////////////////////////////////////////////////////////////
  // Manipulator debug-draw in global reference frame G.
  // B1 reference frame.
  lines.push_back(GLLine(GdB1, GdB1 + GeB1.RotateFast(xAxis), red));
  lines.push_back(GLLine(GdB1, GdB1 + GeB1.RotateFast(yAxis), green));
  lines.push_back(GLLine(GdB1, GdB1 + GeB1.RotateFast(zAxis), blue));

  // B2 reference frame translation relatively to B1 reference frame.
  const Vector3 GB2 = GdB1 + GeB1.RotateFast(B1dB2);
  lines.push_back(GLLine(GdB1, GB2, orange));

  // B2 reference frame.
  lines.push_back(GLLine(GB2, GB2 + GeB2.RotateFast(xAxis), red));
  lines.push_back(GLLine(GB2, GB2 + GeB2.RotateFast(yAxis), green));
  lines.push_back(GLLine(GB2, GB2 + GeB2.RotateFast(zAxis), blue));

  // Tip of the manipulator P.
  lines.push_back(GLLine(GB2, GrP, white));

  // Print out joint current angles.
  //std::cout << "RevJ1: angle(DEG): " << MathTools::Rad2Deg(GeB1.GetAngle())
  //          << " RevJ2: angle(DEG): " << MathTools::Rad2Deg(B1eB2.GetAngle()) << std::endl;
}
//////////////////////////////////////////////////////////////////////
void Init(void)
{
  glShadeModel(GL_SMOOTH);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(45.0f, (GLfloat)400/(GLfloat)400, 1.0f, 1000.0f);
  glEnable(GL_DEPTH_TEST);
  glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
}
//////////////////////////////////////////////////////////////////////
void Display(void)
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  gluLookAt(10.0, 10.0, 6.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);

  lines.push_back(GLLine(zero, xAxis, Vector3(1, 0, 0)));
  lines.push_back(GLLine(zero, yAxis, Vector3(0, 1, 0)));
  lines.push_back(GLLine(zero, zAxis, Vector3(0, 0, 1)));

  // Draw lines.
  GLLineConstIter iter = lines.begin();
  for (iter; iter != lines.end(); ++iter)
  {
    iter->Draw();
  }

  lines.clear();

  glutSwapBuffers();
}
//////////////////////////////////////////////////////////////////////
void TimerFunction(int value)
{
  SimStep(timeDelta);
  Display();
  glutTimerFunc(10, TimerFunction, 1);
}
//////////////////////////////////////////////////////////////////////
int main (int argc, char **argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
  glutInitWindowSize(400, 400);
  glutInitWindowPosition(380, 180);
  glutCreateWindow("Revolute-Prismatic-Revolute (RPR) Manipulator");
  glClearColor(0.0, 0.0, 0.0, 0.0);
  glutDisplayFunc(Display);
  glutTimerFunc(10, TimerFunction, 1);
  Init();
  glutMainLoop();
  std::cin.get();
  return 0;
}


text:
require 'spec_helper'

describe 'taurus::firewall' do
  context 'centos' do
    context 'When firewall_support attributes is enabled' do
      let(:runner) { ChefSpec::SoloRunner.new(CENTOS_OPTS) }
      let(:node) { runner.node }
      let(:chef_run) do
        node.set['taurus']['firewall_support'] = true
        node.set['taurus']['jmeter_service'] = true
        node.set['taurus']['locustio_service'] = true
        runner.converge(described_recipe)
      end

      it 'installs a firewall' do
        expect(chef_run).to install_firewall('default')
      end

      it 'add firewall access to jmeter service ports' do
        expect(chef_run).to create_firewall_rule('jmeter_master_udp').with(
          protocol: :udp, port: [1098, 1099],
          direction: :in, command: :allow
        )
        expect(chef_run).to create_firewall_rule('jmeter_master_tcp').with(
          protocol: :tcp, port: [1098, 1099],
          direction: :in, command: :allow
        )
      end
      it 'add firewall access to locustio service ports' do
        expect(chef_run).to create_firewall_rule('locustio_master_tcp').with(
          protocol: :tcp, port: [5557, 5558],
          direction: :in, command: :allow
        )
        expect(chef_run).to create_firewall_rule('locustio_web_tcp').with(
          protocol: :tcp, port: 8089,
          direction: :in, command: :allow
        )
      end
    end
  end

  context 'When firewall_support attributes is disabled' do
    let(:runner) { ChefSpec::SoloRunner.new(CENTOS_OPTS) }
    let(:node) { runner.node }
    let(:chef_run) do
      node.set['taurus']['firewall_support'] = false
      runner.converge(described_recipe)
    end
    it 'does not install iptables' do
      expect(chef_run).to_not install_package('iptables')
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
module Mnemosyne
  class Trace < Span
    BT_REGEXP = /^((?:[a-zA-Z]:)?[^:]+):(\d+)(?::in `([^']+)')?$/.freeze

    attr_reader :uuid, :transaction, :origin, :span, :errors

    def initialize(instrumenter, name, transaction: nil, origin: nil, **kwargs)
      super(name, **kwargs)

      @uuid   = ::SecureRandom.uuid
      @span   = []
      @errors = []

      @origin      = origin
      @transaction = transaction

      @instrumenter = instrumenter
    end

    def <<(span)
      @span << span
    end

    def attach_error(error)
      case error
        when Exception
          @errors << Error.new(error)
        when String
          @errors << Error.new(RuntimeError.new(error))
        else
          raise ArgumentError.new "Invalid error type: #{error.inspect}"
      end
    end

    def submit
      finish! unless finish

      @instrumenter.submit self
    end

    def release
      @instrumenter.release self
    end

    def serialize
      {
        uuid: uuid,
        origin: origin,
        transaction: transaction,
        name: name,
        start: start,
        stop: finish,
        meta: meta,
        span: @span.map(&:serialize),
        errors: @errors.map(&:serialize)
      }
    end

    Error = Struct.new(:error) do
      def serialize
        {
          type: error.class.name,
          text: error.message.to_s,
          cause: serialize_cause,
          stacktrace: serialize_backtrace
        }.compact
      end

      private

      def serialize_backtrace
        return unless error.backtrace

        error.backtrace.map do |bt|
          md = BT_REGEXP.match(bt.to_s).to_a

          {file: md[1], line: md[2], call: md[3], raw: md[0]}
        end
      end

      def serialize_cause
        self.class.new(error.cause).serialize if error.cause
      end
    end
  end
end


text:
package org.ppojo.data;

import org.ppojo.CopyStyleTypes;
import org.ppojo.*;

/**
 * Represents a copy style that can be applied to an artifact of type {@link ArtifactTypes#Pojo}
 * @see CopyStyleTypes
 * @see CopyStyleDataSerializer
 */
public class CopyStyleData {
    public CopyStyleTypes style;
    /**
     * The name of the method that will be created when the style is applied
     */
    public String methodName;
}


text:
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
module Marvin.API.Algorithms.NaiveBayes (
  NaiveBayes (..)
  , defaultNaiveBayes

  , BernoulliModel
  , threshold
  , setThreshold
  , probabilityOfTrue
  , trueProbabilities
  , falseProbabilities
) where

import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed as UVec
import qualified Data.Vector as Vec

import Data.List
import Control.Monad.Except

import Control.Arrow
import Marvin.API.Table.Internal
import Marvin.API.Meta.Model
import Marvin.API.Fallible

-- * Parameters

-- | Parameters.
data NaiveBayes = NaiveBayes {
  smoothingValue :: Double
}

-- | Default parameters.
defaultNaiveBayes = NaiveBayes { smoothingValue = 1.0 }

-- * Model

-- | Resulting model.
data BernoulliModel = BM {
  probabilityOfTrue_ :: Double
  , trueProbabilities_ :: UVec.Vector Double
  , falseProbabilities_ :: UVec.Vector Double
  , threshold_ :: Double
}

-- | Retrieves the threshold to decide 'True' or 'False' based on probability.
threshold = threshold_
-- | Sets the threshold that decides 'True' or 'False' based on probability.
setThreshold t model = model { threshold_ = t }

-- | Retrieves the probability that the target is 'True'.
probabilityOfTrue = probabilityOfTrue_
-- | Retrieves the conditional probabilities of 'True' target.
trueProbabilities = UVec.toList . trueProbabilities_
-- | Retrieves the conditional probabilities of 'False' target.
falseProbabilities = UVec.toList . falseProbabilities_

instance Show BernoulliModel where
  show model = "\n\nBernoulliModel\n\n" ++
    "\tp(y = 1) = " ++ show (probabilityOfTrue model) ++ "\n" ++
    "\tp(x_i = 1 | y = 0) = " ++ show (falseProbabilities model) ++ "\n" ++
    "\tp(x_i = 1 | y = 1) = " ++ show (trueProbabilities model) ++ "\n"

instance Estimator NaiveBayes (BinaryTable, BinaryColumn) where
  type ResultingModel NaiveBayes (BinaryTable, BinaryColumn) = BernoulliModel
  fit = fit'

fit' :: NaiveBayes -> (BinaryTable, BinaryColumn) -> Fallible BernoulliModel
fit' nbParams (bt, bc) = do
  ensureNonNegative
    (InvalidAlgorithmParameter "NaiveBayes" "smoothing value must be non-negative")
      $ smoothingValue nbParams
  ensureTableColSizeMatch "while training Naive Bayes" bt bc
  return $ fitNB nbParams featureMtx targetVar
  where
    featureMtx = tableToRows bt
    targetVar = UVec.toList $ values $ bc

tableToRows = Vec.toList . transposeVectorVectorU . Vec.map values . columnsVec

dimCheck :: BernoulliModel -> BinaryTable -> Fallible ()
dimCheck bernoulliModel binTable =
  if (UVec.length (trueProbabilities_ bernoulliModel) == numberOfColumns binTable)
    then return ()
    else throwError $ RowLengthMismatch "when attempting to make prediction based on NaiveBayes"

instance Predictor BernoulliModel where
  type Testing BernoulliModel = BinaryTable
  type Prediction BernoulliModel = BinaryColumn
  predict m t = do
    dimCheck m t
    return $ predict' m t

predict' model xs = unsafeFromList $
  fmap (\x -> x > threshold model) $
  fmap (predictProbaForOne model) rows
    where rows = tableToRows xs

predictProbaForOne :: BernoulliModel -> UVec.Vector Bool -> Double
predictProbaForOne model xs = pX_Y1 / (pX_Y1 + pX_Y0)
  where
    pXi_Y phis = UVec.zipWith (\x phi -> if x then phi else (1 - phi)) xs phis
    pXi_Y1 = pXi_Y $ trueProbabilities_ model
    pXi_Y0 = pXi_Y $ falseProbabilities_ model
    pX_Y1 = pY1 * (UVec.product pXi_Y1)
    pX_Y0 = (1 - pY1) * (UVec.product pXi_Y0)
    pY1 = probabilityOfTrue model

fitNB :: NaiveBayes -> [UVec.Vector Bool] -> [Bool] -> BernoulliModel
fitNB nb x y = BM {
    probabilityOfTrue_ = fromIntegral (length trueVecs) / fromIntegral m
    , trueProbabilities_ = probs trueVecs
    , falseProbabilities_ = probs falseVecs
    , threshold_ = 0.5
  }
  where
    n = UVec.length $ head x
    m = length x
    a = smoothingValue nb
    (trueVecs, falseVecs) =
      partition (\(xi,yi) -> yi) $
      zip x y
    probs xs = freqs (length xs) $ map fst xs
    freqs ny =
      map (UVec.map (\x -> if x then (1 :: Int) else 0)) >>>
      foldl1 (UVec.zipWith (+)) >>>
      UVec.map (\nyi -> ((fromIntegral nyi) + a) / ((fromIntegral ny) + a*(fromIntegral n)))


text:
/*
 * package-info.java
 * Creation date: Aug 16, 2004.
 * By: Edward Lam
 */

/**
 * Provides classes for interacting with the CAL compiler - please also see the
 * {@link org.openquark.cal.services services} package for the
 * top-level API for accessing the compiler's functionality.
 *
Key classes in this package

 *

 *
{@link org.openquark.cal.compiler.SourceModel} and its
 *         inner classes

 *

 *         These classes provide a programmatic mechanism for constructing fragments of
 *         CAL source. The compiler API provides the ability to compile new CAL modules
 *         and to evaluate CAL expressions defined via SourceModels.
 *

 *             Also available to work with SourceModels are visitor classes
 *             ({@link org.openquark.cal.compiler.SourceModelVisitor},
 *             {@link org.openquark.cal.compiler.SourceModelTraverser},
 *             {@link org.openquark.cal.compiler.SourceModelCopier}) and
 *             utility classes ({@link org.openquark.cal.compiler.SourceModelUtilities}
 *             and its subclasses).

 *

 *

 *

 *
{@link org.openquark.cal.compiler.ModuleTypeInfo} and
 *         related classes: {@link org.openquark.cal.compiler.Function},
 *         {@link org.openquark.cal.compiler.TypeConstructor},
 *         {@link org.openquark.cal.compiler.DataConstructor},
 *         {@link org.openquark.cal.compiler.TypeClass},
 *         {@link org.openquark.cal.compiler.ClassMethod},
 *         {@link org.openquark.cal.compiler.ClassInstance},
 *         {@link org.openquark.cal.compiler.CALDocComment}

 *

 *         These classes provide a reflection API with which one can query information
 *         about CAL modules loaded into the runtime and the entities declared in these
 *         modules.
 *

 *

 *

 *
{@link org.openquark.cal.compiler.TypeExpr}

 *

 *         A TypeExpr is the representation of a CAL type
 *         expression, such as a -> b, Int, (Int, a ->
 *             Boolean).
 *

 *

 *

 *
{@link org.openquark.cal.compiler.QualifiedName}

 *

 *         The Java representation of a qualified name in CAL, e.g. List.map.
 *         See also the {@link org.openquark.cal.module module} package for
 *         binding classes containing QualifiedName constants for entities
 *         defined in modules which form the CAL API.
 *

 *

 *

 *
{@link org.openquark.cal.compiler.MessageLogger}

 *

 *         Many methods in this package accept a MessageLogger argument for
 *         logging messages related to the compilation process (parsing, static analysis,
 *         type-checking, code generation).
 *

 *

 *

 *
{@link org.openquark.cal.compiler.CALSourceGenerator}

 *

 *         The CALSourceGenerator can be used to generate CAL source for
 *         {@link org.openquark.gems.client.Gem Gem}s.
 *

 *

 *
 * @author Joseph Wong
 * @author Edward Lam
 */
package org.openquark.cal.compiler;


text:
package crafttweaker.mc1120.actions;

import crafttweaker.IAction;
import net.minecraft.client.renderer.entity.RenderPlayer;
import net.minecraft.client.renderer.entity.layers.LayerBipedArmor;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.oredict.OreDictionary;

public class ActionOreDictAddItem implements IAction {

    private final String id;
    private final ItemStack item;

    public ActionOreDictAddItem(String id, ItemStack item) {
        this.id = id;
        this.item = item;
    }

    @Override
    public void apply() {
        OreDictionary.registerOre(id, item);
    }

    @Override
    public String describe() {
        return "Adding " + item.getDisplayName() + " to ore dictionary entry " + id;
    }

}


text:
#include "intent/intent_service/IntentEncoder.hpp"
#include "intent/intent_service/TermIndex.hpp"
#include "intent/utils/RegexMatcher.hpp"
#include "intent/utils/TrigramHelper.hpp"

#include <sstream>
#include <iostream>
#include <algorithm>

namespace intent {

std::string IntentEncoder::encode(const std::vector<int>& entities) {
  std::stringstream streamresult;
  std::for_each(entities.begin(), entities.end(),
                [&streamresult](const int& entity) {
                  std::string toAppend;

                  std::stringstream stream;
                  // leave the regex markers untouched
                  if (RegexMatcher::isEntityRegexMarker(entity)) {
                    stream << RegexMatcher::REGEX_MARKERS[0xFFFF - entity];
                    toAppend = stream.str();
                  }
                  // encode others int to hex strings (padded up to 4 chars)
                  else {
                    stream << std::hex << entity;
                    toAppend = stream.str();
                    TrigramHelper::padLeft(toAppend, 4, '0');
                  }

                  streamresult << toAppend;
                });
  return streamresult.str();
}

std::string IntentEncoder::encode(const IntentModel::Intent& intent) {
  return IntentEncoder::encode(intent.entities);
}
}


text:
More advanced topics
====================

.. sectionauthor:: Daniele Varrazzo <daniele.varrazzo@gmail.com>

.. testsetup:: *

    import re
    import select

    cur.execute("CREATE TABLE atable (apoint point)")
    conn.commit()

    def wait(conn):
        while 1:
            state = conn.poll()
            if state == psycopg2.extensions.POLL_OK:
                break
            elif state == psycopg2.extensions.POLL_WRITE:
                select.select([], [conn.fileno()], [])
            elif state == psycopg2.extensions.POLL_READ:
                select.select([conn.fileno()], [], [])
            else:
                raise psycopg2.OperationalError("poll() returned %s" % state)

    aconn = psycopg2.connect(database='test', async=1)
    wait(aconn)
    acurs = aconn.cursor()

.. index::
    double: Subclassing; Cursor
    double: Subclassing; Connection

.. _subclassing-connection:
.. _subclassing-cursor:

Connection and cursor factories
-------------------------------

Psycopg exposes two new-style classes that can be sub-classed and expanded to
adapt them to the needs of the programmer: `psycopg2.extensions.cursor`
and `psycopg2.extensions.connection`.  The `connection` class is
usually sub-classed only to provide an easy way to create customized cursors
but other uses are possible. `cursor` is much more interesting, because
it is the class where query building, execution and result type-casting into
Python variables happens.

.. index::
    single: Example; Cursor subclass

An example of cursor subclass performing logging is::

    import psycopg2
    import psycopg2.extensions
    import logging

    class LoggingCursor(psycopg2.extensions.cursor):
        def execute(self, sql, args=None):
            logger = logging.getLogger('sql_debug')
            logger.info(self.mogrify(sql, args))

            try:
                psycopg2.extensions.cursor.execute(self, sql, args)
            except Exception, exc:
                logger.error("%s: %s" % (exc.__class__.__name__, exc))
                raise

    conn = psycopg2.connect(DSN)
    cur = conn.cursor(cursor_factory=LoggingCursor)
    cur.execute("INSERT INTO mytable VALUES (%s, %s, %s);",
                 (10, 20, 30))

.. index::
    single: Objects; Creating new adapters
    single: Adaptation; Creating new adapters
    single: Data types; Creating new adapters

.. _adapting-new-types:

Adapting new Python types to SQL syntax
---------------------------------------

Any Python class or type can be adapted to an SQL string.  Adaptation mechanism
is similar to the Object Adaptation proposed in the :pep:`246` and is exposed
by the `psycopg2.extensions.adapt()` function.

The `~cursor.execute()` method adapts its arguments to the
`~psycopg2.extensions.ISQLQuote` protocol.  Objects that conform to this
protocol expose a `!getquoted()` method returning the SQL representation
of the object as a string (the method must return `!bytes` in Python 3).
Optionally the conform object may expose a
`~psycopg2.extensions.ISQLQuote.prepare()` method.

There are two basic ways to have a Python object adapted to SQL:

- the object itself is conform, or knows how to make itself conform. Such
  object must expose a `__conform__()` method that will be called with the
  protocol object as argument. The object can check that the protocol is
  `!ISQLQuote`, in which case it can return `!self` (if the object also
  implements `!getquoted()`) or a suitable wrapper object. This option is
  viable if you are the author of the object and if the object is specifically
  designed for the database (i.e. having Psycopg as a dependency and polluting
  its interface with the required methods doesn't bother you). For a simple
  example you can take a look at the source code for the
  `psycopg2.extras.Inet` object.

- If implementing the `!ISQLQuote` interface directly in the object is not an
  option (maybe because the object to adapt comes from a third party library),
  you can use an *adaptation function*, taking the object to be adapted as
  argument and returning a conforming object.  The adapter must be
  registered via the `~psycopg2.extensions.register_adapter()` function.  A
  simple example wrapper is `!psycopg2.extras.UUID_adapter` used by the
  `~psycopg2.extras.register_uuid()` function.

A convenient object to write adapters is the `~psycopg2.extensions.AsIs`
wrapper, whose `!getquoted()` result is simply the `!str()`\ ing conversion of
the wrapped object.

.. index::
    single: Example; Types adaptation

Example: mapping of a `!Point` class into the |point|_ PostgreSQL
geometric type:

.. doctest::

    >>> from psycopg2.extensions import adapt, register_adapter, AsIs

    >>> class Point(object):
    ...    def __init__(self, x, y):
    ...        self.x = x
    ...        self.y = y

    >>> def adapt_point(point):
    ...     return AsIs("'(%s, %s)'" % (adapt(point.x), adapt(point.y)))

    >>> register_adapter(Point, adapt_point)

    >>> cur.execute("INSERT INTO atable (apoint) VALUES (%s)",
    ...             (Point(1.23, 4.56),))

.. |point| replace:: :sql:`point`
.. _point: http://www.postgresql.org/docs/current/static/datatype-geometric.html#DATATYPE-GEOMETRIC

The above function call results in the SQL command::

    INSERT INTO atable (apoint) VALUES ('(1.23, 4.56)');

.. index:: Type casting

.. _type-casting-from-sql-to-python:

Type casting of SQL types into Python objects
---------------------------------------------

PostgreSQL objects read from the database can be adapted to Python objects
through an user-defined adapting function.  An adapter function takes two
arguments: the object string representation as returned by PostgreSQL and the
cursor currently being read, and should return a new Python object.  For
example, the following function parses the PostgreSQL :sql:`point`
representation into the previously defined `!Point` class:

    >>> def cast_point(value, cur):
    ...    if value is None:
    ...        return None
    ...
    ...    # Convert from (f1, f2) syntax using a regular expression.
    ...    m = re.match(r"\(([^)]+),([^)]+)\)", value)
    ...    if m:
    ...        return Point(float(m.group(1)), float(m.group(2)))
    ...    else:
    ...        raise InterfaceError("bad point representation: %r" % value)

In order to create a mapping from a PostgreSQL type (either standard or
user-defined), its OID must be known. It can be retrieved either by the second
column of the `cursor.description`:

    >>> cur.execute("SELECT NULL::point")
    >>> point_oid = cur.description[0][1]
    >>> point_oid
    600

or by querying the system catalog for the type name and namespace (the
namespace for system objects is :sql:`pg_catalog`):

    >>> cur.execute("""
    ...    SELECT pg_type.oid
    ...      FROM pg_type JOIN pg_namespace
    ...             ON typnamespace = pg_namespace.oid
    ...     WHERE typname = %(typename)s
    ...       AND nspname = %(namespace)s""",
    ...    {'typename': 'point', 'namespace': 'pg_catalog'})
    >>> point_oid = cur.fetchone()[0]
    >>> point_oid
    600

After you know the object OID, you can create and register the new type:

    >>> POINT = psycopg2.extensions.new_type((point_oid,), "POINT", cast_point)
    >>> psycopg2.extensions.register_type(POINT)

The `~psycopg2.extensions.new_type()` function binds the object OIDs
(more than one can be specified) to the adapter function.
`~psycopg2.extensions.register_type()` completes the spell.  Conversion
is automatically performed when a column whose type is a registered OID is
read:

    >>> cur.execute("SELECT '(10.2,20.3)'::point")
    >>> point = cur.fetchone()[0]
    >>> print type(point), point.x, point.y
    <class 'Point'> 10.2 20.3

A typecaster created by `!new_type()` can be also used with
`~psycopg2.extensions.new_array_type()` to create a typecaster converting a
PostgreSQL array into a Python list.

.. index::
    pair: Asynchronous; Notifications
    pair: LISTEN; SQL command
    pair: NOTIFY; SQL command

.. _async-notify:

Asynchronous notifications
--------------------------

Psycopg allows asynchronous interaction with other database sessions using the
facilities offered by PostgreSQL commands |LISTEN|_ and |NOTIFY|_. Please
refer to the PostgreSQL documentation for examples about how to use this form of
communication.

Notifications are instances of the `~psycopg2.extensions.Notify` object made
available upon reception in the `connection.notifies` list. Notifications can
be sent from Python code simply executing a :sql:`NOTIFY` command in an
`~cursor.execute()` call.

Because of the way sessions interact with notifications (see |NOTIFY|_
documentation), you should keep the connection in `~connection.autocommit`
mode if you wish to receive or send notifications in a timely manner.

.. |LISTEN| replace:: :sql:`LISTEN`
.. _LISTEN: http://www.postgresql.org/docs/current/static/sql-listen.html
.. |NOTIFY| replace:: :sql:`NOTIFY`
.. _NOTIFY: http://www.postgresql.org/docs/current/static/sql-notify.html

Notifications are received after every query execution. If the user is
interested in receiving notifications but not in performing any query, the
`~connection.poll()` method can be used to check for new messages without
wasting resources.

A simple application could poll the connection from time to time to check if
something new has arrived. A better strategy is to use some I/O completion
function such as :py:func:`~select.select` to sleep until awaken from the kernel when there is
some data to read on the connection, thereby using no CPU unless there is
something to read::

    import select
    import psycopg2
    import psycopg2.extensions

    conn = psycopg2.connect(DSN)
    conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

    curs = conn.cursor()
    curs.execute("LISTEN test;")

    print "Waiting for notifications on channel 'test'"
    while 1:
        if select.select([conn],[],[],5) == ([],[],[]):
            print "Timeout"
        else:
            conn.poll()
            while conn.notifies:
                notify = conn.notifies.pop()
                print "Got NOTIFY:", notify.pid, notify.channel, notify.payload

Running the script and executing a command such as :sql:`NOTIFY test, 'hello'`
in a separate :program:`psql` shell, the output may look similar to::

    Waiting for notifications on channel 'test'
    Timeout
    Timeout
    Got NOTIFY: 6535 test hello
    Timeout
    ...

Note that the payload is only available from PostgreSQL 9.0: notifications
received from a previous version server will have the
`~psycopg2.extensions.Notify.payload` attribute set to the empty string.

.. versionchanged:: 2.3
    Added `~psycopg2.extensions.Notify` object and handling notification
    payload.

.. index::
    double: Asynchronous; Connection

.. _async-support:

Asynchronous support
--------------------

.. versionadded:: 2.2.0

Psycopg can issue asynchronous queries to a PostgreSQL database. An asynchronous
communication style is established passing the parameter *async*\=1 to the
`~psycopg2.connect()` function: the returned connection will work in
*asynchronous mode*.

In asynchronous mode, a Psycopg connection will rely on the caller to poll the
socket file descriptor, checking if it is ready to accept data or if a query
result has been transferred and is ready to be read on the client. The caller
can use the method `~connection.fileno()` to get the connection file
descriptor and `~connection.poll()` to make communication proceed according to
the current connection state.

The following is an example loop using methods `!fileno()` and `!poll()`
together with the Python :py:func:`~select.select` function in order to carry on
asynchronous operations with Psycopg::

    def wait(conn):
        while 1:
            state = conn.poll()
            if state == psycopg2.extensions.POLL_OK:
                break
            elif state == psycopg2.extensions.POLL_WRITE:
                select.select([], [conn.fileno()], [])
            elif state == psycopg2.extensions.POLL_READ:
                select.select([conn.fileno()], [], [])
            else:
                raise psycopg2.OperationalError("poll() returned %s" % state)

The above loop of course would block an entire application: in a real
asynchronous framework, `!select()` would be called on many file descriptors
waiting for any of them to be ready.  Nonetheless the function can be used to
connect to a PostgreSQL server only using nonblocking commands and the
connection obtained can be used to perform further nonblocking queries.  After
`!poll()` has returned `~psycopg2.extensions.POLL_OK`, and thus `!wait()` has
returned, the connection can be safely used:

    >>> aconn = psycopg2.connect(database='test', async=1)
    >>> wait(aconn)
    >>> acurs = aconn.cursor()

Note that there are a few other requirements to be met in order to have a
completely non-blocking connection attempt: see the libpq documentation for
|PQconnectStart|_.

.. |PQconnectStart| replace:: `!PQconnectStart()`
.. _PQconnectStart: http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-PQCONNECTSTARTPARAMS

The same loop should be also used to perform nonblocking queries: after
sending a query via `~cursor.execute()` or `~cursor.callproc()`, call
`!poll()` on the connection available from `cursor.connection` until it
returns `!POLL_OK`, at which point the query has been completely sent to the
server and, if it produced data, the results have been transferred to the
client and available using the regular cursor methods:

    >>> acurs.execute("SELECT pg_sleep(5); SELECT 42;")
    >>> wait(acurs.connection)
    >>> acurs.fetchone()[0]
    42

When an asynchronous query is being executed, `connection.isexecuting()` returns
`!True`. Two cursors can't execute concurrent queries on the same asynchronous
connection.

There are several limitations in using asynchronous connections: the
connection is always in `~connection.autocommit` mode and it is not
possible to change it. So a
transaction is not implicitly started at the first query and is not possible
to use methods `~connection.commit()` and `~connection.rollback()`: you can
manually control transactions using `~cursor.execute()` to send database
commands such as :sql:`BEGIN`, :sql:`COMMIT` and :sql:`ROLLBACK`. Similarly
`~connection.set_session()` can't be used but it is still possible to invoke the
:sql:`SET` command with the proper :sql:`default_transaction_...` parameter.

With asynchronous connections it is also not possible to use
`~connection.set_client_encoding()`, `~cursor.executemany()`, :ref:`large
objects <large-objects>`, :ref:`named cursors <server-side-cursors>`.

:ref:`COPY commands <copy>` are not supported either in asynchronous mode, but
this will be probably implemented in a future release.

.. index::
    single: Greenlet
    single: Coroutine
    single: Eventlet
    single: gevent
    single: Wait callback

.. _green-support:

Support to coroutine libraries
------------------------------

.. versionadded:: 2.2.0

Psycopg can be used together with coroutine_\-based libraries, and participate
to cooperative multithreading.

Coroutine-based libraries (such as Eventlet_ or gevent_) can usually patch the
Python standard library in order to enable a coroutine switch in the presence of
blocking I/O: the process is usually referred as making the system *green*, in
reference to the `green threads`_.

Because Psycopg is a C extension module, it is not possible for coroutine
libraries to patch it: Psycopg instead enables cooperative multithreading by
allowing the registration of a *wait callback* using the
`psycopg2.extensions.set_wait_callback()` function. When a wait callback is
registered, Psycopg will use `libpq non-blocking calls`__ instead of the regular
blocking ones, and will delegate to the callback the responsibility to wait
for the socket to become readable or writable.

Working this way, the caller does not have the complete freedom to schedule the
socket check whenever they want as with an :ref:`asynchronous connection
<async-support>`, but has the advantage of maintaining a complete |DBAPI|
semantics: from the point of view of the end user, all Psycopg functions and
objects will work transparently in the coroutine environment (blocking the
calling green thread and giving other green threads the possibility to be
scheduled), allowing non modified code and third party libraries (such as
SQLAlchemy_) to be used in coroutine-based programs.

.. warning::
    Psycopg connections are not *green thread safe* and can't be used
    concurrently by different green threads. Trying to execute more than one
    command at time using one cursor per thread will result in an error (or a
    deadlock on versions before 2.4.2).

    Therefore, programmers are advised to either avoid sharing connections
    between coroutines or to use a library-friendly lock to synchronize shared
    connections, e.g. for pooling.

Coroutine libraries authors should provide a callback implementation (and
possibly a method to register it) to make Psycopg as green as they want. An
example callback (using `!select()` to block) is provided as
`psycopg2.extras.wait_select()`: it boils down to something similar to::

    def wait_select(conn):
        while 1:
            state = conn.poll()
            if state == extensions.POLL_OK:
                break
            elif state == extensions.POLL_READ:
                select.select([conn.fileno()], [], [])
            elif state == extensions.POLL_WRITE:
                select.select([], [conn.fileno()], [])
            else:
                raise OperationalError("bad state from poll: %s" % state)

Providing callback functions for the single coroutine libraries is out of
psycopg2 scope, as the callback can be tied to the libraries' implementation
details. You can check the `psycogreen`_ project for further informations and
resources about the topic.

.. _coroutine: http://en.wikipedia.org/wiki/Coroutine
.. _greenlet: http://pypi.python.org/pypi/greenlet
.. _green threads: http://en.wikipedia.org/wiki/Green_threads
.. _Eventlet: http://eventlet.net/
.. _gevent: http://www.gevent.org/
.. _SQLAlchemy: http://www.sqlalchemy.org/
.. _psycogreen: http://bitbucket.org/dvarrazzo/psycogreen/
.. __: http://www.postgresql.org/docs/current/static/libpq-async.html

.. warning::

    :ref:`COPY commands <copy>` are currently not supported when a wait callback
    is registered, but they will be probably implemented in a future release.

    :ref:`Large objects <large-objects>` are not supported either: they are
    not compatible with asynchronous connections.

.. testcode::
    :hide:

    aconn.close()
    conn.rollback()
    cur.execute("DROP TABLE atable")
    conn.commit()
    cur.close()
    conn.close()