text:
'use strict';

var models = require('./index');

/**
 * @class
 * Initializes a new instance of the AutoScaleRun class.
 * @constructor
 * @summary The results and errors from an execution of a pool autoscale
 * formula.
 *
 * @member {date} timestamp The time at which the autoscale formula was last
 * evaluated.
 *
 * @member {string} [results] The final values of all variables used in the
 * evaluation of the autoscale formula. Each variable value is returned in
 * the form $variable=value, and variables are separated by semicolons.
 *
 * @member {object} [error] Details of the error encountered evaluating the
 * autoscale formula on the pool, if the evaluation was unsuccessful.
 *
 * @member {string} [error.code]
 *
 * @member {string} [error.message]
 *
 * @member {array} [error.values]
 *
 */
function AutoScaleRun() {
}

/**
 * Defines the metadata of AutoScaleRun
 *
 * @returns {object} metadata of AutoScaleRun
 *
 */
AutoScaleRun.prototype.mapper = function () {
  return {
    required: false,
    serializedName: 'AutoScaleRun',
    type: {
      name: 'Composite',
      className: 'AutoScaleRun',
      modelProperties: {
        timestamp: {
          required: true,
          serializedName: 'timestamp',
          type: {
            name: 'DateTime'
          }
        },
        results: {
          required: false,
          serializedName: 'results',
          type: {
            name: 'String'
          }
        },
        error: {
          required: false,
          serializedName: 'error',
          type: {
            name: 'Composite',
            className: 'AutoScaleRunError'
          }
        }
      }
    }
  };
};

module.exports = AutoScaleRun;


text:
/**
 * Module dependencies.
 */

var zlib = require('zlib');
var bytes = require('bytes');
var Negotiator = require('negotiator');
var compressible = require('compressible');

/**
 * Supported content-encoding methods.
 */

exports.methods = {
    gzip: zlib.createGzip
  , deflate: zlib.createDeflate
};

/**
 * Default filter function.
 */

exports.filter = function(req, res){
  return compressible(res.getHeader('Content-Type'));
};

/**
 * Compress:
 *
 * Compress response data with gzip/deflate.
 *
 * Filter:
 *
 *  A `filter` callback function may be passed to
 *  replace the default logic of:
 *
 *     exports.filter = function(req, res){
 *       return /json|text|javascript/.test(res.getHeader('Content-Type'));
 *     };
 *
 * Threshold:
 *
 *  Only compress the response if the byte size is at or above a threshold.
 *  Always compress while streaming.
 *
 *   - `threshold` - string representation of size or bytes as an integer.
 *
 * Options:
 *
 *  All remaining options are passed to the gzip/deflate
 *  creation functions. Consult node's docs for additional details.
 *
 *   - `chunkSize` (default: 16*1024)
 *   - `windowBits`
 *   - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression
 *   - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more
 *   - `strategy`: compression strategy
 *
 * @param {Object} options
 * @return {Function}
 * @api public
 */

module.exports = function compress(options) {
  options = options || {};
  var filter = options.filter || exports.filter;
  var threshold;

  if (false === options.threshold || 0 === options.threshold) {
    threshold = 0
  } else if ('string' === typeof options.threshold) {
    threshold = bytes(options.threshold)
  } else {
    threshold = options.threshold || 1024
  }

  return function compress(req, res, next){
    var accept = req.headers['accept-encoding']
      , writeHead = res.writeHead
      , write = res.write
      , end = res.end
      , compress = true
      , stream;

    // see #724
    req.on('close', function(){
      res.write = res.end = function(){};
    });

    // flush is noop by default
    res.flush = noop;

    // proxy

    res.write = function(chunk, encoding){
      if (!this.headerSent) {
        // if content-length is set and is lower
        // than the threshold, don't compress
        var length = res.getHeader('content-length');
        if (!isNaN(length) && length < threshold) compress = false;
        this._implicitHeader();
      }
      return stream
        ? stream.write(new Buffer(chunk, encoding))
        : write.call(res, chunk, encoding);
    };

    res.end = function(chunk, encoding){
      if (chunk) {
        if (!this.headerSent && getSize(chunk) < threshold) compress = false;
        this.write(chunk, encoding);
      } else if (!this.headerSent) {
        // response size === 0
        compress = false;
      }
      return stream
        ? stream.end()
        : end.call(res);
    };

    res.writeHead = function(){
      // default request filter
      if (!filter(req, res)) return writeHead.apply(res, arguments);

      // vary
      var vary = res.getHeader('Vary');
      if (!vary) {
        res.setHeader('Vary', 'Accept-Encoding');
      } else if (!~vary.indexOf('Accept-Encoding')) {
        res.setHeader('Vary', vary + ', Accept-Encoding');
      }

      if (!compress) return writeHead.apply(res, arguments);

      var encoding = res.getHeader('Content-Encoding') || 'identity';

      // already encoded
      if ('identity' != encoding) return writeHead.apply(res, arguments);

      // SHOULD use identity
      if (!accept) return writeHead.apply(res, arguments);

      // head
      if ('HEAD' == req.method) return writeHead.apply(res, arguments);

      // compression method
      var method = new Negotiator(req).preferredEncoding(['gzip', 'deflate', 'identity']);
      // negotiation failed
      if (method === 'identity') return writeHead.apply(res, arguments);

      // compression stream
      stream = exports.methods[method](options);

      // overwrite the flush method
      res.flush = function(){
        stream.flush();
      }

      // header fields
      res.setHeader('Content-Encoding', method);
      res.removeHeader('Content-Length');

      // compression
      stream.on('data', function(chunk){
        write.call(res, chunk);
      });

      stream.on('end', function(){
        end.call(res);
      });

      stream.on('drain', function() {
        res.emit('drain');
      });

      writeHead.apply(res, arguments);
    };

    next();
  };
};

function getSize(chunk) {
  return Buffer.isBuffer(chunk)
    ? chunk.length
    : Buffer.byteLength(chunk);
}

function noop(){}

redpajama_set_name: RedPajamaGithub


text:
Hybrid is an encryption mode that uses symmetric and public key ciphers together.
The approach takes advantage of public key cryptography for sharing keys and
symmetric encryption speed for encrypting messages.

Hybrid mode allows you to encrypt a message for one or more receivers, and can
be used in multi-user scenarios where you wish to limit decryption to specific
users.

## How it works

Suppose we have two users: *Alice* and *Bob*. *Alice* wants to send a message to *Bob*
using a hybrid cryptosystem, she needs to:

- Obtain *Bob*'s public key;
- Generates a random session key (one-time pad);
- Encrypts message using a symmetric cipher with the previous session key;
- Encrypts session key using the *Bob*'s public key;
- Sends both the encrypted message and encrypted session key to *Bob*.

A schema of the encryption is reported in the image below:

![Encryption schema](images/zend.crypt.hybrid.png)

To decrypt the message, *Bob* needs to:

- Uses his private key to decrypt the session key;
- Uses this session key to decrypt the message.

## Example of usage

In order to use the `Zend\Crypt\Hybrid` component, you need to have a keyring of
public and private keys. To encrypt a message, use the following code:

```php
use Zend\Crypt\Hybrid;
use Zend\Crypt\PublicKey\RsaOptions;

// Generate public and private key
$rsaOptions = new RsaOptions([
    'pass_phrase' => 'test'
]);
$rsaOptions->generateKeys([
    'private_key_bits' => 4096
]);
$publicKey  = $rsaOptions->getPublicKey();
$privateKey = $rsaOptions->getPrivateKey();

$hybrid     = new Hybrid();
$ciphertext = $hybrid->encrypt('message', $publicKey);
$plaintext  = $hybrid->decrypt($ciphertext, $privateKey);

printf($plaintext === 'message' ? "Success\n" : "Error\n");
```

We generated the keys using the [Zend\Crypt\PublicKey\RsaOptions](public-key.md)
component. You can also use a [PEM](https://en.wikipedia.org/wiki/Privacy-enhanced_Electronic_Mail)
string for the keys. If you use a string for the private key, you need to pass
the pass phrase to use when decrypting, if present, like in the following example:

```php
use Zend\Crypt\Hybrid;
use Zend\Crypt\PublicKey\RsaOptions;

// Generate public and private key
$rsaOptions = new RsaOptions([
    'pass_phrase' => 'test'
]);
$rsaOptions->generateKeys([
    'private_key_bits' => 4096
]);
// Strings in PEM format
$publicKey  = $rsaOptions->getPublicKey()->toString();
$privateKey = $rsaOptions->getPrivateKey()->toString();

$hybrid     = new Hybrid();
$ciphertext = $hybrid->encrypt('message', $publicKey);
$plaintext  = $hybrid->decrypt($ciphertext, $privateKey, 'test'); // pass-phrase

printf($plaintext === 'message' ? "Success\n" : "Error\n");
```

The `Hybrid` component uses `Zend\Crypt\BlockCipher` for the symmetric
cipher and `Zend\Crypt\Rsa` for the public-key cipher.

## Encrypt with multiple keys

The `Zend\Crypt\Hybrid` component can be used to encrypt a message for multiple
users, using a keyring of identifiers and public keys. This keyring can be
specified using an array of `[ 'id' => 'publickey' ]`, where `publickey` can be
a string (PEM) or an instance of `Zend\Crypt\PublicKey\Rsa\PublicKey`. The `id`
can be any string, for example, a receipient email address.

The following details encryption using a keyring with 4 keys:

```php
use Zend\Crypt\Hybrid;
use Zend\Crypt\PublicKey\RsaOptions;

$publicKeys  = [];
$privateKeys = [];
for ($id = 0; $id < 4; $id++) {
    $rsaOptions = new RsaOptions([
        'pass_phrase' => "test-$id"
    ]);
    $rsaOptions->generateKeys([
        'private_key_bits' => 4096
    ]);
    $publicKeys[$id]  = $rsaOptions->getPublicKey();
    $privateKeys[$id] = $rsaOptions->getPrivateKey();
}

$hybrid    = new Hybrid();
$encrypted = $hybrid->encrypt('message', $publicKeys);
for ($id = 0; $id < 4; $id++) {
    $plaintext = $hybrid->decrypt($encrypted, $privateKeys[$id], null, $id);
    printf($plaintext === 'message' ? "Success on %d\n" : "Error on %d\n", $id);
}
```


text:
<?php
namespace frontend\models;
use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;

use yii\base\Model;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

class UserForm extends Model{
    public $name;
    public $email;

    public function rules(){
        return [
            [['name','email'],'required'],
                ['email','email'],
            ];
    }
}


text:
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License.  See License.txt in the project root for license information.

using System.Diagnostics.CodeAnalysis;
using Microsoft.Data.Edm;

namespace System.Web.Http.OData.Builder
{
    /// <summary>
    /// Represents an EdmType
    /// </summary>
    public interface IEdmTypeConfiguration
    {
        /// <summary>
        /// The CLR type associated with the EdmType.
        /// </summary>
        Type ClrType { get; }

        /// <summary>
        /// The fullname (including namespace) of the EdmType.
        /// </summary>
        string FullName { get; }

        /// <summary>
        /// The namespace of the EdmType.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Namespace", Justification = "Namespace matches the EF naming scheme")]
        string Namespace { get; }

        /// <summary>
        /// The name of the EdmType.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// The kind of the EdmType.
        /// Examples include EntityType, ComplexType, PrimitiveType, CollectionType.
        /// </summary>
        EdmTypeKind Kind { get; }

        /// <summary>
        /// The ODataModelBuilder used to create this IEdmType.
        /// </summary>
        ODataModelBuilder ModelBuilder { get; }
    }
}


text:
package healthcheck

import (
	"errors"
	"testing"

	"github.com/premkit/healthcheck/result"

	"github.com/hashicorp/go-multierror"
	"github.com/stretchr/testify/assert"
)

// Some mock types to make this testable.
type HealthcheckStepEmpty struct{}

func (h HealthcheckStepEmpty) RunSynchronously() result.HealthcheckStepResult {
	return HealthcheckStepResultEmpty{}
}

type HealthcheckStepResultEmpty struct{}

func (h HealthcheckStepResultEmpty) Status() result.HealthcheckResponse {
	return result.HealthcheckResponseAvailable
}

// The tests
func TestValidateHealthcheckNoChecks(t *testing.T) {
	healthcheck := &Healthcheck{
		Name: "Name",
	}

	err := validateHealthcheck(healthcheck)
	assert.NotNil(t, err)

	multiError := err.(*multierror.Error)
	assert.Equal(t, 1, len(multiError.Errors))
	assert.Equal(t, errors.New("At least one step is required"), multiError.Errors[0])
}

func TestValidateHealthcheckNoNameNoChecks(t *testing.T) {
	healthcheck := &Healthcheck{}

	err := validateHealthcheck(healthcheck)
	assert.NotNil(t, err)

	multiError := err.(*multierror.Error)
	assert.Equal(t, 2, len(multiError.Errors))
	assert.Equal(t, errors.New("Name is required"), multiError.Errors[0])
	assert.Equal(t, errors.New("At least one step is required"), multiError.Errors[1])
}

func TestCreateHealthcheckEmpty(t *testing.T) {
	healthcheck := Healthcheck{
		Name: "Empty",
	}

	o, err := CreateOrUpdateHealthcheck(&healthcheck)
	assert.Nil(t, o)
	assert.NotNil(t, err)

	multiError := err.(*multierror.Error)
	assert.Equal(t, 1, len(multiError.Errors))
}


text:
<?php

namespace Cysha\Casino\Holdem\Tests\Game;

use Cysha\Casino\Game\Chips;
use Cysha\Casino\Game\Client;
use Cysha\Casino\Game\Contracts\Game;
use Cysha\Casino\Holdem\Game\CashGame;
use Cysha\Casino\Holdem\Game\Parameters\CashGameParameters;
use PHPUnit_Framework_TestCase as PHPUnit;
use Ramsey\Uuid\Uuid;

class BaseGameTestCase extends PHPUnit
{
    /**
     * @param int $playerCount
     *
     * @return Game
     */
    public function createGenericGame($playerCount = 4): Game
    {
        $players = [];
        for ($i = 0; $i < $playerCount; ++$i) {
            $players[] = Client::register(Uuid::uuid4(), 'player' . ($i + 1), Chips::fromAmount(5500));
        }

        $gameRules = new CashGameParameters(Uuid::uuid4(), Chips::fromAmount(50), null, 9, Chips::fromAmount(500));

        // we got a game
        $game = CashGame::setUp(Uuid::uuid4(), 'Demo Cash Game', $gameRules);

        // register clients to game
        foreach ($players as $player) {
            $game->registerPlayer($player, Chips::fromAmount(1000));
        }

        $game->assignPlayersToTables(); // table has max of 9 or 5 players in holdem

        return $game;
    }
}


text:
<?php

namespace Application;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Application\View\Helper\AbsoluteUrl;
use Application\View\Helper\DetectMobile;
use Application\View\Helper\GetPath;
use Application\View\Helper\GetRole;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $e->getApplication()->getServiceManager()->get('translator');
        $e->getApplication()->getServiceManager()->get('viewhelpermanager')->setFactory('controllerName', function($sm) use ($e) {

            $viewHelper = new View\Helper\ControllerName($e->getRouteMatch());
            return $viewHelper;
        });
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getViewHelperConfig()
    {
        return array(
            'factories' => array(
                // the array key here is the name you will call the view helper by in your view scripts
                'absoluteUrl' => function($sm) {
                    $locator = $sm->getServiceLocator(); // $sm is the view helper manager, so we need to fetch the main service manager
                    return new AbsoluteUrl($locator->get('Request'));
                },
                'detectMobile' => function($sm) {
                    $locator = $sm->getServiceLocator(); // $sm is the view helper manager, so we need to fetch the main service manager
                    return new DetectMobile();
                },
                'getPath' => function($sm) {
                	$locator = $sm->getServiceLocator(); // $sm is the view helper manager, so we need to fetch the main service manager
                    return new GetPath();
                },
                'getRole' => function($sm){
                	$locator = $sm->getServiceLocator(); // $sm is the view helper manager, so we need to fetch the main service manager
                    return new GetRole();

                }

            ),
        );
    }

}


text:
namespace mtl {

namespace functor {

    template <unsigned MaxDepth, typename Value, typename Cursor1, typename Prop1, typename Cursor2, typename Prop2, unsigned Depth>
    struct cursor_pseudo_dot_block
    {
	static unsigned const offset= MaxDepth - Depth;

	void operator() (Cursor1 i1, Prop1& prop1, Cursor2 i2, Prop2& prop2,
			 Value& s0, Value& s1, Value& s2, Value& s3,
			 Value& s4, Value& s5, Value& s6, Value& s7)
	{
	    Cursor1 tmp1(i1); tmp1+= offset;
	    Cursor2 tmp2(i2); tmp2+= offset;
	    s0+= prop1(*tmp1) * prop2(*tmp2);
	    // s0+= prop1(i1 + offset) * prop2(i2 + offset);
	    typedef cursor_pseudo_dot_block<MaxDepth, Value, Cursor1, Prop1, Cursor2, Prop2, Depth-1> block_rest;
	    block_rest() (i1, prop1, i2, prop2, s1, s2, s3, s4, s5, s6, s7, s0);
	}
    };

    //template <>
    template <unsigned MaxDepth, typename Value, typename Cursor1, typename Prop1, typename Cursor2, typename Prop2>
    struct cursor_pseudo_dot_block<MaxDepth, Value, Cursor1, Prop1, Cursor2, Prop2, 1>
    {
	static unsigned const offset= MaxDepth - 1;

	void operator() (Cursor1 i1, Prop1& prop1, Cursor2 i2, Prop2& prop2,
			 Value& s0, Value&, Value&, Value&,
			 Value&, Value&, Value&, Value&)
	{
	    s0+= prop1(*(i1 + offset)) * prop2(*(i2 + offset));
	}
    };

    template <unsigned MaxDepth, typename Value, typename Cursor1, typename Prop1, typename Cursor2, typename Prop2>
    struct cursor_pseudo_dot_t
    {
	Value operator() (Cursor1 i1, Cursor1 end1, Prop1& prop1, Cursor2 i2, Prop2& prop2)
	{
	    using math::zero;
	    Value         ref, my_zero(zero(ref)),
                          s0= my_zero, s1= my_zero, s2= my_zero, s3= my_zero,
		          s4= my_zero, s5= my_zero, s6= my_zero, s7= my_zero;
	    std::size_t size= end1 - i1, blocks= size / MaxDepth, blocked_size= blocks * MaxDepth;

	    typedef cursor_pseudo_dot_block<MaxDepth, Value, Cursor1, Prop1, Cursor2, Prop2, MaxDepth> dot_block_type;
	    for (unsigned i= 0; i < blocked_size; i+= MaxDepth, i1+= MaxDepth, i2+= MaxDepth) {
		dot_block_type()(i1, prop1, i2, prop2, s0, s1, s2, s3, s4, s5, s6, s7);
	    }

	    typedef cursor_pseudo_dot_block<MaxDepth, Value, Cursor1, Prop1, Cursor2, Prop2, MaxDepth> dot_single_type;
	    s0+= s1 + s2 + s3 + s4 + s5 + s6 + s7;
	    for (unsigned i= blocked_size; i < size; ++i, ++i1, ++i2)
		dot_single_type()(i1, prop1, i2, prop2, s0, s1, s2, s3, s4, s5, s6, s7);
	    return s0;
	}
    };

} // namespace functor

template <unsigned MaxDepth, typename Value, typename Cursor1, typename Prop1, typename Cursor2, typename Prop2>
Value cursor_pseudo_dot(Cursor1 i1, Cursor1 end1, Prop1 prop1, Cursor2 i2, Prop2 prop2, Value)
{
    return functor::cursor_pseudo_dot_t<MaxDepth, Value, Cursor1, Prop1, Cursor2, Prop2>()(i1, end1, prop1, i2, prop2);
}

} // namespace mtl

#endif // MTL_CURSOR_PSEUDO_DOT_INCLUDE


text:
package org.apache.camel.component.aws2.cw;

import java.time.Instant;

import org.apache.camel.BindToRegistry;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.StandardUnit;

public class CwComponentTest extends CamelTestSupport {

    @BindToRegistry("now")
    private static final Instant NOW = Instant.now();

    private static final Instant LATER = Instant.ofEpochMilli(NOW.getNano() + 1);

    @BindToRegistry("amazonCwClient")
    private CloudWatchClient cloudWatchClient = new CloudWatchClientMock();

    @EndpointInject("mock:result")
    private MockEndpoint mock;

    @Test
    public void sendMetricFromHeaderValues() throws Exception {
        mock.expectedMessageCount(1);
        template.send("direct:start", new Processor() {
            public void process(Exchange exchange) {
                exchange.getIn().setHeader(Cw2Constants.METRIC_NAMESPACE, "camel.apache.org/overriden");
                exchange.getIn().setHeader(Cw2Constants.METRIC_NAME, "OverridenMetric");
                exchange.getIn().setHeader(Cw2Constants.METRIC_VALUE, Double.valueOf(3));
                exchange.getIn().setHeader(Cw2Constants.METRIC_UNIT, StandardUnit.BYTES.toString());
                exchange.getIn().setHeader(Cw2Constants.METRIC_TIMESTAMP, LATER);
            }
        });

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("direct:start").to(
                        "aws2-cw://camel.apache.org/test?amazonCwClient=#amazonCwClient&name=testMetric&unit=BYTES&timestamp=#now")
                        .to("mock:result");
            }
        };
    }
}


text:
package com.orientechnologies.orient.core.command.script.formatter;

import com.orientechnologies.orient.core.metadata.function.OFunction;

/**
 * Javascript script formatter.
 *
 * @author Luca Garulli
 *
 */
public class OJSScriptFormatter implements OScriptFormatter {
  public String getFunctionDefinition(final OFunction f) {

    final StringBuilder fCode = new StringBuilder();
    fCode.append("function ");
    fCode.append(f.getName());
    fCode.append('(');
    int i = 0;
    if (f.getParameters() != null)
      for (String p : f.getParameters()) {
        if (i++ > 0)
          fCode.append(',');
        fCode.append(p);
      }
    fCode.append(") {\n");
    fCode.append(f.getCode());
    fCode.append("\n}\n");

    return fCode.toString();
  }

  @Override
  public String getFunctionInvoke(final OFunction iFunction, final Object[] iArgs) {
    final StringBuilder code = new StringBuilder();

    code.append(iFunction.getName());
    code.append('(');
    if (iArgs != null) {
      int i = 0;
      for (Object a : iArgs) {
        if (i++ > 0)
          code.append(',');
        code.append(a);
      }
    }
    code.append(");");

    return code.toString();
  }
}


text:
package org.apache.activemq.artemis.core.config.impl;

import java.util.List;

import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.config.FileDeploymentManager;
import org.apache.activemq.artemis.core.config.amqpBrokerConnectivity.AMQPBrokerConnectConfiguration;
import org.junit.Assert;
import org.junit.Test;

public class FileConfigurationBrokerConnectionEncryptedTest extends ConfigurationImplTest {

   protected String getConfigurationName() {
      return "ConfigurationTest-broker-connection-encrypted-config.xml";
   }

   @Override
   @Test
   public void testDefaults() {
      // empty
   }

   @Test
   public void testAMQPBrokerConfigEncryptedUserAndPassword() {

      List<AMQPBrokerConnectConfiguration> brokerConnections = conf.getAMQPConnection();
      Assert.assertNotNull("brokerConnections is null", brokerConnections);
      Assert.assertFalse("brokerConnections is empty", brokerConnections.isEmpty());

      boolean encTest = false;
      boolean plainTest = false;
      boolean emptyTest = false;

      for (AMQPBrokerConnectConfiguration brokerConnection : brokerConnections) {
         // Check each expected configuration is present
         encTest = encTest || "enc-test".equals(brokerConnection.getName());
         plainTest = plainTest || "plain-test".equals(brokerConnection.getName());
         emptyTest = emptyTest || "empty-test".equals(brokerConnection.getName());

         if ("empty-test".equals(brokerConnection.getName())) {

            // Empty configuration should have null user and password
            Assert.assertNull(brokerConnection.getUser());
            Assert.assertNull(brokerConnection.getPassword());

         } else {

            // Both the encrypted and plain user and password use the same expected value
            Assert.assertEquals("testuser", brokerConnection.getUser());
            Assert.assertEquals("testpassword", brokerConnection.getPassword());

         }
      }

      Assert.assertTrue("enc-test configuration is not present", encTest);
      Assert.assertTrue("plain-test configuration is not present", plainTest);
      Assert.assertTrue("empty-test configuration is not present", emptyTest);

   }

   @Override
   protected Configuration createConfiguration() throws Exception {
      FileConfiguration fc = new FileConfiguration();
      FileDeploymentManager deploymentManager = new FileDeploymentManager(getConfigurationName());
      deploymentManager.addDeployable(fc);
      deploymentManager.readConfiguration();
      return fc;
   }

}


text:
layout: post
title:  "Core Plot的使用(一):基础篇"
tags: [iOS 笔记]
---
在iOS开发中,在展示统计数据的时候,时常会选择柱状图、线形图、饼状图的表现方式。而Core Plot就是一个用来绘制这些统计图的开源库。
在开始了解Core Plot这个库之前,要清楚Core Plot不仅可以用于iOS平台,也可以用于Mac OS X平台,所以呢,就会有一些限制:不能使用 *AppKit*。而*UIView* 相关的操作只能在 *CPTGraphHostingView* 中进行。绘图的实现使用了底层的 *Quartz 2D API*,并且使用 *Core Animation* 来创建 *layer* 层视图。
先通过一张图了解一下Core Plot库中主要类的层次结构:
![Core Plot库中类层次结构.png](/assets/article_images/2018-11-16-Core Plot的使用(一):基础篇01.png)
Core Plot库中主要类在视图中的层级关系:
![Core Plot库中类在视图中对应的层级关系.png](/assets/article_images/2018-11-16-Core Plot的使用(一):基础篇02.png)
Core Plot库中主要类在视图中的位置:
![Core Plot库中类在视图中的位置.png](/assets/article_images/2018-11-16-Core Plot的使用(一):基础篇03.png)

#### • Layers
*Core Plot* 声明了一个继承于 *CALayer* 的类 *CPTLayer*,这个类包含了绘制复杂的矢量图的方法和一些事件处理方法。
```OC
// 绘图方法
-(void)renderAsVectorInContext:(CGContextRef)context;
-(void)recursivelyRenderInContext:(CGContextRef)context;
-(NSData *)dataForPDFRepresentationOfLayer;
```
当继承 *CPTLayer*,需要重写方法 <code>-renderAsVectorInContext:</code> 来绘制矢量图。

#### • Graphs
*Core Plot* 中最核心的类是 *CPTGraph*,是一个包含了 *CPTAxisSet、CPTPlotArea、CPTPlotSpace* 等属性的抽象类,而 *CPTXYGraph* 就是它的子类。
```Objective-C
@interface CPTGraph : CPTBorderedLayer
    @property (nonatomic, readwrite, copy) NSString *title;
    @property (nonatomic, readwrite, copy) CPTTextStyle *titleTextStyle;
    @property (nonatomic, readwrite, assign) CGPoint titleDisplacement;
    @property (nonatomic, readwrite, assign) CPTRectAnchor titlePlotAreaFrameAnchor;

    @property (nonatomic, readwrite, retain) CPTAxisSet *axisSet;
    @property (nonatomic, readwrite, retain) CPTPlotAreaFrame *plotAreaFrame;
    @property (nonatomic, readonly, retain) CPTPlotSpace *defaultPlotSpace;
    @property (nonatomic, readwrite, retain) NSArray *topDownLayerOrder;

    @property (nonatomic, readwrite, retain) CPTLegend *legend;
    @property (nonatomic, readwrite, assign) CPTRectAnchor legendAnchor;
    @property (nonatomic, readwrite, assign) CGPoint legendDisplacement;

    -(void)reloadData;
    -(void)reloadDataIfNeeded;

    -(NSArray *)allPlots;
    -(CPTPlot *)plotAtIndex:(NSUInteger)index;
    -(CPTPlot *)plotWithIdentifier:(id <NSCopying>)identifier;

    -(void)addPlot:(CPTPlot *)plot;
    -(void)addPlot:(CPTPlot *)plot toPlotSpace:(CPTPlotSpace *)space;
    -(void)removePlot:(CPTPlot *)plot;
    -(void)removePlotWithIdentifier:(id <NSCopying>)identifier;
    -(void)insertPlot:(CPTPlot *)plot atIndex:(NSUInteger)index;
    -(void)insertPlot:(CPTPlot *)plot atIndex:(NSUInteger)index intoPlotSpace:(CPTPlotSpace *)space;

    -(NSArray *)allPlotSpaces;
    -(CPTPlotSpace *)plotSpaceAtIndex:(NSUInteger)index;
    -(CPTPlotSpace *)plotSpaceWithIdentifier:(id <NSCopying>)identifier;

    -(void)addPlotSpace:(CPTPlotSpace *)space;
    -(void)removePlotSpace:(CPTPlotSpace *)plotSpace;

    -(void)applyTheme:(CPTTheme *)theme;
@end
```
#### • Plot Area
*Plot Area* 是展示数据的区域(柱状图、线形图、饼状图等)。每个 *graph* 有且仅有一个 *plot area*,即 *CPTGraph* 中的 *CPTPlotArea* 属性。而在 *Plot Area* 外边还有一个 *CPTPlotAreaFrame* ,它的作用就是设置 *plot area* 的外边距。
#### • Plot Spaces
*Plot Space* 定义了 *plot area* 中坐标系与数据之间的映射关系。一个 *CPTPlotSpace* 的子类必须包含物理坐标(即View上的坐标点)与数据坐标相互转换的方法。
```Objective-C
-(CGPoint)plotAreaViewPointForPlotPoint:(NSDecimal *)plotPoint;
-(CGPoint)plotAreaViewPointForDoublePrecisionPlotPoint:(double *)plotPoint;
-(void)plotPoint:(NSDecimal *)plotPoint forPlotAreaViewPoint:(CGPoint)point;
-(void)doublePrecisionPlotPoint:(double *)plotPoint forPlotAreaViewPoint:(CGPoint)point;
```
*plot space* 决定了每个 *CPTPlot* 将会绘制在 *plot area* 中的哪些位置上。每个 *CPTPlot* 都关联着一个 *plot space*,而一个 *graph* 可以包含多个 *CPTPlot*,比如一个线形图可以有多条线形,或者是一个图表里面既有柱状图又有线形图。
#### • Plots
*Plot* 就是数据在图表上的呈现。它和 *UITableView* 有点类似,同样需要设置 *dataSource*,通过实现 *CPTPlotDataSource* 代理的方法完成数据解析绘制成图表。
```Objective-C
@protocol CPTPlotDataSource <NSObject>

-(NSUInteger)numberOfRecords;

@optional

// Implement one of the following
-(NSArray *)numbersForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange;
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index;

@end
```
可以理解 *field* 相当于一个 *tableView*,而 *recoreIndex* 就相当于 *tableView* 中的 *indexPath.row*。比如说 *CPTScatterPlot*,一个坐标点相当于 *tableView* 中的 *indexPath.row*,而一个坐标点又是由 *x* 值和 *y* 值组成。
```Objective-C
typedef enum _CPTScatterPlotField {
    CPTScatterPlotFieldX,
    CPTScatterPlotFieldY
} CPTScatterPlotField;
```
根据 *CPTScatterPlotField* 的枚举值,在代理方法中将相应的 *x* 值和 *y* 值返回。
*plot* 不仅可以使用 *CPTPlotDataSource* 代理方法,还可以用数据绑定的方式。
```Objective-C
CPTGraph *graph = ...;
CPTScatterPlot *boundLinePlot = [[[CPTScatterPlot alloc] initWithFrame:CGRectZero] autorelease];
boundLinePlot.identifier = @"Bindings Plot";
boundLinePlot.dataLineStyle.lineWidth = 2.f;
[graph addPlot:boundLinePlot];
[boundLinePlot bind:CPTScatterPlotBindingXValues toObject:self withKeyPath:@"arrangedObjects.x" options:nil];
[boundLinePlot bind:CPTScatterPlotBindingYValues toObject:self withKeyPath:@"arrangedObjects.y" options:nil];
```
#### • Axis
*Axis* 就是图表中的坐标轴(刻度尺标题、坐标轴标题)。一般一个图标会有两个 *Axis*,即 *CPTAxis*,这些 *axis* 都包含在 * CPTAxisSet* 中。而刻度尺标题则通过 *CPTAxisLabel* 来实现。

相关文章:
[Core Plot的使用(二):柱状图](http://blog.wangjace.site/2018/11/Core-Plot%E7%9A%84%E4%BD%BF%E7%94%A8(%E4%BA%8C)-%E6%9F%B1%E7%8A%B6%E5%9B%BE/)
[Core Plot的使用(三):线形图](http://blog.wangjace.site/2018/11/Core-Plot%e7%9a%84%e4%bd%bf%e7%94%a8(%e4%b8%89)-%e7%ba%bf%e5%bd%a2%e5%9b%be/)

参考:[Core-Plot High Level Design Overview](https://github.com/core-plot/core-plot/wiki/High-Level-Design-Overview)


text:
/**
 * Created by Jerry on 2016/11/25.
 */
"use strict";
var ReportForm = (function () {
    function ReportForm() {
    }
    return ReportForm;
}());
exports.ReportForm = ReportForm;
//# sourceMappingURL=report-form.js.map


text:
'use strict';

module.exports = exports;
module.exports.__cmd = require('./cmd');

/**
 * @param whaler
 */
async function exports (whaler) {

    whaler.on('run', async ctx => {
        let appName = ctx.options['ref'];
        let serviceName = null;

        const parts = ctx.options['ref'].split('.');
        if (2 == parts.length) {
            appName = parts[1];
            serviceName = parts[0];
        }

        if (!serviceName) {
            throw new Error('Command requires to specify a service name.');
        }

        const { default: docker } = await whaler.fetch('docker');
        // const { default: storage } = await whaler.fetch('apps');
        // const app = await storage.get(appName);

        // await docker.listContainers({
        //     all: false,
        //     filters: JSON.stringify({
        //         name: [
        //             docker.util.nameFilter(appName)
        //         ]
        //     })
        // });

        const attachStdin = ctx.options['stdin'];
        const serviceContainer = docker.getContainer(serviceName + '.' + appName);

        let info;
        try {
            info = await serviceContainer.inspect();
        } catch (e) {
            await whaler.emit('create', {
                ref: serviceName + '.' + appName
            });
            info = await serviceContainer.inspect();
        }

        if ('string' === typeof ctx.options['cmd']) {
            const hasEntrypoint = !!info['Config']['Entrypoint'] && info['Config']['Entrypoint'].length && ctx.options['entrypoint'];
            if (hasEntrypoint) {
                ctx.options['cmd'] = docker.util.parseCmd(ctx.options['cmd']);
            } else {
                ctx.options['cmd'] = ['/bin/sh', '-c', ctx.options['cmd']];
            }
        }

        let nameSuffix;
        if (ctx.options['detach'] || false) {
            nameSuffix = '_detached_' + process.pid;
        } else {
            nameSuffix = '_pty_' + process.pid;
        }

        const createOpts = {
            'name': serviceName + '.' + appName + nameSuffix,
            'Hostname': '',
            'Cmd': ctx.options['cmd'],
            'Env': (info['Config']['Env'] || []).concat(ctx.options['env'] || []),
            'Labels': {},
            'Image': info['Config']['Image'],
            'WorkingDir': info['Config']['WorkingDir'],
            'Entrypoint': false === ctx.options['entrypoint'] ? [] : info['Config']['Entrypoint'],
            'StdinOnce': false,
            'AttachStdin': attachStdin,
            'AttachStdout': true,
            'AttachStderr': true,
            'OpenStdin': attachStdin,
            'Tty': ctx.options['tty'],
            'HostConfig': {
                'AutoRemove': true,
                'ExtraHosts': info['HostConfig']['ExtraHosts'],
                'Binds': info['HostConfig']['Binds'],
                'VolumesFrom': info['HostConfig']['VolumesFrom']
            }
        };

        const startOpts = {};

        const container = await docker.createContainer(createOpts);

        let whalerNetwork = docker.getNetwork('whaler_nw');
        await whalerNetwork.connect({
            'Container': container.id
        });

        let appNetwork = docker.getNetwork('whaler_nw.' + appName);
        await appNetwork.connect({
            'Container': container.id
        });

        container.run = async () => {
            let err = null;
            let data = null;

            if (ctx.options['detach'] || false) {
                try {
                    await container.start(startOpts);
                    data = await container.inspect();
                } catch (e) {
                    err = e;
                }

            } else {
                let revertPipe = () => {};
                let revertResize = () => {};

                try {
                    const stream = await container.attach({
                        stream: true,
                        stdin: attachStdin,
                        stdout: true,
                        stderr: true
                    });

                    revertPipe = await pipe(stream, attachStdin, ctx.options['tty']);

                    await container.start(startOpts);

                    if (ctx.options['tty']) {
                        revertResize = docker.util.resizeTTY(container);
                    }

                    data = await container.wait();
                } catch (e) {
                    err = e;
                }

                revertPipe();
                revertResize();
            }

            if (err) {
                throw err;
            }

            return data;
        };

        container.exit = async () => {
            try {
                await container.remove({
                    v: true,
                    force: true
                });
            } catch (e) {}
        };

        ctx.result = container;
    });

    // PRIVATE

    const pipe = async (stream, attachStdin, tty) => {
        let unpipeStream = () => {};

        if (tty) {
            stream.setEncoding('utf8');
            stream.pipe(process.stdout, { end: false });
            unpipeStream = () => {
                stream.unpipe(process.stdout);
            };
        } else {
            (await whaler.fetch('docker')).default.modem.demuxStream(stream, process.stdout, process.stderr);
        }

        const CTRL_ALT_C = '\u001B\u0003';
        const isRaw = process.isRaw;
        const keyPress = (key) => {
            if (key === CTRL_ALT_C) {
                whaler.kill('SIGINT');
            }
        };

        if (attachStdin) {
            process.stdin.resume();
            process.stdin.setRawMode(true);
            process.stdin.pipe(stream);
            process.stdin.on('data', keyPress);
        }

        return function revert () {
            if (stream.end) {
                stream.end();
            }

            unpipeStream();

            if (attachStdin) {
                process.stdin.removeListener('data', keyPress);
                process.stdin.unpipe(stream);
                process.stdin.setRawMode(isRaw);
                process.stdin.resume();
                process.stdin.pause();
            }
        }
    };
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace ClassesAndInterfaces
{
    public class WeaponMemoryRepository : IWeaponRepository
    {
        private List<Weapon> weapons;
        public WeaponMemoryRepository()
        {
            weapons = new List<Weapon>() {
                new Weapon() {
                    WeaponId = 1,
                    Name = "Sword",
                    Damage = "1d10"
                },
                new Weapon() {
                    WeaponId = 2,
                    Name = "Axe",
                    Damage = "1d12"
                }
            };
        }

        #region IWeaponRepository implementation

        public IEnumerable<Weapon> GetAll()
        {
            return weapons;
        }

        public Weapon GetWeapon(int weaponId)
        {
            return weapons.First(x => x.WeaponId == weaponId);
        }

        #endregion
    }
}


text:
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Queries;

namespace ScoresApp.UITests
{
	[TestFixture (Platform.Android)]
	[TestFixture (Platform.iOS)]
	public class Tests
	{
		IApp app;
		Platform platform;

		public Tests (Platform platform)
		{
			this.platform = platform;
		}

		[SetUp]
		public void BeforeEachTest ()
		{
			app = AppInitializer.StartApp (platform);
		}

		[Test]
		public void WelcomeTextIsDisplayed ()
		{
			AppResult[] results = app.WaitForElement (c => c.Marked ("Welcome to Xamarin Forms!"));
			app.Screenshot ("Welcome screen.");

			Assert.IsTrue (results.Any ());
		}

		[Test]
		public void BasicTest ()
		{
			app.Tap(x => x.Class("ImageButton").Marked("OK"));
			app.Screenshot("Tapped on view ImageButton");
			app.Tap(x => x.Class("TextView").Text("Bundesliga"));
			app.Screenshot("Tapped on view TextView with Text: 'Bundesliga'");
			app.Tap(x => x.Class("FloatingActionButton"));
			app.Screenshot("Tapped on view FloatingActionButton");
			app.Tap(x => x.Class("AppCompatButton").Id("button1").Text("Ok"));
			app.Screenshot("Tapped on view AppCompatButton with ID: 'button1' with Text: 'Ok'");
			app.Tap(x => x.Class("ImageButton").Marked("OK"));
			app.Screenshot("Tapped on view ImageButton");
			app.Tap(x => x.Class("TextView").Text("Favorites"));
			app.Screenshot("Tapped on view TextView with Text: 'Favorites'");
			app.Tap(x => x.Class("AppCompatButton"));
			app.Screenshot("Tapped on view AppCompatButton");
			app.Tap(x => x.Class("FloatingActionButton"));
			app.Screenshot("Tapped on view FloatingActionButton");
			app.Tap(x => x.Class("AppCompatButton").Id("button1").Text("Ok"));
			app.Screenshot("Tapped on view AppCompatButton with ID: 'button1' with Text: 'Ok'");
			app.ScrollUp();
			app.Tap(x => x.Class("ImageButton").Index(1));
			app.Screenshot("Tapped on view ImageButton");
		}
	}
}


text:
#ifndef CFG_PARSER
#define CFG_PARSER

#include <stdio.h>

struct Keyword {
    const char *const keyword;
    void *(*const create)();
    int (*const parse_arg)(void *, const char *);
    const struct Keyword *const block_grammar;
    int (*const finalize)(void *, void *);
};

int parse_config(void *, FILE *, const struct Keyword *);

#endif


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.6: http://docutils.sourceforge.net/" />
<title>The Boost.Iterator Library Boost</title>
<link rel="stylesheet" href="../../../rst.css" type="text/css" />

The Boost.Iterator Library

<col class="field-name" />
<col class="field-body" />

Authors:	David Abrahams, Jeremy Siek, Thomas Witt

Contact:	dave@boost-consulting.com, jsiek@osl.iu.edu, witt@styleadvisor.com

organizations:	Boost Consulting, Indiana University Open Systems
Lab, Zephyr Associates, Inc.

date:	$Date$

copyright:	Copyright David Abrahams, Jeremy Siek, Thomas Witt 2003.

<col class="field-name" />
<col class="field-body" />

Abstract:	The Boost Iterator Library contains two parts. The first
is a system of concepts which extend the C++ standard
iterator requirements. The second is a framework of
components for building iterators based on these
extended concepts and includes several useful iterator
adaptors. The extended iterator concepts have been
carefully designed so that old-style iterators
can fit in the new concepts and so that new-style
iterators will be compatible with old-style algorithms,
though algorithms may need to be updated if they want to
take full advantage of the new-style iterator
capabilities.  Several components of this library have
been accepted into the C++ standard technical report.
The components of the Boost Iterator Library replace the
older Boost Iterator Adaptor Library.

Table of Contents

New-Style Iterators

Iterator Facade and Adaptor

Specialized Adaptors

Iterator Utilities

Traits

Testing and Concept Checking

Upgrading from the old Boost Iterator Adaptor Library

History

New-Style Iterators

The iterator categories defined in C++98 are extremely limiting
because they bind together two orthogonal concepts: traversal and
element access.  For example, because a random access iterator is
required to return a reference (and not a proxy) when dereferenced,
it is impossible to capture the capabilities of
<tt class="docutils literal">vector<bool>::iterator</tt> using the C++98 categories.  This is the
infamous "<tt class="docutils literal">vector<bool></tt> is not a container, and its iterators
aren't random access iterators", debacle about which Herb Sutter
wrote two papers for the standards comittee (n1185 and n1211),
and a Guru of the Week.  New-style iterators go well beyond
patching up <tt class="docutils literal">vector<bool></tt>, though: there are lots of other
iterators already in use which can't be adequately represented by
the existing concepts.  For details about the new iterator
concepts, see our

Standard Proposal For New-Style Iterators (PDF)

Iterator Facade and Adaptor

Writing standard-conforming iterators is tricky, but the need comes
up often.  In order to ease the implementation of new iterators,
the Boost.Iterator library provides the <tt class="docutils literal">iterator_facade</tt> class template,
which implements many useful defaults and compile-time checks
designed to help the iterator author ensure that his iterator is
correct.

It is also common to define a new iterator that is similar to some
underlying iterator or iterator-like type, but that modifies some
aspect of the underlying type's behavior.  For that purpose, the
library supplies the <tt class="docutils literal">iterator_adaptor</tt> class template, which is specially
designed to take advantage of as much of the underlying type's
behavior as possible.

The documentation for these two classes can be found at the following
web pages:

<tt class="docutils literal">iterator_facade</tt> (PDF)

<tt class="docutils literal">iterator_adaptor</tt> (PDF)

Both <tt class="docutils literal">iterator_facade</tt> and <tt class="docutils literal">iterator_adaptor</tt> as well as many of the specialized
adaptors mentioned below have been proposed for standardization,
and accepted into the first C++ technical report; see our

Standard Proposal For Iterator Facade and Adaptor (PDF)

for more details.

Specialized Adaptors

The iterator library supplies a useful suite of standard-conforming
iterator templates based on the Boost iterator facade and adaptor.

<tt class="docutils literal">counting_iterator</tt> (PDF): an iterator over a sequence of consecutive values.
Implements a "lazy sequence"

<tt class="docutils literal">filter_iterator</tt> (PDF): an iterator over the subset of elements of some
sequence which satisfy a given predicate

<tt class="docutils literal">function_input_iterator</tt> (PDF): an input iterator wrapping a generator (nullary
function object); each time the iterator is dereferenced, the function object
is called to get the value to return.

<tt class="docutils literal">function_output_iterator</tt> (PDF): an output iterator wrapping a unary function
object; each time an element is written into the dereferenced
iterator, it is passed as a parameter to the function object.

<tt class="docutils literal">generator_iterator</tt>: an input iterator wrapping a reference to a generator (nullary function object);
each time the iterator is dereferenced, the function object
is called to get the value to return. This is a more outdated analogue of <tt class="docutils literal">function_input_iterator</tt>.

<tt class="docutils literal">indirect_iterator</tt> (PDF): an iterator over the objects pointed-to by the
elements of some sequence.

<tt class="docutils literal">permutation_iterator</tt> (PDF): an iterator over the elements of some random-access
sequence, rearranged according to some sequence of integer indices.

<tt class="docutils literal">reverse_iterator</tt> (PDF): an iterator which traverses the elements of some
bidirectional sequence in reverse.  Corrects many of the
shortcomings of C++98's <tt class="docutils literal">std::reverse_iterator</tt>.

<tt class="docutils literal">shared_container_iterator</tt>: an iterator over elements of a container whose
lifetime is maintained by a <tt class="docutils literal">shared_ptr</tt> stored in the iterator.

<tt class="docutils literal">transform_iterator</tt> (PDF): an iterator over elements which are the result of
applying some functional transformation to the elements of an
underlying sequence.  This component also replaces the old
<tt class="docutils literal">projection_iterator_adaptor</tt>.

<tt class="docutils literal">zip_iterator</tt> (PDF): an iterator over tuples of the elements at corresponding
positions of heterogeneous underlying iterators.

Iterator Utilities

Traits

<tt class="docutils literal">pointee.hpp</tt> (PDF): Provides the capability to deduce the referent types
of pointers, smart pointers and iterators in generic code.  Used
in <tt class="docutils literal">indirect_iterator</tt>.

<tt class="docutils literal">iterator_traits.hpp</tt> (PDF): Provides MPL-compatible metafunctions which
retrieve an iterator's traits.  Also corrects for the deficiencies
of broken implementations of <tt class="docutils literal">std::iterator_traits</tt>.

Testing and Concept Checking

<tt class="docutils literal">iterator_concepts.hpp</tt> (PDF): Concept checking classes for the new iterator concepts.

<tt class="docutils literal">iterator_archetypes.hpp</tt> (PDF): Concept archetype classes for the new iterators concepts.

Upgrading from the old Boost Iterator Adaptor Library

If you have been using the old Boost Iterator Adaptor library to
implement iterators, you probably wrote a <tt class="docutils literal">Policies</tt> class which
captures the core operations of your iterator.  In the new library
design, you'll move those same core operations into the body of the
iterator class itself.  If you were writing a family of iterators,
you probably wrote a type generator to build the
<tt class="docutils literal">iterator_adaptor</tt> specialization you needed; in the new library
design you don't need a type generator (though may want to keep it
around as a compatibility aid for older code) because, due to the
use of the Curiously Recurring Template Pattern (CRTP) [Cop95],
you can now define the iterator class yourself and acquire
functionality through inheritance from <tt class="docutils literal">iterator_facade</tt> or
<tt class="docutils literal">iterator_adaptor</tt>.  As a result, you also get much finer control
over how your iterator works: you can add additional constructors,
or even override the iterator functionality provided by the
library.

If you're looking for the old <tt class="docutils literal">projection_iterator</tt> component,
its functionality has been merged into <tt class="docutils literal">transform_iterator</tt>: as
long as the function object's <tt class="docutils literal">result_type</tt> (or the <tt class="docutils literal">Reference</tt>
template argument, if explicitly specified) is a true reference
type, <tt class="docutils literal">transform_iterator</tt> will behave like
<tt class="docutils literal">projection_iterator</tt> used to.

History

In 2000 Dave Abrahams was writing an iterator for a container of
pointers, which would access the pointed-to elements when
dereferenced.  Naturally, being a library writer, he decided to
generalize the idea and the Boost Iterator Adaptor library was born.
Dave was inspired by some writings of Andrei Alexandrescu and chose a
policy based design (though he probably didn't capture Andrei's idea
very well - there was only one policy class for all the iterator's
orthogonal properties).  Soon Jeremy Siek realized he would need the
library and they worked together to produce a "Boostified" version,
which was reviewed and accepted into the library.  They wrote a paper
and made several important revisions of the code.

Eventually, several shortcomings of the older library began to make
the need for a rewrite apparent.  Dave and Jeremy started working
at the Santa Cruz C++ committee meeting in 2002, and had quickly
generated a working prototype.  At the urging of Mat Marcus, they
decided to use the GenVoca/CRTP pattern approach, and moved the
policies into the iterator class itself.  Thomas Witt expressed
interest and became the voice of strict compile-time checking for
the project, adding uses of the SFINAE technique to eliminate false
converting constructors and operators from the overload set.  He
also recognized the need for a separate <tt class="docutils literal">iterator_facade</tt>, and
factored it out of <tt class="docutils literal">iterator_adaptor</tt>.  Finally, after a
near-complete rewrite of the prototype, they came up with the
library you see today.

<colgroup><col class="label" /><col /></colgroup>

[Cop95]	[Coplien, 1995] Coplien, J., Curiously Recurring Template
Patterns, C++ Report, February 1995, pp. 24-27.

View document source.
Generated by Docutils from reStructuredText source.


text:
<!DOCTYPE html>
<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org">
<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1289999">


text:
package com.github.jmccrae.yuzu

import com.github.jmccrae.yuzu.YuzuSettings._
import com.github.jmccrae.yuzu.YuzuUserText._
import com.github.mustachejava.{DefaultMustacheFactory, Mustache, MustacheResolver}
import com.hp.hpl.jena.query.ResultSetFormatter
import com.hp.hpl.jena.rdf.model.{Model, ModelFactory}
import com.hp.hpl.jena.vocabulary._
import java.io.{ByteArrayOutputStream, PipedOutputStream, PipedInputStream,
  StringReader, InputStream, OutputStream, File, FileInputStream, StringWriter,
  FileNotFoundException}
import java.net.URL
import java.nio.file.Files
import java.util.concurrent.{TimeoutException}
import javax.servlet.http.HttpServletResponse._
import javax.servlet.http.{HttpServlet, HttpServletResponse, HttpServletRequest}
import javax.xml.transform.stream.{StreamSource, StreamResult}
import javax.xml.transform.{TransformerFactory}
import org.apache.jena.riot.{RDFDataMgr, RDFFormat}
import scala.collection.JavaConversions._
import scala.language.implicitConversions
import scala.language.reflectiveCalls
import scala.math.max

sealed class ResultType(val mime : String, val jena : Option[RDFFormat])

object sparql extends ResultType("application/sparql-results+xml", None)
object sparqljson extends ResultType("application/sparql-results+json", None)
object rdfxml extends ResultType("application/rdf+xml", Some(RDFFormat.RDFXML_PRETTY))
object html extends ResultType("text/html", None)
object turtle extends ResultType("text/turtle", Some(RDFFormat.TURTLE))
object nt extends ResultType("text/plain", Some(RDFFormat.NT))
object jsonld extends ResultType("application/ld+json", Some(RDFFormat.JSONLD))
object error extends ResultType("text/html", None)

trait PathResolver {
  def apply(fname : String) : URL
}

class MustachePattern(m : Mustache) {
  def substitute(args : (String,Any)*) = {
    val out = new StringWriter()
    m.execute(out, deepToJava(Map((("context" -> CONTEXT) +: args):_*)))
    out.toString
  }
  def generate(obj : Any) = {
    val out = new StringWriter()
    m.execute(out, obj)
    out.toString
  }

  private def deepToJava(x : Any) : Any = x match {
    case Some(x) => deepToJava(x)
    case None => null
    case m : Map[_,_] =>
      scala.collection.JavaConversions.mapAsJavaMap(m.map {
        case (k,v) => k -> deepToJava(v)
      })
    case s : Seq[_] =>
      scala.collection.JavaConversions.seqAsJavaList(s.map {
        e => deepToJava(e)
      })
    case other => other
  }
}

object mustache {
  val mf = new DefaultMustacheFactory()
  private var inited = false
  def apply(pattern : String) = new MustachePattern(mf.compile(new StringReader(pattern),pattern))
  def apply(file : URL) = new MustachePattern(mf.compile(new java.io.InputStreamReader(file.openStream()),file.toString))
  def rdf2html(implicit resolve : PathResolver) = {
    val resolver = new MustacheResolver {
      def getReader(resourceName : String) = new java.io.InputStreamReader(resourceName match {
        case "triple" => resolve("html/triple.mustache").openStream()
        case "triple2" => resolve("html/triple.mustache").openStream()
        case "rdf2html" => resolve("html/rdf2html.mustache").openStream()
        case _ => throw new FileNotFoundException()
      })
    }
    val mf = new DefaultMustacheFactory(resolver)
    new MustachePattern(mf.compile("rdf2html"))
  }
}

object RDFServer {

  def quotePlus(s : String) = java.net.URLEncoder.encode(s, "UTF-8")
  def renderHTML(title : String, text : String, isTest : Boolean)(implicit resolve : PathResolver) = {
    val template = mustache(resolve("html/page.mustache"))
    template.substitute("title"-> title, "app_title" -> DISPLAY_NAME,
      "content" -> text, "is_test" -> isTest)
  }

  def send302(resp : HttpServletResponse, location : String) { resp.sendRedirect(location) }
  def send400(resp : HttpServletResponse, message : String = YZ_INVALID_QUERY) {
    resp.sendError(SC_BAD_REQUEST, message)
  }
  def send404(resp : HttpServletResponse) {
    resp.sendError(SC_NOT_FOUND, YZ_NOT_FOUND_PAGE)
  }
  def send501(resp : HttpServletResponse, message : String = YZ_JSON_LD_NOT_INSTALLED)(implicit resolve : PathResolver) {
    resp.sendError(SC_NOT_IMPLEMENTED,
      renderHTML(YZ_NOT_IMPLEMENTED, message, false))
  }

  def mimeToResultType(mime : String, deflt : ResultType) = mime match {
    case "text/html" => Some(html)
    case "application/rdf+xml" => Some(rdfxml)
    case "text/turtle" => Some(turtle)
    case "application/x-turtle" => Some(turtle)
    case "application/n-triples" => Some(nt)
    case "text/plain" => Some(nt)
    case "application/ld+json" => Some(jsonld)
    case "application/sparql-results+xml" => Some(sparql)
    case "application/sparql-results+json" => Some(sparqljson)
    case "application/json" if deflt==sparqljson => Some(sparqljson)
    case "application/json" => Some(jsonld)
    case "application/javascript" if deflt==sparqljson => Some(sparqljson)
    case "application/javascript" => Some(jsonld)
    case _ => None
  }

  def bestMimeType(acceptString : String, deflt : ResultType) : ResultType = {
    val accepts = acceptString.split("\\s*,\\s*")
    for(accept <- accepts) {
      mimeToResultType(accept, deflt) match {
        case Some(t) => return t
        case None => // noop
     }
    }
    val weightedAccepts : Seq[(Double, ResultType)] = accepts.flatMap {
      accept => if(accept.contains(";")) {
        try {
          val e = accept.split("\\s*;\\s*")
          val mime = mimeToResultType(e.head, deflt)
          val extensions = e.tail
          for(extension <- extensions if extension.startsWith("q=") && mime != None) yield {
            (extension.drop(2).toDouble, mime.get)
          }
        } catch {
          case x : Exception => Nil
        }
      } else {
        Nil
      }
    }
    if(weightedAccepts.isEmpty) {
      return deflt
    } else {
      return weightedAccepts.maxBy(_._1)._2
    }
  }

  def slurp(name : String) = _slurp(io.Source.fromFile(name))
  def slurp(url : URL) = _slurp(io.Source.fromURL(url))

  def _slurp(src : io.Source) = src.getLines.mkString("\n")
  implicit def responsePimp(resp : HttpServletResponse) = new {
    def respond(contentType : String, status : Int, args : (String,String)*)(foo : java.io.PrintWriter => Unit) = {
      resp.setCharacterEncoding("utf-8")
      resp.addHeader("Content-type", contentType)
      for((a,b) <- args) {
        resp.addHeader(a,b)
      }
      resp.setStatus(status)
      val out = resp.getWriter()
      foo(out)
      out.flush()
    }
    def binary(contentType : String, file : URL) {
      try {
        val in = file.openStream()
        resp.addHeader("Content-type", contentType)
        if(file.getProtocol() == "file") {
          resp.addHeader("Content-length", new File(file.getPath()).length().toString)
        }
        val out = resp.getOutputStream()
        val buf = new Array[Byte](4096)
        var read = 0
        while({ read = in.read(buf) ; read } >= 0) {
          out.write(buf, 0, read)
        }
        out.flush()
      } catch {
        case x : java.io.FileNotFoundException =>
          resp.sendError(SC_NOT_FOUND, YZ_BINARY_NOT_FOUND)
      }
    }
  }
}

class RDFServer(backend : Backend = new TripleBackend(DB_FILE)) extends HttpServlet {
  import RDFServer._

  implicit class URLPimps(url : URL) {
    def exists = if(url.getProtocol() == "file") {
      new File(url.getPath()).exists
    } else {
      true
    }
  }

  implicit val resolve = new PathResolver {
    private def resolveLocal(fname : String) = {
      val cls = this.getClass()
      val pd = cls.getProtectionDomain()
      val cs = pd.getCodeSource()
      val loc = cs.getLocation()
      if(loc.getProtocol() == "file" && new File(loc.getPath()).isDirectory()
          && new File(loc.getPath() + fname).exists) {
        new URL("file:"+loc.getPath() + fname)
      } else {
        if(new File(fname).exists) {
          new URL("file:"+fname)
        } else if(new File("../" + fname).exists) {
          new URL("file:../" + fname)
        // This is a 'hack' for sbt container:launch
        } else if(new File("../../" + fname).exists) {
          new URL("file:../../" + fname)
        } else {
          System.err.println("Could not locate %s from %s" format (
            fname, System.getProperty("user.dir")))
          new URL("file:"+fname)
        }
      }
    }

    def apply(fname : String) = try {
      Option(getServletContext().getResource("/WEB-INF/classes/"+fname)).getOrElse(resolveLocal(fname))
    } catch {
      case x : IllegalStateException =>
        resolveLocal(fname)
    }
  }

  private val resourceURIRegex = "^/(.*?)(|\\.nt|\\.html|\\.rdf|\\.ttl|\\.json)$".r

  def sparqlQuery(query : String, mimeType : ResultType, defaultGraphURI : Option[String],
    resp : HttpServletResponse, timeout : Int = 10) {
      val result = try {
        backend.query(query, mimeType, defaultGraphURI, timeout)
      } catch {
        case x : TimeoutException =>
          resp.sendError(SC_SERVICE_UNAVAILABLE, YZ_TIME_OUT)
          return
      }
      if(mimeType == html) {
        val content = result match {
          case r : TableResult =>
            val d = r.toDict
            mustache(resolve("html/sparql-results.mustache")).
              substitute((("context" -> CONTEXT) +: d):_*)
          case BooleanResult(r) =>
            val l = if(r) { "True" } else { "False" }
            mustache(resolve("html/sparql-results.mustache")).
              substitute("boolean" -> l)
          case ModelResult(model) =>
            rdfxmlToHtml(model, None)
          case ErrorResult(msg, t) =>
            throw new RuntimeException(msg, t)
        }
        resp.respond("text/html", SC_OK) {
          out => out.println(renderHTML("SPARQL Results", content, false))
        }
      } else {
        val (content, mime) = result match {
          case r : TableResult =>
            if(mimeType == sparql) {
              (r.toXML, sparql)
            } else {
              (r.toJSON, sparqljson)
            }
          case BooleanResult(r) =>
            if(mimeType == sparql) {
              (ResultSetFormatter.asXMLString(r), sparql)
            } else {
              val baos = new java.io.ByteArrayOutputStream()
              ResultSetFormatter.outputAsJSON(baos, r)
              (baos.toString(), sparqljson)
            }
          case ModelResult(model) =>
            val out = new java.io.StringWriter()
            val mime = if(mimeType == sparql) {
              rdfxml
            } else {
              mimeType
            }
            addNamespaces(model)
            RDFDataMgr.write(out, model, mime.jena.getOrElse(rdfxml.jena.get))
            if(mime == jsonld) {
              (addContextToJsonLD(out.toString()), mime)
            } else {
              (out.toString(), mime)
            }
          case ErrorResult(msg, t) =>
            throw new RuntimeException(msg, t)
        }
        resp.respond(mime.mime, SC_OK) {
          out => out.println(content)
        }
      }
    }

  def addNamespaces(model : Model) {
    model.setNsPrefix("ontology", BASE_NAME+"ontology#")
    model.setNsPrefix(PREFIX1_QN, PREFIX1_URI)
    model.setNsPrefix(PREFIX2_QN, PREFIX2_URI)
    model.setNsPrefix(PREFIX3_QN, PREFIX3_URI)
    model.setNsPrefix(PREFIX4_QN, PREFIX4_URI)
    model.setNsPrefix(PREFIX5_QN, PREFIX5_URI)
    model.setNsPrefix(PREFIX6_QN, PREFIX6_URI)
    model.setNsPrefix(PREFIX7_QN, PREFIX7_URI)
    model.setNsPrefix(PREFIX8_QN, PREFIX8_URI)
    model.setNsPrefix(PREFIX9_QN, PREFIX9_URI)
    model.setNsPrefix("rdf", RDF.getURI())
    model.setNsPrefix("rdfs", RDFS.getURI())
    model.setNsPrefix("owl", OWL.getURI())
    model.setNsPrefix("dc", DC_11.getURI())
    model.setNsPrefix("dct", DCTerms.getURI())
    model.setNsPrefix("xsd", XSD.getURI())
    model.setNsPrefix("dcat", DCAT)
    model.setNsPrefix("void", VOID)
    model.setNsPrefix("dataid", DATAID)
    model.setNsPrefix("foaf", FOAF)
    model.setNsPrefix("odrl", ODRL)
    model.setNsPrefix("prov", PROV)
  }

  def rdfxmlToHtml(model : Model, query : Option[String], title : String = "") : String = query match {
    case Some(q) =>
      val elem = QueryElement.fromModel(model, q)
      return renderHTML(title, mustache.rdf2html.generate(elem), false)
    case None =>
      throw new UnsupportedOperationException("TODO")
  }

  def addContextToJsonLD(doc : String) = {
    val jsonObject = com.github.jsonldjava.utils.JsonUtils.
      fromString(doc)
    val options = new com.github.jsonldjava.core.JsonLdOptions()
    val compact = com.github.jsonldjava.core.JsonLdProcessor.compact(
      jsonObject, jsonldContext, options)
    com.github.jsonldjava.utils.JsonUtils.toPrettyString(compact)
  }

  override def service(req : HttpServletRequest, resp : HttpServletResponse) { try {
    val uri2 = UnicodeEscape.safeURI(req.getRequestURI().substring(req.getContextPath().length))
    val uri = if(!uri2.startsWith("/")) { "/" + uri2 } else { uri2 }
    //val uri = req.getPathInfo()
    val isTest = req.getRequestURL().toString() == (BASE_NAME + uri)
    var mime = if(uri.matches(".*\\.html")) {
      html
    } else if(uri.matches(".*\\.rdf")) {
      rdfxml
    } else if(uri.matches(".*\\.ttl")) {
      turtle
    } else if(uri.matches(".*\\.nt")) {
      nt
    } else if(uri.matches(".*\\.json")) {
      jsonld
    } else if(req.getHeader("Accept") != null) {
      if(SPARQL_PATH != null && (uri == SPARQL_PATH || uri == (SPARQL_PATH + "/"))) {
        bestMimeType(req.getHeader("Accept"), sparqljson)
      } else {
        bestMimeType(req.getHeader("Accept"), html)
      }
    } else {
      if(SPARQL_PATH != null && (uri == SPARQL_PATH || uri == (SPARQL_PATH + "/"))) {
        sparqljson
      } else {
        html
      }
    }

    if(uri == "/" || uri == "/index.html") {
      if(!new File(DB_FILE).exists && !new File(DB_FILE + ".mv.db").exists) {
        resp.respond("text/html", SC_OK) {
          _.println(renderHTML(DISPLAY_NAME,
            mustache(resolve("html/onboarding.html")).substitute(), isTest))
        }
      } else {
       resp.respond("text/html",SC_OK) {
          out => out.print(renderHTML(DISPLAY_NAME, mustache(resolve("html/index.html")).substitute("property_facets" -> FACETS), isTest))
        }
      }
    } else if(LICENSE_PATH != null && uri == LICENSE_PATH) {
      resp.respond("text/html",SC_OK) {
        out => out.print(renderHTML(DISPLAY_NAME, slurp(resolve("html/license.html")), isTest))
      }
    } else if(SEARCH_PATH != null && (uri == SEARCH_PATH || uri == (SEARCH_PATH + "/"))) {
      if(req.getQueryString() != null) {
        val qsParsed = req.getParameterMap().asInstanceOf[java.util.Map[String,Array[String]]]
        if(qsParsed.containsKey("query")) {
          val query = qsParsed.get("query")(0)
          val prop = if(qsParsed.containsKey("property") && qsParsed.get("property")(0) != "") {
            Some("<" + qsParsed.get("property")(0) + ">")
          } else {
            None
          }
          val offset = if(qsParsed.containsKey("offset") && qsParsed.get("offset")(0) != "") {
            try {
              qsParsed.get("offset")(0).toInt
            } catch {
              case x : NumberFormatException =>
                0
            }
          } else {
            0
          }
          search(resp, query, prop, offset)
        } else {
          send400(resp, YZ_NO_QUERY)
        }
      } else {
        send400(resp, YZ_NO_QUERY)
      }
    } else if(uri == DUMP_URI) {
      resp.binary("application/x-gzip", resolve(DUMP_FILE))
    } else if(uri == "/favicon.ico" && (resolve("assets/favicon.ico")).exists) {
      resp.binary("image/png", resolve("assets/favicon.ico"))
    } else if(uri.startsWith(ASSETS_PATH) && (resolve(uri.drop(1))).exists) {
      resp.binary(Files.probeContentType(new File(uri).toPath()), resolve(uri.drop(1)))
    } else if(SPARQL_PATH != null && (uri == SPARQL_PATH || uri == (SPARQL_PATH + "/"))) {
      if(req.getQueryString() != null) {
        val qs = req.getParameterMap().asInstanceOf[java.util.Map[String,Array[String]]]
        if(qs.containsKey("query")) {
          sparqlQuery(qs.get("query")(0), mime,
            Option(qs.get("default-graph-uri")).map(_(0)), resp)
        } else {
          resp.respond("text/html", SC_OK) {
            out => out.print(renderHTML(DISPLAY_NAME, slurp(resolve("html/sparql.html")), isTest))
          }
        }
      } else {
        resp.respond("text/html", SC_OK) {
          out => out.print(renderHTML(DISPLAY_NAME, slurp(resolve("html/sparql.html")), isTest))
        }
      }
    } else if(LIST_PATH != null && (uri == LIST_PATH || uri == (LIST_PATH + "/"))) {
      val offset = if(req.getQueryString() != null) {
        val qs = req.getParameterMap().asInstanceOf[java.util.Map[String,Array[String]]]
        if(qs.containsKey("offset")) {
          try {
            qs.get("offset")(0).toInt
          } catch {
            case x : NumberFormatException => {
              send400(resp)
              return
            }
          }
        } else { 0 }
      } else { 0 }
      val property2 = req.getParameter("prop")
      val property = if(property2 == null || property2 == "") {
        None
      } else if(property2.startsWith("<") && property2.endsWith(">")) {
        Some(property2)
      } else {
        Some("<" + property2 + ">")
      }
      val obj = Option(req.getParameter("obj"))
      val numRegex = "(\\d+)".r
      val objOffset = req.getParameter("obj_offset") match {
        case null => None
        case numRegex(i) => Some(i.toInt)
        case _ => None
      }
      listResources(resp, offset, property, obj, objOffset)
    } else if(METADATA_PATH != null && (
        uri == ("/" + METADATA_PATH) || uri == ("/" + METADATA_PATH + ".rdf") ||
        uri == ("/" + METADATA_PATH + ".ttl") || uri == ("/" + METADATA_PATH + ".json") ||
        uri == ("/" + METADATA_PATH + ".nt"))) {
      val model = DataID.get
      val content = if(mime == html) {
        rdfxmlToHtml(model, Some(BASE_NAME + METADATA_PATH), YZ_METADATA)
      } else {
        val out = new java.io.StringWriter()
        addNamespaces(model)
        if(mime == jsonld) {
          JsonLDPrettySerializer.write(out, model, BASE_NAME + METADATA_PATH)
        } else {
          RDFDataMgr.write(out, model, mime.jena.getOrElse(rdfxml.jena.get))
        }
        out.toString()
      }
      resp.respond(mime.mime, SC_OK, "Vary" -> "Accept", "Content-length" -> content.size.toString) {
        out => out.print(content)
      }
    } else if(resolve("html/%s.html" format uri.replaceAll("/$", "")).exists) {
      resp.respond("text/html", SC_OK) {
        out => out.println(renderHTML(DISPLAY_NAME,
          mustache(resolve("html/%s.html" format uri.replaceAll("/$", ""))).substitute(
            "dump_uri" -> DUMP_URI), isTest))
      }
    } else if(uri.matches(resourceURIRegex.toString)) {
      val resourceURIRegex(id,_) = uri
      val modelOption = backend.lookup(id)
      modelOption match {
        case None => send404(resp)
        case Some(model) => {
          val title = model.listStatements(model.createResource(BASE_NAME + id),
                                            RDFS.label,
                                            null).map(s => DISPLAYER.apply(s.getObject())).mkString(", ")
          val content = if(mime == html) {
            if(title == "") {
              rdfxmlToHtml(model, Some(BASE_NAME + id),
                           DISPLAYER.uriToStr(BASE_NAME + id))
            } else {
              rdfxmlToHtml(model, Some(BASE_NAME + id), title)
            }
          } else {
            val out = new java.io.StringWriter()
            addNamespaces(model)
            if(mime == jsonld) {
              JsonLDPrettySerializer.write(out, model, BASE_NAME + id)
              out.toString()
            } else {
              RDFDataMgr.write(out, model, mime.jena.getOrElse(rdfxml.jena.get))
              out.toString()
            }
          }
          resp.respond(mime.mime, SC_OK, "Vary" -> "Accept", "Content-length" -> content.getBytes("utf-8").length.toString) {
            out => out.print(content)
          }
        }
      }
    } else {
      send404(resp)
    }
  } catch {
    case x : Exception => {
      System.err.println("INTERNAL SERVER ERROR: %s" format x.getMessage())
      throw x
    }
  }}

  def listResources(resp : HttpServletResponse, offset : Int, property : Option[String], obj : Option[String], obj_offset : Option[Int]) {
    val limit = 20
    val (hasMore, results) = backend.listResources(offset, limit, property, obj)
    val template = mustache(resolve("html/list.html"))
    val hasPrev = if(offset > 0) { "" } else { "disabled" }
    val prev = math.max(offset - limit, 0)
    val hasNext = if(hasMore) { "" } else { "disabled" }
    val next = offset + limit
    val pages = "%d - %d" format(offset + math.min(1, results.size), offset + math.min(limit, results.size))
    val facets = FACETS.filter(_.getOrElse("list", true) == true).map { facet =>
      val uri_enc = quotePlus(facet("uri").toString)
      if(property != None && ("<" + facet("uri") + ">") == property.get) {
        val (moreValues, vs) = backend.listValues(obj_offset.getOrElse(0),20,property.get)
        facet ++ Map("uri_enc" -> uri_enc,
          "values" -> vs.map { v => Map[String,String](
                  "prop_uri" -> uri_enc,
                  "value_enc" -> quotePlus(v.link),
                  "value" -> v.label.take(100),
                  "count" -> v.count.toString,
                  "offset" -> obj_offset.getOrElse(0).toString
                )},
          "more_values" -> (if(moreValues) { Some(obj_offset.getOrElse(0) + limit) } else { None }))
      } else {
        facet + ("uri_enc" -> uri_enc)
      }
    }
    val queryString = (property match {
        case Some(p) => "&prop=" + quotePlus(p.drop(1).dropRight(1))
        case None => "" }) +
      (obj match {
        case Some(o) => "&obj=" + quotePlus(o)
        case None => "" }) +
      (obj_offset match {
        case Some(o) => "&obj_offset=" + o
        case None => "" })
    val results2 = for(result <- results) yield {
      Map(
        "title" -> result.label,
        "link" -> result.link,
        "model" -> QueryElement.fromModel(backend.summarize(result.id),
                                          BASE_NAME + result.id).head) }

    resp.respond("text/html", SC_OK) {
      out => out.println(renderHTML(DISPLAY_NAME,
        template.substitute(
          "facets" -> facets,
          "results" -> results2,
          "has_prev" -> hasPrev,
          "prev" -> prev.toString,
          "has_next" -> hasNext,
          "next" -> next.toString,
          "pages" -> pages,
          "query" -> queryString), false))
    }
  }

  def search(resp : HttpServletResponse, query : String, property : Option[String],
             offset : Int) {
    val limit = 20
    val buf = new StringBuilder()
    val results = backend.search(query, property, offset, limit + 1)
    val prev = math.max(0, offset - limit)
    val next = offset + limit
    val pages = "%d - %d" format (offset + 1, offset + math.min(limit, results.size))
    val hasPrev = if(offset == 0) { " disabled" } else { "" }
    val hasNext = if(results.size <= limit) { " disabled" } else { "" }
    val qs = "&query=" + quotePlus(query) + (
      property match {
        case Some(p) => "&property=" + quotePlus(p).drop(1).dropRight(1)
        case None => ""
      })
    val results2 = for(result <- results) yield {
      Map(
        "title" -> result.label,
        "link" -> result.link,
        "model" -> QueryElement.fromModel(backend.summarize(result.id),
                                          BASE_NAME + result.id).head) }
    val page = mustache(resolve("html/search.html")).substitute(
      "results" -> results2.take(limit),
      "prev" -> prev,
      "has_prev" -> hasPrev,
      "next" -> next,
      "has_next" -> hasNext,
      "pages" -> pages,
      "query" -> qs
    )
    resp.respond("text/html", SC_OK) {
      out => out.println(renderHTML(DISPLAY_NAME, page, false))
    }
  }

  def jsonldContext = mapAsJavaMap(Map(
    "@base" -> BASE_NAME,
    PREFIX1_QN -> PREFIX1_URI,
    PREFIX2_QN -> PREFIX2_URI,
    PREFIX3_QN -> PREFIX3_URI,
    PREFIX4_QN -> PREFIX4_URI,
    PREFIX5_QN -> PREFIX5_URI,
    PREFIX6_QN -> PREFIX6_URI,
    PREFIX7_QN -> PREFIX7_URI,
    PREFIX8_QN -> PREFIX8_URI,
    PREFIX9_QN -> PREFIX9_URI,
    "rdf" -> RDF.getURI(),
    "rdfs" -> RDFS.getURI(),
    "owl" -> OWL.getURI(),
    "dc" -> DC_11.getURI(),
    "dct" -> DCTerms.getURI(),
    "xsd" -> XSD.getURI()
  ))

  override def destroy() {
    //backend.close()
  }

}

class YuzuServlet extends RDFServer


text:
package org.ovirt.engine.core.bll;

import java.util.List;

import org.ovirt.engine.core.bll.snapshots.RemoveSnapshotCommandCallback;
import org.ovirt.engine.core.bll.tasks.CommandCoordinatorUtil;
import org.ovirt.engine.core.bll.tasks.interfaces.CommandCallback;
import org.ovirt.engine.core.common.action.MergeParameters;
import org.ovirt.engine.core.compat.CommandStatus;
import org.ovirt.engine.core.compat.Guid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MergeExtendCommandCallback extends CommandCallback {
    private static final Logger log = LoggerFactory.getLogger(RemoveSnapshotCommandCallback.class);

    @Override
    public void doPolling(Guid cmdId, List<Guid> childCmdIds) {
        boolean failed = false;
        for (Guid childCmdId : childCmdIds) {
            switch (CommandCoordinatorUtil.getCommandStatus(childCmdId)) {
            case ACTIVE:
                log.info("Waiting on disk extension child commands to complete");
                return;
            case ENDED_WITH_FAILURE:
            case FAILED:
            case FAILED_RESTARTED:
            case UNKNOWN:
                failed = true;
                break;
            default:
                break;
            }
        }

        MergeExtendCommand<MergeParameters> command = getCommand(cmdId);
        command.setCommandStatus(failed ? CommandStatus.FAILED : CommandStatus.SUCCEEDED);
        log.info("Disk extension complete, status '{}'", command.getCommandStatus());
    }

    private MergeExtendCommand<MergeParameters> getCommand(Guid cmdId) {
        return CommandCoordinatorUtil.retrieveCommand(cmdId);
    }
}


text:
<?php

namespace LaravelPropertyBag\Settings;

use Illuminate\Database\Eloquent\Model;

class PropertyBag extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'property_bag';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'key',
        'value',
    ];

    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'value' => 'array',
    ];
}


text:
TEST(FunctionsTarget, CheckUnused) {
  Scheduler scheduler;
  TestWithScope setup;

  // The target generator needs a place to put the targets or it will fail.
  Scope::ItemVector item_collector;
  setup.scope()->set_item_collector(&item_collector);

  // Test a good one first.
  TestParseInput good_input(
      "source_set(\"foo\") {\n"
      "}\n");
  ASSERT_FALSE(good_input.has_error());
  Err err;
  good_input.parsed()->Execute(setup.scope(), &err);
  ASSERT_FALSE(err.has_error()) << err.message();

  // Test a source set (this covers everything but component) with an unused
  // variable.
  TestParseInput source_set_input(
      "source_set(\"foo\") {\n"
      "  unused = 5\n"
      "}\n");
  ASSERT_FALSE(source_set_input.has_error());
  err = Err();
  source_set_input.parsed()->Execute(setup.scope(), &err);
  ASSERT_TRUE(err.has_error());

  // Test a component, which is a different code path.
  TestParseInput component_input(
      "component_mode = \"static_library\"\n"
      "component(\"bar\") {\n"
      "  unused = 5\n"
      "}\n");
  ASSERT_FALSE(component_input.has_error());
  err = Err();
  component_input.parsed()->Execute(setup.scope(), &err);
  ASSERT_TRUE(err.has_error()) << err.message();
}


text:
import pytest
from rest_framework import status
from rest_framework.test import APITestCase

from .. import factories

pytestmark = pytest.mark.django_db

# Create your tests here.

class TestFeedbackQuestionListApi(APITestCase):
    def setUp(self):
        self.schedule_item_types = ["Talk", "Workshop"]

    def test_get_questions_without_conference(self):
        res = self.client.get("/api/v1/feedback_questions/?conference_id=23")

        assert res.status_code == status.HTTP_200_OK
        assert res.data == {}

    def test_get_questions(self):
        num_choice_questions = 2
        num_text_questions = 1
        objects = factories.create_feedback_questions(
            schedule_item_types=self.schedule_item_types,
            num_text_questions=num_text_questions,
            num_choice_questions=num_choice_questions,
        )
        conference = objects["conference"]

        res = self.client.get(
            "/api/v1/feedback_questions/?conference_id={}".format(conference.id)
        )

        assert res.status_code == status.HTTP_200_OK
        result = res.data

        for rest in list(result.keys()):
            assert rest in self.schedule_item_types
        for item_type in self.schedule_item_types:
            assert len(result[item_type]["text"]) == num_text_questions
            assert len(result[item_type]["choice"]) == num_choice_questions

class TestFeedbackListApi(APITestCase):
    def setUp(self):
        self.device = factories.create_device()
        self.schedule_item_types = ["Workshop", "Talk"]
        num_choice_questions = 1
        num_text_questions = 1
        self.objects = factories.create_feedback_questions(
            schedule_item_types=self.schedule_item_types,
            num_text_questions=num_text_questions,
            num_choice_questions=num_choice_questions,
        )
        self.schedule_items = factories.create_schedule_items(
            conference=self.objects["conference"], item_types=self.schedule_item_types
        )

    def test_feedback_without_device_token(self):
        res = self.client.post("/api/v1/feedback/", {}, format="json")

        assert res.status_code == status.HTTP_403_FORBIDDEN

    def _submit_feedback(self):
        choice = [
            x
            for x in self.objects["choices"]
            if x.schedule_item_type.title == self.schedule_item_types[0]
        ][0]
        text = [
            x
            for x in self.objects["text"]
            if x.schedule_item_type.title == self.schedule_item_types[0]
        ][0]
        schedule_item = [
            x for x in self.schedule_items if x.type == self.schedule_item_types[0]
        ][0]
        data = {
            "text": [{"id": text.id, "text": "Ok"}],
            "choices": [
                {"id": choice.id, "value_id": choice.allowed_values.all()[0].id}
            ],
            "schedule_item_id": schedule_item.id,
        }

        self.client.credentials(HTTP_AUTHORIZATION="Token " + str(self.device.uuid))

        res = self.client.post("/api/v1/feedback/", data, format="json")
        """Data is sent in below format
        {'text': [{'text': 'Ok', 'id': 1}], 'schedule_item_id': 1,
        'choices': [{'id': 1, 'value_id': 1}]}
        """
        assert res.status_code == status.HTTP_201_CREATED
        assert len(res.data["text"]) == 1
        assert len(res.data["choices"]) == 1
        assert res.data["text"][0]["text"] == data["text"][0]["text"]
        assert res.data["choices"][0]["value_id"] == data["choices"][0]["value_id"]

    def test_submit_feedback(self):
        self._submit_feedback()

    def test_resubmit_feedback(self):
        self._submit_feedback()

        choice = [
            x
            for x in self.objects["choices"]
            if x.schedule_item_type.title == self.schedule_item_types[0]
        ][0]
        text = [
            x
            for x in self.objects["text"]
            if x.schedule_item_type.title == self.schedule_item_types[0]
        ][0]
        schedule_item = [
            x for x in self.schedule_items if x.type == self.schedule_item_types[0]
        ][0]
        data = {
            "text": [{"id": text.id, "text": "Ok"}],
            "choices": [
                {"id": choice.id, "value_id": choice.allowed_values.all()[0].id}
            ],
            "schedule_item_id": schedule_item.id,
        }

        self.client.credentials(HTTP_AUTHORIZATION="Token " + str(self.device.uuid))
        res = self.client.post("/api/v1/feedback/", data, format="json")

        assert res.status_code == status.HTTP_400_BAD_REQUEST
        assert res.data["error"] == "Feedback already submitted"

    def test_feedback_with_proper_data(self):
        pass

    def test_feedback_with_wrong_choice_value(self):
        choice = [
            x
            for x in self.objects["choices"]
            if x.schedule_item_type.title == self.schedule_item_types[0]
        ][0]
        text = [
            x
            for x in self.objects["text"]
            if x.schedule_item_type.title == self.schedule_item_types[0]
        ][0]
        schedule_item = [
            x for x in self.schedule_items if x.type == self.schedule_item_types[0]
        ][0]
        data = {
            "text": [{"id": text.id, "text": "Ok"}],
            "choices": [{"id": choice.id, "value_id": 23}],
            "schedule_item_id": schedule_item.id,
        }

        self.client.credentials(HTTP_AUTHORIZATION="Token " + str(self.device.uuid))
        res = self.client.post("/api/v1/feedback/", data, format="json")

        msg = "The multiple choice value isn't associated with question"

        assert res.status_code == status.HTTP_400_BAD_REQUEST
        assert res.data == {"choices": [{"non_field_errors": [msg]}]}

    def test_feedback_with_missing_required_text_data(self):
        choice = [
            x
            for x in self.objects["choices"]
            if x.schedule_item_type.title == self.schedule_item_types[0]
        ][0]
        schedule_item = [
            x for x in self.schedule_items if x.type == self.schedule_item_types[0]
        ][0]
        data = {
            "choices": [
                {"id": choice.id, "value_id": choice.allowed_values.all()[0].id}
            ],
            "schedule_item_id": schedule_item.id,
        }

        self.client.credentials(HTTP_AUTHORIZATION="Token " + str(self.device.uuid))
        res = self.client.post("/api/v1/feedback/", data, format="json")

        assert res.status_code == status.HTTP_400_BAD_REQUEST
        assert res.data == {"error": "Text Feedback is missing"}

    def test_feedback_with_missing_required_choice_data(self):
        text = [
            x
            for x in self.objects["text"]
            if x.schedule_item_type.title == self.schedule_item_types[0]
        ][0]
        schedule_item = [
            x for x in self.schedule_items if x.type == self.schedule_item_types[0]
        ][0]
        data = {
            "text": [{"id": text.id, "text": "Boom"}],
            "schedule_item_id": schedule_item.id,
        }

        self.client.credentials(HTTP_AUTHORIZATION="Token " + str(self.device.uuid))
        res = self.client.post("/api/v1/feedback/", data, format="json")

        assert res.status_code == status.HTTP_400_BAD_REQUEST
        assert res.data == {"error": "Choice feedback is missing"}


text:
//
//  WeiboCell.h
//  代码布局UITableviewCell
//
//  Created by majianjie on 16/5/16.
//  Copyright © 2016年 ddtc. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "WeiboFrame.h"
#import "HMStatusPhotosView.h"

@interface WeiboCell : UITableViewCell

+ (WeiboCell *)cellWithTableView:(UITableView *)tableView;

/**  接收外界传入的模型*/
@property (nonatomic, strong) WeiboFrame *weiboFrame;
/**配图相册*/
@property (nonatomic,strong) HMStatusPhotosView *photosView;

@end


text:
set +u

[ -z ${PGDATA} ] && PGDATA=/var/lib/pgsql/data/userdata

# Depending on the postgresql implementation the directory to write is not the same.
if [ -d /var/lib/pgsql ]; then
	INITFLAG=/var/lib/pgsql/initialized.flag
else
	INITFLAG=/var/lib/postgresql/initialized.flag
fi

if [ ! -f $INITFLAG ] ; then
	if [ "${SAMPLE}" = "true" ] ; then
		echo "$(date) - Restore ODM sample database"
        pg_restore -Fc -d odmdb /upload/data-8.10.next.dump
        echo "$(date) - Database restored successfully"
		echo ""
		if [ -n "$ODM_CONTEXT_ROOT" ] ; then
			echo "Updating Decision Center endpoint user setting with $ODM_CONTEXT_ROOT context."
			cp /upload/update-usersetting.sql /tmp/
			sed -i 's|ODM_CONTEXT_ROOT|'$ODM_CONTEXT_ROOT'|g' /tmp/update-usersetting.sql
			psql -U $POSTGRES_USER -d $POSTGRES_DB -f /tmp/update-usersetting.sql
			echo "Change committed."
			echo "Verifying values:"
			psql -U $POSTGRES_USER -d $POSTGRES_DB -f /upload/verify-usersetting.sql
		fi;
	fi;
	touch $INITFLAG
fi;


text:
<md-card style="max-width: 400px;margin: 10px auto;vertical-align:middle;" flex-gt-xs="33" layout-align="center center">
    <md-card-header>
        <md-card-header-text class="md-title">

Add Author

        </md-card-header-text>
    </md-card-header>

    <md-card-content layout-fill style="text-align: center;">

        <md-input-container class="md-icon-float md-block">
            Author Name
            <input ng-model="name" type="text">
        </md-input-container>

        <md-button class="md-button md-raised" style="margin: 0 auto;" ng-click="add_author()">Submit</md-button>

    </md-card-content>
</md-card>


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>statsmodels.stats.diagnostic.linear_lm — statsmodels v0.10.2 documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.stats.diagnostic.breaks_cusumolsresid" href="statsmodels.stats.diagnostic.breaks_cusumolsresid.html" />
    <link rel="prev" title="statsmodels.stats.diagnostic.linear_rainbow" href="statsmodels.stats.diagnostic.linear_rainbow.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Statistics stats |

statsmodels.stats.diagnostic.linear_lm¶

statsmodels.stats.diagnostic.linear_lm(resid, exog, func=None)[source]¶

Lagrange multiplier test for linearity against functional alternative

limitations: Assumes currently that the first column is integer.
Currently it doesn't check whether the transformed variables contain NaNs,
for example log of negative number.

Parameters

residndarray

residuals of a regression

exogndarray

exogenous variables for which linearity is tested

funccallable

If func is None, then squares are used. func needs to take an array
of exog and return an array of transformed variables.

Returns

lmfloat

Lagrange multiplier test statistic

lm_pvalfloat

p-value of Lagrange multiplier tes

ftestContrastResult instance

the results from the F test variant of this test

Notes

written to match Gretl's linearity test.
The test runs an auxilliary regression of the residuals on the combined
original and transformed regressors.
The Null hypothesis is that the linear specification is correct.

Previous topic

statsmodels.stats.diagnostic.linear_rainbow

Next topic

statsmodels.stats.diagnostic.breaks_cusumolsresid

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>

        © Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 2.2.1.


text:
package org.globsframework.metamodel.index;

public interface NotUniqueIndex extends SingleFieldIndex {
}


text:
class Partner < ApplicationRecord
  belongs_to :type, class_name: 'PartnerType', inverse_of: nil

  translates :name
  translates :description

  mount_uploader :logo, LogoUploader

  validates :name, :logo, presence: true

  default_scope -> { order(order: :asc) }
end


text:
package com.smartdevicelink.test.rpc.datatypes;

import com.smartdevicelink.marshal.JsonRPCMarshaller;
import com.smartdevicelink.proxy.rpc.DateTime;
import com.smartdevicelink.proxy.rpc.WeatherAlert;
import com.smartdevicelink.test.JsonUtils;
import com.smartdevicelink.test.TestValues;
import com.smartdevicelink.test.Validator;

import junit.framework.TestCase;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

/**
 * This is a unit test class for the SmartDeviceLink library project class :
 * {@link com.smartdevicelink.proxy.rpc.WeatherAlert}
 */
public class WeatherAlertTests extends TestCase {

    private WeatherAlert msg;

    @Override
    public void setUp() {

        msg = new WeatherAlert();
        msg.setExpires(TestValues.GENERAL_DATETIME);
        msg.setTimeIssued(TestValues.GENERAL_DATETIME);
        msg.setRegions(TestValues.GENERAL_STRING_LIST);
        msg.setSeverity(TestValues.GENERAL_STRING);
        msg.setSummary(TestValues.GENERAL_STRING);
        msg.setTitle(TestValues.GENERAL_STRING);
    }

    /**
     * Tests the expected values of the RPC message.
     */
    public void testRpcValues() {
        // Test Values
        DateTime expires = msg.getExpires();
        DateTime issued = msg.getTimeIssued();
        List<String> regions = msg.getRegions();
        String severity = msg.getSeverity();
        String summary = msg.getSummary();
        String title = msg.getTitle();

        // Valid Tests
        assertEquals(TestValues.MATCH, expires, TestValues.GENERAL_DATETIME);
        assertEquals(TestValues.MATCH, issued, TestValues.GENERAL_DATETIME);
        assertEquals(TestValues.MATCH, regions, TestValues.GENERAL_STRING_LIST);
        assertEquals(TestValues.MATCH, severity, TestValues.GENERAL_STRING);
        assertEquals(TestValues.MATCH, summary, TestValues.GENERAL_STRING);
        assertEquals(TestValues.MATCH, title, TestValues.GENERAL_STRING);

        // Invalid/Null Tests
        WeatherAlert msg = new WeatherAlert();
        assertNotNull(TestValues.NOT_NULL, msg);

        assertNull(TestValues.NULL, msg.getExpires());
        assertNull(TestValues.NULL, msg.getTimeIssued());
        assertNull(TestValues.NULL, msg.getRegions());
        assertNull(TestValues.NULL, msg.getSeverity());
        assertNull(TestValues.NULL, msg.getSummary());
        assertNull(TestValues.NULL, msg.getTitle());
    }

    public void testRequiredParamsConstructor() {
        msg = new WeatherAlert(TestValues.GENERAL_STRING_LIST);
        List<String> regions = msg.getRegions();
        assertEquals(TestValues.MATCH, regions, TestValues.GENERAL_STRING_LIST);
    }

    public void testJson() {
        JSONObject reference = new JSONObject();

        try {
            reference.put(WeatherAlert.KEY_EXPIRES, TestValues.GENERAL_DATETIME);
            reference.put(WeatherAlert.KEY_TIME_ISSUED, TestValues.GENERAL_DATETIME);
            reference.put(WeatherAlert.KEY_REGIONS, JsonUtils.createJsonArray(TestValues.GENERAL_STRING_LIST));
            reference.put(WeatherAlert.KEY_SEVERITY, TestValues.GENERAL_STRING);
            reference.put(WeatherAlert.KEY_SUMMARY, TestValues.GENERAL_STRING);
            reference.put(WeatherAlert.KEY_TITLE, TestValues.GENERAL_STRING);

            JSONObject underTest = msg.serializeJSON();
            assertEquals(TestValues.MATCH, reference.length(), underTest.length());

            Iterator<?> iterator = reference.keys();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                if (key.equals(WeatherAlert.KEY_EXPIRES) || key.equals(WeatherAlert.KEY_TIME_ISSUED)) {
                    JSONObject testEquals = (JSONObject) JsonUtils.readObjectFromJsonObject(underTest, key);
                    Hashtable<String, Object> hashTest = JsonRPCMarshaller.deserializeJSONObject(testEquals);
                    assertTrue(TestValues.TRUE, Validator.validateDateTime(TestValues.GENERAL_DATETIME, new DateTime(hashTest)));
                } else if (key.equals(WeatherAlert.KEY_REGIONS)) {
                    JSONArray referenceArray = JsonUtils.readJsonArrayFromJsonObject(reference, key);
                    JSONArray underTestArray = JsonUtils.readJsonArrayFromJsonObject(underTest, key);
                    assertEquals(TestValues.MATCH, referenceArray.length(), underTestArray.length());
                    assertTrue(TestValues.TRUE, Validator.validateStringList(JsonUtils.readStringListFromJsonObject(reference, key), JsonUtils.readStringListFromJsonObject(underTest, key)));
                } else {
                    assertEquals(TestValues.MATCH, JsonUtils.readObjectFromJsonObject(reference, key), JsonUtils.readObjectFromJsonObject(underTest, key));
                }
            }
        } catch (JSONException e) {
            fail(TestValues.JSON_FAIL);
        }
    }
}