text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto

package com.google.cloud.compute.v1;

public interface LocationPolicyLocationConstraintsOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.LocationPolicyLocationConstraints)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Maximum number of items that are allowed to be placed in this zone. The value must be non-negative.
   *

   *
   * optional int32 max_count = 287620724;
   *
   * @return Whether the maxCount field is set.
   */
  boolean hasMaxCount();
  /**
   *
   *
   *

   * Maximum number of items that are allowed to be placed in this zone. The value must be non-negative.
   *

   *
   * optional int32 max_count = 287620724;
   *
   * @return The maxCount.
   */
  int getMaxCount();
}


text:
require 'spec_helper'

module Bosh::AwsCloud
  describe 'BlockDeviceManager' do
    let(:logger) { Logger.new('/dev/null') }
    let(:default_root) do
      {
        device_name: default_root_dev,
        ebs: {
          volume_type: 'gp3',
          delete_on_termination: true,
        },
      }
    end
    let(:default_root_dev) { '/dev/xvda' }
    let(:aws_config) do
      instance_double(Bosh::AwsCloud::AwsConfig)
    end
    let(:global_config) { instance_double(Bosh::AwsCloud::Config, aws: aws_config) }
    let(:instance_type) { 'm3.xlarge' }
    let(:vm_type) do
      {
        'key_name' => 'bar',
        'availability_zone' => 'us-east-1a',
        'instance_type' => instance_type,
        'raw_instance_storage' => false
      }
    end
    let(:vm_cloud_props) do
      Bosh::AwsCloud::VMCloudProps.new(vm_type, global_config)
    end

    let(:image_id) { 'ami-1234567' }
    let(:image) { instance_double(Aws::EC2::Image, id: image_id) }
    let(:stemcell) { instance_double(Bosh::AwsCloud::Stemcell, ami: image, image_id: image_id) }

    let(:virtualization_type) { 'hvm' }
    let(:root_device_name) { '/dev/xvda' }
    let(:original_block_device_mappings) { [] }

    let(:manager) { BlockDeviceManager.new(logger, stemcell, vm_cloud_props) }

    before do
      allow(aws_config).to receive(:default_iam_instance_profile)
      allow(aws_config).to receive(:encrypted)
      allow(aws_config).to receive(:kms_key_arn)

      allow(image).to receive(:virtualization_type).and_return(virtualization_type)
      allow(image).to receive(:root_device_name).and_return(root_device_name)
      allow(image).to receive(:block_device_mappings).and_return(original_block_device_mappings)
    end

    describe '#mappings_and_info' do
      shared_examples 'NVMe required instance types' do
        let(:expected_output) do
          [
            {
              device_name: '/dev/sdb',
              ebs: {
                volume_size: 10,
                volume_type: 'gp3',
                delete_on_termination: true,
              }
            },
            default_root,
          ]
        end
        let(:expected_agent_info) do
          {
              'ephemeral' => [{ 'path' => '/dev/sdb' }]
          }
        end

        let(:device_path) do
          BlockDeviceManager.device_path('/dev/sdf', instance_type, 'vol-123')
        end

        it 'returns an EBS volume with /dev/sdb' do
          actual_output, _ = manager.mappings_and_info
          expect(actual_output).to eq(expected_output)
        end

        it 'returns ephemeral disk settings to the agent with /dev/sdb' do
          _, actual_agent_info = manager.mappings_and_info
          expect(actual_agent_info).to eq(expected_agent_info)
        end

        it 'returns persistent disk name by volume ID' do
          expect(device_path)
            .to eq('/dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_vol123')
        end
      end

      BlockDeviceManager::NVME_INSTANCE_FAMILIES.each do |nvme_instance_family|
        context "when creating #{nvme_instance_family} instances" do
          let(:instance_type) { "#{nvme_instance_family}.large" }

          it_behaves_like 'NVMe required instance types'
        end
      end

      context 'when omitting the ephemeral disk EBS' do
        context 'when using instance storage for ephemeral disk' do
          context 'when instance type has instance storage' do
            let(:instance_type) { 'm3.xlarge' }
            let(:vm_type) do
              {
                'key_name' => 'bar',
                'availability_zone' => 'us-east-1a',
                'instance_type' => instance_type,
                'raw_instance_storage' => raw_instance_storage
              }
            end

            context 'when raw_instance_storage is false' do
              let(:raw_instance_storage) { false }
              it 'returns an EBS volume with size determined by the instance_type' do
                actual_output, agent_info = manager.mappings_and_info
                expected_output = [
                  {
                    device_name: '/dev/sdb',
                    ebs: {
                      volume_size: 40,
                      volume_type: 'gp3',
                      delete_on_termination: true,
                    }
                  },
                  default_root,
                ]
                expect(actual_output).to eq(expected_output)
                expect(agent_info).to eq('ephemeral' => [{'path' => '/dev/sdb'}])
              end
            end

            context 'when raw_instance_storage is true' do
              let(:raw_instance_storage) { true }

              it 'returns an EBS volume with size 10GB and disks for each instance storage disk' do
                actual_output, agent_info = manager.mappings_and_info
                expected_output = [default_root]
                instance_storage_disks = [
                  {
                    virtual_name: 'ephemeral0',
                    device_name: '/dev/xvdba'
                  },
                  {
                    virtual_name: 'ephemeral1',
                    device_name: '/dev/xvdbb'
                  }
                ]
                expected_output += instance_storage_disks

                ebs_disk = {
                  device_name: '/dev/sdb',
                  ebs: {
                    volume_size: 10,
                    volume_type: 'gp3',
                    delete_on_termination: true,
                  }
                }
                expected_output << ebs_disk
                expect(actual_output).to match_array(expected_output)
                expect(agent_info).to eq(
                  'ephemeral' => [{'path' => '/dev/sdb'}],
                  'raw_ephemeral' => [{'path' => '/dev/xvdba'}, {'path' => '/dev/xvdbb'}]
                )
              end

              context 'and NVMe storage types' do
                let(:instance_type) { 'i3.4xlarge' }

                it 'returns an EBS volume with size 10GB and NO disks NVMe instance storage' do
                  actual_output, agent_info = manager.mappings_and_info
                  expected_output = [default_root]
                  instance_storage_disks = []
                  expected_output += instance_storage_disks

                  ebs_disk = {
                    device_name: '/dev/sdb',
                    ebs: {
                      volume_size: 10,
                      volume_type: 'gp3',
                      delete_on_termination: true,
                    }
                  }
                  expected_output << ebs_disk
                  expect(actual_output).to match_array(expected_output)
                  expect(agent_info).to eq(
                    'ephemeral' => [{'path' => '/dev/sdb'}],
                    'raw_ephemeral' => [{'path' => '/dev/nvme0n1'}, {'path' => '/dev/nvme1n1'}],
                  )
                end
              end

              context 'when the instance is paravirtual' do
                let(:default_root_dev) { '/dev/sda' }
                let(:virtualization_type) { 'paravirtual' }

                it 'attaches instance disks under /dev/sd[c-z]' do
                  actual_output, _agent_info = manager.mappings_and_info
                  expected_output = [default_root]
                  instance_storage_disks = [
                    {
                      virtual_name: 'ephemeral0',
                      device_name: '/dev/sdc'
                    },
                    {
                      virtual_name: 'ephemeral1',
                      device_name: '/dev/sdd'
                    }
                  ]
                  expected_output += instance_storage_disks

                  ebs_disk = {
                    device_name: '/dev/sdb',
                    ebs: {
                      volume_size: 10,
                      volume_type: 'gp3',
                      delete_on_termination: true,
                    }
                  }
                  expected_output << ebs_disk
                  expect(actual_output).to match_array(expected_output)
                end
              end
            end
          end

          context 'when instance type does not have instance storage' do
            let(:vm_type) do
              {
                'key_name' => 'bar',
                'availability_zone' => 'us-east-1a',
                'instance_type' => 't2.small'
              }
            end

            it 'uses a default 10GB EBS storage for ephemeral disk' do
              mappings, agent_info = manager.mappings_and_info
              ebs_disk = {
                device_name: '/dev/sdb',
                ebs: {
                  volume_size: 10,
                  volume_type: 'gp3',
                  delete_on_termination: true,
                }
              }
              expect(mappings).to contain_exactly(ebs_disk, default_root)
              expect(agent_info).to eq('ephemeral' => [{'path' => '/dev/sdb'}])
            end

            context 'when asked for raw instance storage' do
              let(:vm_type) do
                {
                  'key_name' => 'bar',
                  'availability_zone' => 'us-east-1a',
                  'instance_type' => 't2.small',
                  'raw_instance_storage' => true
                }
              end

              it 'raises an error when asked for raw instance storage' do
                expect { manager.mappings_and_info }.to raise_error(
                  Bosh::Clouds::CloudError,
                  "raw_instance_storage requested for instance type 't2.small' that does not have instance storage"
                )
              end
            end
          end
        end

        context 'when using root device for ephemeral disk' do
          let(:vm_type) do
            {
              'key_name' => 'bar',
              'availability_zone' => 'us-east-1a',
              'instance_type' => instance_type,
              'ephemeral_disk' => {
                'use_root_disk' => true,
              }
            }
          end

          it 'does not configure a block device for ephemeral disk' do
            manager = BlockDeviceManager.new(logger, stemcell, vm_cloud_props)

            expected_output = [
              default_root
            ]

            mappings, agent_info = manager.mappings_and_info
            expect(mappings).to match_array(expected_output)
            expect(agent_info).to eq({})
          end
        end
      end

      context 'when specifying the ephemeral disk size' do
        let(:vm_type) do
          {
            'key_name' => 'bar',
            'availability_zone' => 'us-east-1a',
            'instance_type' => 'm3.xlarge',
            'raw_instance_storage' => false,
            'ephemeral_disk' => {
              'size' => 4000
            }
          }
        end

        it 'returns an EBS with the specified ephemeral disk size' do
          manager = BlockDeviceManager.new(logger, stemcell, vm_cloud_props)

          expected_output = [
            {
              device_name: '/dev/sdb',
              ebs: {
                volume_size: 4,
                volume_type: 'gp3',
                delete_on_termination: true,
              },
            },
            default_root,
          ]

          mappings, _agent_info = manager.mappings_and_info
          expect(mappings).to match_array(expected_output)
        end

        context 'when raw_instance_storage is true' do
          let(:vm_type) do
            {
              'key_name' => 'bar',
              'availability_zone' => 'us-east-1a',
              # this instance type has 2 instance storage disks
              'instance_type' => 'm3.xlarge',
              'raw_instance_storage' => true,
              'ephemeral_disk' => {
                'size' => 4000
              }
            }
          end

          it 'returns disks for new EBS volume and instance storage disks' do
            expected_disks = [
              default_root,
              {
                virtual_name: 'ephemeral0',
                device_name: '/dev/xvdba',
              },
              {
                virtual_name: 'ephemeral1',
                device_name: '/dev/xvdbb',
              },
              {
                device_name: '/dev/sdb',
                ebs: {
                  volume_size: 4,
                  volume_type: 'gp3',
                  delete_on_termination: true,
                }
              }
            ]

            mappings, _agent_info = manager.mappings_and_info
            expect(mappings).to match_array(expected_disks)
          end

          context 'when the instance is paravirtual' do
            let(:default_root_dev) { '/dev/sda' }
            let(:vm_type) do
              {
                'key_name' => 'bar',
                'availability_zone' => 'us-east-1a',
                'instance_type' => 'm3.xlarge',
                'raw_instance_storage' => true,
                'ephemeral_disk' => {
                  'size' => 4000
                }
              }
            end
            let(:virtualization_type) { 'paravirtual' }

            it 'returns disks for new EBS volume and instance storage disks under /dev/sd[c-z]' do
              expected_disks = [
                default_root,
                {
                  virtual_name: 'ephemeral0',
                  device_name: '/dev/sdc'
                },
                {
                  virtual_name: 'ephemeral1',
                  device_name: '/dev/sdd',
                },
                {
                  device_name: '/dev/sdb',
                  ebs: {
                    volume_size: 4,
                    volume_type: 'gp3',
                    delete_on_termination: true,
                  }
                }
              ]

              mappings, _agent_info = manager.mappings_and_info
              expect(mappings).to match_array(expected_disks)
            end
          end
        end
      end

      context 'when specifying the ephemeral disk type' do
        let(:vm_type) do
          {
            'key_name' => 'bar',
            'availability_zone' => 'us-east-1a',
            'instance_type' => 't2.small',
            'ephemeral_disk' => ephemeral_disk
          }
        end
        let(:ephemeral_disk) do
          {
            'type' => 'gp3'
          }
        end

        it 'uses the specified type' do
          ebs_disk = {
            device_name: '/dev/sdb',
            ebs: {
              volume_size: 10,
              volume_type: 'gp3',
              delete_on_termination: true
            }
          }
          mappings, _agent_info = manager.mappings_and_info
          expect(mappings).to contain_exactly(ebs_disk, default_root)
        end

        context 'when type is io1' do
          let(:ephemeral_disk) do
            {
              'type' => 'io1',
              'iops' => 123
            }
          end

          it 'configures the io1 disk' do
            ebs_disk = {
              device_name: '/dev/sdb',
              ebs: {
                volume_size: 10,
                volume_type: 'io1',
                iops: 123,
                delete_on_termination: true
              }
            }
            mappings, _agent_info = manager.mappings_and_info
            expect(mappings).to  contain_exactly(ebs_disk, default_root)
          end
        end
      end

      context 'when specifying encrypted' do
        let(:vm_type) do
          {
            'key_name' => 'bar',
            'availability_zone' => 'us-east-1a',
            'instance_type' => 't2.small',
            'ephemeral_disk' => {
              'size' => 4000,
              'encrypted' => true
            }
          }
        end

        it 'will add it to the EBS configuration' do
          expected_output = [
            {
              device_name: '/dev/sdb',
              ebs: {
                volume_size: 4,
                volume_type: 'gp3',
                delete_on_termination: true,
                encrypted: true
              }
            },
            default_root
          ]

          mappings, _agent_info = manager.mappings_and_info
          expect(mappings).to  match_array(expected_output)
        end

        context 'and kms_key_arn' do
          let(:vm_type) do
            {
              'key_name' => 'bar',
              'availability_zone' => 'us-east-1a',
              'instance_type' => 't2.small',
              'ephemeral_disk' => {
                'size' => 4000,
                'encrypted' => true,
                'kms_key_arn' => 'arn:aws:kms:us-east-1:XXXXXX:key/e1c1f008-779b-4ebe-8116-0a34b77747dd'
              }
            }
          end
          let(:volume) { instance_double(Aws::EC2::Volume) }

          it 'will add encrypted and kms_key_id to the EBS conbfiguration' do
            expected_output = [
              {
                device_name: '/dev/sdb',
                ebs: {
                  volume_size: 4,
                  volume_type: 'gp3',
                  delete_on_termination: true,
                  encrypted: true,
                  kms_key_id: 'arn:aws:kms:us-east-1:XXXXXX:key/e1c1f008-779b-4ebe-8116-0a34b77747dd'
                }
              },
              default_root
            ]

            mappings, _agent_info = manager.mappings_and_info
            expect(mappings).to match_array(expected_output)
          end
        end
      end

      context 'when specifying use_instance_storage' do
        context 'when the instance_type has instance storage' do
          let(:vm_type) do
            {
              'key_name' => 'bar',
              'availability_zone' => 'us-east-1a',
              'instance_type' => 'm3.xlarge',
              'ephemeral_disk' => {
                'use_instance_storage' => true
              }
            }
          end

          it 'returns instance storage disks as ephemeral disk' do
            expected_disks = [
              {
                virtual_name: 'ephemeral0',
                device_name: '/dev/sdb'
              },
              default_root
            ]

            mappings, _agent_info = manager.mappings_and_info
            expect(mappings).to  match_array(expected_disks)
          end
        end

        context 'when the instance_type has NO instance storage' do
          let(:vm_type) do
            {
              'key_name' => 'bar',
              'availability_zone' => 'us-east-1a',
              'instance_type' => 't2.small',
              'ephemeral_disk' => {
                'use_instance_storage' => true
              }
            }
          end

          it 'raises an error' do
            expect { manager.mappings_and_info }.to raise_error(
              Bosh::Clouds::CloudError,
              "use_instance_storage requested for instance type 't2.small' that does not have instance storage"
            )
          end
        end

        context 'when any other properties are set for ephemeral_disk' do
          let(:vm_type) do
            {
              'key_name' => 'bar',
              'availability_zone' => 'us-east-1a',
              'instance_type' => 'm3.medium',
              'ephemeral_disk' => {
                'use_instance_storage' => true,
                'size' => 512
              }
            }
          end

          it 'raises an error' do
            expect { manager.mappings_and_info }.to raise_error(
              Bosh::Clouds::CloudError,
              "use_instance_storage cannot be combined with additional ephemeral_disk properties"
            )
          end
        end

        context 'when raw_instance_storage is also set' do
          let(:vm_type) do
            {
              'key_name' => 'bar',
              'availability_zone' => 'us-east-1a',
              'instance_type' => 'm3.medium',
              'ephemeral_disk' => {
                'use_instance_storage' => true
              },
              'raw_instance_storage' => true
            }
          end

          it 'raises an error' do
            expect { manager.mappings_and_info }.to raise_error(
              Bosh::Clouds::CloudError,
              "ephemeral_disk.use_instance_storage and raw_instance_storage cannot both be true"
            )
          end
        end
      end

      context 'when root disk is specified' do
        let(:vm_type) do
          {
            'key_name' => 'bar',
            'availability_zone' => 'us-east-1a',
            'instance_type' => 'm3.medium',
            'root_disk' => {
              'size' => 42 * 1024.0
            }
          }
        end

        it 'should default root disk type to gp3 if type is not specified' do
          mappings, agent_info = manager.mappings_and_info

          expected_disks = [
            {
              device_name: '/dev/xvda',
              ebs: {
                volume_size: 42,
                volume_type: 'gp3',
                delete_on_termination: true
              }
            },
            {
              device_name: '/dev/sdb',
              ebs: {
                volume_size: 4,
                volume_type: 'gp3',
                delete_on_termination: true
              }
            }
          ]

          expect(agent_info).to eq('ephemeral' => [{'path' => '/dev/sdb'}])
          expect(mappings).to match_array(expected_disks)
        end

        context 'when root disk type is io1' do
          let(:vm_type) do
            {
              'key_name' => 'bar',
              'availability_zone' => 'us-east-1a',
              'instance_type' => 'm3.medium',
              'root_disk' => {
                'size' => 42 * 1024.0
              }
            }
          end

          it 'should create disk type of io1 with iops' do
            vm_type['root_disk']['type'] = 'io1'
            vm_type['root_disk']['iops'] = 1000

            manager = BlockDeviceManager.new(logger, stemcell, vm_cloud_props)
            expected_disks = []

            ephemeral_disks = [{
                                 device_name: '/dev/sdb',
                                 ebs: {
                                   volume_size: 4,
                                   volume_type: 'gp3',
                                   delete_on_termination: true,
                                 }
                               }]
            expected_disks += ephemeral_disks

            root_disk = {
              device_name: '/dev/xvda',
              ebs: {
                volume_size: 42,
                volume_type: 'io1',
                iops: 1000,
                delete_on_termination: true,
              }
            }
            expected_disks << root_disk

            actual_disks, _agent_info = manager.mappings_and_info
            expect(actual_disks).to match_array(expected_disks)
          end
        end

        context 'when virtualization_type is not hvm' do
          let(:virtualization_type) { 'paravirtual' }
          it 'should set device name' do
            expected_disks = []

            ephemeral_disks = [{
              device_name: '/dev/sdb',
              ebs: {
                volume_size: 4,
                volume_type: 'gp3',
                delete_on_termination: true,
              }
            }]
            expected_disks += ephemeral_disks

            root_disk = {
              device_name: '/dev/sda',
              ebs: {
                volume_size: 42,
                volume_type: 'gp3',
                delete_on_termination: true,
              }
            }
            expected_disks << root_disk

            actual_disks, _agent_info = manager.mappings_and_info
            expect(actual_disks).to match_array(expected_disks)
          end
        end
      end
    end

    describe '#block_device_ready' do
      before do
        allow(BlockDeviceManager).to receive(:sleep).with(1)
      end

      context 'nvme device path' do
        it 'checks for nvme block device' do
          allow(File).to receive(:blockdev?).and_return(false, true)
          actual = BlockDeviceManager.block_device_ready?(BlockDeviceManager::NVME_EBS_BY_ID_DEVICE_PATH_PREFIX + "volid")
          expect(actual).to match(BlockDeviceManager::NVME_EBS_BY_ID_DEVICE_PATH_PREFIX + "volid")
          expect(File).to have_received(:blockdev?).exactly(2).times
        end
      end

      context 'not an nvme device path' do
        context 'device mounted at /dev/sda' do
          it 'checks for sd* or xvd* block device' do
            allow(File).to receive(:blockdev?).with('/dev/sda').and_return(false, true)
            allow(File).to receive(:blockdev?).with('/dev/xvda').and_return(false)
            actual = BlockDeviceManager.block_device_ready?('/dev/sda')
            expect(actual).to match('/dev/sda')
            expect(File).to have_received(:blockdev?).exactly(3).times
          end
        end
        context 'device mounted at /dev/xvda' do
          it 'checks for sd* or xvd* block device' do
            allow(File).to receive(:blockdev?).with('/dev/sda').and_return(false)
            allow(File).to receive(:blockdev?).with('/dev/xvda').and_return(false, true)
            actual = BlockDeviceManager.block_device_ready?('/dev/sda')
            expect(actual).to match('/dev/xvda')
            expect(File).to have_received(:blockdev?).exactly(4).times
          end
        end
      end

      context 'block device never mounted' do
        it 'raises cloud error' do
          allow(File).to receive(:blockdev?).and_return(false)
          expect {
            BlockDeviceManager.block_device_ready?(BlockDeviceManager::NVME_EBS_BY_ID_DEVICE_PATH_PREFIX + "volid")
          }.to raise_error(Bosh::Clouds::CloudError, /Cannot find EBS volume on current instance/)
          expect(File).to have_received(:blockdev?).exactly(60).times
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.capcaval.c3.c3application.objectfactory;

import java.awt.Color;

public class ColorFromStringValue implements ObjectFactoryFromStringValue <Color>{

	@Override
	public Color newObjectFromStringValue(String stringValue,
			StringBuffer errorMessage) {
		Color c = new Color(Integer.decode(stringValue));

		return c;
	}

	@Override
	public String newStringFromObjectValue(Color object,
			StringBuffer errorMessage) {
		return Integer.toHexString(object.getRGB());
	}

}


text:
@extends('layouts.app')

@section('content')

You are going to create a PFX Archive for: {{ $subjectCommonName }}

    {{ Form::open(['url' => 'converter/storeP12', 'method' => 'post']) }}
    <input type="hidden" name="subjectCommonName" value="{{ $subjectCommonName }}">
    {{ Form::label('password: ', 'Passphrase: ', ['class' => '']) }}
    {{ Form::password('password', ['placeholder' => 'Passphrase', 'class' => 'form-control' ]) }}
        @if($errors->has('password'))
        {{ $errors->first('password') }}
    @endif

    {{ Form::token() }}
    {{ Form::button(' Create & Get PFX(P12)', ['class' => 'btn btn-primary btn-md', 'type' => 'submit']) }}
    {{ Form::close() }}

@endsection


text:
using System;
using Android.Widget;
using Android.Util;
using Android.Runtime;
using Android.Graphics.Drawables;
using Android.Content;

namespace AskXhacker
{
	public class CircleImageView : ImageView
	{
		public CircleImageView(Context context, IAttributeSet attrs)
			: base(context, attrs)
		{
		}

		public CircleImageView(Context context)
			: base(context)
		{
		}
		protected CircleImageView(IntPtr javaReference, JniHandleOwnership transfer)
			: base(javaReference, transfer)
		{
		}

		public override void SetImageDrawable(Drawable drawable)
		{
			var inputBitmap = drawable.DrawableToBitmap();
			var drawable2 = new CircleDrawable(inputBitmap);
			base.SetImageDrawable(drawable2);
		}

		public override void SetImageBitmap(Android.Graphics.Bitmap bm)
		{

			var drawable = new CircleDrawable(bm);
			base.SetImageDrawable(drawable);

		}

		public override void SetImageResource(int resId)
		{
			var inputBitmap = Resources.GetDrawable(resId).DrawableToBitmap();

			var drawable = new CircleDrawable(inputBitmap);
			base.SetImageDrawable(drawable);
		}

		protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
		{
			base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
			SetMeasuredDimension (MeasuredWidth, MeasuredWidth);
		}
	}
}


text:
"""
General interpolation
---------------------
Module which contains the general functions and classes to interpolate features
distributed in a space.

"""

import numpy as np

def general_interpolate(features, points, method, kwargs):
    """General function which acts as a switcher to interpolate features
    distributed in the space.

    """

    if method == "":
        interpolation = np.zeros((points.shape[0], features.shape[1]))

    return interpolation


text:
title: Backgrounder
taxonomy:
    category: docs
---

![Backgrounder](backgrounder.png)

## Description of elements

This template is initially composed of items:

![Backgrounder](home1.png)

1- Logo
2- Menu
3- Menu Canvas
4- Slideshow
5- Social Icons

## Logo

Custom html module published to the logo position.

![Logo](home1_01.png)

### The position of the logo in the template follows the image below:

![Logo](logo1.png)

### You can adjust some of the logo settings. But for this, your logo should be composed of text.

![Logo](logo2.png)

## Social Icons

Social icon block generated by the template.
![Social Icons](home1_06.png)

### The social module is configured according to the image below:

![Social Icons](social.png)

### And the responsive social module is configured according to the image below:

![Social Icons](social-mobile.png)

## Offcanvas trigger

Offcanvas trigger generated by the template.

![Offcanvas](home1_04.png)

### Offcanvas Position

The offcanvas trigger is positioned in the template via the layout tool.

![Offcanvas Position](canvas1.png)

### Offcanvas Settings

Features such as the button style for the offcanvas trigger, the side of the screen the offcanvas opens on, when it becomes visible and the text for the trigger are controlled in the menus > offcanvas panel of the template.

![Offcanvas Settings](canvas23.png)

### Offcanvas button color

The color of the offcanvas button is controlled in the row settings panel for the top-right position. The btn-empty style inherits the color set in the colors section of the top-right row settings panel.

![Button Color](canvas2.png)

## Menu Top

![menu](home1_03.png)
#### This menu is controlled by a menu-type module and inserted in the position "menu".

### This module is available in the position of the temple according to the image below:
![menu](menu1.png)

### You can also control some features of this module by going to the menu inside the template:

![menu](menu2.png)

### You can also adjust some functions of the menu, such as animations, alignment and others by going to the dropdown menu in the template:

![menu](menu3.png)

## Slideshow

![slide](home1_05.png)
### This menu is controlled by a zentools module and inserted in the position "banner".

this module is customized according to the image below:
![slide](slide1.gif)

## Content

![content](home2_01.png)
#### This menu is controlled by a module type custom and inserted in the position "grid5".

## Filter

![filter](home2_02.png)
#### This menu is controlled by a module zentools and inserted in the position "grid8".

### The configuration of this module is:

![filter](filtro.gif)

###  For this module to work, you must insert the 'no-margin' class in the 'Advanced Settings' tab.

### The content of this module is fed by the articles indicated in the tab content field 'Content Selection'.

## Frequently Asked Questions

![faq](home3_01.png)
#### This menu is controlled by a module zentools and inserted in the position "grid17".

### The configuration of this module is:
![filter](faq.gif)

### The content of this module is fed by the articles indicated in the tab content field 'Content Selection'.

## Latest Gallery

![faq](home3_02.png)
#### This menu is controlled by a module zentools and inserted in the position "grid18".

### The configuration of this module is:
![filter](gallery.gif)

### The images of this module is fed by the folder images indicated in the field "Select a folder".

## Theme Overview

![skill](home4_01.png)
#### This menu is controlled by a module Skillset and inserted in the position "grid21".

### The configuration of this module is:
![filter](skill.gif)

## By the Numbers

![skill](home4_02.png)
#### This menu is controlled by a module Skillset and inserted in the position "grid24".

### The configuration of this module is:
![filter](skill2.gif)

## Menu About Us

![about](home5_01.png)
#### This menu is controlled by a module Custom and inserted in the position "bottom1".

### The configuration of this module is:
![filter](about.png)

To use other icone access the menu that already installed as display content of the template: "Features > Tools > Zen Shortcode.

Each menu you should link using the text editor.

## Location

![about](home5_02.png)
#### This menu is controlled by a module Custom and inserted in the position "bottom2".

### The configuration of this module is:
![filter](legal.png)

## Legal

![about](home5_04.png)
#### This menu is controlled by a module Custom and inserted in the position "bottom3".

### The configuration of this module is:
![filter](legal2.png)

To use other icone access the menu that already installed as display content of the template: "Features > Tools > Zen Shortcode.

Each menu you should link using the text editor.

## Get in touch

![about](home5_05.png)
#### This menu is controlled by a module Custom and inserted in the position "bottom4".

### The configuration of this module is:
![filter](get.png)

Exemple in the template:

<input type="text" placeholder="Email" /><button class="btn">Submit</button>

## Footer Menu

Joomla menu published to the footer position

![Footer Menu](home5_06.png)

## Footer Social Icons

Zensocial module published to the footer position

![Social Footer](home5_09.png)

## Footer logo and text

Custom html module published to the footer position

![Footer Logo](logo-bottom.png)

## Recent News Module
The recent news module is an instance of the Zentools2 module displaying Joomla content using the list layout.

![Recent News](news.png)

#### This menu is controlled by a module zentools and inserted in the position "offcanvas".

### The configuration of this module is:
![filter](news.gif)

### The content of this module is fed by the articles indicated in the tab content field 'Content Selection'.


text:
/**
 * Developer: Kadvin Date: 14-5-28 下午3:01
 */
package spring.test.ann_application.beans;

import org.springframework.context.Lifecycle;
import org.springframework.stereotype.Component;

/**
 * A annotation bean for annotation driven context
 */
@Component
public class AnnotationBean implements Lifecycle {
    private boolean running;
    @Override
    public void start() {
        System.out.println("AnnotationBean started");
        running = true;
    }

    @Override
    public void stop() {
        System.out.println("AnnotationBean stopped");
        running = false;
    }

    @Override
    public boolean isRunning() {
        return running;
    }
}


text:
package org.finra.datagenerator.scaffolding.random.predicate

/**
  * Created by dkopel on 12/6/16.
  */
sealed trait PredicateType
object InternalPredicate extends PredicateType
object CustomPredicate extends PredicateType


text:
goog.provide("main.main");
main.main = function(){
    window.alert("hello!");
    var not_used;
    window.alert(not_usd); // typo
    /* it will cause:
    js/main.js:5: ERROR - variable not_usd is undeclared
    window.alert(not_usd); // typo
                 ^
     */
}


text:
package com.mercadopago.android.px.internal.features.payment_result.components;

import android.content.Context;
import com.mercadopago.android.px.R;
import com.mercadopago.android.px.configuration.PaymentResultScreenConfiguration;
import com.mercadopago.android.px.internal.features.review_and_confirm.components.actions.ChangePaymentMethodAction;
import com.mercadopago.android.px.internal.view.ActionDispatcher;
import com.mercadopago.android.px.internal.view.Footer;
import com.mercadopago.android.px.internal.view.NextAction;
import com.mercadopago.android.px.internal.view.RecoverPaymentAction;
import com.mercadopago.android.px.mocks.PaymentResults;
import com.mercadopago.android.px.model.PaymentResult;
import com.mercadopago.android.px.tracking.internal.MPTracker;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@PrepareForTest(MPTracker.class)
@RunWith(PowerMockRunner.class)
public class FooterPaymentResultTest {

    private static final String LABEL_CONTINUE = "Continue";
    private static final String LABEL_CHANGE = "Change payment method";
    private static final String LABEL_ALREADY_ACTIVATED = "Already activated";
    private static final String LABEL_ALREADY_AUTHORIZED = "Already authorized";
    private static final String LABEL_REVIEW_TC_INFO = "REVIEW INFO";
    private static final String LABEL_OK = "ok";

    @Mock private Context context;
    @Mock private ActionDispatcher actionDispatcher;

    @Before
    public void setup() {
        PowerMockito.mockStatic(MPTracker.class);
        when(MPTracker.getInstance()).thenReturn(mock(MPTracker.class));
        new PaymentResultScreenConfiguration.Builder().build();
    }

    @Test
    public void testApproved() {
        when(context.getString(R.string.px_button_continue)).thenReturn(LABEL_CONTINUE);
        final PaymentResult paymentResult = PaymentResults.getStatusApprovedPaymentResult();
        final FooterPaymentResult footerPaymentResult = new FooterPaymentResult(paymentResult, actionDispatcher);

        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNull(props.buttonAction);
        assertNotNull(props.linkAction);

        assertEquals(LABEL_CONTINUE, props.linkAction.label);
        assertNotNull(props.linkAction.action);
        assertTrue(props.linkAction.action instanceof NextAction);
    }

    @Test
    public void testRejectedCardDisabledPaymentResult() {
        when(context.getString(R.string.px_text_card_enabled)).thenReturn(LABEL_ALREADY_ACTIVATED);
        final PaymentResult paymentResult = PaymentResults.getStatusRejectedCardDisabled();
        final FooterPaymentResult footerPaymentResult = new FooterPaymentResult(paymentResult, actionDispatcher);
        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNotNull(props.buttonAction);
        assertEquals(LABEL_ALREADY_ACTIVATED, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertTrue(props.buttonAction.action instanceof RecoverPaymentAction);
        assertNotNull(props.linkAction);
        assertTrue(LABEL_CHANGE, props.linkAction.action instanceof ChangePaymentMethodAction);
    }

    @Test
    public void testRejectedOtherReasonPaymentResult() {
        when(context.getString(R.string.px_change_payment)).thenReturn(LABEL_CHANGE);
        final PaymentResult paymentResult = PaymentResults.getStatusRejectedOtherPaymentResult();
        final FooterPaymentResult footerPaymentResult = new FooterPaymentResult(paymentResult, actionDispatcher);
        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNotNull(props.buttonAction);
        assertEquals(LABEL_CHANGE, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertNull(props.linkAction);
        assertTrue(props.buttonAction.action instanceof ChangePaymentMethodAction);
    }

    @Test
    public void testRejectedBadFilledDatePaymentResult() {

        when(context.getString(R.string.px_text_pay_with_other_method)).thenReturn(LABEL_CHANGE);
        when(context.getString(R.string.px_error_bad_filled_action)).thenReturn(LABEL_REVIEW_TC_INFO);

        final PaymentResult paymentResult = PaymentResults.getStatusRejectedBadFilledDatePaymentResult();
        final FooterPaymentResult footerPaymentResult =
            new FooterPaymentResult(paymentResult, actionDispatcher);

        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNotNull(props.buttonAction);
        assertEquals(LABEL_REVIEW_TC_INFO, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertTrue(props.buttonAction.action instanceof RecoverPaymentAction);

        assertNotNull(props.linkAction);
        assertEquals(LABEL_CHANGE, props.linkAction.label);
        assertNotNull(props.linkAction.action);
        assertTrue(props.linkAction.action instanceof ChangePaymentMethodAction);
    }

    @Test
    public void testRejectedMaxAttemptsPaymentResult() {

        when(context.getString(R.string.px_change_payment)).thenReturn(LABEL_CHANGE);
        final PaymentResult paymentResult = PaymentResults.getStatusRejectedMaxAttemptsPaymentResult();
        final FooterPaymentResult footerPaymentResult =
            new FooterPaymentResult(paymentResult, actionDispatcher);

        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNotNull(props.buttonAction);
        assertEquals(LABEL_CHANGE, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertTrue(props.buttonAction.action instanceof ChangePaymentMethodAction);

        assertNull(props.linkAction);
    }

    @Test
    public void testRejectedCallForAuth() {
        when(context.getString(R.string.px_text_authorized_call_for_authorize)).thenReturn(LABEL_ALREADY_AUTHORIZED);
        final PaymentResult paymentResult = PaymentResults.getStatusCallForAuthPaymentResult();
        final FooterPaymentResult footerPaymentResult = new FooterPaymentResult(paymentResult, actionDispatcher);
        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNotNull(props.buttonAction);
        assertEquals(LABEL_ALREADY_AUTHORIZED, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertTrue(props.buttonAction.action instanceof RecoverPaymentAction);
        assertNotNull(props.linkAction);
        assertTrue(LABEL_CHANGE, props.linkAction.action instanceof ChangePaymentMethodAction);
    }

    @Test
    public void testRejectedInsufficientAmountPaymentResult() {
        when(context.getString(R.string.px_change_payment)).thenReturn(LABEL_CHANGE);

        final PaymentResult paymentResult = PaymentResults.getStatusRejectedInsufficientAmountPaymentResult();
        final FooterPaymentResult footerPaymentResult =
            new FooterPaymentResult(paymentResult, actionDispatcher);

        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNull(props.linkAction);

        assertNotNull(props.buttonAction);
        assertEquals(LABEL_CHANGE, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertTrue(props.buttonAction.action instanceof ChangePaymentMethodAction);
    }

    @Test
    public void testContingencyAndUnsupported() {
        when(context.getString(R.string.px_got_it)).thenReturn(LABEL_OK);

        final PaymentResult paymentResult = PaymentResults.getStatusInProcessContingencyPaymentResult();
        final FooterPaymentResult footerPaymentResult =
            new FooterPaymentResult(paymentResult, actionDispatcher);

        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNull(props.buttonAction);

        assertNotNull(props.linkAction);
        assertEquals(LABEL_OK, props.linkAction.label);
        assertNotNull(props.linkAction.action);
        assertTrue(props.linkAction.action instanceof NextAction);
    }

    @Test
    public void testReviewManual() {
        when(context.getString(R.string.px_got_it)).thenReturn(LABEL_OK);

        final PaymentResult paymentResult = PaymentResults.getStatusInProcessReviewManualPaymentResult();
        final FooterPaymentResult footerPaymentResult =
            new FooterPaymentResult(paymentResult, actionDispatcher);

        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNull(props.buttonAction);

        assertNotNull(props.linkAction);
        assertEquals(LABEL_OK, props.linkAction.label);
        assertNotNull(props.linkAction.action);
        assertTrue(props.linkAction.action instanceof NextAction);
    }

    @Test
    public void testRejected() {
        when(context.getString(R.string.px_change_payment)).thenReturn(LABEL_CHANGE);
        final PaymentResult paymentResult = PaymentResults.getStatusRejectedOtherPaymentResult();
        final FooterPaymentResult footerPaymentResult = new FooterPaymentResult(paymentResult, actionDispatcher);
        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNotNull(props.buttonAction);
        assertEquals(LABEL_CHANGE, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertTrue(props.buttonAction.action instanceof ChangePaymentMethodAction);
        assertNull(props.linkAction);
    }

    @Test
    public void testRejectedDuplicatedPaymentResult() {
        when(context.getString(R.string.px_got_it)).thenReturn(LABEL_OK);

        final PaymentResult paymentResult = PaymentResults.getStatusRejectedDuplicatedPaymentResult();
        final FooterPaymentResult footerPaymentResult =
            new FooterPaymentResult(paymentResult, actionDispatcher);

        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNull(props.buttonAction);

        assertNotNull(props.linkAction);
        assertEquals(LABEL_OK, props.linkAction.label);
        assertNotNull(props.linkAction.action);
        assertTrue(props.linkAction.action instanceof NextAction);
    }

    @Test
    public void testRejectedBlackListPaymentResult() {
        when(context.getString(R.string.px_change_payment)).thenReturn(LABEL_CHANGE);

        final PaymentResult paymentResult = PaymentResults.getStatusRejectedBlacklist();
        final FooterPaymentResult footerPaymentResult =
            new FooterPaymentResult(paymentResult, actionDispatcher);

        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNull(props.linkAction);

        assertNotNull(props.buttonAction);
        assertEquals(LABEL_CHANGE, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertTrue(props.buttonAction.action instanceof ChangePaymentMethodAction);
    }

    @Test
    public void testRejectedFraudPaymentResult() {
        when (context.getString(R.string.px_button_continue)).thenReturn(LABEL_CONTINUE);

        final PaymentResult paymentResult = PaymentResults.getStatusRejectedFraud();
        final FooterPaymentResult footerPaymentResult =
            new FooterPaymentResult(paymentResult, actionDispatcher);

        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNull(props.linkAction);

        assertNotNull(props.buttonAction);
        assertEquals(LABEL_CONTINUE, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertTrue(props.buttonAction.action instanceof NextAction);
    }

    @Test
    public void testRejectedHighRiskPaymentResult() {
        when (context.getString(R.string.px_change_payment)).thenReturn(LABEL_CHANGE);

        final PaymentResult paymentResult = PaymentResults.getStatusRejectedHighRisk();
        final FooterPaymentResult footerPaymentResult =
            new FooterPaymentResult(paymentResult, actionDispatcher);

        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNull(props.linkAction);

        assertNotNull(props.buttonAction);
        assertEquals(LABEL_CHANGE, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertTrue(props.buttonAction.action instanceof ChangePaymentMethodAction);
    }

    @Test
    public void testRejectedByRegulationsPaymentResult() {
        when (context.getString(R.string.px_change_payment)).thenReturn(LABEL_CHANGE);

        final PaymentResult paymentResult = PaymentResults.getStatusRejectedByRegulations();
        final FooterPaymentResult footerPaymentResult =
            new FooterPaymentResult(paymentResult, actionDispatcher);

        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNull(props.linkAction);

        assertNotNull(props.buttonAction);
        assertEquals(LABEL_CHANGE, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertTrue(props.buttonAction.action instanceof ChangePaymentMethodAction);
    }

    @Test
    public void testRejectedUnknown() {
        when(context.getString(R.string.px_change_payment)).thenReturn(LABEL_CHANGE);
        final PaymentResult paymentResult = PaymentResults.getStatusRejectedUnknown();
        final FooterPaymentResult footerPaymentResult = new FooterPaymentResult(paymentResult, actionDispatcher);
        final Footer.Props props = footerPaymentResult.getFooterProps(context);

        assertNotNull(props);
        assertNotNull(props.buttonAction);
        assertEquals(LABEL_CHANGE, props.buttonAction.label);
        assertNotNull(props.buttonAction.action);
        assertTrue(props.buttonAction.action instanceof ChangePaymentMethodAction);
        assertNull(props.linkAction);
    }
}


text:
using Q42.HueApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Q42.HueApi.ColorConverters.Original
{
  /// <summary>
  /// Used to convert colors between XY and RGB
  /// internal: Do not expose
  /// </summary>
  internal static partial class HueColorConverter
  {
    private static CGPoint Red = new CGPoint(0.675F, 0.322F);
    private static CGPoint Lime = new CGPoint(0.4091F, 0.518F);
    private static CGPoint Blue = new CGPoint(0.167F, 0.04F);
    private static float factor = 10000.0f;
    private static int maxX = 452;
    private static int maxY = 302;

    /// <summary>
    /// Get XY from red,green,blue strings / ints
    /// </summary>
    /// <param name="red"></param>
    /// <param name="green"></param>
    /// <param name="blue"></param>
    /// <returns></returns>
    private static CGPoint XyFromColor(string red, string green, string blue)
    {
      return XyFromColor(int.Parse(red), int.Parse(green), int.Parse(blue));
    }

    /// <summary>
    ///  Get XY from red,green,blue ints
    /// </summary>
    /// <param name="red"></param>
    /// <param name="green"></param>
    /// <param name="blue"></param>
    /// <returns></returns>
    public static CGPoint XyFromColor(int red, int green, int blue)
    {
      double r = (red > 0.04045f) ? Math.Pow((red + 0.055f) / (1.0f + 0.055f), 2.4f) : (red / 12.92f);
      double g = (green > 0.04045f) ? Math.Pow((green + 0.055f) / (1.0f + 0.055f), 2.4f) : (green / 12.92f);
      double b = (blue > 0.04045f) ? Math.Pow((blue + 0.055f) / (1.0f + 0.055f), 2.4f) : (blue / 12.92f);

      double X = r * 0.4360747f + g * 0.3850649f + b * 0.0930804f;
      double Y = r * 0.2225045f + g * 0.7168786f + b * 0.0406169f;
      double Z = r * 0.0139322f + g * 0.0971045f + b * 0.7141733f;

      double cx = X / (X + Y + Z);
      double cy = Y / (X + Y + Z);

      if (Double.IsNaN(cx))
      {
        cx = 0.0f;
      }

      if (Double.IsNaN(cy))
      {
        cy = 0.0f;
      }

      //Check if the given XY value is within the colourreach of our lamps.
      CGPoint xyPoint = new CGPoint(cx, cy);
      bool inReachOfLamps = HueColorConverter.CheckPointInLampsReach(xyPoint);

      if (!inReachOfLamps)
      {
        //It seems the colour is out of reach
        //let's find the closes colour we can produce with our lamp and send this XY value out.

        //Find the closest point on each line in the triangle.
        CGPoint pAB = HueColorConverter.GetClosestPointToPoint(Red, Lime, xyPoint);
        CGPoint pAC = HueColorConverter.GetClosestPointToPoint(Blue, Red, xyPoint);
        CGPoint pBC = HueColorConverter.GetClosestPointToPoint(Lime, Blue, xyPoint);

        //Get the distances per point and see which point is closer to our Point.
        double dAB = HueColorConverter.GetDistanceBetweenTwoPoints(xyPoint, pAB);
        double dAC = HueColorConverter.GetDistanceBetweenTwoPoints(xyPoint, pAC);
        double dBC = HueColorConverter.GetDistanceBetweenTwoPoints(xyPoint, pBC);

        double lowest = dAB;
        CGPoint closestPoint = pAB;

        if (dAC < lowest)
        {
          lowest = dAC;
          closestPoint = pAC;
        }
        if (dBC < lowest)
        {
          lowest = dBC;
          closestPoint = pBC;
        }

        //Change the xy value to a value which is within the reach of the lamp.
        cx = closestPoint.x;
        cy = closestPoint.y;
      }

      return new CGPoint(cx, cy);
    }

    /// <summary>
    ///  Method to see if the given XY value is within the reach of the lamps.
    /// </summary>
    /// <param name="p">p the point containing the X,Y value</param>
    /// <returns>true if within reach, false otherwise.</returns>
    private static bool CheckPointInLampsReach(CGPoint p)
    {
      CGPoint v1 = new CGPoint(Lime.x - Red.x, Lime.y - Red.y);
      CGPoint v2 = new CGPoint(Blue.x - Red.x, Blue.y - Red.y);

      CGPoint q = new CGPoint(p.x - Red.x, p.y - Red.y);

      double s = HueColorConverter.CrossProduct(q, v2) / HueColorConverter.CrossProduct(v1, v2);
      double t = HueColorConverter.CrossProduct(v1, q) / HueColorConverter.CrossProduct(v1, v2);

      if ((s >= 0.0f) && (t >= 0.0f) && (s + t <= 1.0f))
      {
        return true;
      }
      else
      {
        return false;
      }
    }

    /// <summary>
    /// Calculates crossProduct of two 2D vectors / points.
    /// </summary>
    /// <param name="p1"> p1 first point used as vector</param>
    /// <param name="p2">p2 second point used as vector</param>
    /// <returns>crossProduct of vectors</returns>
    //private static double CrossProduct(CGPoint p1, CGPoint p2)
    //{
    //  return (p1.x * p2.y - p1.y * p2.x);
    //}

    /// <summary>
    /// Find the closest point on a line.
    /// This point will be within reach of the lamp.
    /// </summary>
    /// <param name="A">A the point where the line starts</param>
    /// <param name="B">B the point where the line ends</param>
    /// <param name="P">P the point which is close to a line.</param>
    /// <returns> the point which is on the line.</returns>
    private static CGPoint GetClosestPointToPoint(CGPoint A, CGPoint B, CGPoint P)
    {
      CGPoint AP = new CGPoint(P.x - A.x, P.y - A.y);
      CGPoint AB = new CGPoint(B.x - A.x, B.y - A.y);
      double ab2 = AB.x * AB.x + AB.y * AB.y;
      double ap_ab = AP.x * AB.x + AP.y * AB.y;

      double t = ap_ab / ab2;

      if (t < 0.0f)
        t = 0.0f;
      else if (t > 1.0f)
        t = 1.0f;

      CGPoint newPoint = new CGPoint(A.x + AB.x * t, A.y + AB.y * t);
      return newPoint;
    }

    /// <summary>
    /// Find the distance between two points.
    /// </summary>
    /// <param name="one"></param>
    /// <param name="two"></param>
    /// <returns>the distance between point one and two</returns>
    //private static double GetDistanceBetweenTwoPoints(CGPoint one, CGPoint two)
    //{
    //  double dx = one.x - two.x; // horizontal difference
    //  double dy = one.y - two.y; // vertical difference
    //  double dist = Math.Sqrt(dx * dx + dy * dy);

    //  return dist;
    //}

    /// <summary>
    /// Returns hexvalue from Light State
    /// </summary>
    /// <param name="state"></param>
    /// <returns></returns>
    public static string HexFromState(State state)
    {
      if (state == null)
        throw new ArgumentNullException(nameof(state));
      if (state.On == false || state.Brightness <= 5) //Off or low brightness
        return "000000";
      if (state.ColorCoordinates != null && state.ColorCoordinates.Length == 2) //Based on XY value
        return HexFromXy(state.ColorCoordinates[0], state.ColorCoordinates[1]);

      return "FFFFFF"; //White
    }

    /// <summary>
    /// Get the HEX color from an XY value
    /// </summary>
    /// <param name="xNumber"></param>
    /// <param name="yNumber"></param>
    /// <returns></returns>
    private static string HexFromXy(double xNumber, double yNumber)
    {
      if (xNumber == 0 && yNumber == 0)
      {
        return "ffffff";
      }

      int closestValue = Int32.MaxValue;
      int closestX = 0, closestY = 0;

      double fX = xNumber;
      double fY = yNumber;

      int intX = (int)(fX * factor);
      int intY = (int)(fY * factor);

      for (int y = 0; y < maxY; y++)
      {
        for (int x = 0; x < maxX; x++)
        {
          int differenceForPixel = 0;
          differenceForPixel += Math.Abs(xArray[x, y] - intX);
          differenceForPixel += Math.Abs(yArray[x, y] - intY);

          if (differenceForPixel < closestValue)
          {
            closestX = x;
            closestY = y;
            closestValue = differenceForPixel;
          }
        }
      }

      int color = cArray[closestX, closestY];
      int red = (color >> 16) & 0xFF;
      int green = (color >> 8) & 0xFF;
      int blue = color & 0xFF;

      return string.Format("{0}{1}{2}", red.ToString("X2"), green.ToString("X2"), blue.ToString("X2"));
    }

    /*****************************************************************************************
    The code below is based on http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
    Converted to C# by Niels Laute
    *****************************************************************************************/

    public static CGPoint CalculateXY(RGBColor color, string model)
    {
      //CGColorRef cgColor = [color CGColor];

      //const CGFloat* components = CGColorGetComponents(cgColor);
      //long numberOfComponents = CGColorGetNumberOfComponents(cgColor);

      // Default to white
      double red = 1.0f;
      double green = 1.0f;
      double blue = 1.0f;

      //if (numberOfComponents == 4)
      //{
      // Full color
      red = color.R;
      green = color.G;
      blue = color.B;
      //}
      //else if (numberOfComponents == 2)
      //{
      //    // Greyscale color
      //    red = green = blue = color.A;
      //}

      // Apply gamma correction
      double r;
      double g;
      double b;

      if (red > 0.04045f)
      {
        r = (float)Math.Pow((red + 0.055f) / (1.0f + 0.055f), 2.4f);
      }
      else
      {
        r = red / 12.92f;
      }

      if (green > 0.04045f)
      {
        g = (float)Math.Pow((green + 0.055f) / (1.0f + 0.055f), 2.4f);
      }
      else
      {
        g = green / 12.92f;
      }

      if (blue > 0.04045f)
      {
        b = (float)Math.Pow((blue + 0.055f) / (1.0f + 0.055f), 2.4f);
      }
      else
      {
        b = blue / 12.92f;
      }

      // Wide gamut conversion D65
      double X = r * 0.664511f + g * 0.154324f + b * 0.162028f;
      double Y = r * 0.283881f + g * 0.668433f + b * 0.047685f;
      double Z = r * 0.000088f + g * 0.072310f + b * 0.986039f;

      double cx = 0.0f;

      if ((X + Y + Z) != 0)
        cx = X / (X + Y + Z);

      double cy = 0.0f;
      if ((X + Y + Z) != 0)
        cy = Y / (X + Y + Z);

      //Check if the given XY value is within the colourreach of our lamps.

      CGPoint xyPoint = new CGPoint(cx, cy);
      List<CGPoint> colorPoints = ColorPointsForModel(model);
      bool inReachOfLamps = CheckPointInLampsReach(xyPoint, colorPoints);

      if (!inReachOfLamps)
      {
        //It seems the colour is out of reach
        //let's find the closest colour we can produce with our lamp and send this XY value out.

        //Find the closest point on each line in the triangle.
        CGPoint pAB = GetClosestPointToPoints(colorPoints[0], colorPoints[1], xyPoint);
        CGPoint pAC = GetClosestPointToPoints(colorPoints[2], colorPoints[0], xyPoint);
        CGPoint pBC = GetClosestPointToPoints(colorPoints[1], colorPoints[2], xyPoint);

        //Get the distances per point and see which point is closer to our Point.
        float dAB = GetDistanceBetweenTwoPoints(xyPoint, pAB);
        float dAC = GetDistanceBetweenTwoPoints(xyPoint, pAC);
        float dBC = GetDistanceBetweenTwoPoints(xyPoint, pBC);

        float lowest = dAB;
        CGPoint closestPoint = pAB;

        if (dAC < lowest)
        {
          lowest = dAC;
          closestPoint = pAC;
        }
        if (dBC < lowest)
        {
          lowest = dBC;
          closestPoint = pBC;
        }

        //Change the xy value to a value which is within the reach of the lamp.
        cx = (float)closestPoint.x;
        cy = (float)closestPoint.y;
      }

      return new CGPoint(cx, cy);
    }

    private static List<CGPoint> ColorPointsForModel(string ModelID)
    {
      List<CGPoint> colorPoints = new List<CGPoint>();
      List<string> hueBulbs = new List<string>() {
        "LCT001" /* Hue A19 */,
           "LCT002" /* Hue BR30 */,
                           "LCT003" /* Hue GU10 */

    };

      List<string> livingColors = new List<string>() {
                "LLC001" /* Monet, Renoir, Mondriaan (gen II) */,
                             "LLC005" /* Bloom (gen II) */,
                             "LLC006" /* Iris (gen III) */,
                             "LLC007" /* Bloom, Aura (gen III) */,
                             "LLC011" /* Hue Bloom */,
                             "LLC012" /* Hue Bloom */,
                             "LLC013" /* Storylight */,
                             "LST001" /* Light Strips */ };

      if (hueBulbs.Contains(ModelID))
      {
        // Hue bulbs color gamut triangle
        colorPoints.Add(new CGPoint(0.674F, 0.322F)); // Red
        colorPoints.Add(new CGPoint(0.408F, 0.517F)); // Green
        colorPoints.Add(new CGPoint(0.168F, 0.041F)); // Blue
      }
      else if (livingColors.Contains(ModelID))
      {
        // LivingColors color gamut triangle
        colorPoints.Add(new CGPoint(0.703F, 0.296F)); // Red
        colorPoints.Add(new CGPoint(0.214F, 0.709F)); // Green
        colorPoints.Add(new CGPoint(0.139F, 0.081F)); // Blue
      }
      else
      {
        // Default construct triangle wich contains all values
        colorPoints.Add(new CGPoint(1.0F, 0.0F)); // Red
        colorPoints.Add(new CGPoint(0.0F, 1.0F)); // Green
        colorPoints.Add(new CGPoint(0.0F, 0.0F)); // Blue
      }

      return colorPoints;
    }

    private static CGPoint GetClosestPointToPoints(CGPoint A, CGPoint B, CGPoint P)
    {
      CGPoint AP = new CGPoint(P.x - A.x, P.y - A.y);
      CGPoint AB = new CGPoint(B.x - A.x, B.y - A.y);
      float ab2 = (float)(AB.x * AB.x + AB.y * AB.y);
      float ap_ab = (float)(AP.x * AB.x + AP.y * AB.y);

      float t = ap_ab / ab2;

      if (t < 0.0f)
      {
        t = 0.0f;
      }
      else if (t > 1.0f)
      {
        t = 1.0f;
      }

      return new CGPoint(A.x + AB.x * t, A.y + AB.y * t);
    }

    private static float GetDistanceBetweenTwoPoints(CGPoint one, CGPoint two)
    {
      float dx = (float)(one.x - two.x); // horizontal difference
      float dy = (float)(one.y - two.y); // vertical difference
      return (float)Math.Sqrt(dx * dx + dy * dy);
    }

    private static bool CheckPointInLampsReach(CGPoint p, List<CGPoint> colorPoints)
    {
      CGPoint red = colorPoints[0];
      CGPoint green = colorPoints[1];
      CGPoint blue = colorPoints[2];

      CGPoint v1 = new CGPoint(green.x - red.x, green.y - red.y);
      CGPoint v2 = new CGPoint(blue.x - red.x, blue.y - red.y);

      CGPoint q = new CGPoint(p.x - red.x, p.y - red.y);

      float s = CrossProduct(q, v2) / CrossProduct(v1, v2);
      float t = CrossProduct(v1, q) / CrossProduct(v1, v2);

      if ((s >= 0.0f) && (t >= 0.0f) && (s + t <= 1.0f))
      {
        return true;
      }
      else
      {
        return false;
      }
    }

    private static float CrossProduct(CGPoint p1, CGPoint p2)
    {
      return (float)(p1.x * p2.y - p1.y * p2.x);
    }

    /// <summary>
    /// Returns hexvalue from Light State
    /// </summary>
    /// <param name="state"></param>
    /// <returns></returns>
    public static string HexColorFromState(State state, string model)
    {
      if (state == null)
        throw new ArgumentNullException(nameof(state));
      if (state.On == false || state.Brightness <= 1) //Off or low brightness
        return "000000";
      if (state.ColorCoordinates != null && state.ColorCoordinates.Length == 2) //Based on XY value
      {
        RGBColor color = ColorFromXY(new CGPoint(state.ColorCoordinates[0], state.ColorCoordinates[1]), model);

        //Brightness of state (0.0-1.0)
        double b = Convert.ToDouble(state.Brightness) / 255;
        //color with brightness
        RGBColor colorWithB = new RGBColor(color.R * b, color.G * b, color.B * b);
        return colorWithB.ToHex();
      }

      return "FFFFFF"; //White
    }

    /// <summary>
    /// Returns hexvalue from Light State
    /// </summary>
    /// <param name="state"></param>
    /// <returns></returns>
    public static RGBColor RGBColorFromState(State state, string model)
    {
      if (state == null)
        throw new ArgumentNullException(nameof(state));
      //if (state.On == false || state.Brightness <= 5) //Off or low brightness
      //  return new RGBColor("000000");
      if (state.ColorCoordinates != null && state.ColorCoordinates.Length == 2) //Based on XY value
      {
        return ColorFromXY(new CGPoint(state.ColorCoordinates[0], state.ColorCoordinates[1]), model);
      }
      return new RGBColor("FFFFFF"); //White
    }

    private static RGBColor ColorFromXY(CGPoint xy, string model)
    {
      List<CGPoint> colorPoints = ColorPointsForModel(model);
      bool inReachOfLamps = CheckPointInLampsReach(xy, colorPoints);

      if (!inReachOfLamps)
      {
        //It seems the colour is out of reach
        //let's find the closest colour we can produce with our lamp and send this XY value out.

        //Find the closest point on each line in the triangle.
        CGPoint pAB = GetClosestPointToPoints(colorPoints[0], colorPoints[1], xy);
        CGPoint pAC = GetClosestPointToPoints(colorPoints[2], colorPoints[0], xy);
        CGPoint pBC = GetClosestPointToPoints(colorPoints[1], colorPoints[2], xy);

        //Get the distances per point and see which point is closer to our Point.
        float dAB = GetDistanceBetweenTwoPoints(xy, pAB);
        float dAC = GetDistanceBetweenTwoPoints(xy, pAC);
        float dBC = GetDistanceBetweenTwoPoints(xy, pBC);

        float lowest = dAB;
        CGPoint closestPoint = pAB;

        if (dAC < lowest)
        {
          lowest = dAC;
          closestPoint = pAC;
        }
        if (dBC < lowest)
        {
          lowest = dBC;
          closestPoint = pBC;
        }

        //Change the xy value to a value which is within the reach of the lamp.
        xy.x = closestPoint.x;
        xy.y = closestPoint.y;
      }

      float x = (float)xy.x;
      float y = (float)xy.y;
      float z = 1.0f - x - y;

      float Y = 1.0f;
      float X = (Y / y) * x;
      float Z = (Y / y) * z;

      // sRGB D65 conversion
      float r = X * 1.656492f - Y * 0.354851f - Z * 0.255038f;
      float g = -X * 0.707196f + Y * 1.655397f + Z * 0.036152f;
      float b = X * 0.051713f - Y * 0.121364f + Z * 1.011530f;

      if (r > b && r > g && r > 1.0f)
      {
        // red is too big
        g = g / r;
        b = b / r;
        r = 1.0f;
      }
      else if (g > b && g > r && g > 1.0f)
      {
        // green is too big
        r = r / g;
        b = b / g;
        g = 1.0f;
      }
      else if (b > r && b > g && b > 1.0f)
      {
        // blue is too big
        r = r / b;
        g = g / b;
        b = 1.0f;
      }

      // Apply gamma correction
      if (r <= 0.0031308f)
      {
        r = 12.92f * r;
      }
      else
      {
        r = (1.0f + 0.055f) * (float)Math.Pow(r, (1.0f / 2.4f)) - 0.055f;
      }

      if (g <= 0.0031308f)
      {
        g = 12.92f * g;
      }
      else
      {
        g = (1.0f + 0.055f) * (float)Math.Pow(g, (1.0f / 2.4f)) - 0.055f;
      }

      if (b <= 0.0031308f)
      {
        b = 12.92f * b;
      }
      else
      {
        b = (1.0f + 0.055f) * (float)Math.Pow(b, (1.0f / 2.4f)) - 0.055f;
      }

      if (r > b && r > g)
      {
        // red is biggest
        if (r > 1.0f)
        {
          g = g / r;
          b = b / r;
          r = 1.0f;
        }
      }
      else if (g > b && g > r)
      {
        // green is biggest
        if (g > 1.0f)
        {
          r = r / g;
          b = b / g;
          g = 1.0f;
        }
      }
      else if (b > r && b > g)
      {
        // blue is biggest
        if (b > 1.0f)
        {
          r = r / b;
          g = g / b;
          b = 1.0f;
        }
      }

      return new RGBColor(r, g, b);
    }
  }
}


text:
"""
This test compares the NEON GRU layer against a numpy reference GRU
implementation and compares the NEON GRU bprop deltas to the gradients
estimated by finite differences.
The numpy reference GRU contains static methods for forward pass
and backward pass.
It runs a SINGLE layer of GRU and compare numerical values

The following are made sure to be the same in both GRUs
    -   initial h values (all zeros)
    -   initial W, b (ones or random values)
    -   input data (random data matrix)
    -   input error (random data matrix)
    -   the data shape inside GRU_ref is seq_len, 1, input_size.
        Need transpose
    -   the data shape inside GRU (neon) is is batch_size, seq_len * batch_size

"""
import itertools as itt
import numpy as np

from neon import NervanaObject
from neon.initializers.initializer import Constant, Gaussian
from neon.layers import GRU
from neon.transforms import Logistic, Tanh
from tests.gru_ref import GRU as RefGRU
from tests.utils import allclose_with_out

def pytest_generate_tests(metafunc):
    bsz_rng = [1]

    if 'refgruargs' in metafunc.fixturenames:
        fargs = []
        if metafunc.config.option.all:
            seq_rng = [2, 3, 4]
            inp_rng = [3, 5, 10]
            out_rng = [3, 5, 10]
        else:
            seq_rng = [3]
            inp_rng = [5]
            out_rng = [10]
        fargs = itt.product(seq_rng, inp_rng, out_rng, bsz_rng)
        metafunc.parametrize('refgruargs', fargs)

    if 'gradgruargs' in metafunc.fixturenames:
        fargs = []
        if metafunc.config.option.all:
            seq_rng = [2, 3]
            inp_rng = [5, 10]
            out_rng = [3, 5, 10]
        else:
            seq_rng = [3]
            inp_rng = [5]
            out_rng = [10]
        fargs = itt.product(seq_rng, inp_rng, out_rng, bsz_rng)
        metafunc.parametrize('gradgruargs', fargs)

def test_ref_compare_ones(backend_default, refgruargs):
    # run comparison with reference code
    # for all ones init
    seq_len, input_size, hidden_size, batch_size = refgruargs
    NervanaObject.be.bsz = NervanaObject.be.batch_size = batch_size

    check_gru(seq_len, input_size, hidden_size,
              batch_size, Constant(val=1.0), [1.0, 0.0])

def test_ref_compare_rand(backend_default, refgruargs):
    # run comparison with reference code
    # for all ones init
    seq_len, input_size, hidden_size, batch_size = refgruargs
    NervanaObject.be.bsz = NervanaObject.be.batch_size = batch_size

    check_gru(seq_len, input_size, hidden_size, batch_size,
              Gaussian())

# compare neon GRU to reference GRU implementstion
def check_gru(seq_len, input_size, hidden_size,
              batch_size, init_func, inp_moms=[0.0, 1.0]):
    # init_func is the initializer for the model params
    # inp_moms is the [ mean, std dev] of the random input
    input_shape = (input_size, seq_len * batch_size)
    output_shape = (hidden_size, seq_len * batch_size)
    NervanaObject.be.bsz = NervanaObject.be.batch_size = batch_size

    # neon GRU
    gru = GRU(hidden_size,
              init_func,
              activation=Tanh(),
              gate_activation=Logistic())

    # generate random input tensor
    inp = np.random.rand(*input_shape)*inp_moms[1] + inp_moms[0]
    inpa = gru.be.array(inp)
    # generate random deltas tensor
    deltas = np.random.randn(*output_shape)

    # run neon fprop
    gru.configure((input_size, seq_len))
    gru.prev_layer = True
    gru.allocate()
    gru.set_deltas([gru.be.iobuf(gru.in_shape)])
    gru.fprop(inpa)

    # reference numpy GRU
    gru_ref = RefGRU(input_size, hidden_size)
    WGRU = gru_ref.weights

    # make ref weights and biases the same with neon model
    r_range = range(hidden_size)
    z_range = range(hidden_size, hidden_size * 2)
    c_range = range(hidden_size * 2, hidden_size * 3)

    WGRU[gru_ref.weights_ind_br][:] = gru.b.get()[r_range]
    WGRU[gru_ref.weights_ind_bz][:] = gru.b.get()[z_range]
    WGRU[gru_ref.weights_ind_bc][:] = gru.b.get()[c_range]

    WGRU[gru_ref.weights_ind_Wxr][:] = gru.W_input.get()[r_range]
    WGRU[gru_ref.weights_ind_Wxz][:] = gru.W_input.get()[z_range]
    WGRU[gru_ref.weights_ind_Wxc][:] = gru.W_input.get()[c_range]

    WGRU[gru_ref.weights_ind_Rhr][:] = gru.W_recur.get()[r_range]
    WGRU[gru_ref.weights_ind_Rhz][:] = gru.W_recur.get()[z_range]
    WGRU[gru_ref.weights_ind_Rhc][:] = gru.W_recur.get()[c_range]

    # transpose input X and do fprop
    # the reference code expects these shapes:
    # input_shape: (seq_len, input_size, batch_size)
    # output_shape: (seq_len, hidden_size, batch_size)
    inp_ref = inp.copy().T.reshape(
        seq_len, batch_size, input_size).swapaxes(1, 2)
    deltas_ref = deltas.copy().T.reshape(
        seq_len, batch_size, hidden_size).swapaxes(1, 2)

    (dWGRU_ref, h_ref_list, dh_ref_list,
        dr_ref_list, dz_ref_list, dc_ref_list) = gru_ref.lossFun(inp_ref,
                                                                 deltas_ref)

    print '====Verifying hidden states===='
    print allclose_with_out(gru.outputs.get(),
                            h_ref_list,
                            rtol=0.0,
                            atol=1.0e-5)

    print 'fprop is verified'

    # now test the bprop
    print 'Making sure neon GRU match numpy GRU in bprop'
    gru.bprop(gru.be.array(deltas))
    # grab the delta W from gradient buffer
    dWinput_neon = gru.dW_input.get()
    dWrecur_neon = gru.dW_recur.get()
    db_neon = gru.db.get()
    dWxr_neon = dWinput_neon[r_range]
    dWxz_neon = dWinput_neon[z_range]
    dWxc_neon = dWinput_neon[c_range]
    dWrr_neon = dWrecur_neon[r_range]
    dWrz_neon = dWrecur_neon[z_range]
    dWrc_neon = dWrecur_neon[c_range]
    dbr_neon = db_neon[r_range]
    dbz_neon = db_neon[z_range]
    dbc_neon = db_neon[c_range]

    drzc_neon = gru.rzhcan_delta_buffer.get()
    dr_neon = drzc_neon[r_range]
    dz_neon = drzc_neon[z_range]
    dc_neon = drzc_neon[c_range]

    dWxr_ref = dWGRU_ref[gru_ref.dW_ind_Wxr]
    dWxz_ref = dWGRU_ref[gru_ref.dW_ind_Wxz]
    dWxc_ref = dWGRU_ref[gru_ref.dW_ind_Wxc]
    dWrr_ref = dWGRU_ref[gru_ref.dW_ind_Rhr]
    dWrz_ref = dWGRU_ref[gru_ref.dW_ind_Rhz]
    dWrc_ref = dWGRU_ref[gru_ref.dW_ind_Rhc]
    dbr_ref = dWGRU_ref[gru_ref.dW_ind_br]
    dbz_ref = dWGRU_ref[gru_ref.dW_ind_bz]
    dbc_ref = dWGRU_ref[gru_ref.dW_ind_bc]

    # print '====Verifying hidden deltas ===='
    print '====Verifying r deltas ===='
    assert allclose_with_out(dr_neon,
                             dr_ref_list,
                             rtol=0.0,
                             atol=1.0e-5)

    print '====Verifying z deltas ===='
    assert allclose_with_out(dz_neon,
                             dz_ref_list,
                             rtol=0.0,
                             atol=1.0e-5)

    print '====Verifying hcan deltas ===='
    assert allclose_with_out(dc_neon,
                             dc_ref_list,
                             rtol=0.0,
                             atol=1.0e-5)

    print '====Verifying update on W_input===='
    print 'dWxr'
    assert allclose_with_out(dWxr_neon,
                             dWxr_ref,
                             rtol=0.0,
                             atol=1.0e-5)
    print 'dWxz'
    assert allclose_with_out(dWxz_neon,
                             dWxz_ref,
                             rtol=0.0,
                             atol=1.0e-5)
    print 'dWxc'
    assert allclose_with_out(dWxc_neon,
                             dWxc_ref,
                             rtol=0.0,
                             atol=1.0e-5)

    print '====Verifying update on W_recur===='

    print 'dWrr'
    assert allclose_with_out(dWrr_neon,
                             dWrr_ref,
                             rtol=0.0,
                             atol=1.0e-5)
    print 'dWrz'
    assert allclose_with_out(dWrz_neon,
                             dWrz_ref,
                             rtol=0.0,
                             atol=1.0e-5)
    print 'dWrc'
    assert allclose_with_out(dWrc_neon,
                             dWrc_ref,
                             rtol=0.0,
                             atol=1.0e-5)

    print '====Verifying update on bias===='
    print 'dbr'
    assert allclose_with_out(dbr_neon,
                             dbr_ref,
                             rtol=0.0,
                             atol=1.0e-5)
    print 'dbz'
    assert allclose_with_out(dbz_neon,
                             dbz_ref,
                             rtol=0.0,
                             atol=1.0e-5)
    print 'dbc'
    assert allclose_with_out(dbc_neon,
                             dbc_ref,
                             rtol=0.0,
                             atol=1.0e-5)

    print 'bprop is verified'

    return

def reset_gru(gru):
    # in order to run fprop multiple times
    # for the gradient check tests the
    # gru internal variables need to be
    # cleared
    gru.x = None
    gru.xs = None  # just in case
    gru.outputs = None
    return

def test_gradient_neon_gru(backend_default, gradgruargs):
    seq_len, input_size, hidden_size, batch_size = gradgruargs
    NervanaObject.be.bsz = NervanaObject.be.batch_size = batch_size
    gradient_check(seq_len, input_size, hidden_size, batch_size)

def gradient_check(seq_len, input_size, hidden_size, batch_size,
                   threshold=1.0e-3):
    # 'threshold' is the max fractional difference
    #             between gradient estimate and
    #             bprop deltas (def is 5%)
    # for a given set of layer parameters calculate
    # the gradients and compare to the derivatives
    # obtained with the bprop function.  repeat this
    # for a range of perturbations and use the
    # perturbation size with the best results.
    # This is necessary for 32 bit computations

    min_max_err = -1.0  # minimum max error
    print 'Perturb mag, max grad diff'
    for pert_exp in range(-5, 0):
        # need to generate the scaling and input outside
        # having an issue with the random number generator
        # when these are generated inside the gradient_calc
        # function
        input_shape = (input_size, seq_len * batch_size)
        output_shape = (hidden_size, seq_len * batch_size)

        rand_scale = np.random.random(output_shape)*2.0 - 1.0
        inp = np.random.randn(*input_shape)

        pert_mag = 10.0**pert_exp
        (grad_est, deltas) = gradient_calc(seq_len,
                                           input_size,
                                           hidden_size,
                                           batch_size,
                                           epsilon=pert_mag,
                                           rand_scale=rand_scale,
                                           inp_bl=inp)
        dd = np.max(np.abs(grad_est-deltas))
        print '%e, %e' % (pert_mag, dd)
        if min_max_err < 0.0 or dd < min_max_err:
            min_max_err = dd
        # reset the seed so models are same in each run
        # allclose_with_out(grad_est,deltas, rtol=0.0, atol=0.0)
        NervanaObject.be.rng_reset()

    # check that best value of worst case error is less than threshold
    print 'Worst case error %e with perturbation %e' % (min_max_err, pert_mag)
    print 'Threshold %e' % (threshold)
    assert min_max_err < threshold

def gradient_calc(seq_len, input_size, hidden_size, batch_size,
                  epsilon=None, rand_scale=None, inp_bl=None):
    NervanaObject.be.bsz = NervanaObject.be.batch_size = batch_size

    input_shape = (input_size, seq_len * batch_size)

    # generate input if one is not given
    if inp_bl is None:
        inp_bl = np.random.randn(*input_shape)

    # neon gru instance
    gru = GRU(hidden_size, init=Gaussian(), activation=Tanh(), gate_activation=Logistic())
    inpa = gru.be.array(np.copy(inp_bl))

    # run fprop on the baseline input
    gru.configure((input_size, seq_len))
    gru.prev_layer = True
    gru.allocate()
    gru.set_deltas([gru.be.iobuf(gru.in_shape)])
    out_bl = gru.fprop(inpa).get()

    # random scaling/hash to generate fake loss
    if rand_scale is None:
        rand_scale = np.random.random(out_bl.shape) * 2.0 - 1.0
    # loss function would be:
    # loss_bl = np.sum(rand_scale * out_bl)

    # run back prop with rand_scale as the errors
    # use copy to avoid any interactions
    deltas_neon = gru.bprop(gru.be.array(np.copy(rand_scale))).get()

    # add a perturbation to each input element
    grads_est = np.zeros(inpa.shape)
    inp_pert = inp_bl.copy()
    for pert_ind in range(inpa.size):
        save_val = inp_pert.flat[pert_ind]

        inp_pert.flat[pert_ind] = save_val + epsilon
        reset_gru(gru)
        gru.allocate()
        out_pos = gru.fprop(gru.be.array(inp_pert)).get()

        inp_pert.flat[pert_ind] = save_val - epsilon
        reset_gru(gru)
        gru.allocate()
        out_neg = gru.fprop(gru.be.array(inp_pert)).get()

        # calculate the loss with perturbations
        loss_pos = np.sum(rand_scale*out_pos)
        loss_neg = np.sum(rand_scale*out_neg)
        # compute the gradient estimate
        grad = 0.5*(loss_pos-loss_neg)/epsilon

        grads_est.flat[pert_ind] = grad

        # reset the perturbed input element
        inp_pert.flat[pert_ind] = save_val

    del gru
    return (grads_est, deltas_neon)


text:
package com.junichi11.netbeans.modules.jaco.ui.actions;

import org.netbeans.api.editor.EditorActionRegistration;

/**
 *
 * @author junichi11
 */
@EditorActionRegistration(name = "jaco-katakanize")
public class JacoKatakanizeAction extends JacoBaseAction {

    private static final long serialVersionUID = 5594368988410915966L;

    public JacoKatakanizeAction() {
        super("katakanize"); // NOI18N
    }

}


text:
FROM cohorte/runtime:latest

#-----------------------------------------------------------------------------
# Cohorte Runtime image.
#
# Cohorte Platform version: 1.2.1
#-----------------------------------------------------------------------------

MAINTAINER "Bassem Debbabi" <bassem.debbabi@cohorte-technologies.com>

ENV REFRESHED_AT 20170707_1130

# Installation commands

ENV COHORTE_BASE /opt/node
ENV COHORTE_DATA /opt/data

RUN mkdir -p $COHORTE_BASE
RUN mkdir -p $COHORTE_DATA
COPY ./install/run_service /opt
COPY ./install/boot.sh /opt
COPY ./install/cohorte.service ./etc/systemd/system/cohorte.service
COPY ./install/init_* /opt/

RUN chmod +x /opt/init*.sh

# install simpleeval and jsoncomment
RUN pip3 install jsoncomment simpleeval
RUN apt-get install -y psmisc

RUN chmod +x /opt/boot.sh

RUN systemctl disable getty@tty1.service
RUN systemctl disable getty@tty2.service
RUN systemctl disable getty@tty3.service
RUN systemctl disable getty@tty4.service
RUN systemctl disable getty@tty5.service
RUN systemctl disable getty@tty6.service

RUN systemctl enable cohorte.service

ENTRYPOINT ["/opt/boot.sh"]

RUN ls -l /opt

VOLUME [ "/opt/node" ]

EXPOSE 9000 9001 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Purdue.OnlineClassScheduler.BAL.BusinessEntities
{
    public class Schedule
    {
        //Default constructor
        public Schedule()
        {
        }

        public Schedule(int scheduleTypeId, string scheduleType)
        {
            // TODO: Complete member initialization
            this.scheduleTypeId = scheduleTypeId;
            this.scheduleType = scheduleType;
        }

        private int scheduleTypeId;

        public int ScheduleTypeId
        {
            get { return scheduleTypeId; }
            set { scheduleTypeId = value; }
        }
        private string scheduleType;

        public string ScheduleType
        {
            get { return scheduleType; }
            set { scheduleType = value; }
        }

    }
}


text:
package jp.gr.java_conf.ange.mastodon.api;

import android.support.annotation.NonNull;

import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Streaming;
import rx.Observable;

/**
 * Mastodon API Streaming Timeline.
 */
public interface StreamingService {
    @Streaming
    @GET("/api/v1/streaming/home")
    Observable<ResponseBody> home(@NonNull @Header("Authorization") String authorization);

    @Streaming
    @GET("/api/v1/streaming/public")
    Observable<ResponseBody> pub(@NonNull @Header("Authorization") String authorization);

    @Streaming
    @GET("/api/v1/streaming/tags")
    Observable<ResponseBody> tags(@NonNull @Header("Authorization") String authorization);

}


text:
package sample;

import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@XmlRootElement
@Table(name = "MY_ENTITY")
public class MyEntity {

    @Id
    @Column(name = "ME_ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ME_TABLE_SEQ")
    @SequenceGenerator(name = "ME_TABLE_SEQ", sequenceName = "ME_TABLE_SEQ", allocationSize = 1)
    private Long id;

    @Column(name = "ME_NAME", length = 200)
    private String name;

    public MyEntity() {
    }

    public MyEntity(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "{" + id + ", " + name + '}';
    }
}


text:
#include <base/cpuinfo.h>
#include <db/db.h>
#include <cmn/agent_cmn.h>
#include <oper/interface_common.h>
#include <oper/interface.h>

#include "vr_genetlink.h"
#include "nl_util.h"

#include <uve/agent_uve_base.h>
#include <uve/vn_uve_table_base.h>
#include <uve/stats_interval_types.h>
#include <init/agent_param.h>
#include <oper/mirror_table.h>
#include <uve/vrouter_stats_collector.h>

using process::ConnectionInfo;
using process::ProcessState;
using process::ConnectionStatus;
using process::ConnectionState;
using process::ConnectionStateManager;
using process::g_process_info_constants;

AgentUveBase *AgentUveBase::singleton_;

AgentUveBase::AgentUveBase(Agent *agent, uint64_t intvl)
    : vn_uve_table_(new VnUveTableBase(agent)),
      vm_uve_table_(new VmUveTableBase(agent)),
      vrouter_uve_entry_(new VrouterUveEntryBase(agent)),
      prouter_uve_table_(new ProuterUveTable(agent)),
      agent_(agent), bandwidth_intvl_(intvl),
      vrouter_stats_collector_(new VrouterStatsCollector(
                                   *(agent->event_manager()->io_service()),
                                   this)) {
    singleton_ = this;
}

AgentUveBase::~AgentUveBase() {
}

void AgentUveBase::Shutdown() {
    vn_uve_table_.get()->Shutdown();
    vm_uve_table_.get()->Shutdown();
    vrouter_uve_entry_.get()->Shutdown();
    prouter_uve_table_.get()->Shutdown();
    connection_state_manager_->Shutdown();
    vrouter_stats_collector_->Shutdown();
}

void AgentUveBase::Init() {
    std::string module_id(agent_->discovery_client_name());
    std::string instance_id(agent_->instance_id());
    EventManager *evm = agent_->event_manager();
    boost::asio::io_service &io = *evm->io_service();

    CpuLoadData::Init();
    connection_state_manager_ =
        ConnectionStateManager<NodeStatusUVE, NodeStatus>::
            GetInstance();
    agent_->set_connection_state(ConnectionState::GetInstance());
    connection_state_manager_->Init(io, agent_->agent_name(),
            module_id, instance_id,
            boost::bind(&AgentUveBase::VrouterAgentProcessState,
                        this, _1, _2, _3));
}

uint8_t AgentUveBase::ExpectedConnections(uint8_t &num_control_nodes,
                                          uint8_t &num_dns_servers) {
    uint8_t count = 0;
    AgentParam *cfg = agent_->params();

    /* If Discovery server is configured, increment the count by 1 for each
     * possible discovery service if we subscribe to that service. We subscribe
     * to a discovery service only if the service IP is not configured
     * explicitly */
    if (!agent_->discovery_server().empty()) {
        // Discovery:Collector
        if (cfg->collector_server_list().size() == 0) {
            count++;
        }
        // Discovery:dns-server
        if (!cfg->dns_server_1().to_ulong() &&
            !cfg->dns_server_2().to_ulong()) {
            count++;
        }
        // Discovery:xmpp-server
        if (!cfg->xmpp_server_1().to_ulong() &&
            !cfg->xmpp_server_2().to_ulong() ) {
            count++;
        }
    }
    for (int i = 0; i < MAX_XMPP_SERVERS; i++) {
        if (!agent_->controller_ifmap_xmpp_server(i).empty()) {
            num_control_nodes++;
            count++;
        }
        if (agent_->services() && !agent_->dns_server(i).empty()) {
            num_dns_servers++;
            count++;
        }
    }
    //Increment 1 for collector service
    if (!agent_->discovery_server().empty() ||
        cfg->collector_server_list().size() != 0) {
        count++;
    }
    return count;
}

void AgentUveBase::UpdateMessage(const ConnectionInfo &cinfo,
                             std::string &message) {
    if (message.empty()) {
        message = cinfo.get_type();
    } else {
        message += ", " + cinfo.get_type();
    }
    const std::string &name(cinfo.get_name());
    if (!name.empty()) {
        message += ":" + name;
    }
}

void AgentUveBase::VrouterAgentProcessState
    (const std::vector<ConnectionInfo> &cinfos,
     ProcessState::type &pstate, std::string &message) {
    size_t num_conns(cinfos.size());
    uint8_t num_control_nodes = 0, num_dns_servers = 0;
    uint8_t down_control_nodes = 0;
    uint8_t expected_conns = ExpectedConnections(num_control_nodes,
                                                 num_dns_servers);
    std::string cup(g_process_info_constants.ConnectionStatusNames.
        find(ConnectionStatus::UP)->second);
    bool is_cup = true;
    // Iterate to determine process connectivity status
    for (std::vector<ConnectionInfo>::const_iterator it = cinfos.begin();
         it != cinfos.end(); it++) {
        const ConnectionInfo &cinfo(*it);
        const std::string &conn_status(cinfo.get_status());
        if (conn_status != cup) {
            if (cinfo.get_name().compare(0, 13,
                agent_->xmpp_control_node_prefix()) == 0) {
                down_control_nodes++;
                is_cup = false;
                UpdateMessage(cinfo, message);
                continue;
            } else if (cinfo.get_name().compare(0, 11,
                agent_->xmpp_dns_server_prefix()) == 0) {
                is_cup = false;
                UpdateMessage(cinfo, message);
                continue;
            } else {
                is_cup = false;
                UpdateMessage(cinfo, message);
                continue;
            }
        }
    }
    if ((num_control_nodes == 0) || (num_control_nodes == down_control_nodes)) {
        pstate = ProcessState::NON_FUNCTIONAL;
    } else {
        pstate = ProcessState::FUNCTIONAL;
    }
    if (num_conns != expected_conns) {
        message = "Number of connections:" + integerToString(num_conns) +
            ", Expected: " + integerToString(expected_conns);
        return;
    }
    if (!is_cup) {
        message += " connection down";
    }
    return;
}

void AgentUveBase::RegisterDBClients() {
    vn_uve_table_.get()->RegisterDBClients();
    vm_uve_table_.get()->RegisterDBClients();
    vrouter_uve_entry_.get()->RegisterDBClients();
    prouter_uve_table_.get()->RegisterDBClients();
}


text:
exports.ProcessManagerHomeView = require('./process-manager-home-view');
exports.ProcessManagerHostView = require('./process-manager-host-view');
exports.LoadBalancerView = require('./load-balancer-view');


text:
package com.example.clown.dailyzhihu.bean;

import com.google.gson.Gson;

import java.util.ArrayList;

/**
 * Created by Clown on 2016/5/14.
 */
public class DataWrapper {

    public String date;
    public ArrayList<News> stories;
    public ArrayList<News> top_stories;

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public ArrayList<News> getStories() {
        return stories;
    }

    public void setStories(ArrayList<News> stories) {
        this.stories = stories;
    }

    public ArrayList<News> getTop_stories() {
        return top_stories;
    }

    public void setTop_stories(ArrayList<News> top_stories) {
        this.top_stories = top_stories;
    }

    public static DataWrapper fromJson(String string){
        return new Gson().fromJson(string, DataWrapper.class);
    }

    public String toString(){
        return new Gson().toJson(this);
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:intelxdk="http://xdk.intel.com/ns/v1" id="xdk.intel.blank.ad.template" version="0.0.0.1">
<!--This file is generated by the Intel XDK. Do not edit this file as your edits will be lost.           -->
<!--To change the contents of this file, see the documentation on the intelxdk.config.additions.xml file.-->
<intelxdk:version value="1.0"/>
<intelxdk:cordova-cli version="5.4.1"/>
<name>FC2</name>
<description>Template to develop a Cordova mobile web app using the App Designer UI editor.</description>
<author>Intel XDK</author>
<content src="index.html"/>
<access origin="*"/>
<intelxdk:plugin intelxdk:name="StatusBar" intelxdk:value="cordova-plugin-statusbar" intelxdk:version="2.1.0" intelxdk:checksum="858cc583" intelxdk:type="file"/>
<intelxdk:plugin intelxdk:name="Device" intelxdk:value="cordova-plugin-device" intelxdk:version="1.1.1" intelxdk:checksum="927290ca" intelxdk:type="file"/>
<intelxdk:plugin intelxdk:name="Splashscreen" intelxdk:value="cordova-plugin-splashscreen" intelxdk:version="3.2.0" intelxdk:checksum="452a4659" intelxdk:type="file"/>
<preference name="windows-publisher-display-name"/>
<preference name="windows-publisher-id"/>
<preference name="windows-target-version" value="10.0"/>
<preference name="windows-phone-target-version" value="10.0"/>
<!--creationInfo:{"src":"jsapp/template-blank-cordova-ad-project/sample.zip","projectTypeName":"com.intel.xdk.projecttype.jsapp"}-->
<preference name="debuggable" value="false"/>
<platform name="ios">
    <!-- below requires the splash screen plugin -->
    <!-- docs: https://github.com/apache/cordova-plugin-splashscreen -->
    <preference name="AutoHideSplashScreen" value="false"/>
    <preference name="FadeSplashScreen" value="false"/>
    <preference name="FadeSplashScreenDuration" value="2"/>
    <preference name="ShowSplashScreenSpinner" value="false"/>

    <!-- below requires the status bar plugin -->
    <!-- docs: https://github.com/apache/cordova-plugin-statusbar -->
    <!-- see http://devgirl.org/2014/07/31/phonegap-developers-guid -->
    <preference name="StatusBarOverlaysWebView" value="false"/>
    <preference name="StatusBarBackgroundColor" value="#000000"/>
    <preference name="StatusBarStyle" value="lightcontent"/>
</platform>
<platform name="android">
    <!-- below requires the splash screen plugin -->
    <!-- docs: https://github.com/apache/cordova-plugin-splashscreen -->
    <preference name="SplashMaintainAspectRatio" value="false"/>
</platform>
<intelxdk:crosswalk xmlns:intelxdk="http://xdk.intel.com/ns/v1" xwalk-command-line="--disable-pull-to-refresh-effect"/>
<intelxdk:crosswalk xmlns:intelxdk="http://xdk.intel.com/ns/v1" xwalk-command-line="--ignore-gpu-blacklist"/></widget>