text:
from unittest import mock
from unittest.mock import MagicMock
from unittest.mock import Mock
from unittest.mock import patch

from glanceclient import exc as glance_exceptions
import jsonschema

from trove.common import clients
from trove.common import exception
from trove.configuration import models as config_models
from trove.datastore import models
from trove.extensions.mgmt.datastores.service import DatastoreVersionController
from trove.tests.unittests import trove_testtools
from trove.tests.unittests.util import util

class TestDatastoreVersionController(trove_testtools.TestCase):
    @classmethod
    def setUpClass(cls):
        util.init_db()
        cls.ds_name = cls.random_name('datastore')
        cls.ds_version_number = '5.7.30'
        models.update_datastore(name=cls.ds_name, default_version=None)

        models.update_datastore_version(
            cls.ds_name, 'test_vr1', 'mysql', cls.random_uuid(), '', 'pkg-1',
            1)
        models.update_datastore_version(
            cls.ds_name, 'test_vr2', 'mysql', cls.random_uuid(), '', 'pkg-1',
            1, version=cls.ds_version_number)

        cls.ds = models.Datastore.load(cls.ds_name)
        cls.ds_version1 = models.DatastoreVersion.load(cls.ds, 'test_vr1')
        cls.ds_version2 = models.DatastoreVersion.load(
            cls.ds, 'test_vr2', version=cls.ds_version_number)
        cls.version_controller = DatastoreVersionController()

        super(TestDatastoreVersionController, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        util.cleanup_db()

        super(TestDatastoreVersionController, cls).tearDownClass()

    def test_create_schema(self):
        image_id = self.random_uuid()
        ver_name = self.random_name('dsversion')
        body = {
            "version": {
                "datastore_name": self.ds_name,
                "name": ver_name,
                "datastore_manager": "mysql",
                "image": image_id,
                "image_tags": [],
                "active": True,
                "default": False
            }
        }

        schema = self.version_controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)

        self.assertTrue(validator.is_valid(body))

    def test_create_schema_too_many_image_tags(self):
        ver_name = self.random_name('dsversion')
        body = {
            "version": {
                "datastore_name": self.ds_name,
                "name": ver_name,
                "datastore_manager": "mysql",
                "image_tags": ['a', 'b', 'c', 'd', 'e', 'f'],
                "active": True,
                "default": False
            }
        }

        schema = self.version_controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)

        self.assertFalse(validator.is_valid(body))

    def test_create_schema_emptyname(self):
        image_id = self.random_uuid()
        body = {
            "version": {
                "datastore_name": self.ds_name,
                "name": " ",
                "datastore_manager": "mysql",
                "image": image_id,
                "image_tags": [],
                "active": True,
                "default": False
            }
        }
        schema = self.version_controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)

        self.assertFalse(validator.is_valid(body))

        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        self.assertEqual(1, len(errors))
        self.assertEqual("' ' does not match '^.*[0-9a-zA-Z]+.*$'",
                         errors[0].message)

    @patch.object(clients, 'create_glance_client')
    def test_create(self, mock_glance_client):
        image_id = self.random_uuid()
        ver_name = self.random_name('dsversion')
        body = {
            "version": {
                "datastore_name": self.ds_name,
                "name": ver_name,
                "datastore_manager": "mysql",
                "image": image_id,
                "image_tags": [],
                "packages": "test-pkg",
                "active": True,
                "default": True
            }
        }
        output = self.version_controller.create(MagicMock(), body, mock.ANY)
        self.assertEqual(202, output.status)

        new_ver = models.DatastoreVersion.load(self.ds, ver_name)
        self.assertEqual(image_id, new_ver.image_id)
        self.assertEqual(ver_name, new_ver.version)

    @patch.object(clients, 'create_glance_client')
    def test_create_same_version_number(self, mock_glance_client):
        image_id = self.random_uuid()
        ver_name = self.random_name('dsversion')
        body = {
            "version": {
                "datastore_name": self.ds_name,
                "name": ver_name,
                "datastore_manager": "mysql",
                "image": image_id,
                "image_tags": [],
                "packages": "",
                "active": True,
                "default": False,
                "version": self.ds_version_number
            }
        }
        output = self.version_controller.create(MagicMock(), body, mock.ANY)
        self.assertEqual(202, output.status)

        new_ver = models.DatastoreVersion.load(self.ds, ver_name,
                                               version=self.ds_version_number)
        self.assertEqual(image_id, new_ver.image_id)
        self.assertEqual(ver_name, new_ver.name)
        self.assertEqual(self.ds_version_number, new_ver.version)
        self.assertNotEqual(self.ds_version2.id, new_ver.id)

    @patch.object(clients, 'create_glance_client')
    def test_create_by_image_tags(self, mock_create_client):
        ver_name = self.random_name('dsversion')
        body = {
            "version": {
                "datastore_name": self.ds_name,
                "name": ver_name,
                "datastore_manager": "mysql",
                "image_tags": ["trove", "mysql"],
                "active": True,
                "default": True
            }
        }
        mock_client = MagicMock()
        mock_client.images.list.return_value = [{"id": self.random_uuid()}]
        mock_create_client.return_value = mock_client

        output = self.version_controller.create(MagicMock(), body, mock.ANY)
        self.assertEqual(202, output.status)

        mock_client.images.list.assert_called_once_with(
            filters={'tag': ["trove", "mysql"], 'status': 'active'},
            sort='created_at:desc',
            limit=1
        )

        new_ver = models.DatastoreVersion.load(self.ds, ver_name)
        self.assertIsNone(new_ver.image_id)
        self.assertEqual('trove,mysql', new_ver.image_tags)

    @patch.object(clients, 'create_glance_client')
    def test_create_exist(self, mock_glance_client):
        image_id = self.random_uuid()
        ver_name = 'test_vr1'
        body = {
            "version": {
                "datastore_name": self.ds_name,
                "name": ver_name,
                "datastore_manager": "mysql",
                "image": image_id,
                "image_tags": [],
                "packages": "test-pkg",
                "active": True,
                "default": True
            }
        }
        self.assertRaises(
            exception.DatastoreVersionAlreadyExists,
            self.version_controller.create, MagicMock(), body, mock.ANY)

    def test_create_no_image(self):
        ver_name = self.random_name('dsversion')
        body = {
            "version": {
                "datastore_name": self.ds_name,
                "name": ver_name,
                "datastore_manager": "mysql",
                "active": True,
                "default": False
            }
        }
        self.assertRaises(
            exception.BadRequest,
            self.version_controller.create, MagicMock(), body, mock.ANY)

    @patch.object(clients, 'create_glance_client')
    def test_create_image_notfound(self, mock_create_client):
        image_id = self.random_uuid()
        ver_name = self.random_name('dsversion')
        body = {
            "version": {
                "datastore_name": self.ds_name,
                "name": ver_name,
                "datastore_manager": "mysql",
                "image": image_id,
                "active": True,
                "default": False
            }
        }
        mock_client = Mock()
        mock_client.images.get.side_effect = [glance_exceptions.HTTPNotFound()]
        mock_create_client.return_value = mock_client

        self.assertRaises(
            exception.ImageNotFound,
            self.version_controller.create, MagicMock(), body, mock.ANY)

    def test_update_name(self):
        new_name = self.random_name('ds-version-name')
        body = {
            "name": new_name
        }

        orig_ver = models.DatastoreVersion.load(self.ds, self.ds_version1.id)

        output = self.version_controller.edit(MagicMock(), body, mock.ANY,
                                              self.ds_version1.id)
        self.assertEqual(202, output.status)

        updated_ver = models.DatastoreVersion.load(self.ds,
                                                   self.ds_version1.id)

        self.assertEqual(new_name, updated_ver.name)
        self.assertEqual(orig_ver.image_id, updated_ver.image_id)
        self.assertEqual(orig_ver.image_tags, updated_ver.image_tags)
        self.assertEqual(orig_ver.version, updated_ver.version)

    @patch.object(clients, 'create_glance_client')
    def test_update_image(self, mock_create_client):
        new_image = self.random_uuid()
        body = {
            "image": new_image
        }

        output = self.version_controller.edit(MagicMock(), body, mock.ANY,
                                              self.ds_version1.id)
        self.assertEqual(202, output.status)

        updated_ver = models.DatastoreVersion.load(self.ds,
                                                   self.ds_version1.id)
        self.assertEqual(new_image, updated_ver.image_id)

    @patch.object(clients, 'create_glance_client')
    def test_update_image_tags(self, mock_create_client):
        name = self.random_name('dsversion')
        models.update_datastore_version(
            self.ds_name, name, 'mysql', self.random_uuid(), '', '', 1)
        ver = models.DatastoreVersion.load(self.ds, name)

        mock_client = MagicMock()
        mock_client.images.list.return_value = [{"id": self.random_uuid()}]
        mock_create_client.return_value = mock_client

        body = {
            "image_tags": ['trove', 'mysql']
        }

        output = self.version_controller.edit(MagicMock(), body, mock.ANY,
                                              ver.id)
        self.assertEqual(202, output.status)

        updated_ver = models.DatastoreVersion.load(self.ds, ver.id)
        self.assertEqual("", updated_ver.image_id)
        self.assertEqual("trove,mysql", updated_ver.image_tags)

    def test_delete(self):
        name = self.random_name('dsversion')
        models.update_datastore_version(
            self.ds_name, name, 'mysql', self.random_uuid(), '', '', 1)
        ver = models.DatastoreVersion.load(self.ds, name)

        # Add config param for the datastore version. Should be automatically
        # removed.
        param_name = self.random_name('param')
        config_models.create_or_update_datastore_configuration_parameter(
            param_name, ver.id, False, 'string', None, None)

        output = self.version_controller.delete(MagicMock(),
                                                mock.ANY,
                                                ver.id)
        self.assertEqual(202, output.status)

        self.assertRaises(
            exception.DatastoreVersionNotFound,
            models.DatastoreVersion.load_by_uuid, ver.id)

        config_params_cls = config_models.DatastoreConfigurationParameters
        self.assertRaises(
            exception.NotFound,
            config_params_cls.load_parameter_by_name,
            ver.id, param_name)

    def test_index(self):
        output = self.version_controller.index(MagicMock(), mock.ANY)
        self.assertEqual(200, output.status)

        data = output.data(None)
        self.assertGreater(len(data['versions']), 0)

    def test_show(self):
        output = self.version_controller.show(
            MagicMock(), mock.ANY, self.ds_version2.id)
        self.assertEqual(200, output.status)
        self.assertEqual(self.ds_version2.id,
                         output._data['version']['id'])
        self.assertEqual(self.ds_version2.name,
                         output._data['version']['name'])
        self.assertEqual(self.ds_version2.datastore_id,
                         output._data['version']['datastore_id'])
        self.assertEqual(self.ds_version2.datastore_name,
                         output._data['version']['datastore_name'])
        self.assertEqual(self.ds_version2.manager,
                         output._data['version']['datastore_manager'])
        self.assertEqual(self.ds_version2.image_id,
                         output._data['version']['image'])
        self.assertEqual(self.ds_version2.packages.split(','),
                         output._data['version']['packages'])
        self.assertEqual(self.ds_version2.active,
                         output._data['version']['active'])
        self.assertEqual(self.ds_version2.version,
                         output._data['version']['version'])

    def test_show_image_tags(self):
        ver_name = self.random_name('dsversion')
        tags = ['trove', 'mysql']
        models.update_datastore_version(self.ds_name, ver_name, 'mysql', '',
                                        tags, '', 1)
        ver = models.DatastoreVersion.load(self.ds, ver_name)

        output = self.version_controller.show(
            MagicMock(), mock.ANY, ver.id)
        self.assertEqual(200, output.status)

        data = output.data(None)
        self.assertEqual(tags, data['version']['image_tags'])


text:
## copyrightedFunction()
**Kind**: global function
**Copyright**: Lloyd Brookes <75pound@gmail.com>

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: Tensorflow JS
description:
categories: neural-nets
excerpt:
series: Deep Learning Journal
tags: []
image:
    feature: anns_everywhere.png
comments: true
custom_css:
custom_js:
---

Note, gcc-c++ is needed to install Tensorflow using `npm`.
```
sudo yum install -y nodejs gcc-c++
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
mkdir tox_com_det_service
cd tox_com_det_service
npm init
npm install @tensorflow/tfjs-node
npm install express body-parser axios mongoose
nano config.json
```

### Convert Model from Keras to TensorflowJS
https://js.tensorflow.org/tutorials/import-keras.html
```
mkdir tfjs_models
tensorflowjs_converter --input_format keras \
                       /home/ladvien/tox_com_det.h5 \
                       /home/ladvien/tox_com_det_service/tfjs_model/
```


text:
from setuptools import setup

from whoisp import __author__, __version__

with open('README.md') as readme_file:
    readme = readme_file.read()

setup(
    name='whoisp',
    version=__version__,
    description='simple whois parser',
    long_description=readme,
    author=__author__,
    author_email='r.sayargaliev@gmail.com',
    license='MIT',
    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
    ],
    url='https://github.com/amureki/whoisp.git',
    packages=['whoisp'],
    zip_safe=False,
    keywords='domain,whois',
    test_suite='tests',
)


text:
package ca.qc.johnabbott.cs603.Activities;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;

import ca.qc.johnabbott.cs603.Fragments.CreateFragment;
import ca.qc.johnabbott.cs603.Fragments.LoginFragment;
import ca.qc.johnabbott.cs603.R;
import ca.qc.johnabbott.cs603.ExternalLibraries.SlidingTabLayout;

public class startupActivity extends ActionBarActivity {
    private SlidingTabLayout mSlidingTabLayout;
    private ViewPager mViewPager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startup);

        mViewPager = (ViewPager) findViewById(R.id.startupPager);
        mViewPager.setAdapter(new StartupAdapter(getSupportFragmentManager()));
        mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
        mSlidingTabLayout.setDistributeEvenly(true);
        mSlidingTabLayout.setViewPager(mViewPager);

        //setting indicator and divider color
        mSlidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.colorSecondary);    //define any color in xml resources and set it here, I have used white
            }
        });
    }

    public class StartupAdapter extends FragmentStatePagerAdapter {
        private String[] titles = {"Login", "Register" };

        public StartupAdapter(FragmentManager fm) { super(fm); }

        @Override
        public Fragment getItem(int i) {
            switch (i) {
                case 0:
                    return new LoginFragment();
                case 1:
                    return new CreateFragment();
            }
            return null;
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
}


text:
<?php

Prado::using('System.Security.TUser');
Prado::using('System.Security.TUserManager');

/**
 * @package System.Security
 */
class TUserTest extends PHPUnit_Framework_TestCase {
	public static $app=null;
	public static $mgr=null;

	public function setUp() {
		if(self::$app === null) {
			self::$app = new TApplication(dirname(__FILE__).'/app');
			prado::setPathofAlias('App', dirname(__FILE__));
		}

		if (self::$mgr===null) {
			$config=new TXmlDocument('1.0','utf8');
			$config->loadFromString('<users><user name="Joe" password="demo"/><user name="John" password="demo" /><role name="Administrator" users="John" /><role name="Writer" users="Joe,John" /></users>');
			self::$mgr=new TUserManager();
			self::$mgr->init($config);
		}
	}

	public function tearDown() {
	}

	public function testConstruct() {
		$user = new TUser (self::$mgr);
		self::assertEquals('Guest', $user->getName());
		self::assertEquals(self::$mgr, $user->getManager());
	}

	public function testManager() {
		$user = new TUser (self::$mgr);
		self::assertEquals(self::$mgr, $user->getManager());
	}

	public function testName() {
		$user = new TUser (self::$mgr);
		$user->setName('joe');
		self::assertEquals('joe', $user->getName());
	}

	public function testIsGuest() {
		$user = new TUser (self::$mgr);
		$user->setName('John');
		$user->setIsGuest(false);
		$user->setRoles('Administrator, Writer');
		self::assertFalse($user->getIsGuest());
		$user->setIsGuest(true);
		self::assertTrue($user->getIsGuest());
		self::assertEquals(array(),$user->getRoles());
	}

	public function testRoles() {
		$user=new TUser(self::$mgr);
		$user->setRoles(array('Administrator','Writer'));
		self::assertEquals(array('Administrator','Writer'), $user->getRoles());
		$user->setRoles('Reader,User');
		self::assertEquals(array('Reader','User'), $user->getRoles());
	}

	public function testIsInRole() {
		$user=new TUser(self::$mgr);
		$user->setRoles(array('Administrator','Writer'));
		// Roles are case insensitive
		self::assertTrue($user->IsInRole('writer'));
		self::assertTrue($user->IsInRole('Writer'));
		self::assertFalse($user->isInRole('Reader'));
	}

	public function testSaveToString() {
		$user = new TUser (self::$mgr);
		$user->setName('John');
		$user->setIsGuest(false);
		$user->setRoles('Administrator, Writer');
		// State array should now be :
		$assumedState=array ('Name' => 'John', 'IsGuest' => false, 'Roles' => array ('Administrator', 'Writer'));
		self::assertEquals(serialize($assumedState), $user->saveToString());
	}

	public function testLoadFromString() {
		$user = new TUser (self::$mgr);
		$user->setName('John');
		$user->setIsGuest(false);
		$user->setRoles('Administrator, Writer');
		$save=$user->saveToString();

		$user2 = new TUser (self::$mgr);
		$user2->loadFromString($save);

		self::assertEquals($user, $user2);
	}

	/* getState & setState are protected methods, will be tested with other tests.
	public function testState() {
		throw new PHPUnit_Framework_IncompleteTestError();
	}
	*/

	public function testStateChanged() {
		$user = new TUser (self::$mgr);
		$user->setName('John');
		self::assertTrue($user->getStateChanged());
		$user->setStateChanged(false);
		self::assertFalse($user->getStateChanged());
	}

}


text:
package com.akx2.ld32;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pool;

public class FireworkFactory {

    Texture fireworkTexture;
    TextureRegion[] fireworkTextureRegion;

    Array<Firework> activeFireworks = new Array<Firework>();
    Pool<Firework> fireworkPool = new Pool<Firework>() {
        @Override
        protected Firework newObject() {
            return new Firework();
        }
    };

    Firework tFirework;

    int tLen = 0;
    int tI = 0;

    Color batchColor;

    public FireworkFactory()
    {
        fireworkTexture = new Texture(Gdx.files.internal("images/firework1.png"), true);
        fireworkTextureRegion = new TextureRegion[2];
        fireworkTextureRegion[0] = new TextureRegion(fireworkTexture, 0, 0, 16, 16);
        fireworkTextureRegion[1] = new TextureRegion(fireworkTexture, 16, 0, 16, 16);
    }

    public void add (float x, float y, float velX, float velY)
    {
        tFirework = fireworkPool.obtain();
        tFirework.init(x, y, velX, velY);
        activeFireworks.add(tFirework);
    }

    public void render (SpriteBatch batch)
    {
        tLen = activeFireworks.size;
        for (tI = tLen; --tI >= 0;) {
            tFirework = activeFireworks.get(tI);
            if (tFirework.isAlive) {

                batchColor = batch.getColor();
                batch.setColor(tFirework.color);

                switch (tFirework.modeIndex)
                {
                    case 0:
                        batch.draw(fireworkTextureRegion[0], tFirework.position.x, tFirework.position.y, 8, 8, 16, 16, 2f, 2f, 0f);
                        break;
                    case 1:
                        batch.draw(fireworkTextureRegion[0], tFirework.position.x, tFirework.position.y, 8, 8, 16, 16, 2f, 2f, 0f);
                        batch.draw(fireworkTextureRegion[1], tFirework.position.x, tFirework.position.y, 8, 8, 16, 16, 2f, 2f, 0f);
                        break;
                    case 2:
                        batch.draw(fireworkTextureRegion[1], tFirework.position.x, tFirework.position.y, 8, 8, 16, 16, 2f, 2f, 0f);
                        break;

                }
                batch.setColor(1,1,1,1);
            }
        }
    }

    public void update (float delta)
    {
        // RELEASE FIREWORKS
        tLen = activeFireworks.size;
        for (tI = tLen; --tI >= 0;) {
            tFirework = activeFireworks.get(tI);
            if (tFirework.isAlive == false) {
                activeFireworks.removeIndex(tI);
                fireworkPool.free(tFirework);
            } else {
                tFirework.update(delta);
            }
        }
    }

    public void clearAll ()
    {
        tLen = activeFireworks.size;
        for (tI = tLen; --tI >= 0;) {
            tFirework = activeFireworks.get(tI);
            activeFireworks.removeIndex(tI);
            fireworkPool.free(tFirework);
        }
    }

    public void dispose ()
    {
        fireworkTexture.dispose();
    }
}


text:
import * as reactLogo from './react.svg';
import * as reduxLogo from './redux.png';
import * as nodeLogo from './node.svg';
import * as jQueryLogo from './jQurery.png';
import * as aspNetLogo from './aspnet.png';
import * as adfLogo from './Oracle-ADF.png';
import * as html5Logo from './html5.png';
import * as css3logo from './css3.png';
import * as sqlLogo from './sql-logo.png';
import * as mongoLogo from './mongo.png';
import * as androidLogo from './android.png';

export const react = reactLogo;
export const redux = reduxLogo;
export const node = nodeLogo;
export const jQuery = jQueryLogo;
export const aspNet = aspNetLogo;
export const adf = adfLogo;
export const mongo = mongoLogo;
export const html5 = html5Logo;
export const css3 = css3logo;
export const sql = sqlLogo;
export const android = androidLogo;


text:
using System;
using System.Collections;

namespace MonoCov {

public class NamespaceCoverageItem : CoverageItem {

	public string ns;

	public NamespaceCoverageItem (CoverageItem parent, string ns) : base (parent) {
		this.ns = ns;
	}

	public NamespaceCoverageItem ParentNamespace {
		get {
			return (NamespaceCoverageItem)parent;
		}
	}
}
}


text:
<?php

/**
 * This class defines the structure of the 'clientaddressship' table.
 *
 *
 *
 * This map class is used by Propel to do runtime db structure discovery.
 * For example, the createSelectSql() method checks the type of a given column used in an
 * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
 * (i.e. if it's a text column type).
 *
 * @package    propel.generator.api.map
 */
class ClientaddressshipTableMap extends TableMap
{

    /**
     * The (dot-path) name of this class
     */
    const CLASS_NAME = 'api.map.ClientaddressshipTableMap';

    /**
     * Initialize the table attributes, columns and validators
     * Relations are not initialized by this method since they are lazy loaded
     *
     * @return void
     * @throws PropelException
     */
    public function initialize()
    {
        // attributes
        $this->setName('clientaddressship');
        $this->setPhpName('Clientaddressship');
        $this->setClassname('Clientaddressship');
        $this->setPackage('api');
        $this->setUseIdGenerator(true);
        // columns
        $this->addPrimaryKey('idclientaddressship', 'Idclientaddressship', 'INTEGER', true, null, null);
        $this->addForeignKey('idclient', 'Idclient', 'INTEGER', 'client', 'idclient', true, null, null);
        $this->addColumn('clientaddressship_iso_codecountry', 'ClientaddressshipIsoCodecountry', 'VARCHAR', true, 5, null);
        $this->addColumn('clientaddressship_iso_codephone', 'ClientaddressshipIsoCodephone', 'VARCHAR', true, 5, null);
        $this->addColumn('clientaddressship_addressee', 'ClientaddressshipAddressee', 'VARCHAR', true, 145, null);
        $this->addColumn('clientaddressship_addressee_cellular', 'ClientaddressshipAddresseeCellular', 'VARCHAR', true, 18, null);
        $this->addColumn('clientaddressship_addressee_phone', 'ClientaddressshipAddresseePhone', 'VARCHAR', true, 18, null);
        $this->addColumn('clientaddressship_address', 'ClientaddressshipAddress', 'VARCHAR', true, 145, null);
        $this->addColumn('clientaddressship_address2', 'ClientaddressshipAddress2', 'VARCHAR', true, 145, null);
        $this->addColumn('clientaddressship_city', 'ClientaddressshipCity', 'VARCHAR', true, 145, null);
        $this->addColumn('clientaddressship_state', 'ClientaddressshipState', 'VARCHAR', true, 145, null);
        $this->addColumn('clientaddressship_zipcode', 'ClientaddressshipZipcode', 'VARCHAR', true, 5, null);
        // validators
    } // initialize()

    /**
     * Build the RelationMap objects for this table relationships
     */
    public function buildRelations()
    {
        $this->addRelation('Client', 'Client', RelationMap::MANY_TO_ONE, array('idclient' => 'idclient', ), 'CASCADE', 'CASCADE');
    } // buildRelations()

} // ClientaddressshipTableMap


text:
require 'chef/provisioning'

with_machine_options :bootstrap_options => {
  :key_name => 'pburkholder@ec-sync-w',
}

machine 'aws_ebs' do
  action :destroy
end


text:
require 'sso_identity_manager.rb'
require 'sso_identity_provider.rb'

class Jossoagent

  def initialize(sso_identity_manager_endpoint_url = nil,sso_identity_provider_endpoint_url = nil)
    @agent_identity_manager = SSOIdentityManager.new(sso_identity_manager_endpoint_url)
    @sso_identity_provider = SSOIdentityProvider.new(sso_identity_provider_endpoint_url)
  end

  def fin_roles_by_username(username)
    @agent_identity_manager.findRolesByUsername(username)
  end

  def find_user(username)
    begin
      @roles = @agent_identity_manager.findUser(username)
    rescue SOAP::FaultError
      return nil
    else
      return @roles
    end
  end

  def find_user_in_session(josso_session_id)
    begin
      @sso_user = @agent_identity_manager.findUserInSession(josso_session_id)
    rescue SOAP::FaultError
      return nil
    else
      return @sso_user
    end
  end

  def get_josso_session_id(josso_assertionid)
    begin
      @josso_session_id = @sso_identity_provider.resolveAuthenticationAssertion(josso_assertionid)
    rescue SOAP::FaultError
      return nil
    else
      return @josso_session_id
    end
  end

  def logout(josso_session_id)
    @sso_identity_provider.globalSignoff(josso_session_id)
  end

end


text:
from datetime import datetime

def remove_none(d):
    """
    Delete keys with the value ``None`` in a dictionary, recursively.
    This alters the input so you may wish to ``copy`` the dict first.

    :return: dict
    """
    for key, value in d.items():
        if value is None:
            del d[key]
        elif isinstance(value, dict):
            remove_none(value)
    return d

def time_now():
    """
    :return: str of time now like -20160906-1224
    """
    return datetime.strftime(datetime.now(), '-%Y%m%d-%H%M')

class Terraform:
    @staticmethod
    def set_provider(region):
        """
        :param region: str
        """
        return 'aws.' + region

    @staticmethod
    def set_id(resource, name):
        """
        :param resource: str
        :param name: str
        """
        return '${' + resource + '.' + name + '.id}'

    @classmethod
    def aws_instance(
            cls,
            name=None,
            region=None,
            ami=None,
            instance_type='m3.medium',
            subnet_id=None,
            key_name=None,  # the keypair name
            tags=None,
            vpc_security_group_ids=None,
            associate_public_ip_address=None,
            source_dest_check=None):
        """
        :param name: str
        :param region: str
        :param ami: str
        :param instance_type: str
        :param subnet_id: str
        :param key_name: str
        :param tags: dict
        :param vpc_security_group_ids: list
        :param associate_public_ip_address: bool
        :param source_dest_check: bool
        :return: Terraform
        """

        tags.update({'Name': name}) if tags else tags

        resource = 'aws_instance'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, ami=ami, subnet_id=subnet_id,
                       key_name=key_name, instance_type=instance_type,
                       vpc_security_group_ids=vpc_security_group_ids, tags=tags,
                       associate_public_ip_address=associate_public_ip_address,
                       source_dest_check=source_dest_check)}))

    @classmethod
    def aws_ami_from_instance(
            cls,
            name,
            region,
            source_instance_id,
            tags=None):
        """
        :param name: str
        :param region: str
        :param source_instance_id: str
        :param tags: dict
        :return: Terraform
        """
        name += time_now()
        tags.update({'Name': name}) if tags else None

        resource = 'aws_ami_from_instance'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, name=name,
                       source_instance_id=source_instance_id, tags=tags)}))

    @classmethod
    def aws_elb(
            cls,
            name,
            region,
            listeners,
            subnets,
            health_check=None,
            internal=None,
            security_groups=None,
            instances=None):
        """
        :param name: str
        :param region: str
        :param listeners: list
        :param subnets: list
        :param health_check: dict
        :param internal: bool
        :param security_groups: list
        :param instances: list
        :return: Terraform
        """
        resource = 'aws_elb'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, name=name, listener=listeners,
                       subnets=subnets, health_check=health_check,
                       internal=internal, security_groups=security_groups,
                       instances=instances)}))

    @classmethod
    def aws_elasticache_cluster(
            cls,
            name,
            region,
            node_type,
            num_cache_nodes,
            parameter_group_name,
            port,
            engine,
            subnet_group_name=None,
            security_group_ids=None):
        """

        :param name: str
        :param region: str
        :param node_type: str
        :param num_cache_nodes: str
        :param parameter_group_name: str
        :param port: int
        :param engine: str
        :param subnet_group_name: str
        :param security_group_ids: list
        :return: Terraform
        """
        resource = 'aws_elasticache_cluster'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, cluster_id=name, node_type=node_type,
                       num_cache_nodes=num_cache_nodes,
                       parameter_group_name=parameter_group_name, port=port,
                       subnet_group_name=subnet_group_name,
                       security_group_ids=security_group_ids, engine=engine)}))

    @classmethod
    def aws_rds(
            cls,
            name,
            region,
            instance_class,
            snapshot_id,
            allocated_storage=None,
            engine=None,
            engine_version=None,
            db_subnet_group_name=None,
            vpc_security_group_ids=None,
            parameter_group_name=None,
            publicly_accessible=False,
            username=None,
            password=''):
        """
        :param name: str
        :param region: str
        :param instance_class: str
        :param snapshot_id: str
        :param allocated_storage: str
        :param engine: str
        :param engine_version: str
        :param db_subnet_group_name: str
        :param vpc_security_group_ids: list
        :param parameter_group_name: str
        :param publicly_accessible: bool
        :param username:
        :param password:
        :return: Terraform
        """
        resource = 'aws_db_instance'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, identifier=name,
                       snapshot_identifier=snapshot_id,
                       allocated_storage=allocated_storage, engine=engine,
                       engine_version=engine_version,
                       instance_class=instance_class,
                       db_subnet_group_name=db_subnet_group_name,
                       vpc_security_group_ids=vpc_security_group_ids,
                       parameter_group_name=parameter_group_name,
                       publicly_accessible=publicly_accessible,
                       username=username, password=password)}))

    @classmethod
    def aws_security_group(
            cls,
            name,
            region,
            name_prefix=None,
            description=None,
            ingress=None,
            egress=None,
            vpc_id=None,
            tags=None):
        """
        :param name:
        :param region:
        :param name_prefix:
        :param description:
        :param ingress:
        :param egress:
        :param vpc_id:
        :param tags:
        :return:
        """
        resource = 'aws_security_group'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, name=name, name_prefix=name_prefix,
                       description=description, ingress=ingress, egress=egress,
                       tags=tags, vpc_id=vpc_id)}))

    # *** VPC (Networking) ***

    @classmethod
    def aws_vpc(
            cls,
            name,
            region,
            cidr_block,
            instance_tenancy=None,
            enable_dns_support=None,
            enable_dns_hostnames=None,
            enable_classiclink=None,
            tags=None):
        """
        :param name: str
        :param region: str
        :param cidr_block: str
        :param instance_tenancy: str
        :param enable_dns_support: str
        :param enable_dns_hostnames: str
        :param enable_classiclink: str
        :param tags: dict
        :return: Terraform
        """
        resource = 'aws_vpc'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, cidr_block=cidr_block,
                       instance_tenancy=instance_tenancy,
                       enable_dns_support=enable_dns_support,
                       enable_dns_hostnames=enable_dns_hostnames,
                       enable_classiclink=enable_classiclink, tags=tags)}))

    @classmethod
    def aws_internet_gateway(
            cls,
            name,
            region,
            vpc_id,
            tags=None):
        """
        :param name: str
        :param region: str
        :param vpc_id: str
        :param tags: dict
        :return: Terraform
        """
        resource = 'aws_internet_gateway'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, vpc_id=vpc_id, tags=tags)}))

    @classmethod
    def aws_subnet(
            cls,
            name,
            region,
            vpc_id,
            cidr_block,
            map_public_ip_on_launch=None,
            availability_zone=None,
            tags=None):
        """
        :param name: str
        :param region: str
        :param vpc_id: str
        :param cidr_block: str
        :param map_public_ip_on_launch: bool
        :param availability_zone: str
        :param tags: dict
        :return: Terraform
        """
        resource = 'aws_subnet'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, vpc_id=vpc_id, cidr_block=cidr_block,
                       map_public_ip_on_launch=map_public_ip_on_launch,
                       availability_zone=availability_zone, tags=tags)}))

    @classmethod
    def aws_eip(
            cls,
            name,
            region,
            vpc=None,
            instance=None,
            network_interface=None,
            associate_with_private_ip=None):
        """
        :param name: str
        :param region: str
        :param vpc: str
        :param instance: str
        :param network_interface: str
        :param associate_with_private_ip: bool
        :return: Terraform
        """
        resource = 'aws_eip'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, vpc=vpc, instance=instance,
                       network_interface=network_interface,
                       associate_with_private_ip=associate_with_private_ip)}))

    @classmethod
    def aws_nat_gateway(
            cls,
            name,
            region,
            allocation_id,
            subnet_id):
        """
        :param name: str
        :param region: str
        :param allocation_id: str
        :param subnet_id: str
        :return: Terraform
        """
        resource = 'aws_nat_gateway'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, allocation_id=allocation_id,
                       subnet_id=subnet_id)}))

    @classmethod
    def aws_route_table(
            cls,
            name,
            region,
            vpc_id,
            route=None,
            propagating_vgws=None,
            tags=None):
        """
        :param name: str
        :param region: str
        :param vpc_id: str
        :param route: dict
        :param propagating_vgws: bool
        :param tags: dict
        :return:
        """
        resource = 'aws_route_table'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, vpc_id=vpc_id, route=route,
                       propagating_vgws=propagating_vgws, tags=tags)}))

    @classmethod
    def aws_route(
            cls,
            name,
            region,
            route_table_id,
            destination_cidr_block,
            vpc_peering_connection_id=None,
            gateway_id=None,
            nat_gateway_id=None,
            instance_id=None,
            network_interface_id=None):
        """
        :param name: str
        :param region: str
        :param route_table_id: str
        :param destination_cidr_block: str
        :param vpc_peering_connection_id: str
        :param gateway_id: str
        :param nat_gateway_id: str
        :param instance_id: str
        :param network_interface_id: str
        :return: Terraform
        """
        resource = 'aws_route'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, route_table_id=route_table_id,
                       destination_cidr_block=destination_cidr_block,
                       vpc_peering_connection_id=vpc_peering_connection_id,
                       gateway_id=gateway_id, nat_gateway_id=nat_gateway_id,
                       instance_id=instance_id,
                       network_interface_id=network_interface_id)}))

    @classmethod
    def aws_route_table_association(
            cls,
            name,
            region,
            subnet_id,
            route_table_id):
        """
        :param name: str
        :param region: str
        :param subnet_id: str
        :param route_table_id: str
        :return: Terraform
        """
        resource = 'aws_route_table_association'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, subnet_id=subnet_id,
                       route_table_id=route_table_id)}))

    @classmethod
    def aws_main_route_table_association(
            cls,
            name,
            region,
            vpc_id,
            route_table_id):
        """
        :param name: str
        :param region: str
        :param vpc_id: str
        :param route_table_id: str
        :return: Terraform
        """
        resource = 'aws_main_route_table_association'
        id = Terraform.set_id(resource, name)
        provider = Terraform.set_provider(region)

        return cls(id, name, provider, resource, remove_none({
            name: dict(provider=provider, vpc_id=vpc_id,
                       route_table_id=route_table_id)}))

    def __init__(self, id, name, provider, resource, terraform):
        """
        :param id: str
        :param name: str
        :param provider: str
        :param resource: str
        :param terraform: dict
        """
        self.id = id
        self.terraform = terraform
        self.name = name
        self.resource = resource
        self.provider = provider

    def __str__(self):
        return self.id


text:
<?xml version="1.0" encoding="utf-8"?>
<com.weygo.weygophone.pages.order.commit.widget.WGCommitOrderFooterView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/x91">

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/separate_color">
    </View>

    <RelativeLayout
        android:id="@+id/ress"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="@dimen/x13">

        <TextView
            android:id="@+id/totalPriceTV"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/x17"
            android:gravity="right|center_horizontal"
            android:textColor="@color/WGAppBaseColor" />

        <TextView
            android:id="@+id/reducePriceTV"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/x17"
            android:layout_toRightOf="@+id/totalPriceTV"
            android:layout_marginLeft="@dimen/x10"
            android:gravity="center"
            android:textColor="#ffffff"
            android:background="@drawable/common_good_price_bg"
            android:textAlignment="center" />

        <Button
            android:id="@+id/commitOrderBtn"
            android:layout_width="match_parent"
            android:layout_height="@dimen/x34"
            android:textColor="#ffffff"
            android:textSize="@dimen/ft12"
            android:layout_alignParentBottom="true"
            android:background="@drawable/register_btn_bg"
            android:text="@string/CommitOrder_Confirm" />

    </RelativeLayout>

</com.weygo.weygophone.pages.order.commit.widget.WGCommitOrderFooterView>


text:
#if !defined (OMIT_RCSID_STRINGS)
char ROMlib_rcsid_qColorMgr[] =
		"$Id: qColorMgr.c 63 2004-12-24 18:19:43Z ctm $";
#endif

/* color manager */

#include "rsys/common.h"
#include "QuickDraw.h"
#include "CQuickDraw.h"
#include "MemoryMgr.h"

#include "rsys/smash.h"
#include "rsys/mman.h"
#include "rsys/cquick.h"
#include "rsys/rgbutil.h"
#include <syn68k_public.h>
#include "rsys/blockinterrupts.h"
#include "rsys/host.h"
#include "rsys/vdriver.h"
#include "rsys/dirtyrect.h"

using namespace Executor;

INTEGER ROMlib_qd_error;

P0 (PUBLIC pascal trap, INTEGER, QDError)
{
/* #warning "make QDError work for real" */
  return ROMlib_qd_error;
}

P0 (PUBLIC pascal trap, LONGINT, GetCTSeed)
{
  static LONGINT seed = minSeed;

  return seed ++;
}

PRIVATE uint32
itab_base_size (int res)
{
  uint32 retval;

  retval = offsetof (ITab, iTTable) + ((1 << (3 * res)) *
				       sizeof ((ITab *) 0)->iTTable[0]);
  return retval;
}

#define ITABLE_HASH_SIZE 512

#if defined (ITABLE_HASH_SIZE)

/* TODO: look for better hash function */

PRIVATE int
itable_hash (RGBColor *rgbp, int resolution)
{
  uint32 hash;
  int retval;
  uint16 red, green, blue;

  red   = CW (rgbp->red)   >> (16 - resolution);
  green = CW (rgbp->green) >> (16 - resolution);
  blue  = CW (rgbp->blue)  >> (16 - resolution);

  switch (resolution)
    {
    case 3:
#if ITABLE_HASH_SIZE != 512
#error fix hash funciton
#endif
      hash = (red << 6) | (green << 3) | blue;
      break;
    default:
      warning_unexpected ("resolution = %d", resolution);
      /* FALL THROUGH */
    case 4:
      hash = ((blue&8) << 5) | ((red^((blue>>1)&1)) << 4) | (green ^ (blue&3));
      break;
    case 5:
      hash = ((red&0xf << 5) | green) ^ ((blue<<2)|((red&8)>>2));
      break;
    }
  retval = hash;
  return retval;
}

/*
 */

PRIVATE uint32
rgb_diff (RGBColor *rgb1p, RGBColor *rgb2p)
{
  uint32 retval;

  /*
   * NOTE: the surprising "& 0xff" below was determined empirically by
   * using NIH Image to plot histograms of the "Bone Marrow" image that
   * is on the CD-ROM that Chris Russ gave to me.  Chris is the person
   * who pointed out that histograms weren't working, and it took a while
   * to see that not only did we need to fix Color2Index in general, but
   * that we had to be careful to match like a Mac matches.  Bone Marrow
   * uses a grayscale clut whose low byte of each rgb component is the
   * same as the high byte, instead of zero.  If we don't mask that info
   * off, then we wind up with a different histogram than the Mac produces.
   * From my point of view, the whole way NIH Image and the Mac work
   * together is questionable, since the conversion from the non-standard
   * CLUT that Bone Marrow uses to a standard gray scale clut is dicey.
   * After all, 0x8080 is just as far away from 0x8000 as it is from
   * 0x8100, so counting on it going to a particular value seems risky.
   */

  retval = (ABS (CW (rgb1p->red   & 0xff) - CW (rgb2p->red   & 0xff)) +
	    ABS (CW (rgb1p->green & 0xff) - CW (rgb2p->green & 0xff)) +
	    ABS (CW (rgb1p->blue  & 0xff) - CW (rgb2p->blue  & 0xff)));

  return retval;
}
#endif

/* FIXME: may have to round instead of cleave off the low bits */
#define RGB_TO_ITAB_INDEX(rgb, resolution)				\
  (((CW ((rgb)->red) >> (16 - (resolution))) << (2 * (resolution)))	\
   | ((CW ((rgb)->green) >> (16 - (resolution))) << (resolution))	\
   | ((CW ((rgb)->blue) >> (16 - (resolution)))))

static uint32
ROMlib_search_proc (RGBColor *rgb)
{
  GDHandle gd;
  int pixel_size;
  uint32 retval;

  gd = MR (TheGDevice);
  pixel_size = PIXMAP_PIXEL_SIZE (GD_PMAP (gd));
  if (pixel_size > 8)
    {
      const rgb_spec_t *rgb_spec;

      rgb_spec = pixel_size == 16 ? &mac_16bpp_rgb_spec
	                          : &mac_32bpp_rgb_spec;
      retval = (*rgb_spec->rgbcolor_to_pixel) (rgb_spec, rgb, TRUE);
      if (pixel_size == 16)
	retval = CW (retval);
      else if (pixel_size == 32)
	retval = CL (retval);
      else
	gui_fatal ("unknown pixel size `%d'", pixel_size);
    }
  else
    {
      ITabHandle inverse_table;
      int resolution;

      inverse_table = GD_ITABLE (gd);
      resolution = ITAB_RES (inverse_table);

      retval = ITAB_TABLE (inverse_table)[RGB_TO_ITAB_INDEX (rgb, resolution)];
#if defined (ITABLE_HASH_SIZE)
      {
	CTabHandle ctabh;
	ColorSpec *cspecp;

	ctabh = PIXMAP_TABLE ( GD_PMAP (gd));
	cspecp = CTAB_TABLE (ctabh);
	if (memcmp (rgb, &cspecp[retval].rgb, sizeof *rgb) != 0)
	  {
	    int i;
	    uint8 *hash_table;
	    uint32 candidate;
	    uint32 cur_diff, new_diff;
	    boolean_t done_zero;

	    hash_table = ((uint8 *) STARH (inverse_table)
			  + itab_base_size (resolution));
	    i = itable_hash (rgb, resolution);

	    cur_diff = rgb_diff (rgb, &cspecp[retval].rgb);
	    new_diff = 1;
	    done_zero = FALSE;
	    while (new_diff && (candidate = hash_table[i]) != 0)
	      {
		if (candidate == 1 && !done_zero)
		  {
		    candidate = 0;
		    --i;
		    done_zero = TRUE;
		  }
		new_diff = rgb_diff (rgb, &cspecp[candidate].rgb);
		if (new_diff < cur_diff)
		  {
		    retval = candidate;
		    cur_diff = new_diff;
		  }
		i = (i + 1) % ITABLE_HASH_SIZE;
	      }
	  }
      }
#endif
    }
  return retval;
}

P1 (PUBLIC pascal trap, LONGINT, Color2Index,
    RGBColor *, rgb)
{
  SProcHndl t;
  LONGINT success_p;
  /* default */
  LONGINT position = 0;
  GDHandle gdev;
  ITabHandle gd_itab;
  CTabHandle gd_ctab;

  /* rebuild the inverse table for the current graphics device
     if the color table is newer than the inverse table */
  gdev = MR (TheGDevice);
  gd_ctab = PIXMAP_TABLE (GD_PMAP (gdev));
  gd_itab = GD_ITABLE (gdev);
  if (CTAB_SEED_X (gd_ctab) != ITAB_SEED_X (gd_itab))
    MakeITable (gd_ctab, gd_itab, GD_RES_PREF (gdev));

  for (t = GD_SEARCH_PROC (MR (TheGDevice)), success_p = FALSE;
       t && !success_p;)
    {
      BOOLEAN (*search_fn) ();

      search_fn = (BOOLEAN (*) ()) HxP (t, srchProc);
      /* fetch the next before calling the searchproc,
	 since it can relocate the current `t' */
      t = HxP (t, nxtSrch);

      {
	M68kReg save_regs[16];
	memcpy (save_regs, cpu_state.regs, 16 * sizeof cpu_state.regs[0]);
	EM_A7 -= 128;
	PUSHADDR ((LONGINT) US_TO_SYN68K(rgb));
	PUSHADDR ((LONGINT) US_TO_SYN68K(&position));
	CALL_EMULATOR ((syn68k_addr_t) US_TO_SYN68K(search_fn));
	/* success_p = EM_D0; */
	success_p = POPUB ();
	memcpy (cpu_state.regs, save_regs, 16 * sizeof cpu_state.regs[0]);
      }
#if 0
      /* return value from the search procedure is a BOOLEAN, ignore
	 all but the low byte */
      success_p &= 0xFF;
#endif
    }

  if (! success_p)
    position = ROMlib_search_proc (rgb);
  else
    position = CL (position);  /* They filled this in in big endian order. */
  return position;
}

P2 (PUBLIC pascal trap, void, Index2Color,
    LONGINT, index,
    RGBColor *, rgb)
{
  CTabHandle ctab = PIXMAP_TABLE (GD_PMAP (MR (TheGDevice)));
  *rgb = CTAB_TABLE (ctab)[index].rgb;
}

P1 (PUBLIC pascal trap, void, InvertColor,
    RGBColor *, rgb)
{
/* #warning "only use default InvertColor complement procedure" */

  /* one's complement */
  rgb->red = ~rgb->red;
  rgb->green = ~rgb->green;
  rgb->blue = ~rgb->blue;
}

P1 (PUBLIC pascal trap, BOOLEAN, RealColor,
    RGBColor *, rgb)
{
  GDHandle gdev;
  ITabHandle inverse_table;
  CTabHandle table;
  RGBColor *closest;
  int resolution;
  unsigned short mask;
  int index;

  /* rebuild the inverse table for the current graphics device
     if the color table is newer than the inverse table */
  gdev = MR (TheGDevice);
  table = PIXMAP_TABLE (GD_PMAP (gdev));
  inverse_table = GD_ITABLE (gdev);
  if (CTAB_SEED_X (table) != ITAB_SEED_X (inverse_table))
    MakeITable (table, inverse_table, GD_RES_PREF (gdev));

  resolution = ITAB_RES (inverse_table);

  index = ITAB_TABLE (inverse_table)[RGB_TO_ITAB_INDEX (rgb, resolution)];

  closest = &(CTAB_TABLE (table)[index].rgb);

  /* high `resolution' bits */
  mask = CW (((1 << resolution) - 1) << (16 - resolution));

  return !(((rgb->red ^ closest->red) & mask)
	   || ((rgb->green ^ closest->green) & mask)
	   || ((rgb->blue ^ closest->blue) & mask));
}

P3 (PUBLIC pascal trap, void, GetSubTable,
    CTabHandle, in_ctab,
    INTEGER, resolution,
    CTabHandle, target_ctab)
{
  /* cached itable from the last transaction */
  static ITabHandle cached_itab = NULL;

  GDHandle gdev;
  ITabHandle itab = NULL;
  PixMapHandle gd_pmap;
  int i;

  gdev = MR (TheGDevice);
  gd_pmap = GD_PMAP (gdev);

  if (!target_ctab)
    {
      ITabHandle t = GD_ITABLE (gdev);

      target_ctab = PIXMAP_TABLE (gd_pmap);

      if (resolution == ITAB_RES (t))
	{
	  /* rebuild the inverse table for the current graphics device
	     if the color table is newer than the inverse table */
	  if (CTAB_SEED_X (target_ctab) != ITAB_SEED_X (t))
	    MakeITable (target_ctab, t, GD_RES_PREF (gdev));

	  itab = t;
	}
    }

  if (! itab)
    {
      if (cached_itab
	  && ITAB_SEED_X (cached_itab) == CTAB_SEED_X (target_ctab)
	  && resolution == ITAB_RES (cached_itab))
	itab = cached_itab;
      else
	{
	  /* if we haven't allocated a cached itab; do so now.  make
	     sure to do it out of the system zone, since we will keep
	     this itab around forever */
	  if (cached_itab == NULL)
	    ZONE_SAVE_EXCURSION
	      (SysZone,
	       {
		 cached_itab = (ITabHandle) NewHandle ((Size) sizeof (ITab));
	       });

	  itab = cached_itab;
	  MakeITable (target_ctab, itab, resolution);
	}
    }
  LOCK_HANDLE_EXCURSION_2
    (in_ctab, target_ctab,
     {
       CTabHandle gdev_ctab_save = PIXMAP_TABLE_X (gd_pmap);
       ITabHandle gdev_itab_save = GD_ITABLE_X (gdev);

       /* pull tables into locals for easy access */
       ColorSpec *in_ctab_table = CTAB_TABLE (in_ctab);

       /* ColorSpec *target_ctab_table = CTAB_TABLE (target_ctab); */
       /* int gd_ctab_p = CTAB_FLAGS_X (target_ctab) & CTAB_GDEVICE_BIT_X; */

       PIXMAP_TABLE_X (gd_pmap) = RM (target_ctab);
       GD_ITABLE_X (gdev) = RM (itab);

       for (i = CTAB_SIZE (in_ctab); i >= 0; i --)
	 {
	   ColorSpec *color = &in_ctab_table[i];
	   INTEGER ctab_index;

	   ctab_index = Color2Index (&color->rgb);

	   /* inverse table maps rgb color space to an index
	      within the target color table, not to a value in the
	      color table */
/*
	   if (gd_ctab_p)
	     color->value = CW (ctab_index);
	   else
	     color->value = target_ctab_table[ctab_index].value;
	   color->rgb   = target_ctab_table[ctab_index].rgb;
*/
	   color->value = CW (ctab_index);
	 }

       PIXMAP_TABLE_X (gd_pmap) = gdev_ctab_save;
       GD_ITABLE_X (gdev) = gdev_itab_save;
     });
}

int
Executor::average_color (GDHandle gd,
	       RGBColor *c1, RGBColor *c2, int ratio,
	       RGBColor *out)
{
  RGBColor in_between;
  int c1_index, c2_index, in_between_index;

  PixMapHandle gd_pmap;
  int gd_pixel_size;

  gd_pmap = GD_PMAP (gd);
  gd_pixel_size = PIXMAP_PIXEL_SIZE (gd_pmap);

  in_between.red   = CW (((CW (c1->red) * ratio)
			  + (CW (c2->red) * (65535 - ratio))) / 65535);
  in_between.green = CW (((CW (c1->green) * ratio)
			  + (CW (c2->green) * (65535 - ratio))) / 65535);
  in_between.blue  = CW (((CW (c1->blue) * ratio)
			  + (CW (c2->blue) * (65535 - ratio))) / 65535);
  if (gd_pixel_size <= 8)
    {
      CTabHandle gd_ctab;
      ITabHandle gd_itab;
      unsigned char *itab_table;
      int itab_res;

      gd_ctab = PIXMAP_TABLE (gd_pmap);
      gd_itab = GD_ITABLE (gd);

      if (CTAB_SEED_X (gd_ctab) != ITAB_SEED_X (gd_itab))
	MakeITable (gd_ctab, gd_itab, GD_RES_PREF (gd));

      itab_res = ITAB_RES (gd_itab);
      itab_table = ITAB_TABLE (gd_itab);

      c1_index = itab_table[RGB_TO_ITAB_INDEX (c1, itab_res)];
      c2_index = itab_table[RGB_TO_ITAB_INDEX (c2, itab_res)];
      in_between_index = itab_table[RGB_TO_ITAB_INDEX (&in_between, itab_res)];
    }
  else
    {
      const rgb_spec_t *rgb_spec;

      rgb_spec = pixmap_rgb_spec (STARH (gd_pmap));
      c1_index = (*rgb_spec->rgbcolor_to_pixel) (rgb_spec, c1, TRUE);
      c2_index = (*rgb_spec->rgbcolor_to_pixel) (rgb_spec, c2, TRUE);
      in_between_index = (*rgb_spec->rgbcolor_to_pixel) (rgb_spec, &in_between,
							 TRUE);
    }
  if (c1_index != c2_index
      && (in_between_index == c1_index
	  || in_between_index == c2_index))
    return FALSE;
  else
    {
      *out = in_between;
      return TRUE;
    }
}

P3 (PUBLIC pascal trap, BOOLEAN, GetGray,
    GDHandle, gdev,
    RGBColor *, bk, RGBColor *, fg)
{
  return average_color (gdev, bk, fg, 0x8000, fg);
}

#define ENQUEUE(x)	({ const unsigned _q_elt_ = (x);		      \
                           if (! index_in_queue_p[_q_elt_])		      \
			     {						      \
			       queue[head] = _q_elt_;			      \
			       index_in_queue_p[_q_elt_] = TRUE;	      \
			       head = (head + 1) & (itab_elt_count - 1);      \
			     }						      \
                        })

#define DEQUEUE()	({ const unsigned _q_elt_ = queue[tail];	      \
			   tail = (tail + 1) & (itab_elt_count - 1);	      \
			   index_in_queue_p[_q_elt_] = FALSE;		      \
			   _q_elt_;					      \
                        })

#define SET_RGB_ERROR(ix, err) (rgb_error[ix] = (err))

/* These are the parameters to rgb_error_for_res_*.  Because they
 * remain fixed during loops, we put them in globals.
 */
static unsigned current_red, current_green, current_blue;

#define RGB_ERROR_FOR_RESOLUTION_FUNC(RES)				     \
static ULONGINT								     \
rgb_error_for_res_##RES (unsigned components)				     \
{									     \
  unsigned rc, bc, gc;							     \
  ULONGINT error;							     \
  const unsigned mask = (1 << (RES)) - 1;				     \
  const unsigned mid_bit = (0x8000 >> (RES));				     \
									     \
  bc = ((components & mask) << (16 - (RES))) | mid_bit;			     \
  error = ABS ((long) (bc - current_blue));				     \
									     \
  gc = ((components & (mask << (RES))) << (16 - (RES) * 2)) | mid_bit;	     \
  error += ABS ((long) (gc - current_green));				     \
									     \
  rc = ((components & (mask << ((RES) * 2))) << (16 - (RES) * 3)) | mid_bit; \
  error += ABS ((long) (rc - current_red));				     \
									     \
  return error;								     \
}

RGB_ERROR_FOR_RESOLUTION_FUNC (3)
RGB_ERROR_FOR_RESOLUTION_FUNC (4)
RGB_ERROR_FOR_RESOLUTION_FUNC (5)

static int offsets[3][26];
static const int basis_offsets[26][3] =
{
  { -1, -1, -1 },
  { -1, -1, 0 },
  { -1, -1, 1 },
  { -1, 0, -1 },
  { -1, 0, 0 },
  { -1, 0, 1 },
  { -1, 1, -1 },
  { -1, 1, 0 },
  { -1, 1, 1 },
  { 0, -1, -1 },
  { 0, -1, 0 },
  { 0, -1, 1 },
  { 0, 0, -1 },
#if 0
  { 0, 0, 0 },
#endif
  { 0, 0, 1 },
  { 0, 1, -1 },
  { 0, 1, 0 },
  { 0, 1, 1 },
  { 1, -1, -1 },
  { 1, -1, 0 },
  { 1, -1, 1 },
  { 1, 0, -1 },
  { 1, 0, 0 },
  { 1, 0, 1 },
  { 1, 1, -1 },
  { 1, 1, 0 },
  { 1, 1, 1 },
};

static void
init_offsets (void)
{
  int i, resolution;

  for (resolution = 3; resolution <= 5; resolution ++)
    {
      int *offset;

      offset = offsets[resolution - 3];

      for (i = 0; i < 26; i ++)
	{
	  const int *basis_offset;

	  basis_offset = basis_offsets[i];

	  offset[i] = (basis_offset[0]
		       + (basis_offset[1] << resolution)
		       + (basis_offset[2] << (2 * resolution)));

	}
    }
}

#if defined (ITABLE_HASH_SIZE)
PRIVATE void
add_hash_table (CTabHandle color_table, ITabHandle inverse_table,
		int resolution)
{
  int ctab_size;
  uint8 *hash_tablep;
  int i;

  hash_tablep = ((uint8 *) STARH (inverse_table)
		 + itab_base_size (resolution));
  memset (hash_tablep, 0, ITABLE_HASH_SIZE);
  ctab_size = CTAB_SIZE (color_table);
  for (i = 0; i < ctab_size; ++i)
    {
      RGBColor *ctabcolorp, *itabcolorp;
      int itab_index, index;

      ctabcolorp = &CTAB_TABLE (color_table)[i].rgb;
      itab_index = RGB_TO_ITAB_INDEX (ctabcolorp, resolution);
      index = ITAB_TABLE (inverse_table)[itab_index];
      itabcolorp = &CTAB_TABLE (color_table)[index].rgb;
      if (memcmp (ctabcolorp, itabcolorp, sizeof *ctabcolorp) != 0)
	{
	  int j;

	  j = itable_hash (ctabcolorp, resolution);
	  while (hash_tablep [j])
	    j = (j + 1) % ITABLE_HASH_SIZE;
	  hash_tablep [j] = i ? i : 1; /* don't ever put in zero */
	}
    }
}
#endif

P3 (PUBLIC pascal trap, void, MakeITable,
    CTabHandle, color_table,
    ITabHandle, inverse_table,
    INTEGER, resolution)
{
  /* this also counts the number of elements in the queue */
  int itab_elt_count;
  unsigned short *queue;
  char *index_in_queue_p;
  ULONGINT *rgb_error;
  boolean_t queue_starts_empty_p;
  int head, tail;
  int i;
  int ctab_size;
  ULONGINT (*rgb_error_func) (unsigned);
  unsigned char *itab_table;
  const int *offset;
  ColorSpec color_for_index[256];

  {
    static boolean_t been_here_p = FALSE;
    if (! been_here_p)
      {
 	init_offsets ();
 	been_here_p = TRUE;
      }
  }

  /* We are supposed to override a resolution of zero with the
   * resolution of TheGDevice (IMV-142).  */
  if (resolution == 0)
    resolution = GD_RES_PREF (MR (TheGDevice));

  /* We are supposed to override a color_table of NULL with the color
   * table of TheGDevice (IMV-142).  */
  if (color_table == NULL)
    color_table = PIXMAP_TABLE (GD_PMAP (MR (TheGDevice)));

  /* We are supposed to override an inverse_table of NULL with the
   * inverse table of TheGDevice (IMV-142).  */
  if (inverse_table == NULL)
    {
      inverse_table = GD_ITABLE (MR (TheGDevice));
      if (!inverse_table)
	{
	  inverse_table = (ITabHandle) NewHandle (0);
	  GD_ITABLE_X (MR (TheGDevice)) = RM (inverse_table);
	}
    }

  gui_assert (resolution >= 3 && resolution <= 5);

  /* Set up the function to compute rgb deltas. */
  if (resolution == 3)
    rgb_error_func = rgb_error_for_res_3;
  else if (resolution == 4)
    rgb_error_func = rgb_error_for_res_4;
  else if (resolution == 5)
    rgb_error_func = rgb_error_for_res_5;
  else
    gui_abort ();

  itab_elt_count = 1 << (3 * resolution);
  offset = offsets[resolution - 3];

  /* reallocate `inverse_table' to the appropriate size for the
     current resolution */
  {
    Size new_size;

    new_size = itab_base_size (resolution);
#if defined(ITABLE_HASH_SIZE)
    new_size += ITABLE_HASH_SIZE;
#endif
    SetHandleSize ((Handle) inverse_table, new_size);
  }
  ITAB_RES_X (inverse_table) = CW (resolution);

  itab_table = ITAB_TABLE (inverse_table);

  queue = (unsigned short *) alloca (sizeof (unsigned short) * itab_elt_count);
  head = tail = 0;

  index_in_queue_p = (char*)alloca (sizeof *index_in_queue_p * itab_elt_count);
  memset (index_in_queue_p, '\000', sizeof *index_in_queue_p * itab_elt_count);

  /* Allocate an array for RGB errors and set all entries to the maximum. */
  rgb_error = (ULONGINT *) alloca (sizeof (ULONGINT) * itab_elt_count);
  memset (rgb_error, ~0, sizeof (ULONGINT) * itab_elt_count);

  /* Initialize to a non-0 and non-0xFF value. */
  memset (color_for_index, 0x80, sizeof color_for_index);

  queue_starts_empty_p = TRUE;
  ctab_size = CTAB_SIZE (color_table);
  for (i = ctab_size; i >= 0; i --)
    {
      ColorSpec *color = &CTAB_TABLE (color_table)[i];
      int inverse_table_index;
      ULONGINT error;
      unsigned char new_value;

      /* don't include reserved colors in the inverse table */
      if (color->value & CTAB_RESERVED_BIT_X)
	continue;

      /* We always want to enqueue this color, even if it isn't the
       * lowest error match for the starting itab entry.  It may become
       * the lowest error color for neighboring itab entries.
       */
      inverse_table_index = RGB_TO_ITAB_INDEX (&(color->rgb), resolution);
      ENQUEUE (inverse_table_index);
      queue_starts_empty_p = FALSE;

      /* Figure out what the color index is. */
      if (CTAB_FLAGS_X (color_table) & CTAB_GDEVICE_BIT_X)
	new_value = i;
      else
	new_value = CW (color->value);

      /* Save away the color for this index, in native endian byte order. */
      color_for_index[new_value].rgb.red   = CW (color->rgb.red);
      color_for_index[new_value].rgb.green = CW (color->rgb.green);
      color_for_index[new_value].rgb.blue  = CW (color->rgb.blue);

      current_red   = color_for_index[new_value].rgb.red;
      current_blue  = color_for_index[new_value].rgb.blue;
      current_green = color_for_index[new_value].rgb.green;

      /* Compute the error for this match. */
      error = (*rgb_error_func) (inverse_table_index);

      /* If this beats the best error for this square so far, make
       * that be the new error value.
       */
      if (error < rgb_error[inverse_table_index])
	{
	  itab_table[inverse_table_index] = new_value;
	  SET_RGB_ERROR (inverse_table_index, error);
	}
    }

  if (queue_starts_empty_p)
    {
      /* Some degenerate color tables can cause us to enqueue nothing
       * at all.  It's not clear what to do in the case, but we
       * do _not_ want to start in on the do...while loop below.
       * That can cause mystery smashage deaths, because we'd look
       * at uninitialized queue elements.  This was happening
       * when we were letting FattyBearDemo try a SetDepth to 0 bpp.
       */
      warning_unexpected ("Empty queue!");
    }
  else
    {
      do
	{
	  int inverse_table_index;
	  unsigned char ctab_index;
	  const RGBColor *current_color;
	  int off;

	  inverse_table_index = DEQUEUE ();
	  ctab_index = itab_table[inverse_table_index];

	  /* Stash the current color away in some globals, outside the loop. */
	  current_color = &color_for_index[ctab_index].rgb;
	  current_red   = current_color->red; /* native endian! */
	  current_green = current_color->green; /* native endian! */
	  current_blue  = current_color->blue; /* native endian! */

	  /* Find the adjacent rgb coordinates to this pixel.  If we can
	   * beat the error found at each neighbor, then we spread out to
	   * that neighbor.
	   */
	  for (off = 25; off >= 0; off--)
	    {
	      int next_itab_index;
	      ULONGINT error;

	      /* compute the next adjacent index */
	      next_itab_index = inverse_table_index + offset[off];
	      if ((unsigned) next_itab_index < (unsigned) itab_elt_count)
		{
		  /* Compute the error we'll create by taking this step. */
		  error = (*rgb_error_func) (next_itab_index);

		  /* Did we improve on the best error for that entry? */
		  if (error < rgb_error[next_itab_index])
		    {
		      ENQUEUE (next_itab_index);
		      itab_table[next_itab_index] = ctab_index;
		      rgb_error[next_itab_index] = error;
		    }
		}
	    }

	  check_virtual_interrupt ();
	}
      while (tail != head);
    }

  /* If the first or last entries in the table are black and white,
   * make sure their entries map to them.  This wouldn't be necessary
   * if we were able to do a more fine-grained resolution; however, some
   * programs (like FattyBearDemo) expect that black will definitely
   * map to the last entry in the color table, even if there's more
   * than one black or near-black color.
   */
  for (i = 0; i <= ctab_size; i += ctab_size ?: 1)
    {
      ULONGINT color_sum;

      color_sum = (color_for_index[i].rgb.red
		   + color_for_index[i].rgb.green
		   + color_for_index[i].rgb.blue);

      if (color_sum == 0xFFFF * 3)
	itab_table[itab_elt_count - 1] = i;
      else if (color_sum == 0x0000 * 3)
	itab_table[0] = i;
    }

#if defined (ITABLE_HASH_SIZE)
  add_hash_table (color_table, inverse_table, resolution);
#endif

  ITAB_SEED_X (inverse_table) = CTAB_SEED_X (color_table);
}

P2 (PUBLIC pascal trap, void, ProtectEntry,
    INTEGER, index, BOOLEAN, protect)
{
  GDHandle gdev;
  ColorSpec *entry;

  gdev = MR (TheGDevice);
  entry = &CTAB_TABLE (PIXMAP_TABLE (GD_PMAP (gdev)))[index];
  if (protect)
    {
      if (entry->value & CTAB_PROTECTED_BIT_X)
/* #warning "set error bit here" */
      return;

      /* mark this entry as protected; and set the
	 low byte of the value field with the current
	 device id */
      entry->value = CTAB_PROTECTED_BIT_X | (GD_ID_X (gdev) & CWC (0xFF));
    }
  else
    {
      /* clear the protected bit and id fields of the value */
      entry->value = 0;
    }
  /* this does not effect color lookup, so the seed of the
     current graphics device's colortable is unchanged */
}

P2 (PUBLIC pascal trap, void, ReserveEntry,
    INTEGER, index, BOOLEAN, reserve)
{
  GDHandle gdev;
  CTabHandle ctab;
  ColorSpec *entry;
  INTEGER old_value;

  gdev = MR (TheGDevice);
  ctab = PIXMAP_TABLE (GD_PMAP (gdev));
  entry = &CTAB_TABLE (ctab)[index];

  old_value = entry->value;
  if (reserve)
    {
      if (entry->value & CTAB_RESERVED_BIT_X)
	{
	  ROMlib_qd_error = cProtectErr;
	  return;
	}

      /* mark this entry as reserved; and set the
	 low byte of the value field with the current
	 device id */
      entry->value = CTAB_RESERVED_BIT_X | (GD_ID_X (gdev) & CWC (0xFF));
    }
  else
    {
      /* clear the entry */
      entry->value &= ~CTAB_RESERVED_BIT_X;
    }

  /* success */
  ROMlib_qd_error = noErr;

  /* Only change the seed when necessary. */
  if (old_value != entry->value)
    CTAB_SEED_X (ctab) = CL (GetCTSeed ());
}

P3 (PUBLIC pascal trap, void, SetEntries,
    INTEGER, start, INTEGER, count,
    ColorSpec *, atable /* cSpecArray, atable */)
{
  /* ##### figure out exactly what the mac does */
  GDHandle gd;

  CTabHandle ctab;
  ColorSpec *ctab_table;
  int ctab_changed_p, i;
  RGBColor *r1, *r2;
  /* for calling `vdriver_set_colors ()' */
  int first_color, num_colors;

  gd = MR (TheGDevice);

  if (GD_TYPE_X (gd) != CWC (clutType))
    /* #### return error code? */
    return;

  ctab = PIXMAP_TABLE (GD_PMAP (gd));
  ctab_table = CTAB_TABLE (ctab);
  ctab_changed_p = FALSE;

  if (start >= 0)
    {
      for (i = 0; i <= count; i ++)
	{
	  r1 = &ctab_table[start + i].rgb;
	  r2 = &atable[i].rgb;
	  if (r1->red != r2->red
	      || r1->green != r2->green
	      || r1->blue != r2->blue)
	    {
	      *r1 = *r2;
	      ctab_changed_p = TRUE;
	    }
	}
      first_color = start;
      num_colors = count + 1;
    }
  else
    {
      int min = 10000, max = -10000;

      for (i = 0; i <= count; i ++)
	{
	  int index = CW (atable[i].value);

	  if (index < min)
	    min = index;
	  if (index > max)
	    max = index;

	  r1 = &ctab_table[index].rgb;
	  r2 = &atable[i].rgb;
	  if (r1->red != r2->red
	      || r1->green != r2->green
	      || r1->blue != r2->blue)
	    {
	      *r1 = *r2;
	      ctab_changed_p = TRUE;
	    }
	}

      first_color = min;
      num_colors = max - min + 1;
    }

  /* We need this hack in here so that Wolfenstein 3D will work.
   * If we don't always update the real color table, the colors
   * are simply wrong.
   */
  ctab_changed_p = TRUE;

  if (ctab_changed_p)
    {
      CTAB_SEED_X (ctab) = CL (GetCTSeed ());
      if (gd == MR (MainDevice))
	{
	  if (num_colors > 0)
	    {
	      dirty_rect_update_screen ();
	      vdriver_set_colors (first_color, num_colors,
				  &ctab_table[first_color]);
	    }
	}
    }
}

P1 (PUBLIC pascal trap, void, AddSearch,
    ProcPtr, searchProc)
{
  GDHandle gdev;
  SProcHndl search_list_elt;

  gdev = MR (TheGDevice);

  search_list_elt = (SProcHndl) NewHandle (sizeof (SProcRec));
  HxX (search_list_elt, srchProc) = RM (searchProc);
  HxX (search_list_elt, nxtSrch) = GD_SEARCH_PROC_X (gdev);

  GD_SEARCH_PROC_X (gdev) = RM (search_list_elt);

  /* Invalidate all color conversion tables. */
  ROMlib_invalidate_conversion_tables ();
}

P1 (PUBLIC pascal trap, void, AddComp,
    ProcPtr, compProc)
{
  warning_unimplemented (NULL_STRING);
}

P1 (PUBLIC pascal trap, void, DelSearch,
    ProcPtr, searchProc)
{
  GDHandle gdev;
  SProcHndl s, prev;

  gdev = MR (TheGDevice);

  prev = NULL;
  for (s = GD_SEARCH_PROC (gdev); s != NULL; s = HxP (s, nxtSrch))
    {
      if (HxX (s, srchProc) == RM (searchProc))
	{
	  if (prev == NULL)
	    GD_SEARCH_PROC_X (gdev) = HxX (s, nxtSrch);
	  else
	    HxX (prev, nxtSrch) = HxX (s, nxtSrch);
	  DisposHandle ((Handle) s);
	  /* Invalidate all color conversion tables. */
	  ROMlib_invalidate_conversion_tables ();
	  break;
	}
      else
	prev = s;
    }

  if (s == NULL)
    warning_unimplemented (NULL_STRING);
}

P1 (PUBLIC pascal trap, void, DelComp,
    ProcPtr, compProc)
{
  warning_unimplemented (NULL_STRING);
}

P1 (PUBLIC pascal trap, void, SetClientID,
    INTEGER, id)
{
  GD_ID_X (MR (TheGDevice)) = CW (id);
}

P3 (PUBLIC pascal trap, void, SaveEntries, CTabHandle, src, CTabHandle, result,
    ReqListRec *, selection)
{
  int req_size, src_ctab_size;
  int req_error_p = FALSE;
  int i;

  if (src == NULL)
    src = PIXMAP_TABLE (GD_PMAP (MR (TheGDevice)));

  src_ctab_size = CTAB_SIZE (src);
  req_size = CW (selection->reqLSize);

  SetHandleSize ((Handle) result,
		 CTAB_STORAGE_FOR_SIZE (req_size));
  CTAB_SIZE_X (result)  = CW (req_size);
  /* #### should this set the color table seed? */
  CTAB_SEED_X (result)  = CL (GetCTSeed ());
  CTAB_FLAGS_X (result) = CW (0);

  for (i = 0; i <= req_size; i ++)
    {
      int req_index = CW (selection->reqLData[i]);

      if (req_index >= 0
	  && req_index <= src_ctab_size)
	CTAB_TABLE (result)[i] = CTAB_TABLE (src)[req_index];
      else
	{
	  selection->reqLData[i] = CWC (colReqErr);
	  req_error_p = TRUE;
	}
    }
  if (req_error_p)
    {
      /* #### does SaveEntries return colReqErr if errors occured */
      ROMlib_qd_error = colReqErr;
    }
}

P3 (PUBLIC pascal trap, void, RestoreEntries, CTabHandle, src, CTabHandle, dst,
    ReqListRec *, selection)
{
  int req_size, dst_ctab_size;
  int req_error_p = FALSE;
  int i;

  if (dst == NULL)
    dst = PIXMAP_TABLE (GD_PMAP (MR (TheGDevice)));

  dst_ctab_size = CTAB_SIZE (dst);
  req_size = CW (selection->reqLSize);

  for (i = 0; i < req_size; i ++)
    {
      int req_index = CW (selection->reqLData[i]);

      if (req_index >= 0
	  && req_index <= dst_ctab_size)
	CTAB_TABLE (dst)[req_index] = CTAB_TABLE (src)[i];
      else
	{
	  selection->reqLData[i] = CWC (colReqErr);
	  req_error_p = TRUE;
	}
    }
  if (req_error_p)
    {
/* #warning does SaveEntries return colReqErr if errors occured */
      ROMlib_qd_error = colReqErr;
    }
}


text:
let {session, contextGroup, Protocol} = InspectorTest.start(
    'Test Counters collection using Profiler.getCounters.');

var source =
`
function fib(x) {
  if (x < 2) return 1;
  return fib(x-1) + fib(x-2);
}
fib(5);
`;

function buildCounterMap(result) {
  let counterMap = new Map();

  let counters = result.result.result;
  for (const {name, value} of counters) {
    counterMap.set(name, value);
  }

  return counterMap;
}

function compareCounterMaps(counterMap, counterMap2) {
  // Check for counters that are present in the first map but are not found
  // in the the second map
  for (let counter of counterMap.keys()) {
    if (!counterMap2.has(counter)) {
      InspectorTest.log(`Counter ${counter} is missing`);
      return false;
    }
  }

  // Check for the counter value changes
  let counterValueIncreased = false;
  for (let [counter, value2] of counterMap2) {
    let value = counterMap.get(counter);
    if (value !== undefined) {
      if (value2 < value) {
        InspectorTest.log(`Counter ${counter} value decreased: ${value} -> ${value2}`);
        return false;
      }
      if (value2 > value) {
        counterValueIncreased = true;
      }
    }
  }

  if (!counterValueIncreased && counterMap.size === counterMap2.size) {
    InspectorTest.log(`No counter values has increased or added`);
    return false;
  }

  return true;
}

(async function test() {
  await Protocol.Runtime.enable();
  await Protocol.Profiler.enableCounters();

  let counterMap = buildCounterMap(await Protocol.Profiler.getCounters());

  await Protocol.Runtime.evaluate({ expression: source, sourceURL: arguments.callee.name, persistScript: true });

  let counterMap2 = buildCounterMap(await Protocol.Profiler.getCounters());
  const check1 = compareCounterMaps(counterMap, counterMap2);

  await Protocol.Runtime.evaluate({ expression: source, sourceURL: arguments.callee.name, persistScript: true });

  let counterMap3 = buildCounterMap(await Protocol.Profiler.getCounters());
  const check2 = compareCounterMaps(counterMap2, counterMap3);

  await Protocol.Profiler.disableCounters();
  await Protocol.Runtime.disable();

  InspectorTest.log(check1 && check2 ? 'PASSED' : 'FAILED');

  InspectorTest.completeTest();
})().catch(e => InspectorTest.log('caught: ' + e));


text:
@implementation SAShapeView (Image)

- (CAShapeLayer *)addRectangleLayer:(CGRect)frame {
    return [self addShapeLayer:[SAPath pathWithRect:frame].CGPath];
}

- (CAShapeLayer *)addEllipseLayer:(CGRect)frame {
    return [self addShapeLayer:[SAPath pathWithOvalInRect:frame].CGPath];
}

- (CAShapeLayer *)addCircleLayer:(CGPoint)center radius:(CGFloat)r {
    return [self addEllipseLayer:SARectWithCenter(center, 2 * r, 2 * r)];
}

- (CATextLayer *)addTextLayer:(NSString *)text frame:(CGRect)frame fontSize:(CGFloat)fontSize {
    if ([text length] < 1 || fontSize < 1) {
        return nil;
    }

    CATextLayer *layer = [CATextLayer layer];

    layer.string = text;
    layer.fontSize = fontSize;
    layer.foregroundColor = self.strokeColor.CGColor;
    layer.alignmentMode = kCAAlignmentCenter;
    layer.wrapped = YES;
    [self addSublayer:layer frame:frame];

    return layer;
}

- (CATextLayer *)addTextLayer:(NSString *)text center:(CGPoint)pt fontSize:(CGFloat)fontSize {
    NSDictionary *attr = @{NSFontAttributeName: [SAFont systemFontOfSize:fontSize]};
    CGRect frame = SARectWithCenterSize(pt, [text sizeWithAttributes:attr]);
    return [self addTextLayer:text frame:frame fontSize:fontSize];
}

- (CALayer *)addImageLayer:(SAImage *)image center:(CGPoint)pt {
    if (image.size.width < 1 || image.size.height < 1) {
        return nil;
    }

    CALayer *layer = [CALayer layer];
    CGRect frame = SARectWithCenterSize(pt, image.size);

#ifdef UIKIT_EXTERN
    layer.contents = (__bridge id)(image.CGImage);
#else
    NSGraphicsContext *context = [[NSGraphicsContext currentContext] graphicsPort];
    NSRect rect = SARectFromSize(image.size);
    layer.contents = (__bridge id)([image CGImageForProposedRect:&rect context:context hints:NULL]);
#endif
    [self addSublayer:layer frame:frame];
    return layer;
}

- (CALayer *)addImageLayer:(CGPoint)center named:(NSString *)name {
    return [self addImageLayer:[SAImage imageNamed:name] center:center];
}

- (CALayer *)addImageLayer:(CGPoint)center contentsOfFile:(NSString *)file {
    SAImage *image = [[SAImage alloc] initWithContentsOfFile:file];
    return [self addImageLayer:image center:center];
}

@end


text:
package org.apache.poi.sl.draw.binding;

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

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

 * <complexType name="CT_ConnectionSite">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="pos" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_AdjPoint2D"/>
 *       </sequence>
 *       <attribute name="ang" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjAngle" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CT_ConnectionSite", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = {
    "pos"
})
public class CTConnectionSite {

    @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", required = true)
    protected CTAdjPoint2D pos;
    @XmlAttribute(required = true)
    protected String ang;

    /**
     * Gets the value of the pos property.
     *
     * @return
     *     possible object is
     *     {@link CTAdjPoint2D }
     *
     */
    public CTAdjPoint2D getPos() {
        return pos;
    }

    /**
     * Sets the value of the pos property.
     *
     * @param value
     *     allowed object is
     *     {@link CTAdjPoint2D }
     *
     */
    public void setPos(CTAdjPoint2D value) {
        this.pos = value;
    }

    public boolean isSetPos() {
        return (this.pos!= null);
    }

    /**
     * Gets the value of the ang property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAng() {
        return ang;
    }

    /**
     * Sets the value of the ang property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAng(String value) {
        this.ang = value;
    }

    public boolean isSetAng() {
        return (this.ang!= null);
    }

}


text:
package org.scalajs.testsuite.javalib.io

import java.io.{CharArrayWriter, StringWriter}
import org.junit.Assert._
import org.junit.Test
import org.scalajs.testsuite.utils.AssertThrows.assertThrows

class CharArrayWriterTest {
  private val hw: Array[Char] = Array('H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd')

  private def withClose[T <: AutoCloseable](closeable: T)(fn: T => Unit): Unit = {
    fn(closeable)

    if (closeable != null)
      closeable.close()
  }

  @Test def ctorSize: Unit = {
    withClose(new CharArrayWriter(90)) { cw =>
      assertEquals(0, cw.size)
    }
  }

  @Test def ctorSizeNegativeThrows(): Unit = {
    assertThrows(classOf[IllegalArgumentException], new CharArrayWriter(-1))
  }

  @Test def ctorSizeDefault(): Unit = {
    withClose(new CharArrayWriter) { cw =>
      assertEquals(0, cw.size)
    }
  }

  @Test def close(): Unit = {
    withClose(new CharArrayWriter) { cw =>
      cw.close()
      cw.close() // no-op
      assertEquals(0, cw.size)
    }
  }

  @Test def flush(): Unit = {
    withClose(new CharArrayWriter) { cw =>
      cw.flush()
    }
  }

  @Test def reset(): Unit = {
    withClose(new CharArrayWriter) { cw =>
      cw.write("HelloWorld", 5, 5)
      cw.reset()
      cw.write("HelloWorld", 0, 5)

      assertArrayEquals("Hello".toCharArray, cw.toCharArray)
    }
  }

  @Test def size(): Unit = {
    withClose(new CharArrayWriter) { cw =>
      assertEquals(0, cw.size)
      cw.write(hw, 5, 5)
      assertEquals(5, cw.size)
    }
  }

  @Test def toCharArray(): Unit = {
    withClose(new CharArrayWriter) { cw =>
      cw.write("HelloWorld", 0, 10)
      assertArrayEquals("HelloWorld".toCharArray, cw.toCharArray)
    }
  }

  @Test def testToString(): Unit = {
    withClose(new CharArrayWriter) { cw =>
      cw.write("HelloWorld", 5, 5)
      assertEquals("World", cw.toString)
    }
  }

  @Test def writeSubArrayToCharArray(): Unit = {
    withClose(new CharArrayWriter) { cw =>
      cw.write(hw, 5, 5)
      assertEquals("World", cw.toString)
      assertArrayEquals("World".toCharArray, cw.toCharArray)
    }
  }

  @Test def throwsIndexOutOfBoundsException(): Unit = {
    withClose(new CharArrayWriter) { obj =>
      assertThrows(classOf[IndexOutOfBoundsException],
          obj.write(Array[Char]('0'), 0, -1))
    }
  }

  @Test def writeChar(): Unit = {
    withClose(new CharArrayWriter) { cw =>
      cw.write('T')
      assertEquals("T", cw.toString)
      assertArrayEquals(Array('T'), cw.toCharArray)
    }
  }

  @Test def writeString(): Unit = {
    withClose(new CharArrayWriter) { cw =>
      cw.write("HelloWorld", 5, 5)
      assertEquals("World", cw.toString)
      assertArrayEquals("World".toCharArray, cw.toCharArray)
    }
  }

  @Test def writeToStringWriter(): Unit = {
    withClose(new CharArrayWriter) { cw =>
      cw.write("HelloWorld", 0, 10)
      withClose(new StringWriter) { sw =>
        cw.writeTo(sw)
        assertEquals("HelloWorld", sw.toString)
      }
    }
  }

  @Test def appendChar(): Unit = {
    withClose(new CharArrayWriter(10)) { cw =>
      val testChar = ' '
      cw.append(testChar)
      cw.flush()
      assertEquals(String.valueOf(testChar), cw.toString)
      assertArrayEquals(Array(testChar), cw.toCharArray)
    }
  }

  @Test def appendCharSequence(): Unit = {
    withClose(new CharArrayWriter(10)) { cw =>
      val testString: CharSequence = "My Test String"
      cw.append(testString)
      cw.flush()
      assertEquals("My Test String", cw.toString)
      assertArrayEquals("My Test String".toCharArray, cw.toCharArray)
    }
  }

  @Test def appendCharSequenceWithOffset(): Unit = {
    withClose(new CharArrayWriter(10)) { cw =>
      val testString: String = "My Test String"
      cw.append(testString, 1, 3)
      cw.flush()
      assertEquals(testString.substring(1, 3), cw.toString)
      assertArrayEquals(testString.substring(1, 3).toCharArray, cw.toCharArray)
    }
  }
}


text:
require('suitcss-utils-after');
require('suitcss-utils-before');