text:
package fr.vidal.webservices.productservice;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for pagedResultProduct complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="pagedResultProduct">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="pageNumber" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="pageSize" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="result" type="{urn:Vidal}ArrayOfProduct"/>
 *         <element name="rowCount" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "pagedResultProduct", propOrder = {
    "pageNumber",
    "pageSize",
    "result",
    "rowCount"
})
public class PagedResultProduct {

    protected int pageNumber;
    protected int pageSize;
    @XmlElement(required = true, nillable = true)
    protected ArrayOfProduct result;
    protected int rowCount;

    /**
     * Gets the value of the pageNumber property.
     *
     */
    public int getPageNumber() {
        return pageNumber;
    }

    /**
     * Sets the value of the pageNumber property.
     *
     */
    public void setPageNumber(int value) {
        this.pageNumber = value;
    }

    /**
     * Gets the value of the pageSize property.
     *
     */
    public int getPageSize() {
        return pageSize;
    }

    /**
     * Sets the value of the pageSize property.
     *
     */
    public void setPageSize(int value) {
        this.pageSize = value;
    }

    /**
     * Gets the value of the result property.
     *
     * @return
     *     possible object is
     *     {@link ArrayOfProduct }
     *
     */
    public ArrayOfProduct getResult() {
        return result;
    }

    /**
     * Sets the value of the result property.
     *
     * @param value
     *     allowed object is
     *     {@link ArrayOfProduct }
     *
     */
    public void setResult(ArrayOfProduct value) {
        this.result = value;
    }

    /**
     * Gets the value of the rowCount property.
     *
     */
    public int getRowCount() {
        return rowCount;
    }

    /**
     * Sets the value of the rowCount property.
     *
     */
    public void setRowCount(int value) {
        this.rowCount = value;
    }

}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>Interactive Debugger for the JavaScript Specification</title>

    <link rel="stylesheet" href="js/libraries/bootstrap/css/bootstrap.min.css">

    <link rel=stylesheet href="js/libraries/codemirror/codemirror.css">

    <link type="text/css" href="js/jquery_scroll/jquery.jscrollpane.css" rel="stylesheet" media="all" />

    <link rel="stylesheet" href="js/jquery-ui-1.11.4.custom/jquery-ui.css">

    <link type="text/css" href="driver.css" rel="stylesheet" media="all" />

  <form class="form-inline">

      Menu

      Load example :
      <select id='select_source_code'><option disabled selected>Example Programs</option></select>

      Load file :
      <input type='file' accept='.js' id='select_file' />

      <input type='checkbox' id='use_test262_harness' /> Use test262 harness (not Chrome from file://)

 <button class="btn btn-primary btn-sm" type="button"  id='button_run'>RUN</button>

        Step:

      <input type="text" id='navigation_step' style="width:5em" value="0" class="form-control"/>

        /  ()

    <button class="btn btn-primary btn-sm" type="button" id='button_goto_begin'>Begin</button>

    <button class="btn btn-primary btn-sm" type="button" id='button_goto_end'>End</button>

    <button class="btn btn-primary btn-sm" type="button" id='button_backward'>Backward</button>

    <button class="btn btn-primary btn-sm" type="button" id='button_forward'>Forward</button>

    <button class="btn btn-primary btn-sm" type="button" id='button_previous'>Previous</button>

    <button class="btn btn-primary btn-sm" type="button" id='button_next'>Next</button>

    <button class="btn btn-primary btn-sm" type="button" id='button_finish'>Finish</button>

    <button class="btn btn-primary btn-sm" type="button" id='button_srcprevious'>Source Previous</button>

    <button class="btn btn-primary btn-sm" type="button" id='button_srcnext'>Source Next</button>

    <button class="btn btn-primary btn-sm" type="button" id='button_cursor'>Source Cursor</button>

    Conditions:

  <input type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" id='reach_condition'>

    <button class="btn btn-outline-secondary" type="button" id='button_test_condition'>Test</button>

Using: S('x'), S_raw('x'), S_line(), I('x'), I_line().

  </form>

  <textarea id='interpreter_code' class="source col-sm-auto"></textarea>

ctx here

redpajama_set_name: RedPajamaGithub


text:
require "spec_helper"

describe PlanningFilter, type: :model do
  let(:planning_application) { build(:planning_application, uid: "a/b/123", authority_name: "West Yorkshire") }

  it "is expected to have valid regex rules" do
    subject.authority = "West Yorkshire"
    subject.rule = "[a]"
    expect(subject).to be_valid
    subject.rule = "[a"
    expect(subject.errors_on(:rule)).to eq ["premature end of char-class: /[a/"]
  end

  it "filters irrelavant planning applications" do
    subject.authority = planning_application.authority_name
    subject.rule = "^a"
    expect(subject.matches?(planning_application)).to be_truthy
    subject.rule = "$a"
    expect(subject.matches?(planning_application)).to be_falsey
  end

  describe "star rules" do
    subject { described_class.new(authority: described_class::STAR, rule: "[a]") }

    context "when la has a rule" do
      before { described_class.create!(authority: planning_application.authority_name, rule: "[a]") }

      it "start does not match" do
        expect(subject.matches?(planning_application)).to be_falsey
      end
    end

    context "when la no rules" do
      it "start does match" do
        expect(subject.matches?(planning_application)).to be_truthy
      end
    end
  end
end


text:
Using theories
==============

`Theories`_ are a powerful tool for test-driven development, allowing you
to test a specific behaviour against all permutations of a set of user-defined
parameters known as "data points".

.. _Theories: http://web.archive.org/web/20110608210825/http://shareandenjoy.saff.net/tdd-specifications.pdf

Adding theories
---------------

.. doxygengroup:: TheoryBase

Adding theories is done by defining data points and a theory function:

.. code-block:: c

    #include <criterion/theories.h>

    TheoryDataPoints(suite_name, test_name) = {
        DataPoints(Type0, val0, val1, val2, ..., valN),
        DataPoints(Type1, val0, val1, val2, ..., valN),
        ...
        DataPoints(TypeN, val0, val1, val2, ..., valN),
    }

    Theory((Type0 arg0, Type1 arg1, ..., TypeN argN), suite_name, test_name) {
    }

``suite_name`` and ``test_name`` are the identifiers of the test suite and
the test, respectively. These identifiers must follow the language
identifier format.

``Type0/arg0`` through ``TypeN/argN`` are the parameter types and names of theory
theory function and are available in the body of the function.

Datapoints are declared in the same number, type, and order than the parameters
inside the ``TheoryDataPoints`` macro, with the ``DataPoints`` macro.
Beware! It is undefined behaviour to not have a matching number and type of
theory parameters and datatypes.

Each ``DataPoints`` must then specify the values that will be used for the
theory parameter it is linked to (``val0`` through ``valN``).

Assertions and invariants
-------------------------

You can use any ``cr_assert`` or ``cr_expect`` macro functions inside the body of a
theory function.

Theory invariants are enforced through the ``cr_assume(Condition)`` macro function:
if ``Condition`` is false, then the current theory iteration aborts without
making the test fail.

On top of those, more ``assume`` macro functions are available for common operations:

.. doxygengroup:: TheoryInvariants

Configuring theories
--------------------

Theories can optionally recieve configuration parameters to alter the behaviour
of the underlying test; as such, those parameters are the same ones as the ones
of the ``Test`` macro function (c.f. :ref:`test-config-ref`).

Full sample & purpose of theories
---------------------------------

We will illustrate how useful theories are with a simple example using Criterion:

The basics of theories
~~~~~~~~~~~~~~~~~~~~~~

Let us imagine that we want to test if the algebraic properties of integers,
and specifically concerning multiplication, are respected by the C language:

.. code-block:: c

    int my_mul(int lhs, int rhs) {
        return lhs * rhs;
    }

Now, we know that multiplication over integers is commutative, so we first test
that:

.. code-block:: c

    #include <criterion/criterion.h>

    Test(algebra, multiplication_is_commutative) {
        cr_assert_eq(my_mul(2, 3), my_mul(3, 2));
    }

However, this test is imperfect, because there is not enough triangulation to
insure that my_mul is indeed commutative. One might be tempted to add more
assertions on other values, but this will never be good enough: commutativity
should work for *any* pair of integers, not just an arbitrary set, but, to be
fair, you cannot just test this behaviour for every integer pair that exists.

Theories purposely bridge these two issues by introducing the concept of
"data point" and by refactoring the repeating logic into a dedicated function:

.. code-block:: c

    #include <criterion/theories.h>

    TheoryDataPoints(algebra, multiplication_is_commutative) = {
        DataPoints(int, [...]),
        DataPoints(int, [...]),
    };

    Theory((int lhs, int rhs), algebra, multiplication_is_commutative) {
        cr_assert_eq(my_mul(lhs, rhs), my_mul(rhs, lhs));
    }

As you can see, we refactored the assertion into a theory taking two unspecified
integers.

We first define some data points in the same order and type the parameters have,
from left to right: the first ``DataPoints(int, ...)`` will define the set of values passed
to the ``int lhs`` parameter, and the second will define the one passed to ``int rhs``.

Choosing the values of the data point is left to you, but we might as well use
"interesting" values: ``0``, ``-1``, ``1``, ``-2``, ``2``, ``INT_MAX``, and ``INT_MIN``:

.. code-block:: c

    #include <limits.h>

    TheoryDataPoints(algebra, multiplication_is_commutative) = {
        DataPoints(int, 0, -1, 1, -2, 2, INT_MAX, INT_MIN),
        DataPoints(int, 0, -1, 1, -2, 2, INT_MAX, INT_MIN),
    };

Using theory invariants
~~~~~~~~~~~~~~~~~~~~~~~

The second thing we can test on multiplication is that it is the inverse function
of division. Then, given the division operation:

.. code-block:: c

    int my_div(int lhs, int rhs) {
        return lhs / rhs;
    }

The associated theory is straight-forward:

.. code-block:: c

    #include <criterion/theories.h>

    TheoryDataPoints(algebra, multiplication_is_inverse_of_division) = {
        DataPoints(int, 0, -1, 1, -2, 2, INT_MAX, INT_MIN),
        DataPoints(int, 0, -1, 1, -2, 2, INT_MAX, INT_MIN),
    };

    Theory((int lhs, int rhs), algebra, multiplication_is_inverse_of_division) {
        cr_assert_eq(lhs, my_div(my_mul(lhs, rhs), rhs));
    }

However, we do have a problem because you cannot have the theory function divide
by 0. For this purpose, we can ``assume`` than ``rhs`` will never be 0:

.. code-block:: c

    Theory((int lhs, int rhs), algebra, multiplication_is_inverse_of_division) {
        cr_assume(rhs != 0);
        cr_assert_eq(lhs, my_div(my_mul(lhs, rhs), rhs));
    }

``cr_assume`` will abort the current theory iteration if the condition is not
fulfiled.

Running the test at that point will raise a big problem with the current
implementation of ``my_mul`` and ``my_div``:

.. code-block:: none

    [----] theories.c:24: Assertion failed: (a) == (bad_div(bad_mul(a, b), b))
    [----]   Theory algebra::multiplication_is_inverse_of_division failed with the following parameters: (2147483647, 2)
    [----] theories.c:24: Assertion failed: (a) == (bad_div(bad_mul(a, b), b))
    [----]   Theory algebra::multiplication_is_inverse_of_division failed with the following parameters: (-2147483648, 2)
    [----] theories.c:24: Unexpected signal caught below this line!
    [FAIL] algebra::multiplication_is_inverse_of_division: CRASH!

The theory shows that ``my_div(my_mul(INT_MAX, 2), 2)`` and ``my_div(my_mul(INT_MIN, 2), 2)``
does not respect the properties for multiplication: it happens that the
behaviour of these two functions is undefined because the operation overflows.

Similarly, the test crashes at the end; debugging shows that the source of the
crash is the divison of INT_MAX by -1, which is undefined.

Fixing this is as easy as changing the prototypes of ``my_mul`` and ``my_div``
to operate on ``long long`` rather than ``int``.

What's the difference between theories and parameterized tests ?
----------------------------------------------------------------

While it may at first seem that theories and parameterized tests are the same,
just because they happen to take multiple parameters does not mean that they
logically behave in the same manner.

Parameterized tests are useful to test a specific logic against a fixed, *finite*
set of examples that you need to work.

Theories are, well, just that: theories. They represent a test against an
universal truth, regardless of the input data matching its predicates.

Implementation-wise, Criterion also marks the separation by the way that both
are executed:

Each parameterized test iteration is run in its own test; this means that
one parameterized test acts as a collection of many tests, and gets reported
as such.

On the other hand, a theory act as one single test, since the size and contents
of the generated data set is not relevant. It does not make sense to say that
an universal truth is "partially true", so if one of the iteration fails, then
the whole test fails.


text:
<?php
namespace HtTimeZone\Filter\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use HtTimeZone\Filter\TimeZoneConverter;

class ServerToClientTimeZoneFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $filters)
    {
        $serviceLocator = $filters->getServiceLocator();
        $options = $serviceLocator->get('HtTimeZone\ModuleOptions');

        return new TimeZoneConverter(
            $options->getServerTimeZone()
            $serviceLocator->get('HtTimeZone\TimeZoneService')->getClientTimeZone(),
        );
    }
}


text:
<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */
namespace Praxigento\Core\Api\App\Web\Response;

/**
 * Response result data. If "SUCCESS" then $text is omitted.
 */
class Result
    extends \Praxigento\Core\Data
{
    public function __construct()
    {
        parent::__construct();
        $this->setCode(\Praxigento\Core\Api\App\Web\Response::CODE_FAILED);
    }

    /**
     * @return string
     */
    public function getCode()
    {
        $result = parent::getCode();
        return $result;
    }

    /**
     * @return string|null
     */
    public function getText()
    {
        $result = parent::getText();
        return $result;
    }

    /**
     * @param string $data
     * @return void
     */
    public function setCode($data)
    {
        parent::setCode($data);
    }

    /**
     * @param string $data
     * @return void
     */
    public function setText($data)
    {
        parent::setText($data);
    }
}


text:
<?php

/**
 * @author A.Jafaripur <mjafaripur@yahoo.com>
 *
 * Components for yii2
 *
 */

namespace common\components;

use Yii;
use yii\helpers\Html;
use yii\base\Component;
use yii\helpers\FileHelper;

class Helper extends Component {

	/**
	 * Check the given locale is rtl or not.
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @param string $lang language locale
	 * @return boolean
	 */
	public function isRtl($lang = '') {
		$rtlLang = [
			'fa-IR',
		];
		if (trim($lang) == '') {
			$lang = \Yii::$app->language;
		}
		return in_array($lang, $rtlLang);
	}

	/**
	 * Create button for delete for yii gridview widget
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @param string $url url for delete action
	 * @param string $permission permission for checking the user have an access to delete ir not.
	 * @param string $pjaxGridName Gridview name to update the gridview after deleting.
	 * @param string $messageContainer HTML container ID for show the message
	 * @return string generated link
	 */
	public function createDeleteButton($url, $permission = '', $pjaxGridName = '', $messageContainer = '') {
		if ($permission != '' && !Yii::$app->getUser()->can($permission))
			return '';

		return Html::a('', '#', [
				'title' => Yii::t('app', 'Delete'),
				"onclick" => "return deleteGridButton('{$url}', '" . Yii::t('app', 'Are you sure you want to delete this item?') . "', '{$pjaxGridName}', '{$messageContainer}' );"
		]);
	}

	/**
	 * Create button for updating item for yii gridview widget
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @param string $url url for delete action
	 * @param string $permission permission for checking the user have an access to edit ir not
	 * @param boolean $useFancy show the given url result in fancy or not
	 * @param boolean $usePjax Using PJAX for editing or not
	 * @return string generated link
	 */
	public function createUpdateButton($url, $permission = '', $useFancy = false, $usePjax = false) {
		if ($permission != '' && !Yii::$app->getUser()->can($permission))
			return '';

		return Html::a('', $url, [
				'title' => Yii::t('app', 'Update'),
				'class' => $useFancy ? 'fancybox fancybox.ajax' : '',
				'data-pjax' => $usePjax ? '1' : '0',
		]);
	}

	/**
	 * get the google map API SDK
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @return string url of google map api to include in page.
	 */
	public function getGoogleMapUrl() {
		return 'https://maps.googleapis.com/maps/api/js?v=3.exp&language=' . $this->getTwoCharLanguage();
	}

	/**
	 * get the two chars of the locale
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @return string
	 */
	public function getTwoCharLanguage() {
		return substr(Yii::$app->language, 0, 2);
	}

	/**
	 * check the given name is suitable for file or not and remove unexpected chars from the file name.
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @param string $file name of the file
	 * @return string
	 */
	public function safeFile($file) {
		// Remove any trailing dots, as those aren't ever valid file names.
		$file = rtrim($file, '.');

		$regex = array('#(\.){2,}#', '#[^A-Za-z0-9\.\_\- ]#', '#^\.#');

		return trim(preg_replace($regex, '', $file));
	}

	/**
	 * Normalize the string for adding in the url.
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @param string $text
	 * @return string
	 */
	public static function normalizeTextForUrl($text){
		return preg_replace("#(\p{P}|\p{C}|\p{S}|\p{Z})+#u", "-", $text);
	}

	/**
	 * Format the latitude and longitude with fixed precision.
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @param string $string
	 * @param integer $doubleCount
	 * @return float
	 */
	public function formatLatLng($string = '', $doubleCount = 10) {
		$ex = explode('.', $string);
		$ex[1] = substr($ex[1], 0, $doubleCount);
		$diff = $doubleCount - strlen($ex[1]);
		$zeros = substr('00000000', 0, $diff);
		$ex[1] .= $zeros;

		return implode('.', $ex);
	}

	/**
	 * Remove all directories in given path
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @param string $path location path
	 */
	public function removeDirectories($path){
		$blacklist = array('.', '..');
		if ($handle = opendir($path)) {
			while (false !== ($file = readdir($handle))) {
				if (!in_array($file, $blacklist) && is_dir($path . DIRECTORY_SEPARATOR . $file)) {
					FileHelper::removeDirectory($path . DIRECTORY_SEPARATOR . $file);
				}
			}
			closedir($handle);
		}
	}

	/**
	 * Get list of the languages used in the website with label and url.
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @return array the key, value with label and url items
	 */
	public function getLanguages(){
		$route = Yii::$app->controller->route;
		$appLanguage = Yii::$app->language;
		$params = Yii::$app->getRequest()->get();

		array_unshift($params, $route);
		$items = [];
		foreach ($this->getLanguagesList() as $language) {
            if ($language === $appLanguage) {
                continue;  // Exclude the current language
            }
            $params['language'] = $language;
            $items[] = [
                'label' => $this->getLabelLanguage($language),
                'url' => $params,
            ];
        }

		return $items;
	}

	/**
	 * Get list of language for show in adding or editing mode for selecting the language for content.
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @return array key, value array. key is the language code and value is label for that language
	 */
	public function getLanguageForMultiLingual(){
		$items['*'] = Yii::t('app', 'All');
		foreach ($this->getLanguagesList() as $language) {
            $items[$language] = $this->getLabelLanguage($language);
        }

		return $items;
	}

	/**
	 * Get list of languages
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @return array
	 */
	public function getLanguagesList(){
		return Yii::$app->urlManager->languages;
	}

	/**
	 * Get label for each language available in the website.
	 *
	 * @author A.Jafaripur <mjafaripur@yahoo.com>
	 *
	 * @param string $language language locale
	 * @return string
	 */
	private function getLabelLanguage($language){
		$labels = [
			'en' => Yii::t('app', 'English'),
			'en-GB' => Yii::t('app', 'English'),
			'en-US' => Yii::t('app', 'English'),
			'fa-IR' => Yii::t('app', 'Persian'),
		];

        return isset($labels[$language]) ? $labels[$language] : null;
	}
}


text:
using System;
using NUnit.Framework;
using TickedPriorityQueue;

namespace TickedPriorityQueue {
	[TestFixture()]
	public class TickedQueueItemUnit
	{
		[Test()]
		public void TestCase ()
		{
			TickedObject obj = new TickedObject(null);
			obj.Priority = 6;
			obj.TickLength = 7;
			TickedQueueItem item = new TickedQueueItem(obj);
			Assert.AreEqual(item.Priority, obj.Priority, "TickedQueueItem should report the same priority as the wrapped object");

			DateTime testTime = DateTime.UtcNow;
			Assert.IsFalse(item.CheckTickReady(testTime), "CheckTickReady should return false when time is before next scheduled tick");

			DateTime testTimePlus4 = testTime.AddSeconds(4);
			Assert.IsFalse(item.CheckTickReady(testTimePlus4), "CheckTickReady should return false when time is before next scheduled tick");

			DateTime testTimePlus8 = testTime.AddSeconds(8);
			Assert.IsTrue(item.CheckTickReady(testTimePlus8), "CheckTickReady should return true when time is after next scheduled tick");
		}

		[Test()]
		public void TestTickTimeReset()
		{
			TickedObject obj = new TickedObject(null);
			obj.Priority = 6;
			obj.TickLength = 7;
			var now = DateTime.UtcNow;
			TickedQueueItem item = new TickedQueueItem(obj, now);
			Assert.AreEqual(item.NextTickTime, now.AddSeconds(obj.TickLength), "Initial next tick time did not match");

			var future = now.AddSeconds(3);
			item.ResetTickFromTime(future);
			Assert.AreEqual(item.NextTickTime, future.AddSeconds(obj.TickLength), "Next tick time did not match after reset");
		}
	}
}


text:
import shlex

import mock
import testtools

from sahara import exceptions as ex
from sahara.tests.unit import base
from sahara.utils import ssh_remote

class TestEscapeQuotes(testtools.TestCase):
    def test_escape_quotes(self):
        s = ssh_remote._escape_quotes('echo "\\"Hello, world!\\""')
        self.assertEqual(s, r'echo \"\\\"Hello, world!\\\"\"')

class FakeCluster(object):
    def __init__(self, priv_key):
        self.management_private_key = priv_key
        self.neutron_management_network = 'network1'

    def has_proxy_gateway(self):
        return False

    def get_proxy_gateway_node(self):
        return None

class FakeNodeGroup(object):
    def __init__(self, user, priv_key):
        self.image_username = user
        self.cluster = FakeCluster(priv_key)

class FakeInstance(object):
    def __init__(self, inst_name, management_ip, user, priv_key):
        self.instance_name = inst_name
        self.management_ip = management_ip
        self.node_group = FakeNodeGroup(user, priv_key)

    @property
    def cluster(self):
        return self.node_group.cluster

class TestInstanceInteropHelper(base.SaharaTestCase):
    def setUp(self):
        super(TestInstanceInteropHelper, self).setUp()

        p_sma = mock.patch('sahara.utils.ssh_remote._acquire_remote_semaphore')
        p_sma.start()
        p_smr = mock.patch('sahara.utils.ssh_remote._release_remote_semaphore')
        p_smr.start()

        p_neutron_router = mock.patch(
            'sahara.utils.openstack.neutron.NeutronClient.get_router',
            return_value='fakerouter')
        p_neutron_router.start()

        # During tests subprocesses are not used (because _sahara-subprocess
        # is not installed in /bin and Mock objects cannot be pickled).
        p_start_subp = mock.patch('sahara.utils.procutils.start_subprocess',
                                  return_value=42)
        p_start_subp.start()
        p_run_subp = mock.patch('sahara.utils.procutils.run_in_subprocess')
        self.run_in_subprocess = p_run_subp.start()
        p_shut_subp = mock.patch('sahara.utils.procutils.shutdown_subprocess')
        p_shut_subp.start()

        self.patchers = [p_sma, p_smr, p_neutron_router, p_start_subp,
                         p_run_subp, p_shut_subp]

    def tearDown(self):
        for patcher in self.patchers:
            patcher.stop()
        super(TestInstanceInteropHelper, self).tearDown()

    def setup_context(self, username="test_user", tenant_id="tenant_1",
                      token="test_auth_token", tenant_name='test_tenant',
                      **kwargs):
        service_catalog = '''[
            { "type": "network",
              "endpoints": [ { "region": "RegionOne",
                               "publicURL": "http://localhost/" } ] } ]'''
        super(TestInstanceInteropHelper, self).setup_context(
            username=username, tenant_id=tenant_id, token=token,
            tenant_name=tenant_name, service_catalog=service_catalog, **kwargs)

    # When use_floating_ips=True, no proxy should be used: _connect is called
    # with proxy=None and ProxiedHTTPAdapter is not used.
    @mock.patch('sahara.utils.ssh_remote.ProxiedHTTPAdapter')
    def test_use_floating_ips(self, p_adapter):
        self.override_config('use_floating_ips', True)

        instance = FakeInstance('inst1', '10.0.0.1', 'user1', 'key1')
        remote = ssh_remote.InstanceInteropHelper(instance)

        # Test SSH
        remote.execute_command('/bin/true')
        self.run_in_subprocess.assert_any_call(
            42, ssh_remote._connect, ('10.0.0.1', 'user1', 'key1',
                                      None, None, None))
        # Test HTTP
        remote.get_http_client(8080)
        self.assertFalse(p_adapter.called)

    # When use_floating_ips=False and use_namespaces=True, a netcat socket
    # created with 'ip netns exec qrouter-...' should be used to access
    # instances.
    @mock.patch('sahara.utils.ssh_remote._simple_exec_func')
    @mock.patch('sahara.utils.ssh_remote.ProxiedHTTPAdapter')
    def test_use_namespaces(self, p_adapter, p_simple_exec_func):
        self.override_config('use_floating_ips', False)
        self.override_config('use_namespaces', True)

        instance = FakeInstance('inst2', '10.0.0.2', 'user2', 'key2')
        remote = ssh_remote.InstanceInteropHelper(instance)

        # Test SSH
        remote.execute_command('/bin/true')
        self.run_in_subprocess.assert_any_call(
            42, ssh_remote._connect,
            ('10.0.0.2', 'user2', 'key2',
             'ip netns exec qrouter-fakerouter nc 10.0.0.2 22', None, None))
        # Test HTTP
        remote.get_http_client(8080)
        p_adapter.assert_called_once_with(
            p_simple_exec_func(),
            '10.0.0.2', 8080)
        p_simple_exec_func.assert_any_call(
            shlex.split('ip netns exec qrouter-fakerouter nc 10.0.0.2 8080'))

    # When proxy_command is set, a user-defined netcat socket should be used to
    # access instances.
    @mock.patch('sahara.utils.ssh_remote._simple_exec_func')
    @mock.patch('sahara.utils.ssh_remote.ProxiedHTTPAdapter')
    def test_proxy_command(self, p_adapter, p_simple_exec_func):
        self.override_config('proxy_command', 'ssh fakerelay nc {host} {port}')

        instance = FakeInstance('inst3', '10.0.0.3', 'user3', 'key3')
        remote = ssh_remote.InstanceInteropHelper(instance)

        # Test SSH
        remote.execute_command('/bin/true')
        self.run_in_subprocess.assert_any_call(
            42, ssh_remote._connect,
            ('10.0.0.3', 'user3', 'key3', 'ssh fakerelay nc 10.0.0.3 22',
             None, None))
        # Test HTTP
        remote.get_http_client(8080)
        p_adapter.assert_called_once_with(
            p_simple_exec_func(), '10.0.0.3', 8080)
        p_simple_exec_func.assert_any_call(
            shlex.split('ssh fakerelay nc 10.0.0.3 8080'))

    def test_proxy_command_bad(self):
        self.override_config('proxy_command', '{bad_kw} nc {host} {port}')

        instance = FakeInstance('inst4', '10.0.0.4', 'user4', 'key4')
        remote = ssh_remote.InstanceInteropHelper(instance)

        # Test SSH
        self.assertRaises(ex.SystemError, remote.execute_command, '/bin/true')
        # Test HTTP
        self.assertRaises(ex.SystemError, remote.get_http_client, 8080)


text:
ARG  BASE=ubuntu:18.04
FROM $BASE
ARG  ARCH=x86_64
RUN apt-get -y update \
    && apt-get -y install openvswitch-common libpcap0.8 libxml2 \
    && rm -rf /var/lib/apt/lists/*
COPY skydive.$ARCH /usr/bin/skydive
COPY skydive.yml /etc/skydive.yml
ENTRYPOINT ["/usr/bin/skydive", "--conf", "/etc/skydive.yml"]


text:
\hypertarget{namespacemmasgis}{
\section{mmasgis Namespace Reference}
\label{namespacemmasgis}\index{mmasgis@{mmasgis}}
}
\subsection*{Namespaces}
\begin{DoxyCompactItemize}
\item
namespace \hyperlink{namespacemmasgis_1_1albero}{albero}
\item
namespace \hyperlink{namespacemmasgis_1_1anagrafica}{anagrafica}
\item
namespace \hyperlink{namespacemmasgis_1_1anagrafica2}{anagrafica2}
\item
namespace \hyperlink{namespacemmasgis_1_1AnagraficaDb}{AnagraficaDb}
\item
namespace \hyperlink{namespacemmasgis_1_1Configurator}{Configurator}
\item
namespace \hyperlink{namespacemmasgis_1_1configurazione}{configurazione}
\item
namespace \hyperlink{namespacemmasgis_1_1constants}{constants}
\item
namespace \hyperlink{namespacemmasgis_1_1copia}{copia}

\begin{DoxyCompactList}\small\item\em di test \item\end{DoxyCompactList}

\item
namespace \hyperlink{namespacemmasgis_1_1copia_01di_01test}{copia di test}
\item
namespace \hyperlink{namespacemmasgis_1_1dbDict}{dbDict}
\item
namespace \hyperlink{namespacemmasgis_1_1dbQuery}{dbQuery}
\item
namespace \hyperlink{namespacemmasgis_1_1dict}{dict}
\item
namespace \hyperlink{namespacemmasgis_1_1entities}{entities}
\item
namespace \hyperlink{namespacemmasgis_1_1entities__sqlalchemy}{entities\_\-sqlalchemy}
\item
namespace \hyperlink{namespacemmasgis_1_1Entity}{Entity}
\item
namespace \hyperlink{namespacemmasgis_1_1EntityElements}{EntityElements}
\item
namespace \hyperlink{namespacemmasgis_1_1esportazione}{esportazione}
\item
namespace \hyperlink{namespacemmasgis_1_1esportazioneMain}{esportazioneMain}
\item
namespace \hyperlink{namespacemmasgis_1_1Filter}{Filter}
\item
namespace \hyperlink{namespacemmasgis_1_1filterDb}{filterDb}
\item
namespace \hyperlink{namespacemmasgis_1_1fpdf}{fpdf}
\item
namespace \hyperlink{namespacemmasgis_1_1interrogazioni}{interrogazioni}
\item
namespace \hyperlink{namespacemmasgis_1_1lista}{lista}
\item
namespace \hyperlink{namespacemmasgis_1_1mmasgis}{mmasgis}
\item
namespace \hyperlink{namespacemmasgis_1_1mysql__sqlalchemy__class}{mysql\_\-sqlalchemy\_\-class}
\item
namespace \hyperlink{namespacemmasgis_1_1mysqlEntities}{mysqlEntities}
\item
namespace \hyperlink{namespacemmasgis_1_1Odict}{Odict}
\item
namespace \hyperlink{namespacemmasgis_1_1Profilo}{Profilo}
\item
namespace \hyperlink{namespacemmasgis_1_1queriesDb}{queriesDb}
\item
namespace \hyperlink{namespacemmasgis_1_1resources}{resources}
\item
namespace \hyperlink{namespacemmasgis_1_1risultati}{risultati}
\item
namespace \hyperlink{namespacemmasgis_1_1risultatiMainUi}{risultatiMainUi}
\item
namespace \hyperlink{namespacemmasgis_1_1runmmasgis}{runmmasgis}
\item
namespace \hyperlink{namespacemmasgis_1_1SaveQuery}{SaveQuery}
\item
namespace \hyperlink{namespacemmasgis_1_1selezioneQuery}{selezioneQuery}
\item
namespace \hyperlink{namespacemmasgis_1_1separatore}{separatore}
\item
namespace \hyperlink{namespacemmasgis_1_1sqlAlchemyQueryClass}{sqlAlchemyQueryClass}
\item
namespace \hyperlink{namespacemmasgis_1_1stile__anagrafica__rc}{stile\_\-anagrafica\_\-rc}
\item
namespace \hyperlink{namespacemmasgis_1_1stile__configurazione__rc}{stile\_\-configurazione\_\-rc}
\item
namespace \hyperlink{namespacemmasgis_1_1stile__elenco__rc}{stile\_\-elenco\_\-rc}
\item
namespace \hyperlink{namespacemmasgis_1_1stile__esportazione__rc}{stile\_\-esportazione\_\-rc}
\item
namespace \hyperlink{namespacemmasgis_1_1stile__filtri__rc}{stile\_\-filtri\_\-rc}
\item
namespace \hyperlink{namespacemmasgis_1_1stile__query__rc}{stile\_\-query\_\-rc}
\item
namespace \hyperlink{namespacemmasgis_1_1stile__separatore__rc}{stile\_\-separatore\_\-rc}
\item
namespace \hyperlink{namespacemmasgis_1_1testattributes}{testattributes}
\item
namespace \hyperlink{namespacemmasgis_1_1testClass}{testClass}
\item
namespace \hyperlink{namespacemmasgis_1_1testLista}{testLista}
\item
namespace \hyperlink{namespacemmasgis_1_1testProvincie}{testProvincie}
\item
namespace \hyperlink{namespacemmasgis_1_1testquerytype}{testquerytype}
\item
namespace \hyperlink{namespacemmasgis_1_1testUtility}{testUtility}
\item
namespace \hyperlink{namespacemmasgis_1_1Tree}{Tree}
\item
namespace \hyperlink{namespacemmasgis_1_1Ui__albero}{Ui\_\-albero}
\item
namespace \hyperlink{namespacemmasgis_1_1Ui__anagrafica}{Ui\_\-anagrafica}
\item
namespace \hyperlink{namespacemmasgis_1_1Ui__anagrafica__modificato}{Ui\_\-anagrafica\_\-modificato}
\item
namespace \hyperlink{namespacemmasgis_1_1Ui__configurazione}{Ui\_\-configurazione}
\item
namespace \hyperlink{namespacemmasgis_1_1Ui__esportazione}{Ui\_\-esportazione}
\item
namespace \hyperlink{namespacemmasgis_1_1Ui__interrogazioni}{Ui\_\-interrogazioni}
\item
namespace \hyperlink{namespacemmasgis_1_1Ui__risultati}{Ui\_\-risultati}
\item
namespace \hyperlink{namespacemmasgis_1_1Ui__SaveQuery}{Ui\_\-SaveQuery}
\item
namespace \hyperlink{namespacemmasgis_1_1Ui__selezioneQuery}{Ui\_\-selezioneQuery}
\item
namespace \hyperlink{namespacemmasgis_1_1Ui__separatore}{Ui\_\-separatore}
\item
namespace \hyperlink{namespacemmasgis_1_1ui__test}{ui\_\-test}
\item
namespace \hyperlink{namespacemmasgis_1_1un}{un}

\begin{DoxyCompactList}\small\item\em 'altra copia di test \item\end{DoxyCompactList}

\item
namespace \hyperlink{namespacemmasgis_1_1un'altra_01copia_01di_01test}{un'altra copia di test}
\item
namespace \hyperlink{namespacemmasgis_1_1utility}{utility}
\end{DoxyCompactItemize}
\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
def \hyperlink{namespacemmasgis_a144dcf13d9fc701ba4c2a40f90e51562}{name}
\item
def \hyperlink{namespacemmasgis_aa1fb28ae7e99ef8ad6a1ca117f1a2fb8}{description}
\item
def \hyperlink{namespacemmasgis_a51f3c32751fe698aeb28832d612bb5dd}{version}
\item
def \hyperlink{namespacemmasgis_aedadfd2e8632646282e1ad1abdb6b0df}{icon}
\item
def \hyperlink{namespacemmasgis_a38769dd1d38117adbfe9ddbe0352214d}{qgisMinimumVersion}
\item
def \hyperlink{namespacemmasgis_a1aad04c3e8be8de4b6e86f5ce9bfe17a}{authorName}
\item
def \hyperlink{namespacemmasgis_ae263473e8d399f480e8ba74ac4cf5070}{classFactory}
\end{DoxyCompactItemize}

\subsection{Detailed Description}
\begin{DoxyVerb}

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
 This script initializes the plugin, making it known to QGIS.
\end{DoxyVerb}

\subsection{Function Documentation}
\hypertarget{namespacemmasgis_a1aad04c3e8be8de4b6e86f5ce9bfe17a}{
\index{mmasgis@{mmasgis}!authorName@{authorName}}
\index{authorName@{authorName}!mmasgis@{mmasgis}}
\subsubsection[{authorName}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::authorName (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{namespacemmasgis_a1aad04c3e8be8de4b6e86f5ce9bfe17a}
\hypertarget{namespacemmasgis_ae263473e8d399f480e8ba74ac4cf5070}{
\index{mmasgis@{mmasgis}!classFactory@{classFactory}}
\index{classFactory@{classFactory}!mmasgis@{mmasgis}}
\subsubsection[{classFactory}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::classFactory (
\begin{DoxyParamCaption}
\item[{}]{iface}
\end{DoxyParamCaption}
)}}
\label{namespacemmasgis_ae263473e8d399f480e8ba74ac4cf5070}
\hypertarget{namespacemmasgis_aa1fb28ae7e99ef8ad6a1ca117f1a2fb8}{
\index{mmasgis@{mmasgis}!description@{description}}
\index{description@{description}!mmasgis@{mmasgis}}
\subsubsection[{description}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::description (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{namespacemmasgis_aa1fb28ae7e99ef8ad6a1ca117f1a2fb8}
\hypertarget{namespacemmasgis_aedadfd2e8632646282e1ad1abdb6b0df}{
\index{mmasgis@{mmasgis}!icon@{icon}}
\index{icon@{icon}!mmasgis@{mmasgis}}
\subsubsection[{icon}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::icon (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{namespacemmasgis_aedadfd2e8632646282e1ad1abdb6b0df}
\hypertarget{namespacemmasgis_a144dcf13d9fc701ba4c2a40f90e51562}{
\index{mmasgis@{mmasgis}!name@{name}}
\index{name@{name}!mmasgis@{mmasgis}}
\subsubsection[{name}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::name (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{namespacemmasgis_a144dcf13d9fc701ba4c2a40f90e51562}
\hypertarget{namespacemmasgis_a38769dd1d38117adbfe9ddbe0352214d}{
\index{mmasgis@{mmasgis}!qgisMinimumVersion@{qgisMinimumVersion}}
\index{qgisMinimumVersion@{qgisMinimumVersion}!mmasgis@{mmasgis}}
\subsubsection[{qgisMinimumVersion}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::qgisMinimumVersion (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{namespacemmasgis_a38769dd1d38117adbfe9ddbe0352214d}
\hypertarget{namespacemmasgis_a51f3c32751fe698aeb28832d612bb5dd}{
\index{mmasgis@{mmasgis}!version@{version}}
\index{version@{version}!mmasgis@{mmasgis}}
\subsubsection[{version}]{\setlength{\rightskip}{0pt plus 5cm}def mmasgis::version (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{namespacemmasgis_a51f3c32751fe698aeb28832d612bb5dd}


text:
#ifndef __graphinius_h__
#define __graphinius_h__

#if defined(_WINDOWS)
  #define WIN32_LEAN_AND_MEAN		// exclude unused stuff from Windows headers
  #include <windows.h>
  typedef HDC HPLATFORMGFX;
#elif defined(XWINDOW)
  #include <X11/Xlib.h>
  typedef struct _HDC_tipa
  {
    Display* d;
    Window   w;
    int      gc;
  } *HPLATFORMGFX;
#endif

// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the GRAPHIN_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// GRAPHIN_API functions as being imported from a DLL, wheras this DLL sees symbols
// defined with this macro as being exported.
#ifdef GRAPHIN_EXPORTS
  #if defined(__GNUC__)
    #define GRAPHIN_API extern "C" //__attribute__((dllexport))
    #define GRAPHIN_CALL
  #elif defined( _MSC_VER )
    #define GRAPHIN_API extern "C" __declspec(dllexport)
    #define GRAPHIN_CALL __stdcall
  #endif
#else
  #if defined(__GNUC__)
     #define GRAPHIN_API extern "C" //__attribute__((dllimport))
     #define GRAPHIN_CALL
  #elif defined( _MSC_VER )
     #define GRAPHIN_API extern "C" __declspec(dllimport)
     #define GRAPHIN_CALL __stdcall
  #endif
#endif

enum GRAPHIN_RESULT
{
  GRAPHIN_PANIC = -1,       // e.g. not enough memory
  GRAPHIN_OK = 0,           // ok
  GRAPHIN_OK_FALSE = 2,     // ok but false
  GRAPHIN_BAD_PARAM = 3,    // bad parameter
  GRAPHIN_FAILURE = 4,      // operation failed, e.g. restore() without save()
};

enum GRAPHIN_BLEND_MODE
{
  GBlendClear,
  GBlendSrc,
  GBlendDst,
  GBlendSrcOver,
  GBlendDstOver,
  GBlendSrcIn,
  GBlendDstIn,
  GBlendSrcOut,
  GBlendDstOut,
  GBlendSrcAtop,
  GBlendDstAtop,
  GBlendXor,
  GBlendAdd,
  GBlendSub,
  GBlendMultiply,
  GBlendScreen,
  GBlendOverlay,
  GBlendDarken,
  GBlendLighten,
  GBlendColorDodge,
  GBlendColorBurn,
  GBlendHardLight,
  GBlendSoftLight,
  GBlendDifference,
  GBlendExclusion,
  GBlendContrast,
  GBlendInvert,
  GBlendInvertRGB,

  GBlendAlpha,

  GBlend_count,
};

struct graphics;
struct image;

typedef struct graphics* HGFX;
typedef struct image*    HIMG;

#ifndef BYTE
  typedef unsigned char   BYTE;
#endif
typedef double REAL;        // any floating point value
typedef double POS;         // position
typedef double DIM;         // dimention
typedef double ANGLE;       // angle (radians)
typedef unsigned int COLOR; // guess what?

// image primitives

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        image_create( unsigned int width, unsigned int height, HIMG* poutImg );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        image_release( HIMG himg );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        image_get_info( HIMG himg,
             BYTE** data,
             unsigned int* width,
             unsigned int* height,
             int* stride,
             unsigned int* pixel_format);

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        image_blit( HPLATFORMGFX dst, int dst_x, int dst_y,
                            HIMG src, int src_x, int src_y,
                            int width, int height, bool blend );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        image_load( const BYTE* bytes, unsigned int num_bytes, HIMG* pout_img ); // load png/jpeg/etc. image from stream of bytes

typedef bool GRAPHIN_CALL image_write_function(void* prm, unsigned char* data, unsigned int data_length);

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL // save png/jpeg/etc. image to stream of bytes
        image_save( HIMG himg,
        image_write_function* pfn, void* prm, /* function and its param passed "as is" */
        unsigned bpp /*24,32 if alpha needed*/,
        unsigned type /* 0 - png, 1 - jpg*/,
        unsigned quality /*  only for jpeg, 10 - 100 */ );

// SECTION: graphics primitives and drawing operations

// create color value
GRAPHIN_API COLOR GRAPHIN_CALL
        graphics_rgbt(unsigned int red, unsigned int green, unsigned int blue, unsigned int transparency = 0);
// Note: transparent color (no-color value) is rgba(?, ?, ?, 0xff);

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_create(HIMG img, HGFX* pout_gfx );

// blending mode
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_blend_mode( HGFX gfx, GRAPHIN_BLEND_MODE mode );

GRAPHIN_API GRAPHIN_BLEND_MODE GRAPHIN_CALL
        graphics_blend_mode_get( HGFX gfx );

// antialiasing gamma
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_gamma( HGFX gfx, REAL gamma_value );

GRAPHIN_API REAL GRAPHIN_CALL
        graphics_gamma_get( HGFX gfx );

// --- Dashes -------------------------------------------------------------

// dahed lines

// add one dash
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_dashes_add( HGFX gfx, POS dash_len, POS gap_len );

// remove all dashes
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_dashes_clear( HGFX gfx );

// set dash start offset
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_dashes_start( HGFX gfx, POS dash_start );

// set dash start offset
GRAPHIN_API POS GRAPHIN_CALL
        graphics_dashes_start_get( HGFX gfx );

// --- Dashes (end) --------------------------------------------------------

GRAPHIN_API GRAPHIN_BLEND_MODE GRAPHIN_CALL
        graphics_blend_mode_get( HGFX gfx );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_release(HGFX gfx);

// Set line color
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_line_color ( HGFX hgfx, COLOR c);

// Draws line from x1,y1 to x2,y2 using current lineColor and lineGradient.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_line ( HGFX hgfx, POS x1, POS y1, POS x2, POS y2 );

// Draws not filled arrow directed from point (x_from,y_from) to (x_to,y_to),
// "sz" -- size of arrow side, "angle" -- angle of between main sides of arrow.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_arrow_bone ( HGFX hgfx, POS x_from, POS y_from, POS x_to, POS y_to, POS sz, ANGLE angle );

// Draws not filled arrow directed from point (x_from,y_from) to (x_to,y_to),
// "sz" -- size of arrow side, "angle" -- angle of between main sides of arrow.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_arrow ( HGFX hgfx, POS x_from, POS y_from, POS x_to, POS y_to, POS sz, ANGLE angle, REAL offset );

// Draws triangle using current lineColor/lineGradient and fillColor/fillGradient.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_triangle ( HGFX hgfx, POS x1, POS y1, POS x2, POS y2, POS x3, POS y3 );

// Draws rectangle using current lineColor/lineGradient and fillColor/fillGradient with (optional) rounded corners.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_rectangle ( HGFX hgfx, POS x1, POS y1, POS x2, POS y2 );

// Draws rounded rectangle using current lineColor/lineGradient and fillColor/fillGradient with (optional) rounded corners.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_rounded_rectangle ( HGFX hgfx, POS x1, POS y1, POS x2, POS y2, POS rx, POS ry);

// Draws circle or ellipse using current lineColor/lineGradient and fillColor/fillGradient.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_ellipse ( HGFX hgfx, POS x, POS y, POS rx, POS ry );

// Draws closed arc using current lineColor/lineGradient and fillColor/fillGradient.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_arc ( HGFX hgfx, POS x, POS y, POS rx, POS ry, ANGLE start, ANGLE sweep );

// Draws star.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_star ( HGFX hgfx, POS x, POS y, POS r1, POS r2, ANGLE start, unsigned rays );

// Closed polygon.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_polygon ( HGFX hgfx, POS* xy, unsigned int num_points );

// Polyline.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_polyline ( HGFX hgfx, POS* xy, unsigned int num_points );

// SECTION: Path operations

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_open_path ( HGFX hgfx );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_move_to ( HGFX hgfx, POS x, POS y, bool relative );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_line_to ( HGFX hgfx, POS x, POS y, bool relative );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_hline_to ( HGFX hgfx, POS x, bool relative );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_vline_to ( HGFX hgfx, POS y, bool relative );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_arc_to ( HGFX hgfx, POS x, POS y, ANGLE angle, POS rx, POS ry, bool is_large_arc, bool sweep_flag, bool relative );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_ellipse_to ( HGFX hgfx, POS x, POS y, POS rx, POS ry, bool clockwise );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_quadratic_curve_to ( HGFX hgfx, POS xc, POS yc, POS x, POS y, bool relative );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_bezier_curve_to ( HGFX hgfx, POS xc1, POS yc1, POS xc2, POS yc2, POS x, POS y, bool relative );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_close_path ( HGFX hgfx );

enum DRAW_PATH_MODE
{
    FILL_ONLY,
    STROKE_ONLY,
    FILL_AND_STROKE,
    FILL_BY_LINE_COLOR
};

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_draw_path ( HGFX hgfx, DRAW_PATH_MODE dpm );

// end of path opearations

// SECTION: affine tranformations:

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_rotate ( HGFX hgfx, ANGLE radians, POS* cx = 0, POS* cy = 0 );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_translate ( HGFX hgfx, POS cx, POS cy );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_scale ( HGFX hgfx, double x, double y );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_skew ( HGFX hgfx, double dx, double dy );

// all above in one shot
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_transform ( HGFX hgfx, POS m11, POS m12, POS m21, POS m22, POS dx, POS dy );

// end of affine tranformations.

// SECTION: state save/restore

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_state_save ( HGFX hgfx );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
        graphics_state_restore ( HGFX hgfx );

// end of state save/restore

// SECTION: drawing attributes

// set line width for subsequent drawings.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_line_width ( HGFX hgfx, DIM width );

inline void
      graphics_no_line ( HGFX hgfx ) { graphics_line_width(hgfx,0.0); }

// color for solid lines/strokes
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_line_color ( HGFX hgfx, COLOR color );

// color for solid fills
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_fill_color ( HGFX hgfx, COLOR color );

inline void
      graphics_no_fill ( HGFX hgfx ) { graphics_fill_color(hgfx, graphics_rgbt(0,0,0,0xFF)); }

// image for pattern fills
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_fill_pattern ( HGFX hgfx, HIMG pattern, unsigned opacity, int offset_x, int offset_y );

// setup parameters of linear gradient of lines.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_line_linear_gradient( HGFX hgfx, POS x1, POS y1, POS x2, POS y2, COLOR color1, COLOR color2, double profile = 1.0 );

// setup parameters of linear gradient of fills.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_fill_linear_gradient( HGFX hgfx, POS x1, POS y1, POS x2, POS y2, COLOR color1, COLOR color2, double profile = 1.0 );

// setup parameters of line gradient radial fills.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_line_radial_gradient( HGFX hgfx, POS x, POS y, DIM r, COLOR color1, COLOR color2, double profile = 1.0 );

// setup parameters of gradient radial fills.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_fill_radial_gradient( HGFX hgfx, POS x, POS y, DIM r, COLOR color1, COLOR color2, double profile = 1.0 );

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_fill_mode( HGFX hgfx, bool even_odd /* false - fill_non_zero */ );

// SECTION: text

// define font attributes for all subsequent text operations.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_font( HGFX hgfx, const char* name, DIM size, bool bold = false, bool italic = false, ANGLE angle = 0);

// draw text at x,y with text alignment
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_text( HGFX hgfx, POS x, POS y, const wchar_t* text, unsigned int text_length);

// calculates width of the text string
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_text_width( HGFX hgfx, const wchar_t* text, unsigned int text_length, DIM* out_width);

// returns height and ascent of the font.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_font_metrics( HGFX hgfx, DIM* out_height, DIM* out_ascent );

enum TEXT_ALIGNMENT
{
  ALIGN_TOP,
  ALIGN_BOTTOM,
  ALIGN_CENTER,
  ALIGN_BASELINE,
  ALIGN_RIGHT = ALIGN_TOP,
  ALIGN_LEFT = ALIGN_BOTTOM

};

// calculates width of the text string
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_text_alignment( HGFX hgfx, TEXT_ALIGNMENT x, TEXT_ALIGNMENT y);

// SECTION: image rendering

// draws img onto the graphics surface with current transformation applied (scale, rotation).
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_draw_image ( HGFX hgfx, HIMG himg, POS x, POS y,
                            DIM* w = 0, DIM* h = 0, unsigned* ix = 0, unsigned* iy = 0, unsigned* iw = 0, unsigned* ih = 0 );

// blits image bits onto underlying pixel buffer. no affine transformations.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_blit_image ( HGFX hgfx, HIMG himg, POS x, POS y, unsigned* ix = 0, unsigned* iy = 0, unsigned* iw = 0, unsigned* ih = 0 );

// blends image bits with bits of the buffer. no affine transformations.
GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_blend_image ( HGFX hgfx, HIMG himg, POS x, POS y, unsigned opacity = 0xFF, unsigned* ix = 0, unsigned* iy = 0, unsigned* iw = 0, unsigned* ih = 0 );

// SECTION: coordinate space

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_world_to_screen ( HGFX hgfx, POS* inout_x, POS* inout_y);

inline GRAPHIN_RESULT
      graphics_world_to_screen ( HGFX hgfx, POS* length)
{
   return graphics_world_to_screen ( hgfx, length, 0);
}

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_screen_to_world ( HGFX hgfx, POS* inout_x, POS* inout_y);

inline GRAPHIN_RESULT
      graphics_screen_to_world ( HGFX hgfx, POS* length)
{
   return graphics_screen_to_world (hgfx, length, 0);
}

// SECTION: clipping

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_set_clip_box ( HGFX hgfx, POS x1, POS y1, POS x2, POS y2);

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_get_clip_box ( HGFX hgfx, POS* x1, POS* y1, POS* x2, POS* y2);

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_is_in_clip_box ( HGFX hgfx, POS x, POS y);

GRAPHIN_API GRAPHIN_RESULT GRAPHIN_CALL
      graphics_rect_is_visible ( HGFX hgfx, POS x1, POS y1, POS x2, POS y2, bool* yes);

#endif


text:
package org.kuali.kfs.module.purap.service.impl;

import org.kuali.kfs.coa.businessobject.Account;
import org.kuali.kfs.coa.businessobject.ObjectCode;
import org.kuali.kfs.coa.businessobject.SubAccount;
import org.kuali.kfs.coa.businessobject.SubObjectCode;
import org.kuali.kfs.coa.service.AccountService;
import org.kuali.kfs.coa.service.ObjectCodeService;
import org.kuali.kfs.coa.service.SubObjectCodeService;
import org.kuali.kfs.gl.batch.ScrubberStep;
import org.kuali.kfs.module.purap.PurapConstants.PaymentRequestStatuses;
import org.kuali.kfs.module.purap.PurapKeyConstants;
import org.kuali.kfs.module.purap.document.PaymentRequestDocument;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSKeyConstants;
import org.kuali.kfs.sys.businessobject.AccountingLine;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.krad.datadictionary.DataDictionary;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.ObjectUtils;

public class PaymentRequestAccountingLineRuleHelperServiceImpl extends PurapAccountingLineRuleHelperServiceImpl {

    /**
     * @see org.kuali.kfs.module.purap.service.impl.AccountsPayableAccountingLineRuleHelperServiceImpl#hasRequiredOverrides(org.kuali.kfs.sys.businessobject.AccountingLine, java.lang.String)
     * For payment request we must throw an error after AP approval for C&G accounts that are expired more than 90 days.
     */
    @Override
    public boolean hasRequiredOverrides(AccountingLine line, String overrideCode) {
        boolean hasOverrides = true;

        Account account = SpringContext.getBean(AccountService.class).getByPrimaryId(line.getChartOfAccountsCode(), line.getAccountNumber());
        String docStatus = getDocument().getApplicationDocumentStatus();

        //if account exists
        if(ObjectUtils.isNotNull(account)){
            //after AP approval
            if(PaymentRequestStatuses.APPDOC_AWAITING_SUB_ACCT_MGR_REVIEW.equals(docStatus) ||
                PaymentRequestStatuses.APPDOC_AWAITING_FISCAL_REVIEW.equals(docStatus) ||
                PaymentRequestStatuses.APPDOC_AWAITING_ORG_REVIEW.equals(docStatus) ||
                PaymentRequestStatuses.APPDOC_AWAITING_TAX_REVIEW.equals(docStatus) ||
                PaymentRequestStatuses.APPDOC_DEPARTMENT_APPROVED.equals(docStatus) ||
                PaymentRequestStatuses.APPDOC_AUTO_APPROVED.equals(docStatus) ){

                String expirationExtensionDays = SpringContext.getBean(ParameterService.class).getParameterValueAsString(ScrubberStep.class, KFSConstants.SystemGroupParameterNames.GL_SCRUBBER_VALIDATION_DAYS_OFFSET);
                int expirationExtensionDaysInt = 3 * 30; // default to 90 days (approximately 3 months)

                if (ObjectUtils.isNotNull(expirationExtensionDays) && expirationExtensionDays.trim().length() > 0) {
                    expirationExtensionDaysInt = Integer.parseInt(expirationExtensionDays);
                }

                //if account is expired, c&g and past 90 days, add error
                if(account.isExpired() && account.isForContractsAndGrants() && (SpringContext.getBean(DateTimeService.class).dateDiff(account.getAccountExpirationDate(), SpringContext.getBean(DateTimeService.class).getCurrentDate(), true) > expirationExtensionDaysInt)){
                    GlobalVariables.getMessageMap().putError(KFSConstants.ACCOUNT_NUMBER_PROPERTY_NAME, PurapKeyConstants.ERROR_ITEM_ACCOUNT_EXPIRED_REPLACE, account.getAccountNumber());
                    hasOverrides = false;
                }
            }
        }else{
            //account not valid, shouldn't happen but just in case
            hasOverrides = false;
        }
        return hasOverrides;
    }

    public boolean isValidObjectCode(ObjectCode objectCode, DataDictionary dataDictionary, String errorPropertyName) {
        String label = getObjectCodeLabel();

        // make sure it exists
        if (ObjectUtils.isNull(objectCode)) {
            GlobalVariables.getMessageMap().putError(errorPropertyName, KFSKeyConstants.ERROR_EXISTENCE, label);
            return false;
        }

        Integer universityFiscalYear = ((PaymentRequestDocument)getDocument()).getPostingYearPriorOrCurrent();
        ObjectCode objectCodeForValidation = (SpringContext.getBean(ObjectCodeService.class).getByPrimaryId(universityFiscalYear, objectCode.getChartOfAccountsCode(), objectCode.getFinancialObjectCode()));

        // check active status
        if (!objectCodeForValidation.isFinancialObjectActiveCode()) {
            GlobalVariables.getMessageMap().putError(errorPropertyName, KFSKeyConstants.ERROR_INACTIVE, label);
            return false;
        }

        return true;
    }

    public boolean isValidSubObjectCode(SubObjectCode subObjectCode, DataDictionary dataDictionary, String errorPropertyName) {
        String label = getSubObjectCodeLabel();

        // make sure it exists
        if (ObjectUtils.isNull(subObjectCode)) {
            GlobalVariables.getMessageMap().putError(errorPropertyName, KFSKeyConstants.ERROR_EXISTENCE, label);
            return false;
        }

        Integer universityFiscalYear = ((PaymentRequestDocument)getDocument()).getPostingYearPriorOrCurrent();
        SubObjectCode subObjectCodeForValidation = (SpringContext.getBean(SubObjectCodeService.class).getByPrimaryId(universityFiscalYear, subObjectCode.getChartOfAccountsCode(), subObjectCode.getAccountNumber(), subObjectCode.getFinancialObjectCode(), subObjectCode.getFinancialSubObjectCode()));

        // check active flag
        if(!subObjectCodeForValidation.isActive()) {
            if( ((PaymentRequestDocument)getDocument()).getApplicationDocumentStatus().equals(PaymentRequestStatuses.APPDOC_AWAITING_FISCAL_REVIEW)){
                GlobalVariables.getMessageMap().putError(errorPropertyName, KFSKeyConstants.ERROR_INACTIVE, label);
                return false;
            }

        }

        return true;
    }

    /**
     * @see org.kuali.kfs.sys.document.service.impl.AccountingLineRuleHelperServiceImpl#isValidSubAccount(org.kuali.kfs.coa.businessobject.SubAccount, org.kuali.rice.krad.datadictionary.DataDictionary, java.lang.String)
     */
    @Override
    public boolean isValidSubAccount(SubAccount subAccount, DataDictionary dataDictionary, String errorPropertyName, String errorPropertyIdentifyingName) {
        String label = getSubAccountLabel();

        // make sure it exists
        if (ObjectUtils.isNull(subAccount)) {
            GlobalVariables.getMessageMap().putError(errorPropertyName, KFSKeyConstants.ERROR_EXISTENCE, label);
            return false;
        }
        if(!subAccount.isActive()){
            if( ((PaymentRequestDocument)getDocument()).getApplicationDocumentStatus().equals(PaymentRequestStatuses.APPDOC_AWAITING_FISCAL_REVIEW)){
                GlobalVariables.getMessageMap().putError(errorPropertyName, KFSKeyConstants.ERROR_INACTIVE, label);
                return false;
            }

        }
        return true;
    }

}


text:
require 'spec_helper'

describe Shortener::ShortenerHelper, type: :helper do
  describe '#short_url' do
    let(:destination) { Faker::Internet.url }

    context 'without user or custom key' do
      before do
        expect(Shortener::ShortenedUrl).to receive(:generate).with(destination, owner: nil, custom_key: nil, expires_at: nil).and_return(shortened_url)
      end

      context 'short url was generated' do
        let(:shortened_url) { instance_double('ShortenedUrl', unique_key: '12345') }

        it "shortens the url" do
          expect(helper.short_url(destination)).to eq "http://test.host/12345"
        end
      end

      context 'short url could not be generated' do
        let(:shortened_url) { nil }

        it 'returns the original url' do
          expect(helper.short_url(destination)).to eq destination
        end
      end
    end

    context 'with owner' do
      let(:owner) { double('User') }
      it 'sends user to generate function' do
        expect(Shortener::ShortenedUrl).to receive(:generate).with(destination, owner: owner, custom_key: nil, expires_at: nil)
        helper.short_url(destination, owner: owner)
      end
    end

    context 'with custom_key' do
      it 'sends custom key code to generate function' do
        expect(Shortener::ShortenedUrl).to receive(:generate).with(destination, owner: nil, custom_key: 'custkey', expires_at: nil)
        helper.short_url(destination, custom_key: 'custkey')
      end
    end

    context 'with expires_at' do
      it 'sends custom key code to generate function' do
        expect(Shortener::ShortenedUrl).to receive(:generate).with(destination, owner: nil, custom_key: nil, expires_at: 'testtime')
        helper.short_url(destination, expires_at: 'testtime')
      end
    end

    context 'with url options for https and subdomain' do
      let(:short_url) { double('ShortUrl', unique_key: 'knownkey') }
      it 'sends custom key code to generate function' do
        expect(Shortener::ShortenedUrl).to receive(:generate).and_return(short_url)
        url = helper.short_url(destination, expires_at: 'testtime', url_options: { subdomain: 'foo', protocol: 'https'})
        expect(url).to eq 'https://foo.test.host/knownkey'
      end
    end
  end
end


text:
package org.teavm.flavour.expr;

import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.teavm.flavour.expr.plan.*;

class InterpreterVisitor implements PlanVisitor {
    private Map<String, Object> variables;
    Object value;
    private Map<String, Class<?>> classCache = new HashMap<>();
    private Map<String, Field> fieldCache = new HashMap<>();
    private Map<String, Method> methodCache = new HashMap<>();
    private Map<String, Constructor<?>> constructorCache = new HashMap<>();

    InterpreterVisitor(Map<String, Object> variables) {
        this.variables = variables;
    }

    @Override
    public void visit(ConstantPlan plan) {
        value = plan.getValue();
    }

    @Override
    public void visit(VariablePlan plan) {
        value = variables.get(plan.getName());
    }

    @Override
    public void visit(BinaryPlan plan) {
        plan.getFirstOperand().acceptVisitor(this);
        Object a = value;
        plan.getSecondOperand().acceptVisitor(this);
        Object b = value;
        switch (plan.getType()) {
            case ADD:
                switch (plan.getValueType()) {
                    case INT:
                        value = (Integer) a + (Integer) b;
                        break;
                    case LONG:
                        value = (Long) a + (Long) b;
                        break;
                    case FLOAT:
                        value = (Float) a + (Float) b;
                        break;
                    case DOUBLE:
                        value = (Double) a + (Double) b;
                        break;
                }
                break;
            case SUBTRACT:
                switch (plan.getValueType()) {
                    case INT:
                        value = (Integer) a - (Integer) b;
                        break;
                    case LONG:
                        value = (Long) a - (Long) b;
                        break;
                    case FLOAT:
                        value = (Float) a - (Float) b;
                        break;
                    case DOUBLE:
                        value = (Double) a - (Double) b;
                        break;
                }
                break;
            case MULTIPLY:
                switch (plan.getValueType()) {
                    case INT:
                        value = (Integer) a * (Integer) b;
                        break;
                    case LONG:
                        value = (Long) a * (Long) b;
                        break;
                    case FLOAT:
                        value = (Float) a * (Float) b;
                        break;
                    case DOUBLE:
                        value = (Double) a * (Double) b;
                        break;
                }
                break;
            case DIVIDE:
                switch (plan.getValueType()) {
                    case INT:
                        value = (Integer) a / (Integer) b;
                        break;
                    case LONG:
                        value = (Long) a / (Long) b;
                        break;
                    case FLOAT:
                        value = (Float) a / (Float) b;
                        break;
                    case DOUBLE:
                        value = (Double) a / (Double) b;
                        break;
                }
                break;
            case REMAINDER:
                switch (plan.getValueType()) {
                    case INT:
                        value = (Integer) a % (Integer) b;
                        break;
                    case LONG:
                        value = (Long) a % (Long) b;
                        break;
                    case FLOAT:
                        value = (Float) a % (Float) b;
                        break;
                    case DOUBLE:
                        value = (Double) a % (Double) b;
                        break;
                }
                break;
            case EQUAL:
                switch (plan.getValueType()) {
                    case INT:
                        value = ((Integer) a).intValue() == ((Integer) b).intValue();
                        break;
                    case LONG:
                        value = ((Long) a).intValue() == ((Long) b).intValue();
                        break;
                    case FLOAT:
                        value = ((Float) a).floatValue() == ((Float) b).floatValue();
                        break;
                    case DOUBLE:
                        value = ((Double) a).doubleValue() == ((Double) b).doubleValue();
                        break;
                }
                break;
            case NOT_EQUAL:
                switch (plan.getValueType()) {
                    case INT:
                        value = ((Integer) a).intValue() != ((Integer) b).intValue();
                        break;
                    case LONG:
                        value = ((Long) a).intValue() != ((Long) b).intValue();
                        break;
                    case FLOAT:
                        value = ((Float) a).floatValue() != ((Float) b).floatValue();
                        break;
                    case DOUBLE:
                        value = ((Double) a).doubleValue() != ((Double) b).doubleValue();
                        break;
                }
                break;
            case GREATER:
                switch (plan.getValueType()) {
                    case INT:
                        value = (Integer) a > (Integer) b;
                        break;
                    case LONG:
                        value = (Long) a > (Long) b;
                        break;
                    case FLOAT:
                        value = (Float) a > (Float) b;
                        break;
                    case DOUBLE:
                        value = (Double) a > (Double) b;
                        break;
                }
                break;
            case GREATER_OR_EQUAL:
                switch (plan.getValueType()) {
                    case INT:
                        value = (Integer) a >= (Integer) b;
                        break;
                    case LONG:
                        value = (Long) a >= (Long) b;
                        break;
                    case FLOAT:
                        value = (Float) a >= (Float) b;
                        break;
                    case DOUBLE:
                        value = (Double) a >= (Double) b;
                        break;
                }
                break;
            case LESS:
                switch (plan.getValueType()) {
                    case INT:
                        value = (Integer) a < (Integer) b;
                        break;
                    case LONG:
                        value = (Long) a < (Long) b;
                        break;
                    case FLOAT:
                        value = (Float) a < (Float) b;
                        break;
                    case DOUBLE:
                        value = (Double) a < (Double) b;
                        break;
                }
                break;
            case LESS_OR_EQUAL:
                switch (plan.getValueType()) {
                    case INT:
                        value = (Integer) a <= (Integer) b;
                        break;
                    case LONG:
                        value = (Long) a <= (Long) b;
                        break;
                    case FLOAT:
                        value = (Float) a <= (Float) b;
                        break;
                    case DOUBLE:
                        value = (Double) a <= (Double) b;
                        break;
                }
                break;
        }
    }

    @Override
    public void visit(NegatePlan plan) {
        plan.getOperand().acceptVisitor(this);
        switch (plan.getValueType()) {
            case INT:
                value = -(Integer) value;
                break;
            case LONG:
                value = -(Long) value;
                break;
            case FLOAT:
                value = -(Float) value;
                break;
            case DOUBLE:
                value = -(Double) value;
                break;
        }
    }

    @Override
    public void visit(ReferenceEqualityPlan plan) {
        plan.getFirstOperand().acceptVisitor(this);
        Object a = value;
        plan.getSecondOperand().acceptVisitor(this);
        Object b = value;
        switch (plan.getType()) {
            case EQUAL:
                value = a == b;
                break;
            case NOT_EQUAL:
                value = a != b;
                break;
        }
    }

    @Override
    public void visit(LogicalBinaryPlan plan) {
        plan.getFirstOperand().acceptVisitor(this);
        Boolean a = (Boolean) value;
        switch (plan.getType()) {
            case AND:
                if (!a) {
                    value = false;
                } else {
                    plan.getSecondOperand().acceptVisitor(this);
                }
                break;
            case OR:
                if (a) {
                    value = true;
                } else {
                    plan.getSecondOperand().acceptVisitor(this);
                }
                break;
        }
    }

    @Override
    public void visit(NotPlan plan) {
        plan.getOperand().acceptVisitor(this);
        value = !(Boolean) value;
    }

    @Override
    public void visit(CastPlan plan) {
        plan.getOperand().acceptVisitor(this);
        if (value == null) {
            return;
        }
        Class<?> type = decodeType(plan.getTargetType());
        if (!type.isInstance(value)) {
            throw new InterpretationException("Can't cast value to " + type);
        }
    }

    @Override
    public void visit(ArithmeticCastPlan plan) {
        plan.getOperand().acceptVisitor(this);
        switch (plan.getSourceType()) {
            case INT:
                switch (plan.getTargetType()) {
                    case INT:
                        break;
                    case LONG:
                        value = (long) (Integer) value;
                        break;
                    case FLOAT:
                        value = (float) (Integer) value;
                        break;
                    case DOUBLE:
                        value = (double) (Integer) value;
                        break;
                }
                break;
            case LONG:
                switch (plan.getTargetType()) {
                    case INT:
                        value = (int) ((Long) value).longValue();
                        break;
                    case LONG:
                        break;
                    case FLOAT:
                        value = (float) (Long) value;
                        break;
                    case DOUBLE:
                        value = (double) (Long) value;
                        break;
                }
                break;
            case FLOAT:
                switch (plan.getTargetType()) {
                    case INT:
                        value = ((Float) value).intValue();
                        break;
                    case LONG:
                        value = ((Float) value).longValue();
                        break;
                    case FLOAT:
                        break;
                    case DOUBLE:
                        value = ((Float) value).doubleValue();
                        break;
                }
                break;
            case DOUBLE:
                switch (plan.getTargetType()) {
                    case INT:
                        value = ((Double) value).intValue();
                        break;
                    case LONG:
                        value = ((Double) value).longValue();
                        break;
                    case FLOAT:
                        value = ((Double) value).floatValue();
                        break;
                    case DOUBLE:
                        break;
                }
                break;
        }
    }

    @Override
    public void visit(CastFromIntegerPlan plan) {
        plan.getOperand().acceptVisitor(this);
        switch (plan.getType()) {
            case BYTE:
                value = ((Integer) value).byteValue();
                break;
            case CHAR:
                value = (char) ((Integer) value).intValue();
                break;
            case SHORT:
                value = ((Integer) value).shortValue();
                break;
        }
    }

    @Override
    public void visit(CastToIntegerPlan plan) {
        plan.getOperand().acceptVisitor(this);
        switch (plan.getType()) {
            case BYTE:
                value = ((Byte) value).intValue();
                break;
            case CHAR:
                value = (int) (Character) value;
                break;
            case SHORT:
                value = ((Short) value).intValue();
                break;
        }
    }

    @Override
    public void visit(GetArrayElementPlan plan) {
        plan.getArray().acceptVisitor(this);
        Object array = value;
        plan.getIndex().acceptVisitor(this);
        int index = (Integer) value;
        value = Array.get(array, index);
    }

    @Override
    public void visit(ArrayLengthPlan plan) {
        plan.getArray().acceptVisitor(this);
        value = Array.getLength(value);
    }

    @Override
    public void visit(FieldPlan plan) {
        Object instance;
        if (plan.getInstance() != null) {
            plan.getInstance().acceptVisitor(this);
            instance = value;
        } else {
            instance = null;
        }
        try {
            value = getField(plan.getClassName(), plan.getFieldName()).get(instance);
        } catch (IllegalAccessException e) {
            throw new InterpretationException("Can't access field " + plan.getClassName() + "."
                    + plan.getFieldName(), e);
        }
    }

    @Override
    public void visit(FieldAssignmentPlan plan) {
        Object instance;
        if (plan.getInstance() != null) {
            plan.getInstance().acceptVisitor(this);
            instance = value;
        } else {
            instance = null;
        }
        plan.getValue().acceptVisitor(this);
        try {
            getField(plan.getClassName(), plan.getFieldName()).set(instance, value);
        } catch (IllegalAccessException e) {
            throw new InterpretationException("Can't access field " + plan.getClassName() + "."
                    + plan.getFieldName(), e);
        }
        value = null;
    }

    @Override
    public void visit(InstanceOfPlan plan) {
        plan.getOperand().acceptVisitor(this);
        if (value == null) {
            value = false;
            return;
        }
        Class<?> type = decodeType(plan.getClassName());
        value = type.isInstance(value);
    }

    @Override
    public void visit(InvocationPlan plan) {
        Object instance;
        if (plan.getInstance() != null) {
            plan.getInstance().acceptVisitor(this);
            instance = value;
        } else {
            instance = null;
        }
        Object[] arguments = new Object[plan.getArguments().size()];
        for (int i = 0; i < arguments.length; ++i) {
            plan.getArguments().get(i).acceptVisitor(this);
            arguments[i] = value;
        }
        Method method = getMethod(plan.getClassName(), plan.getMethodName(), plan.getMethodDesc());
        try {
            value = method.invoke(instance, arguments);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new InterpretationException("Can't access method " + plan.getClassName() + "."
                    + plan.getMethodName() + plan.getMethodDesc(), e);
        }
    }

    @Override
    public void visit(ConstructionPlan plan) {
        Object[] arguments = new Object[plan.getArguments().size()];
        for (int i = 0; i < arguments.length; ++i) {
            plan.getArguments().get(i).acceptVisitor(this);
            arguments[i] = value;
        }
        Constructor<?> ctor = getConstructor(plan.getClassName(), plan.getMethodDesc());
        try {
            value = ctor.newInstance(arguments);
        } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
            throw new InterpretationException("Can't access constructor " + plan.getClassName() + ".<init>"
                    + plan.getMethodDesc(), e);
        }
    }

    @Override
    public void visit(ArrayConstructionPlan plan) {
        TypeDecoder decoder = new TypeDecoder(plan.getElementType());
        Class<?> type = decoder.decode();
        Object array = Array.newInstance(type, plan.getElements().size());
        for (int i = 0; i < plan.getElements().size(); ++i) {
            plan.getElements().get(i).acceptVisitor(this);
            Array.set(array, i, value);
        }
        value = array;
    }

    @Override
    public void visit(ConditionalPlan plan) {
        plan.getCondition().acceptVisitor(this);
        Boolean condition = (Boolean) value;
        if (condition) {
            plan.getConsequent().acceptVisitor(this);
        } else {
            plan.getAlternative().acceptVisitor(this);
        }
    }

    @Override
    public void visit(ThisPlan plan) {
        value = variables.get("this");
    }

    @Override
    public void visit(final LambdaPlan plan) {
        Class<?> cls = getClass(plan.getClassName());
        final Method proxyMethod = getMethod(plan.getClassName(), plan.getMethodName(), plan.getMethodDesc());
        value = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class<?>[] { cls },
                (proxy, method, args) -> {
            Object oldValue = value;
            value = null;
            if (method.equals(proxyMethod)) {
                Object[] oldVars = new Object[plan.getBoundVars().size()];
                for (int i = 0; i < plan.getBoundVars().size(); ++i) {
                    oldVars[i] = variables.get(plan.getBoundVars().get(i));
                    variables.put(plan.getBoundVars().get(i), args[i]);
                }
                plan.getBody().acceptVisitor(InterpreterVisitor.this);
                for (int i = 0; i < plan.getBoundVars().size(); ++i) {
                    variables.put(plan.getBoundVars().get(i), oldVars[i]);
                }
            }
            Object result = value;
            value = oldValue;
            return result;
        });
    }

    @Override
    public void visit(ObjectPlan plan) {
        Class<?> cls = getClass(plan.getClassName());
        Object instance;
        try {
            instance = cls.newInstance();
        } catch (IllegalAccessException | InstantiationException e) {
            throw new InterpretationException("Can't access constructor " + plan.getClassName() + ".<init>()", e);
        }

        for (ObjectPlanEntry entry : plan.getEntries()) {
            Method method = getMethod(cls.getName(), entry.getSetterName(), entry.getSetterDesc());
            entry.getValue().acceptVisitor(this);
            try {
                method.invoke(instance, value);
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new InterpretationException("Can't access method " + plan.getClassName() + "."
                        + entry.getSetterName() + entry.getSetterDesc(), e);
            }
        }

        value = instance;
    }

    private Class<?> decodeType(String type) {
        return new TypeDecoder(type).decode();
    }

    private Class<?> getClass(String name) {
        Class<?> cls = classCache.get(name);
        if (cls == null) {
            try {
                cls = Class.forName(name);
            } catch (ClassNotFoundException e) {
                return null;
            }
            classCache.put(name, cls);
        }
        return cls;
    }

    private Field getField(String className, String fieldName) {
        String key = className + "#" + fieldName;
        Field field = fieldCache.get(key);
        if (field == null) {
            Class<?> cls = getClass(className);
            if (cls == null) {
                return null;
            }
            try {
                field = cls.getField(fieldName);
            } catch (NoSuchFieldException e) {
                return null;
            }
            fieldCache.put(key, field);
        }
        return field;
    }

    private Method getMethod(String className, String methodName, String desc) {
        String key = className + "#" + methodName + desc;
        Method method = methodCache.get(key);
        if (method == null) {
            List<Class<?>> argumentTypes = new ArrayList<>();
            TypeDecoder decoder = new TypeDecoder(desc);
            if (decoder.text.charAt(decoder.position++) != '(') {
                throw new InterpretationException("Wrong method descriptor " + desc);
            }
            while (decoder.text.charAt(decoder.position) != ')') {
                argumentTypes.add(decoder.decode());
            }
            Class<?> cls = getClass(className);
            if (cls == null) {
                return null;
            }
            try {
                method = cls.getMethod(methodName, argumentTypes.toArray(new Class<?>[0]));
            } catch (NoSuchMethodException e) {
                return null;
            }
            methodCache.put(key, method);
        }
        return method;
    }

    private Constructor<?> getConstructor(String className, String desc) {
        String key = className + "#" + desc;
        Constructor<?> ctor = constructorCache.get(key);
        if (ctor == null) {
            List<Class<?>> argumentTypes = new ArrayList<>();
            TypeDecoder decoder = new TypeDecoder(desc);
            if (decoder.text.charAt(decoder.position++) != '(') {
                throw new InterpretationException("Wrong method descriptor " + desc);
            }
            while (decoder.text.charAt(decoder.position) != ')') {
                argumentTypes.add(decoder.decode());
            }
            Class<?> cls = getClass(className);
            if (cls == null) {
                return null;
            }
            try {
                ctor = cls.getConstructor(argumentTypes.toArray(new Class<?>[0]));
            } catch (NoSuchMethodException e) {
                return null;
            }
            constructorCache.put(key, ctor);
        }
        return ctor;
    }

    class TypeDecoder {
        int position;
        final String text;

        TypeDecoder(String text) {
            this.text = text;
        }

        Class<?> decode() {
            switch (text.charAt(position++)) {
                case 'Z':
                    return boolean.class;
                case 'C':
                    return char.class;
                case 'B':
                    return byte.class;
                case 'S':
                    return short.class;
                case 'I':
                    return int.class;
                case 'J':
                    return long.class;
                case 'F':
                    return float.class;
                case 'D':
                    return double.class;
                case 'V':
                    return void.class;
                case 'L': {
                    int index = text.indexOf(';', position);
                    Class<?> cls = InterpreterVisitor.this.getClass(text.substring(position, index).replace('/', '.'));
                    position = index + 1;
                    return cls;
                }
                case '[':
                    return Array.newInstance(decode(), 0).getClass();
                default:
                    throw new InterpretationException("Error parsing type descriptor");
            }
        }
    }
}


text:
package com.pivotal.gemfirexd.internal.engine.distributed.metadata;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.sql.Activation;
import com.pivotal.gemfirexd.internal.iapi.sql.ResultDescription;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecRow;
import com.pivotal.gemfirexd.internal.shared.common.ResolverUtils;

/**
 * Class representing a group of AbstractConditionQueryInfo object having
 * dependency on a given column. It gets created if there are more than one
 * conditions in where clause dependent on a column being considered and atleast
 * one of those conditions is parameterized.
 *
 * @author Asif
 *
 */
public class ParameterizedConditionsWrapperQueryInfo extends
    AbstractConditionQueryInfo {
  /**
   * Can be an instance of ComparisonQueryInfo , RangeQueryInfo or
   * ConstantConditionsQueryInfo
   */

  private AbstractConditionQueryInfo constantCondition = null;

  /**
   * List containing parameterized ComparisonQueryInfo
   */
  private final List<AbstractConditionQueryInfo> parameterizedConditions = new ArrayList<AbstractConditionQueryInfo>(
      4);

  ParameterizedConditionsWrapperQueryInfo(
      AbstractConditionQueryInfo condition1,
      AbstractConditionQueryInfo condition2) {

    if (condition1.isWhereClauseDynamic()) {
      this.parameterizedConditions.add(condition1);
      if (condition2.isWhereClauseDynamic()) {
        this.parameterizedConditions.add(condition2);
      }
      else {
        this.constantCondition = condition2;
      }
    }
    else {
      this.constantCondition = condition1;
      assert condition2.isWhereClauseDynamic();
      this.parameterizedConditions.add(condition2);
    }

  }

  AbstractConditionQueryInfo createOrAddToGroup(
      AbstractConditionQueryInfo operand, boolean ignore, Activation activation, boolean forSingleHopPreparePhase)
      throws StandardException {
    // the createConstantCondtionsWrapperIfMergeNotPossible boolean will always
    // be true
    assert ignore;
    assert activation == null;
    if (operand.isWhereClauseDynamic()) {
      this.parameterizedConditions.add(operand);
    }
    else {
      // If constantCondition is an instance of ComparisonQueryInfo or
      // RangeQueryInfo, the merge operation
      // may return an instance of ConstantConditionsQueryInfo. But if it is an
      // instance of
      // ConstantConditionsQueryInfo, it will return itself.
      if(this.constantCondition  != null) {
        this.constantCondition = this.constantCondition.createOrAddToGroup(
          operand, true, activation, false);
      }else {
        this.constantCondition = operand;
      }
    }
    return this;
  }

  /**
   * Test API only
   *
   * @return Returns a List containing parameterized AbstractConditionQueryInfo
   *         objects
   *
   */
  List getParameterizedOperands() {
    return Collections.unmodifiableList(this.parameterizedConditions);
  }

  /**
   * Test API only
   *
   * @return Returns AbstractConditionQueryInfo representing the constant
   *         conditions. Could be any one of ComparisonQueryInfo, RangeQueryInfo
   *         or ConstantConditionsQueryInfo
   *
   */
  AbstractConditionQueryInfo getConstantOperand() {
    return this.constantCondition;
  }

  //TODO:Asif: Currently computing the nodes of constant condition separately from the
  // parameterized condition. The parameterized conditions are being grouped
  // among themselves & not with the constant condition. It might be better
  // in terms of node prunning if the grouping could happen across the constant
  // and parameterized conditions, but that would mean generation of new structures
  // and code becoming messier ( we cannot modify the constant condition object).
  // At some point later , we should look into this optimization
  @Override
  public void computeNodes(Set<Object> routingKeys, Activation activation,
      boolean forSingleHopPreparePhase)
      throws StandardException {
    assert routingKeys.size() ==1;
    assert routingKeys.contains(ResolverUtils.TOK_ALL_NODES);
    //First compute the nodes for constant condition
    Set<Object> nodesCollector = new HashSet<Object>();
    nodesCollector.add(ResolverUtils.TOK_ALL_NODES);
    if (this.constantCondition != null) {
      this.constantCondition.computeNodes(nodesCollector, activation, forSingleHopPreparePhase);
      if(!nodesCollector.contains(ResolverUtils.TOK_ALL_NODES)) {
        routingKeys.remove(ResolverUtils.TOK_ALL_NODES);
        routingKeys.addAll(nodesCollector);
        nodesCollector.clear();
        nodesCollector.add(ResolverUtils.TOK_ALL_NODES);
      }else {
        assert nodesCollector.size() == 1;
      }
    }

    AbstractConditionQueryInfo tempAcqi = this.groupParameterizedConditions(
        activation, forSingleHopPreparePhase);

    tempAcqi.computeNodes(nodesCollector, activation, forSingleHopPreparePhase);
    if(!nodesCollector.contains(ResolverUtils.TOK_ALL_NODES)) {
      if(routingKeys.contains(ResolverUtils.TOK_ALL_NODES)) {
        routingKeys.remove(ResolverUtils.TOK_ALL_NODES);
        routingKeys.addAll(nodesCollector);
      }else {
        routingKeys.retainAll(nodesCollector);
      }
    }
  }

  AbstractConditionQueryInfo groupParameterizedConditions(
      Activation activation, boolean forSingleHopPreparePhase)
      throws StandardException {
    //Try to group the parameterized conditions
    Iterator<AbstractConditionQueryInfo> itr = this.parameterizedConditions
        .iterator();
    assert itr.hasNext();
    AbstractConditionQueryInfo tempAcqi = itr.next();
    while (itr.hasNext()) {
      tempAcqi = tempAcqi.createOrAddToGroup(itr.next(), true /*
       * create ConstantConditionsWrapper if merge not
       * possible*/, activation, forSingleHopPreparePhase);
    }
    return tempAcqi;

  }

  @Override
  boolean isWhereClauseDynamic() {
    return true;
  }

}


text:
namespace png
{
	using byte = unsigned char;

	using ChunkTypeBytes = std::array<char, 4>;

	enum class ColorType
	{
		Indexed,
		Grayscale,
		GrayscaleAlpha,
		RGB,
		RGBA,
	};
}

#endif