text:
[![Build Status](https://api.travis-ci.org/dc-js/dc.js.svg?branch=master)](http://travis-ci.org/dc-js/dc.js)
[![Sauce Status](https://saucelabs.com/buildstatus/sclevine)](https://saucelabs.com/u/sclevine)
[![NPM Status](https://badge.fury.io/js/dc.svg)](http://badge.fury.io/js/dc)
[![cdnjs Status](https://img.shields.io/cdnjs/v/dc?color=green)](https://cdnjs.com/libraries/dc)
[![Join the chat at https://gitter.im/dc-js/dc.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/dc-js/dc.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

dc.js
=====

Dimensional charting built to work natively with [crossfilter](http://crossfilter.github.io/crossfilter/)
rendered using [d3.js](https://d3js.org/).

**NOTE:** We are seeking new maintainers to join Deepak Kumar. See [#1868](https://github.com/dc-js/dc.js/issues/1868) for discussion.

In dc.js, each chart displays an aggregation of some
attributes through the position, size, and color of its elements, and also presents a dimension
which can be filtered. When the filter or brush changes, all other charts are updated dynamically,
using animated transitions.

Check out the [example page](http://dc-js.github.io/dc.js/)
and its [annotated source](http://dc-js.github.io/dc.js/docs/stock.html) for a quick five minute
how-to guide. The detailed [API reference is here](http://dc-js.github.io/dc.js/docs/html/)
([markdown version](https://github.com/dc-js/dc.js/blob/master/docs/api-latest.md)). For
more examples and hints please visit the [Wiki](https://github.com/dc-js/dc.js/wiki).

Support
--------------------
* [Example Site](http://dc-js.github.io/dc.js/)
* [Changelog](https://github.com/dc-js/dc.js/blob/develop/Changelog.md)
* [Frequently Asked Questions](https://github.com/dc-js/dc.js/wiki/FAQ) and [Wiki](https://github.com/dc-js/dc.js/wiki)
* [v4.0 API Reference](http://dc-js.github.io/dc.js/docs/html/) ([markdown](https://github.com/dc-js/dc.js/blob/master/docs/api-latest.md)) ([last - v3.1.9](https://github.com/dc-js/dc.js/blob/master/docs/old-api-docs/api-3.1.9.md))
* [dc.js on StackOverflow](http://stackoverflow.com/questions/tagged/dc.js) - ask questions and get help
* [User Group](https://groups.google.com/forum/?fromgroups#!forum/dc-js-user-group) ("mailing list") - discussion and longer topics
* [GitHub Issues](https://github.com/dc-js/dc.js/issues) - bug reports and feature requests

*Please direct questions and support requests to Stack Overflow or the user group. When posting to Stack Overflow, use the* `[dc.js]` *and/or* `[crossfilter]` *tags - other tags are likely to draw unwanted attention.*

Get help faster with a working example! Fork these to get started:

[blank jsFiddle](https://jsfiddle.net/gordonwoodhull/rL82bguk/1) - [example jsFiddle](https://jsfiddle.net/gordonwoodhull/5ztavmjy/2) - [blank bl.ock](https://blockbuilder.org/gordonwoodhull/f6bab3d2f5b34018548207014b4056bf) - [example bl.ock](https://blockbuilder.org/gordonwoodhull/bcf9eaa0bfc2c84373cffac06d5755e5)

## Versioning
Version 4.* is compatible with d3 versions 4 and 5. It is not compatible with IE. Use dc.js 3.* if you need IE support, or use dc.js 2.* if you need compatibility with d3 version 3.

## CDN location

```
https://unpkg.com/dc@4/dist/dc.js
https://unpkg.com/dc@4/dist/style/dc.css
```

or copy the latest links from [CDNJS](https://cdnjs.com/libraries/dc)

Install with npm
--------------------
```
npm install dc
```

Install without npm
--------------------
Download
* [d3.js](https://github.com/mbostock/d3)
* [crossfilter.js](https://github.com/crossfilter/crossfilter)
* [dc.js - stable](https://github.com/dc-js/dc.js/releases)
* [dc.js - bleeding edge (develop)](https://github.com/dc-js/dc.js)

How to build dc.js locally
---------------------------

### Prerequisite modules

Make sure the following packages are installed on your machine
* node.js
* npm

### Install dependencies
```
$ npm install
```

### Build and Test
```
$ grunt test
```

Developing dc.js
----------------

### Start the development server
```
$ grunt server
```

* Jasmine specs are hosted at http://localhost:8888/spec
* The stock example is at http://localhost:8888/web
* More examples are at http://localhost:8888/web/examples

License
--------------------

dc.js is an open source javascript library and licensed under
[Apache License v2](http://www.apache.org/licenses/LICENSE-2.0.html).


text:
namespace Microsoft.Azure.Management.ContainerRegistry.Fluent.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// An object that represents a webhook for a container registry.
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class WebhookInner : Microsoft.Azure.Management.ResourceManager.Fluent.Resource
    {
        /// <summary>
        /// Initializes a new instance of the WebhookInner class.
        /// </summary>
        public WebhookInner()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the WebhookInner class.
        /// </summary>
        /// <param name="actions">The list of actions that trigger the webhook
        /// to post notifications.</param>
        /// <param name="status">The status of the webhook at the time the
        /// operation was called. Possible values include: 'enabled',
        /// 'disabled'</param>
        /// <param name="scope">The scope of repositories where the event can
        /// be triggered. For example, 'foo:*' means events for all tags under
        /// repository 'foo'. 'foo:bar' means events for 'foo:bar' only. 'foo'
        /// is equivalent to 'foo:latest'. Empty means all events.</param>
        /// <param name="provisioningState">The provisioning state of the
        /// webhook at the time the operation was called. Possible values
        /// include: 'Creating', 'Updating', 'Deleting', 'Succeeded', 'Failed',
        /// 'Canceled'</param>
        public WebhookInner(IList<string> actions, string location = default(string), string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string status = default(string), string scope = default(string), string provisioningState = default(string))
            : base(location, id, name, type, tags)
        {
            Status = status;
            Scope = scope;
            Actions = actions;
            ProvisioningState = provisioningState;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the status of the webhook at the time the operation
        /// was called. Possible values include: 'enabled', 'disabled'
        /// </summary>
        [JsonProperty(PropertyName = "properties.status")]
        public string Status { get; set; }

        /// <summary>
        /// Gets or sets the scope of repositories where the event can be
        /// triggered. For example, 'foo:*' means events for all tags under
        /// repository 'foo'. 'foo:bar' means events for 'foo:bar' only. 'foo'
        /// is equivalent to 'foo:latest'. Empty means all events.
        /// </summary>
        [JsonProperty(PropertyName = "properties.scope")]
        public string Scope { get; set; }

        /// <summary>
        /// Gets or sets the list of actions that trigger the webhook to post
        /// notifications.
        /// </summary>
        [JsonProperty(PropertyName = "properties.actions")]
        public IList<string> Actions { get; set; }

        /// <summary>
        /// Gets the provisioning state of the webhook at the time the
        /// operation was called. Possible values include: 'Creating',
        /// 'Updating', 'Deleting', 'Succeeded', 'Failed', 'Canceled'
        /// </summary>
        [JsonProperty(PropertyName = "properties.provisioningState")]
        public string ProvisioningState { get; private set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Actions == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Actions");
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Threading.Tasks;
using NUnit.Framework;
using ZendeskApi_v2;
using ZendeskApi_v2.Models.Sections;
using ZendeskApi_v2.Requests.HelpCenter;

namespace Tests.HelpCenter
{
    [TestFixture]
    [Category("HelpCenter")]
    class SectionTests
    {
        private ZendeskApi api = new ZendeskApi(Settings.Site, Settings.Email, Settings.Password);

        [Test]
        public void CanGetSections()
        {
            var res = api.HelpCenter.Sections.GetSections();
            Assert.Greater(res.Count, 0);

            var res1 = api.HelpCenter.Sections.GetSectionById(res.Sections[0].Id.Value);
            Assert.AreEqual(res1.Section.Id, res.Sections[0].Id.Value);
        }

        [Test]
        public void CanCreateUpdateAndDeleteSections()
        {
            //https://csharpapi.zendesk.com/hc/en-us/categories/200382245-Category-1
            long category_id = 200382245;

            var res = api.HelpCenter.Sections.CreateSection(new Section
            {
                Name = "My Test section",
                Position = 12,
                CategoryId = category_id
            });
            Assert.Greater(res.Section.Id, 0);

            res.Section.Position = 42;
            var update = api.HelpCenter.Sections.UpdateSection(res.Section);
            Assert.That(update.Section.Position, Is.EqualTo(res.Section.Position));
            Assert.That(api.HelpCenter.Sections.DeleteSection(res.Section.Id.Value), Is.True);
        }

        [Test]
        public void CanGetSectionsAsync()
        {
            var res = api.HelpCenter.Sections.GetSectionsAsync().Result;
            Assert.Greater(res.Count, 0);

            var res1 = api.HelpCenter.Sections.GetSectionById(res.Sections[0].Id.Value);
            Assert.AreEqual(res1.Section.Id, res.Sections[0].Id.Value);
        }

        [Test]
        public async Task CanCreateUpdateAndDeleteSectionsAsync()
        {
            //https://csharpapi.zendesk.com/hc/en-us/categories/200382245-Category-1
            long category_id = 200382245;

            var res = await api.HelpCenter.Sections.CreateSectionAsync(new Section
            {
                Name = "My Test section",
                Position = 12,
                CategoryId = category_id
            });

            Assert.That(res.Section.Id, Is.GreaterThan(0));

            res.Section.Position = 42;
            var update = await api.HelpCenter.Sections.UpdateSectionAsync(res.Section);
            Assert.That(update.Section.Position, Is.EqualTo(res.Section.Position));
            Assert.That(await api.HelpCenter.Sections.DeleteSectionAsync(res.Section.Id.Value), Is.True);
        }
    }
}


text:
define([
    'preact',
    'htm',
    './Empty.styles'
], (
    preact,
    htm,
    styles
) => {
    const {Component} = preact;
    const html = htm.bind(preact.h);

    class Empty extends Component {
        renderMessage() {
            if (this.props.message) {
                return html`<span>${this.props.message}</span>`;
            }
            return this.props.children;
        }
        render() {
            return html`

                        ${this.renderMessage()}

            `;
        }
    }
    return Empty;
});


text:
<?php
defined('_JEXEC') or die('Restricted access');

class SofortLib_EditSr extends SofortLib_Abstract {

	protected $_apiVersion = '1.0';

	protected $_parameters = array();

	protected $_response = array();

	protected $_xmlRootTag = 'edit_sr';

	private $_file;

	/**
	 *
	 * Constructor for SofortLib_EditSr
	 * @param String $apikey your API-key
	 */
	public function __construct($configKey = '') {
		list($userId, $projectId, $apiKey) = explode(':', $configKey);
		$apiUrl = (getenv('sofortApiUrl') != '') ? getenv('sofortApiUrl') : 'https://api.sofort.com/api/xml';
		parent::__construct($userId, $apiKey, $apiUrl);
	}

	/**
	 *
	 * Setter for transaction
	 * @param string $transaction
	 * @param int $invoice
	 */
	public function setTransaction($transaction, $invoice = 0) {
		$this->_parameters['invoice'][$invoice]['transaction'] = $transaction;
		return $this;
	}

	/**
	 *
	 * Setter for invoice's number
	 * @param string $invoiceNumber
	 * @param int $invoice
	 */
	public function setInvoiceNumber($invoiceNumber, $invoice = 0) {
		$this->_parameters['invoice'][$invoice]['invoice_number'] = $invoiceNumber;
		return $this;
	}

	/**
	 *
	 * Setter for customer's number
	 * @param string $customerNumber
	 * @param int $invoice
	 */
	public function setCustomerNumber($customerNumber, $invoice = 0) {
		$this->_parameters['invoice'][$invoice]['customer_id'] = $customerNumber;
		return $this;
	}

	/**
	 *
	 * Setter for order's number
	 * @param string $orderNumber
	 * @param int $invoice
	 */
	public function setOrderNumber($orderNumber, $invoice = 0) {
		$this->_parameters['invoice'][$invoice]['order_id'] = $orderNumber;
		return $this;
	}

	/**
	 * set a comment for refunds
	 * just useable with api version 1.0
	 * @param string $arg
	 */
	public function setComment($comment, $invoice = 0) {
		$this->_parameters['invoice'][$invoice]['comment'] = $comment;
		return $this;
	}

	/**
	 * add one item to the cart if you want to change the invoice
	 *
	 * @param string $itemId itemId
	 * @param double $unit_price gross price of one item
	 * @param int $quantity default 1
	 */
	public function addItem($itemId, $productNumber, $productType, $title, $description, $quantity, $unitPrice, $tax, $invoice = 0) {
		$unitPrice = number_format($unitPrice, 2, '.', '');
		$tax = number_format($tax, 2, '.', '');
		$quantity = intval($quantity);
		$this->_parameters['invoice'][$invoice]['items']['item'][] = array(
			'item_id' => $itemId,
			'product_number' => $productNumber,
			'product_type' => $productType,
			'title' => $title,
			'description' => $description,
			'quantity' => $quantity,
			'unit_price' => $unitPrice,
			'tax' => $tax,
		);
	}

	/**
	 *
	 * Update the invoice's cart via passing an array
	 * @param array $cartItems
	 * @param int $invoice
	 */
	function updateCart($cartItems = array(), $invoice = 0) {
		$i = 0;

		foreach ($cartItems as $cartItem) {
			$this->_parameters['invoice'][$invoice]['items']['item'][$i]['item_id'] = $cartItem['itemId'];
			$this->_parameters['invoice'][$invoice]['items']['item'][$i]['product_number'] = $cartItem['productNumber'];
			$this->_parameters['invoice'][$invoice]['items']['item'][$i]['title'] = $cartItem['title'];
			$this->_parameters['invoice'][$invoice]['items']['item'][$i]['description'] = $cartItem['description'];
			$this->_parameters['invoice'][$invoice]['items']['item'][$i]['quantity'] = $cartItem['quantity'];
			$this->_parameters['invoice'][$invoice]['items']['item'][$i]['unit_price'] = number_format($cartItem['unitPrice'], 2, '.', '') ;
			$this->_parameters['invoice'][$invoice]['items']['item'][$i]['tax'] = $cartItem['tax'];
			$i++;
		}
	}

	/**
	 * after you you changed/confirmed an invoice you
	 * can download the new invoice-pdf with this function
	 * @return string url
	 */
	public function getInvoiceUrl() {
		return $this->_file;
	}

	/**
	 * Parse the XML (override)
	 * @see SofortLib_Abstract::_parseXml()
	 */
	protected function _parseXml() {
		$this->_file = isset($this->_response['invoice']['download_url']['@data']) ? $this->_response['invoice']['download_url']['@data'] : '';
	}

	/**
	 * Error handling (override)
	 * @see SofortLib::_handleErrors()
	 */
	protected function _handleErrors() {
		if (!isset($this->_response['invoices']['invoice'][0])) {
			$tmp = $this->_response['invoices']['invoice'];
			unset($this->_response['invoices']['invoice']);
			$this->_response['invoices']['invoice'][0] = $tmp;
		}

		foreach ($this->_response['invoices']['invoice'] as $response) {
			//handle errors
			if (isset($response['errors']['error'])) {
				if (!isset($response['errors']['error'][0])) {
					$tmp = $response['errors']['error'];
					unset($response['errors']['error']);
					$response['errors']['error'][0] = $tmp;
				}

				foreach ($response['errors']['error'] as $error) {
					$this->errors['sr'][] = $this->_getErrorBlock($error);
				}
			}

			//handle warnings
			if (isset($response['warnings']['warning'])) {
				if (!isset($response['warnings']['warning'][0])) {
					$tmp = $response['warnings']['warning'];
					unset($response['warnings']['warning']);
					$response['warnings']['warning'][0] = $tmp;
				}

				foreach ($response['warnings']['warning'] as $error) {
					$this->warnings['sr'][] = $this->_getErrorBlock($error);
				}
			}
		}
	}
}
?>


text:
<?php

declare(strict_types=1);

namespace App\Infrastructure\Repository;

use App\Domain\Entity\User;
use App\Domain\Value\UserId;
use Doctrine\DBAL\Connection;

final class SqlUsers implements Users
{
    /**
     * @var Connection
     */
    private $connection;

    public function __construct(Connection $connection)
    {
        $this->connection = $connection;
    }

    /**
     * @return User[]
     */
    public function all(): array
    {
        $allChocolatesStatement = $this->connection->executeQuery(
            'SELECT ' .
            '   u.id, ' .
            '   u.username, ' .
            '   u.password, ' .
            '   u.admin ' .
            'FROM users u'
        );

        return $allChocolatesStatement->fetchAll(
            \PDO::FETCH_FUNC,
            [self::class, 'createUser']
        );
    }

    public function add(User $user): void
    {
        $this->connection->executeUpdate(
            'INSERT INTO users (id, username, password, admin) '.
            'VALUES (:id, :username, :password, :admin) '.
            'ON CONFLICT DO NOTHING',
            [
                'id' => (string) $user->id(),
                'username' => $user->username(),
                'password' => $user->password(),
                'admin' => $user->isAdministrator() ? 'true' : 'false'
            ]
        );
    }

    public function createUser(
        string $id,
        string $username,
        string $password,
        bool $isAdministrator
    ) {
        return User::fromNativeData(
            $id,
            $username,
            $password,
            $isAdministrator
        );
    }

    public function findById(UserId $id): ?User
    {
        $retrieveByIdStatement = $this->connection->executeQuery(
            'SELECT ' .
            '   u.id, ' .
            '   u.username, ' .
            '   u.password, ' .
            '   u.admin ' .
            'FROM users u ' .
            'WHERE id = :id',
            [
                'id' => (string) $id
            ]
        );

        $userData = $retrieveByIdStatement->fetch(\PDO::FETCH_ASSOC);

        if (null === $userData) {
            return null;
        }

        return $this->createUser(
            $userData['id'],
            $userData['username'],
            $userData['password'],
            $userData['admin']
        );
    }

    public function findByUsername(string $username): ?User
    {
        $retrieveByUsernameStatement = $this->connection->executeQuery(
            'SELECT ' .
            '   u.id, ' .
            '   u.username, ' .
            '   u.password, ' .
            '   u.admin ' .
            'FROM users u ' .
            'WHERE username = :username',
            [
                'username' => $username
            ]
        );

        $userData = $retrieveByUsernameStatement->fetch(\PDO::FETCH_ASSOC);

        if (null === $userData) {
            return null;
        }

        return $this->createUser(
            $userData['id'],
            $userData['username'],
            $userData['password'],
            $userData['admin']
        );
    }
}


text:
package org.jenkinsci.plugins.tibco.axmeclipseant;

import hudson.Launcher;
import hudson.console.LineTransformationOutputStream;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import org.jenkinsci.plugins.tibco.AmxEclipseAntBuilder;
import org.jenkinsci.plugins.tibco.AmxEclipseAntBuilder.DescriptorImpl;
import org.kohsuke.stapler.StaplerRequest;
/**
 *
 * @author Federico Pastore - federico.pastore@gmail.com
 *
 *
 *
 * Disclaimer -  TIBCO, the TIBCO logo and
 * TIBCO Software are trademarks or
 * registered trademarks of TIBCO Software
 * Inc. in the United States and/or other
 * countries. All other product and company
 * names and marks mentioned are the property of their respective
 * owners.
 *
 */

public class TibcoConsoleAnnotator extends LineTransformationOutputStream {
    private final OutputStream outputConsole;
    private final Charset charset;

    private boolean isEmptyLine;

    public TibcoConsoleAnnotator(OutputStream out, Charset charset) {
        this.outputConsole = out;
        this.charset = charset;
    }

    @Override
    protected void eol(byte[] b, int len) throws IOException {
        String line = charset.decode(ByteBuffer.wrap(b, 0, len)).toString();
        line = trimEOL(line);
        if (isEmptyLine && endsWith(line,':') && line.indexOf(' ')<0)
            new TibcoTargetNote().encodeTo(outputConsole);

        if (line.equals("BUILD SUCCESSFUL") || line.equals("BUILD FAILED"))
            new TibcoOutcomeNote().encodeTo(outputConsole);

        isEmptyLine = line.length()==0;
        outputConsole.write(b,0,len);
    }

    private boolean endsWith(String line, char c) {
        int len = line.length();
        return len>0 && line.charAt(len-1)==c;
    }

    @Override
    public void close() throws IOException {
        super.close();
        outputConsole.close();
    }

}


text:
void PD_KernelArgsParseFn(const phi::KernelKey& default_key,
                          phi::KernelArgsDef* args_def,
                          size_t in_nargs,
                          PD_KernelArgumentType* in_args_type,
                          size_t attr_nargs,
                          PD_KernelArgumentType* attr_args_type,
                          size_t out_nargs,
                          PD_KernelArgumentType* out_args_type) {
  auto default_tensor_layout = phi::DataLayout::NCHW;
  if (default_key.layout() != phi::DataLayout::ANY) {
    default_tensor_layout = default_key.layout();
  }
  // inputs
  for (size_t i = 0; i < in_nargs; ++i) {
    auto arg_type = in_args_type[i];
    if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_CONTEXT) {
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_TENSOR) {
      args_def->AppendInput(default_key.backend(),
                            default_tensor_layout,
                            default_key.dtype(),
                            std::type_index(typeid(const phi::DenseTensor&)));
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_OPTIONAL_TENSOR) {
      args_def->AppendInput(
          default_key.backend(),
          default_tensor_layout,
          default_key.dtype(),
          std::type_index(typeid(const paddle::optional<phi::DenseTensor>&)));
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_LIST_TENSOR) {
      args_def->AppendInput(
          default_key.backend(),
          default_tensor_layout,
          default_key.dtype(),
          std::type_index(typeid(const std::vector<const phi::DenseTensor*>&)));
    } else if (arg_type ==
               PD_KernelArgumentType::PD_ARG_TYPE_OPTIONAL_MULTI_TENSOR) {
      args_def->AppendInput(
          default_key.backend(),
          default_tensor_layout,
          default_key.dtype(),
          std::type_index(typeid(
              const paddle::optional<std::vector<const phi::DenseTensor*>>&)));
    } else {
      PADDLE_THROW(phi::errors::Unavailable(
          "PD_KernelArgumentType %d is not supported.", arg_type));
    }
  }
  // attributes
  for (size_t i = 0; i < attr_nargs; ++i) {
    auto arg_type = attr_args_type[i];
    if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_BOOL) {
      args_def->AppendAttribute(phi::AttributeType::BOOL);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_FLOAT32) {
      args_def->AppendAttribute(phi::AttributeType::FLOAT32);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_FLOAT64) {
      args_def->AppendAttribute(phi::AttributeType::FLOAT64);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_INT32) {
      args_def->AppendAttribute(phi::AttributeType::INT32);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_INT64) {
      args_def->AppendAttribute(phi::AttributeType::INT64);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_STRING) {
      args_def->AppendAttribute(phi::AttributeType::STRING);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_SCALAR) {
      args_def->AppendAttribute(phi::AttributeType::SCALAR);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_INT_ARRAY) {
      args_def->AppendAttribute(phi::AttributeType::INT_ARRAY);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_DATA_TYPE) {
      args_def->AppendAttribute(phi::AttributeType::DATA_TYPE);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_DATA_LAYOUT) {
      args_def->AppendAttribute(phi::AttributeType::DATA_LAYOUT);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_PLACE) {
      args_def->AppendAttribute(phi::AttributeType::PLACE);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_LIST_BOOL) {
      args_def->AppendAttribute(phi::AttributeType::BOOLS);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_LIST_INT32) {
      args_def->AppendAttribute(phi::AttributeType::INT32S);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_LIST_INT64) {
      args_def->AppendAttribute(phi::AttributeType::INT64S);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_LIST_FLOAT32) {
      args_def->AppendAttribute(phi::AttributeType::FLOAT32S);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_LIST_FLOAT64) {
      args_def->AppendAttribute(phi::AttributeType::FLOAT64S);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_LIST_STRING) {
      args_def->AppendAttribute(phi::AttributeType::STRINGS);
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_LIST_SCALAR) {
      args_def->AppendAttribute(phi::AttributeType::SCALARS);
    } else {
      PADDLE_THROW(phi::errors::Unavailable(
          "PD_KernelArgumentType %d is not supported.", arg_type));
    }
  }
  // outputs
  for (size_t i = 0; i < out_nargs; ++i) {
    auto arg_type = out_args_type[i];
    if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_TENSOR) {
      args_def->AppendOutput(default_key.backend(),
                             default_tensor_layout,
                             default_key.dtype(),
                             std::type_index(typeid(phi::DenseTensor*)));
    } else if (arg_type == PD_KernelArgumentType::PD_ARG_TYPE_LIST_TENSOR) {
      args_def->AppendOutput(
          default_key.backend(),
          default_tensor_layout,
          default_key.dtype(),
          std::type_index(typeid(std::vector<phi::DenseTensor*>)));
    } else {
      PADDLE_THROW(phi::errors::Unavailable(
          "PD_KernelArgumentType %d is not supported.", arg_type));
    }
  }
}

void PD_RegisterPhiKernel(const char* kernel_name_cstr,
                          const char* backend_cstr,
                          PD_DataType pd_dtype,
                          PD_DataLayout pd_layout,
                          size_t in_nargs,
                          PD_KernelArgumentType* in_args_type,
                          size_t attr_nargs,
                          PD_KernelArgumentType* attr_args_type,
                          size_t out_nargs,
                          PD_KernelArgumentType* out_args_type,
                          void (*args_def_fn)(const PD_KernelKey*, PD_Kernel*),
                          void (*fn)(PD_KernelContext*),
                          void* variadic_kernel_fn) {
  auto args_def_fn_wrapper = [args_def_fn](const phi::KernelKey& kernel_key,
                                           phi::Kernel* kernel) {
    args_def_fn(reinterpret_cast<const PD_KernelKey*>(&kernel_key),
                reinterpret_cast<PD_Kernel*>(kernel));
  };
  phi::KernelFn kernel_fn = [fn](phi::KernelContext* ctx) {
    fn(reinterpret_cast<PD_KernelContext*>(ctx));
  };
  std::string kernel_name(kernel_name_cstr);

  auto dtype = phi::capi::ToPhiDataType(pd_dtype);
  auto layout = phi::capi::ToPhiDataLayout(pd_layout);
  phi::KernelKey kernel_key(
      paddle::experimental::StringToBackend(backend_cstr), layout, dtype);

  phi::Kernel kernel(kernel_fn, variadic_kernel_fn);
  PD_KernelArgsParseFn(kernel_key,
                       kernel.mutable_args_def(),
                       in_nargs,
                       in_args_type,
                       attr_nargs,
                       attr_args_type,
                       out_nargs,
                       out_args_type);

  args_def_fn_wrapper(kernel_key, &kernel);
  phi::KernelFactory::Instance().kernels()[kernel_name][kernel_key] = kernel;
}

PD_REGISTER_CAPI(kernel_registry);


text:
"use strict";
//# sourceMappingURL=IConnectionContext.js.map


text:
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView

import db.schema as schema
import db.query as query
from handlers.rest import app

admin = Admin(app, url="/admin")

class RoundModelView(ModelView):
  column_list = ('id', 'perspective', 'start_time')
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(RoundModelView, self).__init__(
      schema.Round,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class PerspectiveModelView(ModelView):
  form_columns = \
    ('gender',
     'text',
     'social_text',)

  column_list = ('id', 'gender', 'text', 'created_at')

  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(PerspectiveModelView, self).__init__(
      schema.Perspective,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class SubmissionModelView(ModelView):
  column_list = ('id', 'perspective_id', 'round_id', 'text', 'fb_post_id', 'likes', 'created_at')
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(SubmissionModelView, self).__init__(
      schema.Submission,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(SubmissionModelView())


text:
package main

import (
	"fmt"

	"github.com/opsgenie/opsgenie-go-sdk/_samples/constants"
	ogcli "github.com/opsgenie/opsgenie-go-sdk/client"
	"github.com/opsgenie/opsgenie-go-sdk/notificationv2"
)

func main() {
	cli := new(ogcli.OpsGenieClient)
	cli.SetAPIKey(constants.APIKey)

	notificationCli, _ := cli.NotificationV2()

	response, err := notificationCli.Enable(notificationv2.EnableNotificationRequest{
		Identifier: &notificationv2.Identifier{
			Username: "user@company.com",
			RuleID: "example-notification-id",
		},
	})

	if err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Printf("Result: %s, Request ID: %s\n", response.Result, response.RequestID)
	}
}


text:
import asyncio

import uvloop

from sanic import Sanic, response

app = Sanic("Example")

@app.route("/")
async def test(request):
    return response.json({"answer": "42"})

async def main():
    server = await app.create_server(
        port=8000, host="0.0.0.0", return_asyncio_server=True
    )

    if server is None:
        return

    await server.startup()
    await server.serve_forever()

if __name__ == "__main__":
    asyncio.set_event_loop(uvloop.new_event_loop())
    asyncio.run(main())


text:
<?php defined('SYSPATH') OR die('No direct script access.');

/**
 * This class handles an imporved MySQL connection.
 *
 * @package Leap
 * @category MySQL
 * @version 2011-12-11
 */
class DB_MySQL_Connection_Improved extends Base_DB_MySQL_Connection_Improved {}
?>


text:
#pragma once
#include <aws/wisdom/ConnectWisdomService_EXPORTS.h>
#include <aws/wisdom/model/Document.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/wisdom/model/RelevanceLevel.h>
#include <aws/wisdom/model/RecommendationType.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace ConnectWisdomService
{
namespace Model
{

  /**
   *
Information about the recommendation.

See Also:
   AWS
   * API Reference

   */
  class AWS_CONNECTWISDOMSERVICE_API RecommendationData
  {
  public:
    RecommendationData();
    RecommendationData(Aws::Utils::Json::JsonView jsonValue);
    RecommendationData& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The recommended document.

     */
    inline const Document& GetDocument() const{ return m_document; }

    /**
     *
The recommended document.

     */
    inline bool DocumentHasBeenSet() const { return m_documentHasBeenSet; }

    /**
     *
The recommended document.

     */
    inline void SetDocument(const Document& value) { m_documentHasBeenSet = true; m_document = value; }

    /**
     *
The recommended document.

     */
    inline void SetDocument(Document&& value) { m_documentHasBeenSet = true; m_document = std::move(value); }

    /**
     *
The recommended document.

     */
    inline RecommendationData& WithDocument(const Document& value) { SetDocument(value); return *this;}

    /**
     *
The recommended document.

     */
    inline RecommendationData& WithDocument(Document&& value) { SetDocument(std::move(value)); return *this;}

    /**
     *
The identifier of the recommendation.

     */
    inline const Aws::String& GetRecommendationId() const{ return m_recommendationId; }

    /**
     *
The identifier of the recommendation.

     */
    inline bool RecommendationIdHasBeenSet() const { return m_recommendationIdHasBeenSet; }

    /**
     *
The identifier of the recommendation.

     */
    inline void SetRecommendationId(const Aws::String& value) { m_recommendationIdHasBeenSet = true; m_recommendationId = value; }

    /**
     *
The identifier of the recommendation.

     */
    inline void SetRecommendationId(Aws::String&& value) { m_recommendationIdHasBeenSet = true; m_recommendationId = std::move(value); }

    /**
     *
The identifier of the recommendation.

     */
    inline void SetRecommendationId(const char* value) { m_recommendationIdHasBeenSet = true; m_recommendationId.assign(value); }

    /**
     *
The identifier of the recommendation.

     */
    inline RecommendationData& WithRecommendationId(const Aws::String& value) { SetRecommendationId(value); return *this;}

    /**
     *
The identifier of the recommendation.

     */
    inline RecommendationData& WithRecommendationId(Aws::String&& value) { SetRecommendationId(std::move(value)); return *this;}

    /**
     *
The identifier of the recommendation.

     */
    inline RecommendationData& WithRecommendationId(const char* value) { SetRecommendationId(value); return *this;}

    /**
     *
The relevance level of the recommendation.

     */
    inline const RelevanceLevel& GetRelevanceLevel() const{ return m_relevanceLevel; }

    /**
     *
The relevance level of the recommendation.

     */
    inline bool RelevanceLevelHasBeenSet() const { return m_relevanceLevelHasBeenSet; }

    /**
     *
The relevance level of the recommendation.

     */
    inline void SetRelevanceLevel(const RelevanceLevel& value) { m_relevanceLevelHasBeenSet = true; m_relevanceLevel = value; }

    /**
     *
The relevance level of the recommendation.

     */
    inline void SetRelevanceLevel(RelevanceLevel&& value) { m_relevanceLevelHasBeenSet = true; m_relevanceLevel = std::move(value); }

    /**
     *
The relevance level of the recommendation.

     */
    inline RecommendationData& WithRelevanceLevel(const RelevanceLevel& value) { SetRelevanceLevel(value); return *this;}

    /**
     *
The relevance level of the recommendation.

     */
    inline RecommendationData& WithRelevanceLevel(RelevanceLevel&& value) { SetRelevanceLevel(std::move(value)); return *this;}

    /**
     *
The relevance score of the recommendation.

     */
    inline double GetRelevanceScore() const{ return m_relevanceScore; }

    /**
     *
The relevance score of the recommendation.

     */
    inline bool RelevanceScoreHasBeenSet() const { return m_relevanceScoreHasBeenSet; }

    /**
     *
The relevance score of the recommendation.

     */
    inline void SetRelevanceScore(double value) { m_relevanceScoreHasBeenSet = true; m_relevanceScore = value; }

    /**
     *
The relevance score of the recommendation.

     */
    inline RecommendationData& WithRelevanceScore(double value) { SetRelevanceScore(value); return *this;}

    /**
     *
The type of recommendation.

     */
    inline const RecommendationType& GetType() const{ return m_type; }

    /**
     *
The type of recommendation.

     */
    inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }

    /**
     *
The type of recommendation.

     */
    inline void SetType(const RecommendationType& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
The type of recommendation.

     */
    inline void SetType(RecommendationType&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
The type of recommendation.

     */
    inline RecommendationData& WithType(const RecommendationType& value) { SetType(value); return *this;}

    /**
     *
The type of recommendation.

     */
    inline RecommendationData& WithType(RecommendationType&& value) { SetType(std::move(value)); return *this;}

  private:

    Document m_document;
    bool m_documentHasBeenSet;

    Aws::String m_recommendationId;
    bool m_recommendationIdHasBeenSet;

    RelevanceLevel m_relevanceLevel;
    bool m_relevanceLevelHasBeenSet;

    double m_relevanceScore;
    bool m_relevanceScoreHasBeenSet;

    RecommendationType m_type;
    bool m_typeHasBeenSet;
  };

} // namespace Model
} // namespace ConnectWisdomService
} // namespace Aws


text:
<?php
class Kwc_Articles_Directory_Generator extends Kwf_Component_Generator_Page_Table
{
    protected function _formatSelect($parentData, $select)
    {
        $ret = parent::_formatSelect($parentData, $select);
        if (!$ret) return $ret;

        $ignoreVisible = $select && $select->getPart(Kwf_Component_Select::IGNORE_VISIBLE);
        if (!$ignoreVisible) {
            $ignoreVisible = Kwf_Component_Data_Root::getShowInvisible();
            $ret->where('date <= NOW()');
        }

        $ret->whereEquals('deleted', 0);
        return $ret;
    }
}


text:
namespace {

std::string StringFromJobStatus(cloud_print::PrintJobStatus status) {
  std::string ret;
  switch (status) {
    case cloud_print::PRINT_JOB_STATUS_IN_PROGRESS:
      ret = "IN_PROGRESS";
      break;
    case cloud_print::PRINT_JOB_STATUS_ERROR:
      ret = "ERROR";
      break;
    case cloud_print::PRINT_JOB_STATUS_COMPLETED:
      ret = "DONE";
      break;
    default:
      ret = "UNKNOWN";
      NOTREACHED();
      break;
  }
  return ret;
}

}

namespace cloud_print {

GURL GetUrlForJobStatusUpdate(const GURL& cloud_print_server_url,
                              const std::string& job_id,
                              PrintJobStatus status) {
  return GetUrlForJobStatusUpdate(cloud_print_server_url,
                                  job_id,
                                  StringFromJobStatus(status));
}

GURL GetUrlForJobStatusUpdate(const GURL& cloud_print_server_url,
                              const std::string& job_id,
                              const PrintJobDetails& details) {
  std::string status_string = StringFromJobStatus(details.status);
  std::string path(AppendPathToUrl(cloud_print_server_url, "control"));
  GURL::Replacements replacements;
  replacements.SetPathStr(path);
  std::string query =
      StringPrintf("jobid=%s&status=%s&code=%d&message=%s"
                   "&numpages=%d&pagesprinted=%d",
                   job_id.c_str(),
                   status_string.c_str(),
                   details.platform_status_flags,
                   details.status_message.c_str(),
                   details.total_pages,
                   details.pages_printed);
  replacements.SetQueryStr(query);
  return cloud_print_server_url.ReplaceComponents(replacements);
}

std::string GetHashOfPrinterInfo(
    const printing::PrinterBasicInfo& printer_info) {
  return GetHashOfPrinterTags(printer_info.options);
}

std::string GetPostDataForPrinterInfo(
    const printing::PrinterBasicInfo& printer_info,
    const std::string& mime_boundary) {
  return GetPostDataForPrinterTags(
      printer_info.options,
      mime_boundary,
      kCloudPrintServiceProxyTagPrefix,
      kCloudPrintServiceTagsHashTagName);
}

bool IsDryRunJob(const std::vector<std::string>& tags) {
  return std::find(tags.begin(), tags.end(),
                   std::string(kCloudPrintServiceTagDryRunFlag)) != tags.end();
}

std::string GetCloudPrintAuthHeaderFromStore() {
  CloudPrintTokenStore* token_store = CloudPrintTokenStore::current();
  if (!token_store || token_store->token().empty()) {
    // Using LOG here for critical errors. GCP connector may run in the headless
    // mode and error indication might be useful for user in that case.
    LOG(ERROR) << "CP_PROXY: Missing OAuth token for request";
    return std::string();
  }
  return GetCloudPrintAuthHeader(token_store->token());
}

}  // namespace cloud_print


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using ApathyEngine.Graphics;

namespace ApathyEngine.Input
{
    /// <summary>
    /// A class that represents a keyboard that never reads input.
    /// </summary>
    public class NullKeyboard : IKeyboard
    {
        public KeyboardState RawState { get { return new KeyboardState(); } }

        public Keys[] GetPressedKeys() { return new Keys[] { }; }

        public bool IsKeyDown(Keys key) { return false; }

        public bool IsKeyUp(Keys key) { return false; }

        public bool WasKeyJustReleased(Keys key) { return false; }

        public bool WasKeyJustPressed(Keys key) { return false; }

        public bool IsKeyBeingHeld(Keys key) { return false; }

        public bool IsKeyBeingHeld(Keys key, int consecutiveFrames) { return false; }

        public void Update(GameTime gameTime) { }
    }

    /// <summary>
    /// A class that represents a gamepad that never reads input.
    /// </summary>
    public class NullGamepad : IGamepad
    {
        public GamePadState RawState { get { return new GamePadState(); } }

        public bool IsConnected { get { return false; } }

        public Buttons[] GetPressedButtons() { return new Buttons[] { }; }

        public bool IsButtonDown(Buttons button) { return false; }

        public bool IsButtonUp(Buttons button) { return false; }

        public GamePadButtons Buttons { get { return new GamePadButtons(); } }

        public GamePadThumbSticks ThumbSticks { get { return new GamePadThumbSticks(); } }

        public GamePadDPad DPad { get { return new GamePadDPad(); } }

        public GamePadTriggers Triggers { get { return new GamePadTriggers(); } }

        public bool WasButtonJustReleased(Buttons button) { return false; }

        public bool WasButtonJustPressed(Buttons button) { return false; }

        public bool IsButtonBeingHeld(Buttons button) { return false; }

        public bool IsButtonBeingHeld(Buttons button, int consecutiveFrames) { return false; }

        public void Update(GameTime gameTime) { }
    }

    /// <summary>
    /// Represents a mouse that never reads input and never moves from (0, 0).
    /// </summary>
    public class NullMouse : AbstractMouse
    {
        public override MouseState RawState { get { return new MouseState(); } }

        public override ButtonState LeftButton { get { return ButtonState.Released; } }

        public override ButtonState MiddleButton { get { return ButtonState.Released; } }

        public override ButtonState RightButton { get { return ButtonState.Released; } }

        public override int ScrollWheelValue { get { return 0; } }

        public override int X { get { return 0; } }

        public override int Y { get { return 0; } }

        public override Vector2 MousePositionDelta { get { return Vector2.Zero; } }

        public override int ScrollWheelDelta { get { return 0; } }

        public override bool WasMouseJustClicked(int mouseButton = 1) { return false; }

        public override bool WasMouseJustReleased(int mouseButton = 1) { return false; }

        public override bool IsMouseBeingHeld(int mouseButton = 1) { return false; }

        public override bool IsMouseBeingHeld(int mouseButton, int consecutiveFrames) { return false; }

        public override void Update(GameTime gameTime) { }

        public override bool IsWithinCoordinates(Sprite sprite) { return false; }

        public override bool IsWithinCoordinates(Vector2 center, int radius) { return false; }

        public override bool IsWithinCoordinates(Vector2 upperLeft, Vector2 lowerRight) { return false; }

        public override Vector2 MousePosition { get { return Vector2.Zero; } }
    }
}


text:
local uv    = require('luv')
local tap   = require('util/tap')
local test = tap.test

local isWindows = os.platform() == "win32"

test("test disable_stdio_inheritance", function (expect, uv)
	uv.disable_stdio_inheritance()
end)

test("process stdout", function (expect, uv)
	local stdout = uv.new_pipe(false)

	local handle, pid
	handle, pid = uv.spawn(uv.exepath(), {
		args = {"-e", "print 'Hello World'"},
		stdio = {nil, stdout},

	}, expect(function (code, signal)
		console.log("exit", code, signal)
		uv.close(handle)
	end))

	uv.read_start(stdout, expect(function (err, chunk)
		console.log("stdout", err, chunk)
		assert(not err, err)
		uv.close(stdout)
	end))

end)

if isWindows then return end

test("spawn and kill by pid", function (expect, uv)
	local handle, pid
	handle, pid = uv.spawn("sleep", {
		args = {1},

	}, expect(function (code, signal)
		console.log("exit", handle, code,signal)
		assert(code == 0)
		assert(signal == 2)
		uv.close(handle)
	end))

	--console.log{handle=handle,pid=pid}
	uv.kill(pid, "sigint")
end)

test("spawn and kill by handle", function (expect, uv)
	local handle, pid
	handle, pid = uv.spawn("sleep", {
		args = {1},
	}, expect(function (code, signal)
		console.log("exit", handle, code, signal)
		assert(code == 0)
		assert(signal == 15)
		uv.close(handle)
	end))

	--console.log{handle=handle,pid=pid}
	uv.process_kill(handle, "sigterm")
end)

test("invalid command", function (expect, uv)
		local handle, err
		handle, err = uv.spawn("ksjdfksjdflkjsflksdf", {}, function(exit, code)
		assert(false)
		end)
		assert(handle == nil)
		assert(err)
end)

test("process stdio", function (expect, uv)
	local stdin = uv.new_pipe(false)
	local stdout = uv.new_pipe(false)

	local handle, pid
	handle, pid = uv.spawn("cat", {
		stdio = {stdin, stdout},
	}, expect(function (code, signal)
		console.log("exit", code, signal)
		uv.close(handle)
	end))

	--console.log(handle, pid)

	uv.read_start(stdout, expect(function (err, chunk)
		console.log("stdout", err, chunk)
		assert(not err, err)
		uv.close(stdout)
	end))

	uv.write(stdin, "Hello World")
	uv.shutdown(stdin, expect(function ()
		uv.close(stdin)
	end))

end)

tap.run()


text:
package gnu.javax.net.ssl.provider;

import gnu.classpath.debug.Component;
import gnu.classpath.debug.SystemLogger;
import gnu.java.security.action.GetSecurityPropertyAction;
import gnu.java.security.prng.IRandom;
import gnu.java.security.prng.LimitReachedException;
import gnu.java.security.util.ByteArray;
import gnu.javax.security.auth.callback.CertificateCallback;
import gnu.javax.security.auth.callback.DefaultCallbackHandler;

import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.DigestException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivilegedExceptionAction;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.ConfirmationCallback;

/**
 * The base interface for handshake implementations. Concrete
 * subclasses of this class (one for the server, one for the client)
 * handle the HANDSHAKE content-type in communications.
 */
public abstract class AbstractHandshake
{
  protected static final SystemLogger logger = SystemLogger.SYSTEM;

  /**
   * "server finished" -- TLS 1.0 and later
   */
  protected static final byte[] SERVER_FINISHED
    = new byte[] {
      115, 101, 114, 118, 101, 114,  32, 102, 105, 110, 105, 115,
      104, 101, 100
    };

  /**
   * "client finished" -- TLS 1.0 and later
   */
  protected static final byte[] CLIENT_FINISHED
    = new byte[] {
       99, 108, 105, 101, 110, 116,  32, 102, 105, 110, 105, 115,
      104, 101, 100
    };

  /**
   * "key expansion" -- TLS 1.0 and later
   */
  private static final byte[] KEY_EXPANSION =
    new byte[] { 107, 101, 121,  32, 101, 120, 112,
                  97, 110, 115, 105, 111, 110 };

  /**
   * "master secret" -- TLS 1.0 and later
   */
  private static final byte[] MASTER_SECRET
    = new byte[] {
      109,  97, 115, 116, 101, 114,  32, 115, 101,  99, 114, 101, 116
    };

  /**
   * "client write key" -- TLS 1.0 exportable whitener.
   */
  private static final byte[] CLIENT_WRITE_KEY
    = new byte[] {
       99, 108, 105, 101, 110, 116,  32, 119, 114, 105, 116, 101,  32, 107,
      101, 121
    };

  /**
   * "server write key" -- TLS 1.0 exportable whitener.
   */
  private static final byte[] SERVER_WRITE_KEY
    = new byte[] {
      115, 101, 114, 118, 101, 114,  32, 119, 114, 105, 116, 101,  32, 107,
      101, 121
    };

  private static final byte[] IV_BLOCK
    = new byte[] {
       73,  86,  32,  98, 108, 111,  99, 107
    };

  /**
   * SSL 3.0; the string "CLNT"
   */
  private static final byte[] SENDER_CLIENT
    = new byte[] { 0x43, 0x4C, 0x4E, 0x54 };

  /**
   * SSL 3.0; the string "SRVR"
   */
  private static final byte[] SENDER_SERVER
    = new byte[] { 0x53, 0x52, 0x56, 0x52 };

  /**
   * SSL 3.0; the value 0x36 40 (for SHA-1 hashes) or 48 (for MD5 hashes)
   * times.
   */
  protected static final byte[] PAD1 = new byte[48];

  /**
   * SSL 3.0; the value 0x5c 40 (for SHA-1 hashes) or 48 (for MD5 hashes)
   * times.
   */
  protected static final byte[] PAD2 = new byte[48];

  static
  {
    Arrays.fill(PAD1, SSLHMac.PAD1);
    Arrays.fill(PAD2, SSLHMac.PAD2);
  }

  /**
   * The currently-read handshake messages. There may be zero, or
   * multiple, handshake messages in this buffer.
   */
  protected ByteBuffer handshakeBuffer;

  /**
   * The offset into `handshakeBuffer' where the first unread
   * handshake message resides.
   */
  protected int handshakeOffset;

  protected MessageDigest sha;
  protected MessageDigest md5;

  protected final SSLEngineImpl engine;
  protected KeyAgreement keyAgreement;
  protected byte[] preMasterSecret;
  protected InputSecurityParameters inParams;
  protected OutputSecurityParameters outParams;
  protected LinkedList<DelegatedTask> tasks;
  protected Random serverRandom;
  protected Random clientRandom;
  protected CompressionMethod compression;

  protected AbstractHandshake(SSLEngineImpl engine)
    throws NoSuchAlgorithmException
  {
    this.engine = engine;
    sha = MessageDigest.getInstance("SHA-1");
    md5 = MessageDigest.getInstance("MD5");
    tasks = new LinkedList<DelegatedTask>();
  }

  /**
   * Handles the next input message in the handshake. This is called
   * in response to a call to {@link javax.net.ssl.SSLEngine#unwrap}
   * for a message with content-type HANDSHAKE.
   *
   * @param record The input record. The callee should not assume that
   * the record's buffer is writable, and should not try to use it for
   * output or temporary storage.
   * @return An {@link SSLEngineResult} describing the result.
   */
  public final HandshakeStatus handleInput (ByteBuffer fragment)
    throws SSLException
  {
    if (!tasks.isEmpty())
      return HandshakeStatus.NEED_TASK;

    HandshakeStatus status = status();
    if (status != HandshakeStatus.NEED_UNWRAP)
      return status;

    // Try to read another...
    if (!pollHandshake(fragment))
      return HandshakeStatus.NEED_UNWRAP;

    while (hasMessage() && status != HandshakeStatus.NEED_WRAP)
      {
        int pos = handshakeOffset;
        status = implHandleInput();
        int len = handshakeOffset - pos;
        if (len == 0)
          {
            // Don't bother; the impl is just telling us to go around
            // again.
            continue;
          }
        if (doHash())
          {
            if (Debug.DEBUG)
              logger.logv(Component.SSL_HANDSHAKE, "hashing output\n{0}",
                          Util.hexDump((ByteBuffer) handshakeBuffer
                                       .duplicate().position(pos)
                                       .limit(pos+len), " >> "));
            sha.update((ByteBuffer) handshakeBuffer.duplicate()
                       .position(pos).limit(pos+len));
            md5.update((ByteBuffer) handshakeBuffer.duplicate()
                       .position(pos).limit(pos+len));
          }
      }
    return status;
  }

  /**
   * Called to process more handshake data. This method will be called
   * repeatedly while there is remaining handshake data, and while the
   * status is
   * @return
   * @throws SSLException
   */
  protected abstract HandshakeStatus implHandleInput()
    throws SSLException;

  /**
   * Produce more handshake output. This is called in response to a
   * call to {@link javax.net.ssl.SSLEngine#wrap}, when the handshake
   * is still in progress.
   *
   * @param record The output record; the callee should put its output
   * handshake message (or a part of it) in the argument's
   * fragment, and should set the record length
   * appropriately.
   * @return An {@link SSLEngineResult} describing the result.
   */
  public final HandshakeStatus handleOutput (ByteBuffer fragment)
    throws SSLException
  {
    if (!tasks.isEmpty())
      return HandshakeStatus.NEED_TASK;

    int orig = fragment.position();
    SSLEngineResult.HandshakeStatus status = implHandleOutput(fragment);
    if (doHash())
      {
        if (Debug.DEBUG)
          logger.logv(Component.SSL_HANDSHAKE, "hashing output:\n{0}",
                      Util.hexDump((ByteBuffer) fragment.duplicate().flip().position(orig), " >> "));
        sha.update((ByteBuffer) fragment.duplicate().flip().position(orig));
        md5.update((ByteBuffer) fragment.duplicate().flip().position(orig));
      }
    return status;
  }

  /**
   * Called to implement the underlying output handling. The callee should
   * attempt to fill the given buffer as much as it can; this can include
   * multiple, and even partial, handshake messages.
   *
   * @param fragment The buffer the callee should write handshake messages to.
   * @return The new status of the handshake.
   * @throws SSLException If an error occurs processing the output message.
   */
  protected abstract SSLEngineResult.HandshakeStatus implHandleOutput (ByteBuffer fragment)
    throws SSLException;

  /**
   * Return a new instance of input security parameters, initialized with
   * the session key. It is, of course, only valid to invoke this method
   * once the handshake is complete, and the session keys established.
   *
   *
In the presence of a well-behaving peer, this should be called once
   * the ChangeCipherSpec message is recieved.
   *
   * @return The input parameters for the newly established session.
   * @throws SSLException If the handshake is not complete.
   */
  final InputSecurityParameters getInputParams() throws SSLException
  {
    checkKeyExchange();
    return inParams;
  }

  /**
   * Return a new instance of output security parameters, initialized with
   * the session key. This should be called after the
   * ChangeCipherSpec message is sent to the peer.
   *
   * @return The output parameters for the newly established session.
   * @throws SSLException If the handshake is not complete.
   */
  final OutputSecurityParameters getOutputParams() throws SSLException
  {
    checkKeyExchange();
    return outParams;
  }

  /**
   * Fetch a delegated task waiting to run, if any.
   *
   * @return The task.
   */
  final Runnable getTask()
  {
    if (tasks.isEmpty())
      return null;
    return tasks.removeFirst();
  }

  /**
   * Used by the skeletal code to query the current status of the handshake.
   * This should be the same value as returned by the previous call
   * to {@link #implHandleOutput(ByteBuffer)} or {@link
   *  #implHandleInput(ByteBuffer)}.
   *
   * @return The current handshake status.
   */
  abstract HandshakeStatus status();

  /**
   * Check if the key exchange completed successfully, throwing an exception
   * if not.
   *
   *
Note that we assume that the caller of our SSLEngine is correct, and
   * that they did run the delegated tasks that encapsulate the key exchange.
   * What we are primarily checking, therefore, is that no error occurred in the
   * key exchange operation itself.
   *
   * @throws SSLException If the key exchange did not complete successfully.
   */
  abstract void checkKeyExchange() throws SSLException;

  /**
   * Handle an SSLv2 client hello. This is only used by SSL servers.
   *
   * @param hello The hello message.
   */
  abstract void handleV2Hello(ByteBuffer hello) throws SSLException;

  /**
   * Attempt to read the next handshake message from the given
   * record. If only a partial handshake message is available, then
   * this method saves the incoming bytes and returns false. If a
   * complete handshake is read, or if there was one buffered in the
   * handshake buffer, this method returns true, and `handshakeBuffer'
   * can be used to read the handshake.
   *
   * @param record The input record.
   * @return True if a complete handshake is present in the buffer;
   * false if only a partial one.
   */
  protected boolean pollHandshake (final ByteBuffer fragment)
  {
    // Allocate space for the new fragment.
    if (handshakeBuffer == null
        || handshakeBuffer.remaining() < fragment.remaining())
      {
        // We need space for anything still unread in the handshake
        // buffer...
        int len = ((handshakeBuffer == null) ? 0
                   : handshakeBuffer.position() - handshakeOffset);

        // Plus room for the incoming record.
        len += fragment.remaining();
        reallocateBuffer(len);
      }

    if (Debug.DEBUG)
      logger.logv(Component.SSL_HANDSHAKE, "inserting {0} into {1}",
                  fragment, handshakeBuffer);

    // Put the fragment into the buffer.
    handshakeBuffer.put(fragment);

    return hasMessage();
  }

  protected boolean doHash()
  {
    return true;
  }

  /**
   * Tell if the handshake buffer currently has a full handshake
   * message.
   */
  protected boolean hasMessage()
  {
    if (handshakeBuffer == null)
      return false;
    ByteBuffer tmp = handshakeBuffer.duplicate();
    tmp.flip();
    tmp.position(handshakeOffset);
    if (Debug.DEBUG)
      logger.logv(Component.SSL_HANDSHAKE, "current buffer: {0}; test buffer {1}",
                  handshakeBuffer, tmp);
    if (tmp.remaining() < 4)
      return false;
    Handshake handshake = new Handshake(tmp.slice());
    if (Debug.DEBUG)
      logger.logv(Component.SSL_HANDSHAKE, "handshake len:{0} remaining:{1}",
                  handshake.length(), tmp.remaining());
    return (handshake.length() <= tmp.remaining() - 4);
  }

  /**
   * Reallocate the handshake buffer so it can hold `totalLen'
   * bytes. The smallest buffer allocated is 1024 bytes, and the size
   * doubles from there until the buffer is sufficiently large.
   */
  private void reallocateBuffer (final int totalLen)
  {
    int len = handshakeBuffer == null ? -1
                                      : handshakeBuffer.capacity() - (handshakeBuffer.limit() - handshakeOffset);
    if (len >= totalLen)
      {
        // Big enough; no need to reallocate; but maybe shift the contents
        // down.
        if (handshakeOffset > 0)
          {
            handshakeBuffer.flip().position(handshakeOffset);
            handshakeBuffer.compact();
            handshakeOffset = 0;
          }
        return;
      }

    // Start at 1K (probably the system's page size). Double the size
    // from there.
    len = 1024;
    while (len < totalLen)
      len = len << 1;
    ByteBuffer newBuf = ByteBuffer.allocate (len);

    // Copy the unread bytes from the old buffer.
    if (handshakeBuffer != null)
      {
        handshakeBuffer.flip ();
        handshakeBuffer.position(handshakeOffset);
        newBuf.put(handshakeBuffer);
      }
    handshakeBuffer = newBuf;

    // We just put only unread handshake messages in the new buffer;
    // the offset of the next one is now zero.
    handshakeOffset = 0;
  }

  /**
   * Generate a certificate verify message for SSLv3. In SSLv3, a different
   * algorithm was used to generate this value was subtly different than
   * that used in TLSv1.0 and later. In TLSv1.0 and later, this value is
   * just the digest over the handshake messages.
   *
   *
SSLv3 uses the algorithm:
   *
   *

CertificateVerify.signature.md5_hash
  MD5(master_secret + pad_2 +
      MD5(handshake_messages + master_secret + pad_1));
Certificate.signature.sha_hash
  SHA(master_secret + pad_2 +
      SHA(handshake_messages + master_secret + pad_1));

   *
   * @param md5 The running MD5 hash of the handshake.
   * @param sha The running SHA-1 hash of the handshake.
   * @param session The current session being negotiated.
   * @return The computed to-be-signed value.
   */
  protected byte[] genV3CertificateVerify(MessageDigest md5,
                                          MessageDigest sha,
                                          SessionImpl session)
  {
    byte[] md5value = null;
    if (session.suite.signatureAlgorithm() == SignatureAlgorithm.RSA)
      {
        md5.update(session.privateData.masterSecret);
        md5.update(PAD1, 0, 48);
        byte[] tmp = md5.digest();
        md5.reset();
        md5.update(session.privateData.masterSecret);
        md5.update(PAD2, 0, 48);
        md5.update(tmp);
        md5value = md5.digest();
      }

    sha.update(session.privateData.masterSecret);
    sha.update(PAD1, 0, 40);
    byte[] tmp = sha.digest();
    sha.reset();
    sha.update(session.privateData.masterSecret);
    sha.update(PAD2, 0, 40);
    sha.update(tmp);
    byte[] shavalue = sha.digest();

    if (md5value != null)
      return Util.concat(md5value, shavalue);

    return shavalue;
  }

  /**
   * Generate the session keys from the computed master secret.
   *
   * @param clientRandom The client's nonce.
   * @param serverRandom The server's nonce.
   * @param session The session being established.
   * @return The derived keys.
   */
  protected byte[][] generateKeys(Random clientRandom, Random serverRandom,
                                  SessionImpl session)
  {
    int maclen = 20; // SHA-1.
    if (session.suite.macAlgorithm() == MacAlgorithm.MD5)
      maclen = 16;
    int ivlen = 0;
    if (session.suite.cipherAlgorithm() == CipherAlgorithm.DES
        || session.suite.cipherAlgorithm() == CipherAlgorithm.DESede)
      ivlen = 8;
    if (session.suite.cipherAlgorithm() == CipherAlgorithm.AES)
      ivlen = 16;
    int keylen = session.suite.keyLength();

    byte[][] keys = new byte[6][];
    keys[0] = new byte[maclen]; // client_write_MAC_secret
    keys[1] = new byte[maclen]; // server_write_MAC_secret
    keys[2] = new byte[keylen]; // client_write_key
    keys[3] = new byte[keylen]; // server_write_key
    keys[4] = new byte[ivlen];  // client_write_iv
    keys[5] = new byte[ivlen];  // server_write_iv

    IRandom prf = null;
    if (session.version == ProtocolVersion.SSL_3)
      {
        byte[] seed = new byte[clientRandom.length()
                               + serverRandom.length()];
        serverRandom.buffer().get(seed, 0, serverRandom.length());
        clientRandom.buffer().get(seed, serverRandom.length(),
                                  clientRandom.length());
        prf = new SSLRandom();
        HashMap<String,byte[]> attr = new HashMap<String,byte[]>(2);
        attr.put(SSLRandom.SECRET, session.privateData.masterSecret);
        attr.put(SSLRandom.SEED, seed);
        prf.init(attr);
      }
    else
      {
        byte[] seed = new byte[KEY_EXPANSION.length
                               + clientRandom.length()
                               + serverRandom.length()];
        System.arraycopy(KEY_EXPANSION, 0, seed, 0, KEY_EXPANSION.length);
        serverRandom.buffer().get(seed, KEY_EXPANSION.length,
                                  serverRandom.length());
        clientRandom.buffer().get(seed, (KEY_EXPANSION.length
                                         + serverRandom.length()),
                                  clientRandom.length());

        prf = new TLSRandom();
        HashMap<String,byte[]> attr = new HashMap<String,byte[]>(2);
        attr.put(TLSRandom.SECRET, session.privateData.masterSecret);
        attr.put(TLSRandom.SEED, seed);
        prf.init(attr);
      }

    try
      {
        prf.nextBytes(keys[0], 0, keys[0].length);
        prf.nextBytes(keys[1], 0, keys[1].length);
        prf.nextBytes(keys[2], 0, keys[2].length);
        prf.nextBytes(keys[3], 0, keys[3].length);

        if (session.suite.isExportable())
          {
            if (session.version == ProtocolVersion.SSL_3)
              {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.update(clientRandom.buffer());
                md5.update(serverRandom.buffer());
                byte[] d = md5.digest();
                System.arraycopy(d, 0, keys[4], 0, keys[4].length);

                md5.reset();
                md5.update(serverRandom.buffer());
                md5.update(clientRandom.buffer());
                d = md5.digest();
                System.arraycopy(d, 0, keys[5], 0, keys[5].length);

                md5.reset();
                md5.update(keys[2]);
                md5.update(clientRandom.buffer());
                md5.update(serverRandom.buffer());
                keys[2] = Util.trim(md5.digest(), 8);

                md5.reset();
                md5.update(keys[3]);
                md5.update(serverRandom.buffer());
                md5.update(clientRandom.buffer());
                keys[3] = Util.trim(md5.digest(), 8);
              }
            else
              {
                TLSRandom prf2 = new TLSRandom();
                HashMap<String,byte[]> attr = new HashMap<String,byte[]>(2);
                attr.put(TLSRandom.SECRET, keys[2]);
                byte[] seed = new byte[CLIENT_WRITE_KEY.length +
                                       clientRandom.length() +
                                       serverRandom.length()];
                System.arraycopy(CLIENT_WRITE_KEY, 0, seed, 0,
                                 CLIENT_WRITE_KEY.length);
                clientRandom.buffer().get(seed, CLIENT_WRITE_KEY.length,
                                          clientRandom.length());
                serverRandom.buffer().get(seed, CLIENT_WRITE_KEY.length
                                          + clientRandom.length(),
                                          serverRandom.length());
                attr.put(TLSRandom.SEED, seed);
                prf2.init(attr);
                keys[2] = new byte[8];
                prf2.nextBytes(keys[2], 0, keys[2].length);

                attr.put(TLSRandom.SECRET, keys[3]);
                seed = new byte[SERVER_WRITE_KEY.length +
                                serverRandom.length() +
                                clientRandom.length()];
                System.arraycopy(SERVER_WRITE_KEY, 0, seed, 0,
                                 SERVER_WRITE_KEY.length);
                serverRandom.buffer().get(seed, SERVER_WRITE_KEY.length,
                                          serverRandom.length());
                clientRandom.buffer().get(seed, SERVER_WRITE_KEY.length
                                          + serverRandom.length(),
                                          + clientRandom.length());
                attr.put(TLSRandom.SEED, seed);
                prf2.init(attr);
                keys[3] = new byte[8];
                prf2.nextBytes(keys[3], 0, keys[3].length);

                attr.put(TLSRandom.SECRET, new byte[0]);
                seed = new byte[IV_BLOCK.length +
                                clientRandom.length() +
                                serverRandom.length()];
                System.arraycopy(IV_BLOCK, 0, seed, 0, IV_BLOCK.length);
                clientRandom.buffer().get(seed, IV_BLOCK.length,
                                          clientRandom.length());
                serverRandom.buffer().get(seed, IV_BLOCK.length
                                          + clientRandom.length(),
                                          serverRandom.length());
                attr.put(TLSRandom.SEED, seed);
                prf2.init(attr);
                prf2.nextBytes(keys[4], 0, keys[4].length);
                prf2.nextBytes(keys[5], 0, keys[5].length);
              }
          }
        else
          {
            prf.nextBytes(keys[4], 0, keys[4].length);
            prf.nextBytes(keys[5], 0, keys[5].length);
          }
      }
    catch (LimitReachedException lre)
      {
        // Won't happen with our implementation.
        throw new Error(lre);
      }
    catch (NoSuchAlgorithmException nsae)
      {
        throw new Error(nsae);
      }

    if (Debug.DEBUG_KEY_EXCHANGE)
      logger.logv(Component.SSL_KEY_EXCHANGE,
                  "keys generated;\n  [0]: {0}\n  [1]: {1}\n  [2]: {2}\n" +
                  "  [3]: {3}\n  [4]: {4}\n  [5]: {5}",
                  Util.toHexString(keys[0], ':'),
                  Util.toHexString(keys[1], ':'),
                  Util.toHexString(keys[2], ':'),
                  Util.toHexString(keys[3], ':'),
                  Util.toHexString(keys[4], ':'),
                  Util.toHexString(keys[5], ':'));
    return keys;
  }

  /**
   * Generate a "finished" message. The hashes passed in are modified
   * by this function, so they should be clone copies of the digest if
   * the hash function needs to be used more.
   *
   * @param md5 The MD5 computation.
   * @param sha The SHA-1 computation.
   * @param isClient Whether or not the client-side finished message is
   *  being computed.
   * @param session The current session.
   * @return A byte buffer containing the computed finished message.
   */
  protected ByteBuffer generateFinished(MessageDigest md5,
                                        MessageDigest sha,
                                        boolean isClient,
                                        SessionImpl session)
  {
    ByteBuffer finishedBuffer = null;
    if (session.version.compareTo(ProtocolVersion.TLS_1) >= 0)
      {
        finishedBuffer = ByteBuffer.allocate(12);
        TLSRandom prf = new TLSRandom();
        byte[] md5val = md5.digest();
        byte[] shaval = sha.digest();
        if (Debug.DEBUG)
          logger.logv(Component.SSL_HANDSHAKE, "finished md5:{0} sha:{1}",
                      Util.toHexString(md5val, ':'),
                      Util.toHexString(shaval, ':'));
        byte[] seed = new byte[CLIENT_FINISHED.length
                               + md5val.length
                               + shaval.length];
        if (isClient)
          System.arraycopy(CLIENT_FINISHED, 0, seed, 0, CLIENT_FINISHED.length);
        else
          System.arraycopy(SERVER_FINISHED, 0, seed, 0, SERVER_FINISHED.length);
        System.arraycopy(md5val, 0,
                         seed, CLIENT_FINISHED.length,
                         md5val.length);
        System.arraycopy(shaval, 0,
                         seed, CLIENT_FINISHED.length + md5val.length,
                         shaval.length);
        HashMap<String, Object> params = new HashMap<String, Object>(2);
        params.put(TLSRandom.SECRET, session.privateData.masterSecret);
        params.put(TLSRandom.SEED, seed);
        prf.init(params);
        byte[] buf = new byte[12];
        prf.nextBytes(buf, 0, buf.length);
        finishedBuffer.put(buf).position(0);
      }
    else
      {
        // The SSLv3 algorithm is:
        //
        //   enum { client(0x434C4E54), server(0x53525652) } Sender;
        //
        //   struct {
        //     opaque md5_hash[16];
        //     opaque sha_hash[20];
        //   } Finished;
        //
        //   md5_hash       MD5(master_secret + pad2 +
        //                      MD5(handshake_messages + Sender +
        //                          master_secret + pad1));
        //   sha_hash        SHA(master_secret + pad2 +
        //                       SHA(handshake_messages + Sender +
        //                           master_secret + pad1));
        //

        finishedBuffer = ByteBuffer.allocate(36);

        md5.update(isClient ? SENDER_CLIENT : SENDER_SERVER);
        md5.update(session.privateData.masterSecret);
        md5.update(PAD1);

        byte[] tmp = md5.digest();
        md5.reset();
        md5.update(session.privateData.masterSecret);
        md5.update(PAD2);
        md5.update(tmp);
        finishedBuffer.put(md5.digest());

        sha.update(isClient ? SENDER_CLIENT : SENDER_SERVER);
        sha.update(session.privateData.masterSecret);
        sha.update(PAD1, 0, 40);

        tmp = sha.digest();
        sha.reset();
        sha.update(session.privateData.masterSecret);
        sha.update(PAD2, 0, 40);
        sha.update(tmp);
        finishedBuffer.put(sha.digest()).position(0);
      }
    return finishedBuffer;
  }

  protected void initDiffieHellman(DHPrivateKey dhKey, SecureRandom random)
    throws SSLException
  {
    try
      {
        keyAgreement = KeyAgreement.getInstance("DH");
        keyAgreement.init(dhKey, random);
      }
    catch (InvalidKeyException ike)
      {
        throw new SSLException(ike);
      }
    catch (NoSuchAlgorithmException nsae)
      {
        throw new SSLException(nsae);
      }
  }

  protected void generateMasterSecret(Random clientRandom,
                                      Random serverRandom,
                                      SessionImpl session)
    throws SSLException
  {
    assert(clientRandom != null);
    assert(serverRandom != null);
    assert(session != null);

    if (Debug.DEBUG_KEY_EXCHANGE)
      logger.logv(Component.SSL_KEY_EXCHANGE, "preMasterSecret:\n{0}",
                  new ByteArray(preMasterSecret));

    if (session.version == ProtocolVersion.SSL_3)
      {
        try
          {
            MessageDigest _md5 = MessageDigest.getInstance("MD5");
            MessageDigest _sha = MessageDigest.getInstance("SHA");
            session.privateData.masterSecret = new byte[48];

            _sha.update((byte) 'A');
            _sha.update(preMasterSecret);
            _sha.update(clientRandom.buffer());
            _sha.update(serverRandom.buffer());
            _md5.update(preMasterSecret);
            _md5.update(_sha.digest());
            _md5.digest(session.privateData.masterSecret, 0, 16);

            _sha.update((byte) 'B');
            _sha.update((byte) 'B');
            _sha.update(preMasterSecret);
            _sha.update(clientRandom.buffer());
            _sha.update(serverRandom.buffer());
            _md5.update(preMasterSecret);
            _md5.update(_sha.digest());
            _md5.digest(session.privateData.masterSecret, 16, 16);

            _sha.update((byte) 'C');
            _sha.update((byte) 'C');
            _sha.update((byte) 'C');
            _sha.update(preMasterSecret);
            _sha.update(clientRandom.buffer());
            _sha.update(serverRandom.buffer());
            _md5.update(preMasterSecret);
            _md5.update(_sha.digest());
            _md5.digest(session.privateData.masterSecret, 32, 16);
          }
        catch (DigestException de)
          {
            throw new SSLException(de);
          }
        catch (NoSuchAlgorithmException nsae)
          {
            throw new SSLException(nsae);
          }
      }
    else // TLSv1.0 and later
      {
        byte[] seed = new byte[clientRandom.length()
                               + serverRandom.length()
                               + MASTER_SECRET.length];
        System.arraycopy(MASTER_SECRET, 0, seed, 0, MASTER_SECRET.length);
        clientRandom.buffer().get(seed, MASTER_SECRET.length,
                                  clientRandom.length());
        serverRandom.buffer().get(seed,
                                  MASTER_SECRET.length + clientRandom.length(),
                                  serverRandom.length());
        TLSRandom prf = new TLSRandom();
        HashMap<String,byte[]> attr = new HashMap<String,byte[]>(2);
        attr.put(TLSRandom.SECRET, preMasterSecret);
        attr.put(TLSRandom.SEED, seed);
        prf.init(attr);

        session.privateData.masterSecret = new byte[48];
        prf.nextBytes(session.privateData.masterSecret, 0, 48);
      }

    if (Debug.DEBUG_KEY_EXCHANGE)
      logger.log(Component.SSL_KEY_EXCHANGE, "master_secret: {0}",
                 new ByteArray(session.privateData.masterSecret));

    // Wipe out the preMasterSecret.
    for (int i = 0; i < preMasterSecret.length; i++)
      preMasterSecret[i] = 0;
  }

  protected void setupSecurityParameters(byte[][] keys, boolean isClient,
                                         SSLEngineImpl engine,
                                         CompressionMethod compression)
    throws SSLException
  {
    assert(keys.length == 6);
    assert(engine != null);
    assert(compression != null);

    try
      {
        CipherSuite s = engine.session().suite;
        Cipher inCipher = s.cipher();
        Mac inMac = s.mac(engine.session().version);
        Inflater inflater = (compression == CompressionMethod.ZLIB
                             ? new Inflater() : null);
        inCipher.init(Cipher.DECRYPT_MODE,
                      new SecretKeySpec(keys[isClient ? 3 : 2],
                                        s.cipherAlgorithm().toString()),
                      new IvParameterSpec(keys[isClient ? 5 : 4]));
        inMac.init(new SecretKeySpec(keys[isClient ? 1 : 0],
                                     inMac.getAlgorithm()));
        inParams = new InputSecurityParameters(inCipher, inMac,
                                               inflater,
                                               engine.session(), s);

        Cipher outCipher = s.cipher();
        Mac outMac = s.mac(engine.session().version);
        Deflater deflater = (compression == CompressionMethod.ZLIB
                             ? new Deflater() : null);
        outCipher.init(Cipher.ENCRYPT_MODE,
                       new SecretKeySpec(keys[isClient ? 2 : 3],
                                         s.cipherAlgorithm().toString()),
                       new IvParameterSpec(keys[isClient ? 4 : 5]));
        outMac.init(new SecretKeySpec(keys[isClient ? 0 : 1],
                                      outMac.getAlgorithm()));
        outParams = new OutputSecurityParameters(outCipher, outMac,
                                                 deflater,
                                                 engine.session(), s);
      }
    catch (InvalidAlgorithmParameterException iape)
      {
        throw new SSLException(iape);
      }
    catch (InvalidKeyException ike)
      {
        throw new SSLException(ike);
      }
    catch (NoSuchAlgorithmException nsae)
      {
        throw new SSLException(nsae);
      }
    catch (NoSuchPaddingException nspe)
      {
        throw new SSLException(nspe);
      }
  }

  protected void generatePSKSecret(String identity, byte[] otherkey,
                                   boolean isClient)
    throws SSLException
  {
    SecretKey key = null;
    try
      {
        key = engine.contextImpl.pskManager.getKey(identity);
      }
    catch (KeyManagementException kme)
      {
      }
    if (key != null)
      {
        byte[] keyb = key.getEncoded();
        if (otherkey == null)
          {
            otherkey = new byte[keyb.length];
          }
        preMasterSecret = new byte[otherkey.length + keyb.length + 4];
        preMasterSecret[0] = (byte) (otherkey.length >>> 8);
        preMasterSecret[1] = (byte)  otherkey.length;
        System.arraycopy(otherkey, 0, preMasterSecret, 2, otherkey.length);
        preMasterSecret[otherkey.length + 2]
          = (byte) (keyb.length >>> 8);
        preMasterSecret[otherkey.length + 3]
          = (byte)  keyb.length;
        System.arraycopy(keyb, 0, preMasterSecret,
                         otherkey.length + 4, keyb.length);
      }
    else
      {
        // Generate a random, fake secret.
        preMasterSecret = new byte[8];
        preMasterSecret[1] = 2;
        preMasterSecret[5] = 2;
        preMasterSecret[6] = (byte) engine.session().random().nextInt();
        preMasterSecret[7] = (byte) engine.session().random().nextInt();
      }

    if (Debug.DEBUG_KEY_EXCHANGE)
      logger.logv(Component.SSL_KEY_EXCHANGE, "PSK identity {0} key {1}",
                  identity, key);

    generateMasterSecret(clientRandom, serverRandom,
                         engine.session());
    byte[][] keys = generateKeys(clientRandom, serverRandom,
                                 engine.session());
    setupSecurityParameters(keys, isClient, engine, compression);
  }

  protected class DHPhase extends DelegatedTask
  {
    private final DHPublicKey key;
    private final boolean full;

    protected DHPhase(DHPublicKey key)
    {
      this(key, true);
    }

    protected DHPhase(DHPublicKey key, boolean full)
    {
      this.key = key;
      this.full = full;
    }

    protected void implRun() throws InvalidKeyException, SSLException
    {
      keyAgreement.doPhase(key, true);
      preMasterSecret = keyAgreement.generateSecret();
      if (full)
        {
          generateMasterSecret(clientRandom, serverRandom, engine.session());
          byte[][] keys = generateKeys(clientRandom, serverRandom, engine.session());
          setupSecurityParameters(keys, engine.getUseClientMode(), engine, compression);
        }
    }
  }

  protected class CertVerifier extends DelegatedTask
  {
    private final boolean clientSide;
    private final X509Certificate[] chain;
    private boolean verified;

    protected CertVerifier(boolean clientSide, X509Certificate[] chain)
    {
      this.clientSide = clientSide;
      this.chain = chain;
    }

    boolean verified()
    {
      return verified;
    }

    protected void implRun()
    {
      X509TrustManager tm = engine.contextImpl.trustManager;
      if (clientSide)
        {
          try
            {
              tm.checkServerTrusted(chain, null);
              verified = true;
            }
          catch (CertificateException ce)
            {
              if (Debug.DEBUG)
                logger.log(Component.SSL_DELEGATED_TASK, "cert verify", ce);
              // For client connections, ask the user if the certificate is OK.
              CallbackHandler verify = new DefaultCallbackHandler();
              GetSecurityPropertyAction gspa
                = new GetSecurityPropertyAction("jessie.certificate.handler");
              String clazz = AccessController.doPrivileged(gspa);
              try
                {
                  ClassLoader cl =
                    AccessController.doPrivileged(new PrivilegedExceptionAction<ClassLoader>()
                      {
                        public ClassLoader run() throws Exception
                        {
                          return ClassLoader.getSystemClassLoader();
                        }
                      });
                  verify = (CallbackHandler) cl.loadClass(clazz).newInstance();
                }
              catch (Exception x)
                {
                  // Ignore.
                  if (Debug.DEBUG)
                    logger.log(Component.SSL_DELEGATED_TASK,
                               "callback handler loading", x);
                }
              // XXX Internationalize
              CertificateCallback confirm =
                new CertificateCallback(chain[0],
                "The server's certificate could not be verified. There is no proof " +
                "that this server is who it claims to be, or that their certificate " +
                "is valid. Do you wish to continue connecting? ");

              try
                {
                  verify.handle(new Callback[] { confirm });
                  verified = confirm.getSelectedIndex() == ConfirmationCallback.YES;
                }
              catch (Exception x)
                {
                  if (Debug.DEBUG)
                    logger.log(Component.SSL_DELEGATED_TASK,
                               "callback handler exception", x);
                  verified = false;
                }
            }
        }
      else
        {
          try
            {
              tm.checkClientTrusted(chain, null);
            }
          catch (CertificateException ce)
            {
              verified = false;
            }
        }

      if (verified)
        engine.session().setPeerVerified(true);
    }
  }

  protected class DHE_PSKGen extends DelegatedTask
  {
    private final DHPublicKey dhKey;
    private final SecretKey psKey;
    private final boolean isClient;

    protected DHE_PSKGen(DHPublicKey dhKey, SecretKey psKey, boolean isClient)
    {
      this.dhKey = dhKey;
      this.psKey = psKey;
      this.isClient = isClient;
    }

    /* (non-Javadoc)
     * @see gnu.javax.net.ssl.provider.DelegatedTask#implRun()
     */
    @Override protected void implRun() throws Throwable
    {
      keyAgreement.doPhase(dhKey, true);
      byte[] dhSecret = keyAgreement.generateSecret();
      byte[] psSecret = null;
      if (psKey != null)
        psSecret = psKey.getEncoded();
      else
        {
          psSecret = new byte[8];
          engine.session().random().nextBytes(psSecret);
        }

      preMasterSecret = new byte[dhSecret.length + psSecret.length + 4];
      preMasterSecret[0] = (byte) (dhSecret.length >>> 8);
      preMasterSecret[1] = (byte)  dhSecret.length;
      System.arraycopy(dhSecret, 0, preMasterSecret, 2, dhSecret.length);
      preMasterSecret[dhSecret.length + 2] = (byte) (psSecret.length >>> 8);
      preMasterSecret[dhSecret.length + 3] = (byte)  psSecret.length;
      System.arraycopy(psSecret, 0, preMasterSecret, dhSecret.length + 4,
                       psSecret.length);

      generateMasterSecret(clientRandom, serverRandom, engine.session());
      byte[][] keys = generateKeys(clientRandom, serverRandom, engine.session());
      setupSecurityParameters(keys, isClient, engine, compression);
    }
  }
}


text:
'use strict';

var gulp = require('gulp');

var paths = gulp.paths;

var $ = require('gulp-load-plugins')();

var wiredep = require('wiredep').stream,
  series = require('stream-series');

gulp.task('inject', ['styles'], function () {

  var injectStyles = gulp.src([
    paths.tmp + '/serve/{app,components}/**/*.css',
    '!' + paths.tmp + '/serve/app/vendor.css'
  ], { read: false });

  var injectVendor = gulp.src([
    paths.src + '/vendor/**/*.js'
    ], { read: false });

  var injectScripts = gulp.src([
    paths.src + '/{app,components}/**/*.js',
    '!' + paths.src + '/{app,components}/**/*.test.js',
    '!' + paths.src + '/{app,components}/**/*.mock.js'
  ]).pipe($.angularFilesort());

  var injectOptions = {
    ignorePath: [paths.src, paths.tmp + '/serve'],
    addRootSlash: false
  };

  var wiredepOptions = {
    directory: 'bower_components',
    exclude: [/bootstrap\.css/, /foundation\.css/,/font-awesome.css/],
    overrides: {
      angular: {
        dependencies: {
          jquery: '*'
        }
      }
    }
  };

  return gulp.src(paths.src + '/*.html')
    .pipe($.inject(injectStyles, injectOptions))
    .pipe($.inject(series(injectVendor, injectScripts), injectOptions))
    .pipe(wiredep(wiredepOptions))
    .pipe(gulp.dest(paths.tmp + '/serve'));

});


text:
// Fill out your copyright notice in the Description page of Project Settings.

#include "FogMapGenerator.h"
#include "ProjectFog.h"
#include "FogMapDebugVisualizer.h"
#include <queue>

using std::queue;

// Sets default values
AFogMapGenerator::AFogMapGenerator()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

}

// Called when the game starts or when spawned
void AFogMapGenerator::BeginPlay()
{
	Super::BeginPlay();

}

// Called every frame
void AFogMapGenerator::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

void AFogMapGenerator::ResetMap()
{

	if (PointArray3D.Num() != 0)
	{

		//PointArray2D.Empty();
		PointArray3D.Empty();

		if (FogMapGraph != NULL)
		{
			FogMapGraph->ClearMapPoints();
			FogMapGraph = NewObject<UFogPolyMap>();
		}

	}

}

void AFogMapGenerator::InitializeMap()
{
	FogMapGraph = NewObject<UFogPolyMap>();

	//This is done in the BP Constructor
	//PointArray3D.AddDefaulted(NumberOfPoints);
	//UE_LOG(LogFogMap, Log, TEXT("Point Arrays initialized"));
}

void AFogMapGenerator::BuildGraph()
{
	if (FogMapGraph == NULL)
	{
		return;
	}

	if (NumberOfPoints == 0)
	{
		UE_LOG(LogFogMap, Error, TEXT("The number of points is 0, please increase the variable"));
		return;
	}

	if (PointArray3D.Num() == 0)
	{
		UE_LOG(LogFogMap, Error, TEXT("The PointArray3D.Num() == 0 "));
		return;
	}

	/*Changed to Initialize Map

	PointArray3D.AddDefaulted(NumberOfPoints);
	UE_LOG(LogFogMap, Log, TEXT("Point Arrays initialized"));
	*/

	// Place Points, sending vect3d array of points
	FogMapGraph->SetPoints(PointArray3D);

	// Build graph
	FogMapGraph->BuildGraph(MapSizeInCentimeters, FogIslandData.PolygonMapSettings);

	//TODO: The function to improve corners is empty, for now it zeroes the corner point data
	//that's bad!!!
	//FogMapGraph->ImproveCorners();
}

void AFogMapGenerator::InitializeRenderTarget()
{
	//TODO: Create the render target here, instead of doing it in the editor
}

UFogPolyMap* AFogMapGenerator::GetGraph() const
{
	return FogMapGraph;
}

FFogMapCenter AFogMapGenerator::GetCenter(const int32 index) const
{
	return FogMapGraph->GetCenter(index);
}

FFogMapCorner AFogMapGenerator::GetCorner(const int32 index) const
{
	return FogMapGraph->GetCorner(index);
}

FFogMapEdge AFogMapGenerator::GetEdge(const int32 index) const
{
	return FogMapGraph->GetEdge(index);
}

FFogMapEdge AFogMapGenerator::FindEdgeFromCenters(const FFogMapCenter & v0, const FFogMapCenter & v1) const
{
	return FogMapGraph->FindEdgeFromCenters(v0, v1);
}

FFogMapEdge AFogMapGenerator::FindEdgeFromCorners(const FFogMapCorner & v0, const FFogMapCorner & v1) const
{
	return FogMapGraph->FindEdgeFromCorners(v0, v1);
}

int32 AFogMapGenerator::GetCenterNum() const
{
	if (FogMapGraph == NULL)
	{
		return -1;
	}
	return FogMapGraph->GetCenterNum();
}

int32 AFogMapGenerator::GetCornerNum() const
{
	if (FogMapGraph == NULL)
	{
		return -1;
	}
	return FogMapGraph->GetCornerNum();
}

int32 AFogMapGenerator::GetEdgeNum() const
{
	if (FogMapGraph == NULL)
	{
		return -1;
	}
	return FogMapGraph->GetEdgeNum();
}

void AFogMapGenerator::UpdateCenter(const FFogMapCenter & center)
{
	if (FogMapGraph == NULL)
	{
		return;
	}
	FogMapGraph->UpdateCenter(center);
}

void AFogMapGenerator::UpdateCorner(const FFogMapCorner & corner)
{
	if (FogMapGraph == NULL)
	{
		return;
	}
	FogMapGraph->UpdateCorner(corner);
}

void AFogMapGenerator::UpdateEdge(const FFogMapEdge & edge)
{
	if (FogMapGraph == NULL)
	{
		return;
	}
	FogMapGraph->UpdateEdge(edge);
}

void AFogMapGenerator::SetCenterState(const int32 index, EState state) const
{
	FogMapGraph->SetCenterState(index,state);
	FogMapGraph->UpdateCenter(GetCenter(index));
}

void AFogMapGenerator::SetCenterType(const int32 index, EFNodeType type) const
{
	FogMapGraph->SetCenterType(index,type);
	FogMapGraph->UpdateCenter(GetCenter(index));
}

TArray<FFogMapCenter> AFogMapGenerator::GetCentersArray()
{
	return FogMapGraph->GetCentersArray();
}

TArray<FFogMapCorner> AFogMapGenerator::GetCornersArray()
{
	return FogMapGraph->GetCornersArray();
}

void AFogMapGenerator::SetCornerPoint(const int32 index, FVector point) const
{
	FogMapGraph->SetCornerPoint3d(index, point);
	FogMapGraph->UpdateCorner(GetCorner(index));
}

//http://www.redblobgames.com/pathfinding/a-star/introduction.html

TArray<int32> AFogMapGenerator::BreadthFirstSearch(int32 startIndex)
{
	int32 start = startIndex;
	std::queue<int32> frontier;
	frontier.push(start);

	TArray<int32> visited;
	visited.Add(start);

	while(!frontier.empty())
	{
		auto current = frontier.front();
		frontier.pop();

		for (auto next : FogMapGraph->GetCenter(current).Neighbors) {

			if (!visited.Contains(next))// BFS without state
			{
				frontier.push(next);//Queue
				visited.Add(next);//TArray
			}
		}
	}

	return visited;
}

TArray<int32> AFogMapGenerator::BreadthFirstSearchByState(int32 startIndex, EState state)
{
	int32 start = startIndex;
	std::queue<int32> frontier;
	frontier.push(start);

	TArray<int32> visited;
	visited.Add(start);

	while (!frontier.empty())
	{
		auto current = frontier.front();
		frontier.pop();

		for (auto next : FogMapGraph->GetCenter(current).Neighbors) {

			if (!visited.Contains(next) && FogMapGraph->GetCenter(next).CenterState == state)
			{
				frontier.push(next);//Queue
				visited.Add(next);//TArray
			}

		}

	}

	return visited;
}

TMap<int32, int32> AFogMapGenerator::SimplePathSearch(int32 startIndex, EState state)
{
	int32 start = startIndex;
	std::queue<int32> frontier;
	frontier.push(start);

	TMap<int32, int32> came_from;
	came_from[start] = start;

	while (!frontier.empty())
	{
		auto current = frontier.front();
		frontier.pop();

		for (auto next : FogMapGraph->GetCenter(current).Neighbors) {

			if (!came_from.Contains(next) && FogMapGraph->GetCenter(next).CenterState == state)
			{
				frontier.push(next);//Queue
				came_from[next] = current;//TMap
			}
		}

	}

	return came_from;
}

TMap<int32, int32> AFogMapGenerator::SimplePathSearchEarlyExit(int32 startIndex, int32 goalIndex, EState state)
{
	int32 start = startIndex;
	int32 goal = goalIndex;
	std::queue<int32> frontier;
	frontier.push(start);

	TMap<int32, int32> came_from;
	came_from[start] = start;

	while (!frontier.empty())
	{
		auto current = frontier.front();
		frontier.pop();

		if (current == goal)
			{
				break;
			}

		for (auto next : FogMapGraph->GetCenter(current).Neighbors) {

			if (!came_from.Contains(next) && FogMapGraph->GetCenter(next).CenterState == state)
			{
				frontier.push(next);//Queue
				came_from[next] = current;//TMap
			}
		}

	}

	return came_from;
}

void AFogMapGenerator::FinalizeAllPoints()
{
	if (FogMapGraph == NULL)
	{
		return;
	}
	for (int i = 0; i < GetCornerNum(); i++)
	{
		FFogMapCorner corner = GetCorner(i);
		UpdateCorner(corner);
	}

	for (int i = 0; i < GetCenterNum(); i++)
	{
		FFogMapCenter center = GetCenter(i);
		UpdateCenter(center);
	}

	// Compile to get ready to make heightmap pixels
	//FogMapGraph->CompileMapData();
	// Make the initial heightmap
}

void AFogMapGenerator::DrawDelaunayGraph()
{
	if (FogMapGraph == NULL)
	{
		return;
	}
	UFogMapDebugVisualizer::DrawDebugDelaunayGrid(this, FogIslandData.PolygonMapSettings, FogMapGraph->Centers, FogMapGraph->Edges, MapSizeInCentimeters);
}

void AFogMapGenerator::DrawDelaunayGraph3D()
{
	if (FogMapGraph == NULL)
	{
		return;
	}
	UFogMapDebugVisualizer::DrawDebugDelaunayGrid3D(this, FogIslandData.PolygonMapSettings, FogMapGraph->Centers, FogMapGraph->Edges, MapSizeInCentimeters);
}

void AFogMapGenerator::DrawVoronoiGraph()
{
	if (FogMapGraph == NULL)
	{
		return;
	}

	UFogMapDebugVisualizer::DrawDebugVoronoiGrid(this, FogIslandData.PolygonMapSettings, FogMapGraph->Corners, FogMapGraph->Edges, MapSizeInCentimeters);
}

void AFogMapGenerator::DrawVoronoiGraph3D()
{
	if (FogMapGraph == NULL)
	{
		return;
	}
	UFogMapDebugVisualizer::DrawDebugVoronoiGrid3D(this, FogIslandData.PolygonMapSettings, FogMapGraph->Corners, FogMapGraph->Edges, MapSizeInCentimeters);
}

void AFogMapGenerator::ReadRenderTarget(UTextureRenderTarget2D* renderTarget)
{
	if (renderTarget != NULL)
	{
		UE_LOG(LogFogMap, Log, TEXT("The render target is valid"));
	}

}

//For using ALandscapeProxy I had to do two things first,
//first: link #include #include "Landscape.h" #include "LandscapeProxy.h" in the header
//second: in projectFog.Build.cs added PrivateDependencyModuleNames.AddRange(new string[] { "Landscape" });
UMaterialInterface * AFogMapGenerator::GetLandscapeMat(ALandscapeProxy* Landscape)
{
	if (Landscape == nullptr)
	{
		UE_LOG(LogFogMap, Log, TEXT("Landscape proxy is empty!"));
		return nullptr;

	}

	return Landscape->GetLandscapeMaterial();

}


text:
/**
 * Queue implementation.
 */
package co.cask.coopr.common.queue.internal;