text:
// THIS FILE IS GENERATED BY ZAP

// Prevent multiple inclusion
#pragma once

// User options for plugin Binding Table Library
#define EMBER_BINDING_TABLE_SIZE 10

/**** Network Section ****/
#define EMBER_SUPPORTED_NETWORKS (1)

#define EMBER_APS_UNICAST_MESSAGE_COUNT 10

/**** Cluster endpoint counts ****/
#define EMBER_AF_ON_OFF_CLUSTER_SERVER_ENDPOINT_COUNT (2)
#define EMBER_AF_LEVEL_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_DESCRIPTOR_CLUSTER_SERVER_ENDPOINT_COUNT (4)
#define EMBER_AF_BINDING_CLUSTER_CLIENT_ENDPOINT_COUNT (1)
#define EMBER_AF_BINDING_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_ACCESS_CONTROL_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_OTA_PROVIDER_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_LOCALIZATION_CONFIGURATION_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_TIME_FORMAT_LOCALIZATION_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_UNIT_LOCALIZATION_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_GENERAL_COMMISSIONING_CLUSTER_CLIENT_ENDPOINT_COUNT (1)
#define EMBER_AF_GENERAL_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_NETWORK_COMMISSIONING_CLUSTER_CLIENT_ENDPOINT_COUNT (1)
#define EMBER_AF_NETWORK_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_DIAGNOSTIC_LOGS_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_GENERAL_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_SOFTWARE_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_THREAD_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_WIFI_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_ADMINISTRATOR_COMMISSIONING_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_OPERATIONAL_CREDENTIALS_CLUSTER_CLIENT_ENDPOINT_COUNT (1)
#define EMBER_AF_OPERATIONAL_CREDENTIALS_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_GROUP_KEY_MANAGEMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_FIXED_LABEL_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_USER_LABEL_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_WAKE_ON_LAN_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_CHANNEL_CLUSTER_SERVER_ENDPOINT_COUNT (2)
#define EMBER_AF_TARGET_NAVIGATOR_CLUSTER_SERVER_ENDPOINT_COUNT (2)
#define EMBER_AF_MEDIA_PLAYBACK_CLUSTER_SERVER_ENDPOINT_COUNT (2)
#define EMBER_AF_MEDIA_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_LOW_POWER_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_KEYPAD_INPUT_CLUSTER_SERVER_ENDPOINT_COUNT (2)
#define EMBER_AF_CONTENT_LAUNCH_CLUSTER_SERVER_ENDPOINT_COUNT (2)
#define EMBER_AF_AUDIO_OUTPUT_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_APPLICATION_LAUNCHER_CLUSTER_SERVER_ENDPOINT_COUNT (2)
#define EMBER_AF_APPLICATION_BASIC_CLUSTER_SERVER_ENDPOINT_COUNT (1)
#define EMBER_AF_ACCOUNT_LOGIN_CLUSTER_SERVER_ENDPOINT_COUNT (1)

/**** Cluster Plugins ****/

// Use this macro to check if the server side of the On/Off cluster is included
#define ZCL_USING_ON_OFF_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_ON_OFF_SERVER
#define EMBER_AF_PLUGIN_ON_OFF

// Use this macro to check if the server side of the Level Control cluster is included
#define ZCL_USING_LEVEL_CONTROL_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_LEVEL_CONTROL_SERVER
#define EMBER_AF_PLUGIN_LEVEL_CONTROL
// User options for server plugin Level Control
#define EMBER_AF_PLUGIN_LEVEL_CONTROL_MAXIMUM_LEVEL 254
#define EMBER_AF_PLUGIN_LEVEL_CONTROL_MINIMUM_LEVEL 0
#define EMBER_AF_PLUGIN_LEVEL_CONTROL_RATE 0

// Use this macro to check if the server side of the Descriptor cluster is included
#define ZCL_USING_DESCRIPTOR_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_DESCRIPTOR_SERVER
#define EMBER_AF_PLUGIN_DESCRIPTOR

// Use this macro to check if the client side of the Binding cluster is included
#define ZCL_USING_BINDING_CLUSTER_CLIENT
#define EMBER_AF_PLUGIN_BINDING_CLIENT

// Use this macro to check if the server side of the Binding cluster is included
#define ZCL_USING_BINDING_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_BINDING_SERVER
#define EMBER_AF_PLUGIN_BINDING

// Use this macro to check if the server side of the Access Control cluster is included
#define ZCL_USING_ACCESS_CONTROL_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_ACCESS_CONTROL_SERVER
#define EMBER_AF_PLUGIN_ACCESS_CONTROL

// Use this macro to check if the server side of the Basic cluster is included
#define ZCL_USING_BASIC_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_BASIC_SERVER
#define EMBER_AF_PLUGIN_BASIC

// Use this macro to check if the server side of the OTA Software Update Provider cluster is included
#define ZCL_USING_OTA_PROVIDER_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_OTA_SOFTWARE_UPDATE_PROVIDER_SERVER
#define EMBER_AF_PLUGIN_OTA_SOFTWARE_UPDATE_PROVIDER

// Use this macro to check if the server side of the Localization Configuration cluster is included
#define ZCL_USING_LOCALIZATION_CONFIGURATION_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_LOCALIZATION_CONFIGURATION_SERVER
#define EMBER_AF_PLUGIN_LOCALIZATION_CONFIGURATION

// Use this macro to check if the server side of the Time Format Localization cluster is included
#define ZCL_USING_TIME_FORMAT_LOCALIZATION_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_TIME_FORMAT_LOCALIZATION_SERVER
#define EMBER_AF_PLUGIN_TIME_FORMAT_LOCALIZATION

// Use this macro to check if the server side of the Unit Localization cluster is included
#define ZCL_USING_UNIT_LOCALIZATION_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_UNIT_LOCALIZATION_SERVER
#define EMBER_AF_PLUGIN_UNIT_LOCALIZATION

// Use this macro to check if the client side of the General Commissioning cluster is included
#define ZCL_USING_GENERAL_COMMISSIONING_CLUSTER_CLIENT
#define EMBER_AF_PLUGIN_GENERAL_COMMISSIONING_CLIENT

// Use this macro to check if the server side of the General Commissioning cluster is included
#define ZCL_USING_GENERAL_COMMISSIONING_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_GENERAL_COMMISSIONING_SERVER
#define EMBER_AF_PLUGIN_GENERAL_COMMISSIONING

// Use this macro to check if the client side of the Network Commissioning cluster is included
#define ZCL_USING_NETWORK_COMMISSIONING_CLUSTER_CLIENT
#define EMBER_AF_PLUGIN_NETWORK_COMMISSIONING_CLIENT

// Use this macro to check if the server side of the Network Commissioning cluster is included
#define ZCL_USING_NETWORK_COMMISSIONING_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_NETWORK_COMMISSIONING_SERVER
#define EMBER_AF_PLUGIN_NETWORK_COMMISSIONING

// Use this macro to check if the server side of the Diagnostic Logs cluster is included
#define ZCL_USING_DIAGNOSTIC_LOGS_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_DIAGNOSTIC_LOGS_SERVER
#define EMBER_AF_PLUGIN_DIAGNOSTIC_LOGS

// Use this macro to check if the server side of the General Diagnostics cluster is included
#define ZCL_USING_GENERAL_DIAGNOSTICS_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_GENERAL_DIAGNOSTICS_SERVER
#define EMBER_AF_PLUGIN_GENERAL_DIAGNOSTICS

// Use this macro to check if the server side of the Software Diagnostics cluster is included
#define ZCL_USING_SOFTWARE_DIAGNOSTICS_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_SOFTWARE_DIAGNOSTICS_SERVER
#define EMBER_AF_PLUGIN_SOFTWARE_DIAGNOSTICS

// Use this macro to check if the server side of the Thread Network Diagnostics cluster is included
#define ZCL_USING_THREAD_NETWORK_DIAGNOSTICS_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_THREAD_NETWORK_DIAGNOSTICS_SERVER
#define EMBER_AF_PLUGIN_THREAD_NETWORK_DIAGNOSTICS

// Use this macro to check if the server side of the WiFi Network Diagnostics cluster is included
#define ZCL_USING_WIFI_NETWORK_DIAGNOSTICS_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_WI_FI_NETWORK_DIAGNOSTICS_SERVER
#define EMBER_AF_PLUGIN_WI_FI_NETWORK_DIAGNOSTICS

// Use this macro to check if the server side of the Ethernet Network Diagnostics cluster is included
#define ZCL_USING_ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_ETHERNET_NETWORK_DIAGNOSTICS_SERVER
#define EMBER_AF_PLUGIN_ETHERNET_NETWORK_DIAGNOSTICS

// Use this macro to check if the server side of the AdministratorCommissioning cluster is included
#define ZCL_USING_ADMINISTRATOR_COMMISSIONING_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_ADMINISTRATOR_COMMISSIONING_SERVER
#define EMBER_AF_PLUGIN_ADMINISTRATOR_COMMISSIONING

// Use this macro to check if the client side of the Operational Credentials cluster is included
#define ZCL_USING_OPERATIONAL_CREDENTIALS_CLUSTER_CLIENT
#define EMBER_AF_PLUGIN_OPERATIONAL_CREDENTIALS_CLIENT

// Use this macro to check if the server side of the Operational Credentials cluster is included
#define ZCL_USING_OPERATIONAL_CREDENTIALS_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_OPERATIONAL_CREDENTIALS_SERVER
#define EMBER_AF_PLUGIN_OPERATIONAL_CREDENTIALS

// Use this macro to check if the server side of the Group Key Management cluster is included
#define ZCL_USING_GROUP_KEY_MANAGEMENT_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_GROUP_KEY_MANAGEMENT_SERVER
#define EMBER_AF_PLUGIN_GROUP_KEY_MANAGEMENT

// Use this macro to check if the server side of the Fixed Label cluster is included
#define ZCL_USING_FIXED_LABEL_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_FIXED_LABEL_SERVER
#define EMBER_AF_PLUGIN_FIXED_LABEL

// Use this macro to check if the server side of the User Label cluster is included
#define ZCL_USING_USER_LABEL_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_USER_LABEL_SERVER
#define EMBER_AF_PLUGIN_USER_LABEL

// Use this macro to check if the server side of the Relative Humidity Measurement cluster is included
#define ZCL_USING_RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_RELATIVE_HUMIDITY_MEASUREMENT_SERVER
#define EMBER_AF_PLUGIN_RELATIVE_HUMIDITY_MEASUREMENT

// Use this macro to check if the server side of the Wake on LAN cluster is included
#define ZCL_USING_WAKE_ON_LAN_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_WAKE_ON_LAN_SERVER
#define EMBER_AF_PLUGIN_WAKE_ON_LAN

// Use this macro to check if the server side of the Channel cluster is included
#define ZCL_USING_CHANNEL_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_CHANNEL_SERVER
#define EMBER_AF_PLUGIN_CHANNEL

// Use this macro to check if the server side of the Target Navigator cluster is included
#define ZCL_USING_TARGET_NAVIGATOR_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_TARGET_NAVIGATOR_SERVER
#define EMBER_AF_PLUGIN_TARGET_NAVIGATOR

// Use this macro to check if the server side of the Media Playback cluster is included
#define ZCL_USING_MEDIA_PLAYBACK_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_MEDIA_PLAYBACK_SERVER
#define EMBER_AF_PLUGIN_MEDIA_PLAYBACK

// Use this macro to check if the server side of the Media Input cluster is included
#define ZCL_USING_MEDIA_INPUT_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_MEDIA_INPUT_SERVER
#define EMBER_AF_PLUGIN_MEDIA_INPUT

// Use this macro to check if the server side of the Low Power cluster is included
#define ZCL_USING_LOW_POWER_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_LOW_POWER_SERVER
#define EMBER_AF_PLUGIN_LOW_POWER

// Use this macro to check if the server side of the Keypad Input cluster is included
#define ZCL_USING_KEYPAD_INPUT_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_KEYPAD_INPUT_SERVER
#define EMBER_AF_PLUGIN_KEYPAD_INPUT

// Use this macro to check if the server side of the Content Launcher cluster is included
#define ZCL_USING_CONTENT_LAUNCH_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_CONTENT_LAUNCHER_SERVER
#define EMBER_AF_PLUGIN_CONTENT_LAUNCHER

// Use this macro to check if the server side of the Audio Output cluster is included
#define ZCL_USING_AUDIO_OUTPUT_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_AUDIO_OUTPUT_SERVER
#define EMBER_AF_PLUGIN_AUDIO_OUTPUT

// Use this macro to check if the server side of the Application Launcher cluster is included
#define ZCL_USING_APPLICATION_LAUNCHER_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_APPLICATION_LAUNCHER_SERVER
#define EMBER_AF_PLUGIN_APPLICATION_LAUNCHER

// Use this macro to check if the server side of the Application Basic cluster is included
#define ZCL_USING_APPLICATION_BASIC_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_APPLICATION_BASIC_SERVER
#define EMBER_AF_PLUGIN_APPLICATION_BASIC

// Use this macro to check if the server side of the Account Login cluster is included
#define ZCL_USING_ACCOUNT_LOGIN_CLUSTER_SERVER
#define EMBER_AF_PLUGIN_ACCOUNT_LOGIN_SERVER
#define EMBER_AF_PLUGIN_ACCOUNT_LOGIN

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Answer;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\CompositeItem;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\CompositeLabel;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\CompositeRelation;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Container;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyAggregateOffer;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyCar;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyCarColor;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyFriend;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyGroup;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyOffer;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyProduct;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyProperty;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\EmbeddableDummy;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\EmbeddedDummy;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\FileConfigDummy;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Foo;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Node;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Person;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\PersonToPet;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Pet;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Question;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\RelatedDummy;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\RelatedToDummyFriend;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\RelationEmbedder;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\User;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\UuidIdentifierDummy;
use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behatch\HttpCall\Request;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\Tools\SchemaTool;

/**
 * Defines application features from the specific context.
 */
class FeatureContext implements Context, SnippetAcceptingContext
{
    private $doctrine;

    /**
     * @var ObjectManager
     */
    private $manager;

    /**
     * @var SchemaTool
     */
    private $schemaTool;

    /**
     * @var array
     */
    private $classes;

    /**
     * @var Request
     */
    private $request;

    /**
     * Initializes context.
     *
     * Every scenario gets its own context instance.
     * You can also pass arbitrary arguments to the
     * context constructor through behat.yml.
     */
    public function __construct(ManagerRegistry $doctrine, Request $request)
    {
        $this->doctrine = $doctrine;
        $this->manager = $doctrine->getManager();
        $this->schemaTool = new SchemaTool($this->manager);
        $this->classes = $this->manager->getMetadataFactory()->getAllMetadata();
        $this->request = $request;
    }

    /**
     * Sets the default Accept HTTP header to null (workaround to artificially remove it).
     *
     * @BeforeScenario
     */
    public function removeAcceptHeader()
    {
        $this->request->setHttpHeader('Accept', null);
    }

    /**
     * @BeforeScenario @createSchema
     */
    public function createDatabase()
    {
        $this->schemaTool->createSchema($this->classes);
    }

    /**
     * @AfterScenario @dropSchema
     */
    public function dropDatabase()
    {
        $this->schemaTool->dropSchema($this->classes);
        $this->doctrine->getManager()->clear();
    }

    /**
     * @Given there is :nb dummy objects
     */
    public function thereIsDummyObjects($nb)
    {
        $descriptions = ['Smart dummy.', 'Not so smart dummy.'];

        for ($i = 1; $i <= $nb; ++$i) {
            $dummy = new Dummy();
            $dummy->setName('Dummy #'.$i);
            $dummy->setAlias('Alias #'.($nb - $i));
            $dummy->setDummy('SomeDummyTest'.$i);
            $dummy->setDescription($descriptions[($i - 1) % 2]);

            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there are :nb foo objects with fake names
     */
    public function thereAreFooObjectsWithFakeNames($nb)
    {
        $names = ['Hawsepipe', 'Sthenelus', 'Ephesian', 'Separativeness', 'Balbo'];
        $bars = ['Lorem', 'Dolor', 'Dolor', 'Sit', 'Amet'];

        for ($i = 0; $i < $nb; ++$i) {
            $foo = new Foo();
            $foo->setName($names[$i]);
            $foo->setBar($bars[$i]);

            $this->manager->persist($foo);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb dummy group objects
     */
    public function thereIsDummyGroupObjects($nb)
    {
        for ($i = 1; $i <= $nb; ++$i) {
            $dummyGroup = new DummyGroup();

            foreach (['foo', 'bar', 'baz', 'qux'] as $property) {
                $dummyGroup->$property = ucfirst($property).' #'.$i;
            }

            $this->manager->persist($dummyGroup);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb dummy property objects
     */
    public function thereIsDummyPropertyObjects($nb)
    {
        for ($i = 1; $i <= $nb; ++$i) {
            $dummyProperty = new DummyProperty();
            $dummyGroup = new DummyGroup();

            foreach (['foo', 'bar', 'baz'] as $property) {
                $dummyProperty->$property = $dummyGroup->$property = ucfirst($property).' #'.$i;
            }

            $dummyProperty->group = $dummyGroup;

            $this->manager->persist($dummyGroup);
            $this->manager->persist($dummyProperty);
        }

        $this->manager->flush();
    }

    /**
     * @Given there are :nb embedded dummy objects
     */
    public function thereIsEmbeddedDummyObjects($nb)
    {
        for ($i = 1; $i <= $nb; ++$i) {
            $dummy = new EmbeddedDummy();
            $dummy->setName('Dummy #'.$i);

            $embeddableDummy = new EmbeddableDummy();
            $embeddableDummy->setDummyName('Dummy #'.$i);
            $dummy->setEmbeddedDummy($embeddableDummy);

            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb dummy objects with relatedDummy
     */
    public function thereIsDummyObjectsWithRelatedDummy($nb)
    {
        for ($i = 1; $i <= $nb; ++$i) {
            $relatedDummy = new RelatedDummy();
            $relatedDummy->setName('RelatedDummy #'.$i);

            $dummy = new Dummy();
            $dummy->setName('Dummy #'.$i);
            $dummy->setAlias('Alias #'.($nb - $i));
            $dummy->setRelatedDummy($relatedDummy);

            $this->manager->persist($relatedDummy);
            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb dummy objects with embeddedDummy
     */
    public function thereIsDummyObjectsWithEmbeddedDummy($nb)
    {
        for ($i = 1; $i <= $nb; ++$i) {
            $embeddableDummy = new EmbeddableDummy();
            $embeddableDummy->setDummyName('EmbeddedDummy #'.$i);

            $dummy = new EmbeddedDummy();
            $dummy->setName('Dummy #'.$i);
            $dummy->setEmbeddedDummy($embeddableDummy);

            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb dummy objects having each :nbrelated relatedDummies
     */
    public function thereIsDummyObjectsWithRelatedDummies($nb, $nbrelated)
    {
        for ($i = 1; $i <= $nb; ++$i) {
            $dummy = new Dummy();
            $dummy->setName('Dummy #'.$i);
            $dummy->setAlias('Alias #'.($nb - $i));

            for ($j = 1; $j <= $nbrelated; ++$j) {
                $relatedDummy = new RelatedDummy();
                $relatedDummy->setName('RelatedDummy'.$j.$i);
                $this->manager->persist($relatedDummy);
                $dummy->addRelatedDummy($relatedDummy);
            }

            $this->manager->persist($relatedDummy);
            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb dummy objects with dummyDate
     */
    public function thereIsDummyObjectsWithDummyDate($nb)
    {
        $descriptions = ['Smart dummy.', 'Not so smart dummy.'];

        for ($i = 1; $i <= $nb; ++$i) {
            $date = new \DateTime(sprintf('2015-04-%d', $i), new \DateTimeZone('UTC'));

            $dummy = new Dummy();
            $dummy->setName('Dummy #'.$i);
            $dummy->setAlias('Alias #'.($nb - $i));
            $dummy->setDescription($descriptions[($i - 1) % 2]);

            // Last Dummy has a null date
            if ($nb !== $i) {
                $dummy->setDummyDate($date);
            }

            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb dummy objects with dummyDate and dummyBoolean :bool
     */
    public function thereIsDummyObjectsWithDummyDateAndDummyBoolean($nb, $bool)
    {
        $descriptions = ['Smart dummy.', 'Not so smart dummy.'];

        if (in_array($bool, ['true', '1', 1], true)) {
            $bool = true;
        } elseif (in_array($bool, ['false', '0', 0], true)) {
            $bool = false;
        } else {
            $expected = ['true', 'false', '1', '0'];
            throw new InvalidArgumentException(sprintf('Invalid boolean value for "%s" property, expected one of ( "%s" )', $bool, implode('" | "', $expected)));
        }

        for ($i = 1; $i <= $nb; ++$i) {
            $date = new \DateTime(sprintf('2015-04-%d', $i), new \DateTimeZone('UTC'));

            $dummy = new Dummy();
            $dummy->setName('Dummy #'.$i);
            $dummy->setAlias('Alias #'.($nb - $i));
            $dummy->setDescription($descriptions[($i - 1) % 2]);
            $dummy->setDummyBoolean($bool);

            // Last Dummy has a null date
            if ($nb !== $i) {
                $dummy->setDummyDate($date);
            }

            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb dummy objects with dummyDate and relatedDummy
     */
    public function thereIsDummyObjectsWithDummyDateAndRelatedDummy($nb)
    {
        for ($i = 1; $i <= $nb; ++$i) {
            $date = new \DateTime(sprintf('2015-04-%d', $i), new \DateTimeZone('UTC'));

            $relatedDummy = new RelatedDummy();
            $relatedDummy->setName('RelatedDummy #'.$i);
            $relatedDummy->setDummyDate($date);

            $dummy = new Dummy();
            $dummy->setName('Dummy #'.$i);
            $dummy->setAlias('Alias #'.($nb - $i));
            $dummy->setRelatedDummy($relatedDummy);
            // Last Dummy has a null date
            if ($nb !== $i) {
                $dummy->setDummyDate($date);
            }

            $this->manager->persist($relatedDummy);
            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb embedded dummy objects with dummyDate and embeddedDummy
     */
    public function thereIsDummyObjectsWithDummyDateAndEmbeddedDummy($nb)
    {
        for ($i = 1; $i <= $nb; ++$i) {
            $date = new \DateTime(sprintf('2015-04-%d', $i), new \DateTimeZone('UTC'));

            $embeddableDummy = new EmbeddableDummy();
            $embeddableDummy->setDummyName('Embeddable #'.$i);
            $embeddableDummy->setDummyDate($date);

            $dummy = new EmbeddedDummy();
            $dummy->setName('Dummy #'.$i);
            $dummy->setEmbeddedDummy($embeddableDummy);
            // Last Dummy has a null date
            if ($nb !== $i) {
                $dummy->setDummyDate($date);
            }

            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb dummy objects with dummyPrice
     */
    public function thereIsDummyObjectsWithDummyPrice($nb)
    {
        $descriptions = ['Smart dummy.', 'Not so smart dummy.'];
        $prices = ['9.99', '12.99', '15.99', '19.99'];

        for ($i = 1; $i <= $nb; ++$i) {
            $dummy = new Dummy();
            $dummy->setName('Dummy #'.$i);
            $dummy->setAlias('Alias #'.($nb - $i));
            $dummy->setDescription($descriptions[($i - 1) % 2]);
            $dummy->setDummyPrice($prices[($i - 1) % 4]);

            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb dummy objects with dummyBoolean :bool
     */
    public function thereIsDummyObjectsWithDummyBoolean($nb, $bool)
    {
        if (in_array($bool, ['true', '1', 1], true)) {
            $bool = true;
        } elseif (in_array($bool, ['false', '0', 0], true)) {
            $bool = false;
        } else {
            $expected = ['true', 'false', '1', '0'];
            throw new InvalidArgumentException(sprintf('Invalid boolean value for "%s" property, expected one of ( "%s" )', $bool, implode('" | "', $expected)));
        }
        $descriptions = ['Smart dummy.', 'Not so smart dummy.'];

        for ($i = 1; $i <= $nb; ++$i) {
            $dummy = new Dummy();
            $dummy->setName('Dummy #'.$i);
            $dummy->setAlias('Alias #'.($nb - $i));
            $dummy->setDescription($descriptions[($i - 1) % 2]);
            $dummy->setDummyBoolean($bool);

            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb embedded dummy objects with embeddedDummy.dummyBoolean :bool
     */
    public function thereIsDummyObjectsWithEmbeddedDummyBoolean($nb, $bool)
    {
        if (in_array($bool, ['true', '1', 1], true)) {
            $bool = true;
        } elseif (in_array($bool, ['false', '0', 0], true)) {
            $bool = false;
        } else {
            $expected = ['true', 'false', '1', '0'];
            throw new InvalidArgumentException(sprintf('Invalid boolean value for "%s" property, expected one of ( "%s" )', $bool, implode('" | "', $expected)));
        }

        for ($i = 1; $i <= $nb; ++$i) {
            $dummy = new EmbeddedDummy();
            $dummy->setName('Embedded Dummy #'.$i);
            $embeddableDummy = new EmbeddableDummy();
            $embeddableDummy->setDummyName('Embedded Dummy #'.$i);
            $embeddableDummy->setDummyBoolean($bool);
            $dummy->setEmbeddedDummy($embeddableDummy);
            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is :nb embedded dummy objects with relatedDummy.embeddedDummy.dummyBoolean :bool
     */
    public function thereIsDummyObjectsWithRelationEmbeddedDummyBoolean($nb, $bool)
    {
        if (in_array($bool, ['true', '1', 1], true)) {
            $bool = true;
        } elseif (in_array($bool, ['false', '0', 0], true)) {
            $bool = false;
        } else {
            $expected = ['true', 'false', '1', '0'];
            throw new InvalidArgumentException(sprintf('Invalid boolean value for "%s" property, expected one of ( "%s" )', $bool, implode('" | "', $expected)));
        }

        for ($i = 1; $i <= $nb; ++$i) {
            $dummy = new EmbeddedDummy();
            $dummy->setName('Embedded Dummy #'.$i);
            $embeddableDummy = new EmbeddableDummy();
            $embeddableDummy->setDummyName('Embedded Dummy #'.$i);
            $embeddableDummy->setDummyBoolean($bool);

            $relationDummy = new RelatedDummy();
            $relationDummy->setEmbeddedDummy($embeddableDummy);

            $dummy->setRelatedDummy($relationDummy);

            $this->manager->persist($relationDummy);
            $this->manager->persist($dummy);
        }

        $this->manager->flush();
    }

    /**
     * @Given there is a RelationEmbedder object
     */
    public function thereIsARelationEmbedderObject()
    {
        $relationEmbedder = new RelationEmbedder();

        $this->manager->persist($relationEmbedder);
        $this->manager->flush();
    }

    /**
     * @Given there is a Dummy Object mapped by UUID
     */
    public function thereIsADummyObjectMappedByUUID()
    {
        $dummy = new UuidIdentifierDummy();
        $dummy->setName('My Dummy');
        $dummy->setUuid('41B29566-144B-11E6-A148-3E1D05DEFE78');

        $this->manager->persist($dummy);
        $this->manager->flush();
    }

    /**
     * @Given there are Composite identifier objects
     */
    public function thereIsACompositeIdentifierObject()
    {
        $item = new CompositeItem();
        $item->setField1('foobar');
        $this->manager->persist($item);

        for ($i = 0; $i < 4; ++$i) {
            $label = new CompositeLabel();
            $label->setValue('foo-'.$i);

            $rel = new CompositeRelation();
            $rel->setCompositeLabel($label);
            $rel->setCompositeItem($item);
            $rel->setValue('somefoobardummy');

            $this->manager->persist($label);
            $this->manager->persist($rel);
        }

        $this->manager->flush();
        $this->manager->clear();
    }

    /**
     * @Given there is a FileConfigDummy object
     */
    public function thereIsAFileConfigDummyObject()
    {
        $fileConfigDummy = new FileConfigDummy();
        $fileConfigDummy->setName('ConfigDummy');
        $fileConfigDummy->setFoo('Foo');

        $this->manager->persist($fileConfigDummy);
        $this->manager->flush();
    }

    /**
     * @Given there is a DummyCar entity with related colors
     */
    public function thereIsAFooEntityWithRelatedBars()
    {
        $foo = new DummyCar();
        $this->manager->persist($foo);

        $bar1 = new DummyCarColor();
        $bar1->setProp('red');
        $bar1->setCar($foo);
        $this->manager->persist($bar1);

        $bar2 = new DummyCarColor();
        $bar2->setProp('blue');
        $bar2->setCar($foo);
        $this->manager->persist($bar2);

        $foo->setColors([$bar1, $bar2]);
        $this->manager->persist($foo);

        $this->manager->flush();
    }

    /**
     * @Given there is a RelatedDummy with :nb friends
     */
    public function thereIsARelatedDummyWithFriends($nb)
    {
        $relatedDummy = new RelatedDummy();
        $relatedDummy->setName('RelatedDummy with friends');
        $this->manager->persist($relatedDummy);

        for ($i = 1; $i <= $nb; ++$i) {
            $friend = new DummyFriend();
            $friend->setName('Friend-'.$i);

            $this->manager->persist($friend);

            $relation = new RelatedToDummyFriend();
            $relation->setName('Relation-'.$i);
            $relation->setDummyFriend($friend);
            $relation->setRelatedDummy($relatedDummy);

            $relatedDummy->addRelatedToDummyFriend($relation);

            $this->manager->persist($relation);
        }

        $relatedDummy2 = new RelatedDummy();
        $relatedDummy2->setName('RelatedDummy without friends');
        $this->manager->persist($relatedDummy2);
        $this->manager->flush();
    }

    /**
     * @Given there is an answer ":answer" to the question ":question"
     */
    public function thereIsAnAnswerToTheQuestion(string $a, string $q)
    {
        $answer = new Answer();
        $answer->setContent($a);

        $question = new Question();
        $question->setContent($q);
        $question->setAnswer($answer);
        $answer->addRelatedQuestion($question);

        $this->manager->persist($answer);
        $this->manager->persist($question);

        $this->manager->flush();
    }

    /**
     * @Given there are :nb nodes in a container :uuid
     */
    public function thereAreNodesInAContainer($nb, $uuid)
    {
        $container = new Container();
        $container->setId($uuid);
        $this->manager->persist($container);

        for ($i = 0; $i < $nb; ++$i) {
            $node = new Node();
            $node->setContainer($container);
            $node->setSerial($i);
            $this->manager->persist($node);
        }

        $this->manager->flush();
    }

    /**
     * @Then the password :password for user :user should be hashed
     */
    public function thePasswordForUserShouldBeHashed($password, $user)
    {
        $repository = $this->doctrine->getRepository(User::class);
        $user = $repository->find($user);

        if (!password_verify($password, $user->getPassword())) {
            throw new \Exception('User password mismatch');
        }
    }

    /**
     * @Given I have a product with offers
     */
    public function createProductWithOffers()
    {
        $offer = new DummyOffer();
        $offer->setValue(2);
        $aggregate = new DummyAggregateOffer();
        $aggregate->setValue(1);
        $aggregate->addOffer($offer);

        $product = new DummyProduct();
        $product->setName('Dummy product');
        $product->addOffer($aggregate);

        $relatedProduct = new DummyProduct();
        $relatedProduct->setName('Dummy related product');
        $relatedProduct->setParent($product);

        $product->addRelatedProduct($relatedProduct);

        $this->manager->persist($relatedProduct);
        $this->manager->persist($product);
        $this->manager->flush();
    }

    /**
     * @Given there are people having pets
     */
    public function createPeopleWithPets()
    {
        $personToPet = new PersonToPet();

        $person = new Person();
        $person->name = 'foo';

        $pet = new Pet();
        $pet->name = 'bar';

        $personToPet->person = $person;
        $personToPet->pet = $pet;

        $this->manager->persist($person);
        $this->manager->persist($pet);
        $this->manager->persist($personToPet);

        $person->pets->add($personToPet);
        $this->manager->persist($person);

        $this->manager->flush();
    }
}


text:
"use strict";

const fs = require("fs");
const path = require("path");
const rimrafSync = require("rimraf").sync;

exports.removeDirSync = function removeDirSync(dir) {
  fs.readdirSync(dir); // Will throw if dir is not a directory
  rimrafSync(dir, {
    disableGlob: true,
  });
};

exports.copySubtreeSync = function copySubtreeSync(src, dest) {
  const files = fs.readdirSync(src);
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest);
  }
  files.forEach(function (filename) {
    const srcFile = path.join(src, filename);
    const file = path.join(dest, filename);
    const stats = fs.statSync(srcFile);
    if (stats.isDirectory()) {
      copySubtreeSync(srcFile, file);
    } else {
      fs.writeFileSync(file, fs.readFileSync(srcFile));
    }
  });
};

exports.ensureDirSync = function ensureDirSync(dir) {
  if (fs.existsSync(dir)) {
    return;
  }
  const parts = dir.split(path.sep);
  let i = parts.length;
  while (i > 1 && !fs.existsSync(parts.slice(0, i - 1).join(path.sep))) {
    i--;
  }
  if (i < 0 || (i === 0 && parts[0])) {
    throw new Error();
  }

  while (i <= parts.length) {
    fs.mkdirSync(parts.slice(0, i).join(path.sep));
    i++;
  }
};


text:
namespace System {
using System.Globalization;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;

    //
    // A limited conversion is implemented such as to and from string
    // A conversion to InstanceDescriptor is also provided for design time support.
    //
    public class UriTypeConverter: TypeConverter
    {
        private UriKind m_UriKind;

        public UriTypeConverter() : this(UriKind.RelativeOrAbsolute) { }

        internal UriTypeConverter(UriKind uriKind)
        {
            m_UriKind = uriKind;
        }

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == null)
                throw new ArgumentNullException("sourceType");

            if (sourceType == typeof(string))
                return true;

            if (typeof(Uri).IsAssignableFrom(sourceType))
                return true;

            return base.CanConvertFrom(context, sourceType);
        }
        //
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(InstanceDescriptor))
                return true;

            if (destinationType == typeof(string))
                return true;

            if (destinationType == typeof(Uri))
                return true;

            return base.CanConvertTo(context, destinationType);
        }
        //
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture,  object value)
        {
            string uriString = value as string;
            if (uriString != null)
                return new Uri(uriString, m_UriKind);

            Uri uri = value as Uri;
            if (uri != null)
                return new Uri(uri.OriginalString,
                    m_UriKind == UriKind.RelativeOrAbsolute ? uri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative : m_UriKind);

            return base.ConvertFrom(context, culture, value);
        }
        //
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            Uri uri = value as Uri;

            if (uri != null && destinationType == typeof(InstanceDescriptor))
            {
                ConstructorInfo ci = typeof(Uri).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, new Type[]{typeof(string), typeof(UriKind)}, null);
                return new InstanceDescriptor(ci, new object[] { uri.OriginalString,
                    m_UriKind == UriKind.RelativeOrAbsolute ? uri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative : m_UriKind });
            }

            if (uri != null && destinationType == typeof(string))
                return uri.OriginalString;

            if (uri != null && destinationType == typeof(Uri))
                return new Uri(uri.OriginalString,
                    m_UriKind == UriKind.RelativeOrAbsolute ? uri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative : m_UriKind);

            return base.ConvertTo(context, culture, value, destinationType);
        }
        //
        public override bool IsValid(ITypeDescriptorContext context, object value)
        {
            string str = value as string;
            Uri temp;
            if (str != null)
                return Uri.TryCreate(str, m_UriKind, out temp);

            return value is Uri;
        }
    }

}


text:
var dir_3b37120947cf8e3c990de932a73a0168 =
[
    [ "SegmentedControlViewRenderer.cs", "_segmented_control_view_renderer_8cs.html", [
      [ "SegmentedControlViewRenderer", "class_x_labs_1_1_forms_1_1_controls_1_1_segmented_control_view_renderer.html", "class_x_labs_1_1_forms_1_1_controls_1_1_segmented_control_view_renderer" ]
    ] ]
];


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/Users/gokhanc/src/sdkrm/out/android-sdk/facebook/res/values-hdpi/dimens.xml -->
    <eat-comment/>
    <dimen name="com_facebook_picker_divider_width">1px</dimen>
</resources>


text:
<?php

$orig_post = $post;
global $post;

$categories = get_the_category($post->ID);

if ($categories) {

	$category_ids = array();

	foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;

	$args = array(
		'category__in'     => $category_ids,
		'post__not_in'     => array($post->ID),
		'posts_per_page'   => 3, // Number of related posts that will be shown.
		'ignore_sticky_posts' => 1,
		'orderby' => 'rand'
	);

	$my_query = new wp_query( $args );
	if( $my_query->have_posts() ) { ?>

<?php _e('You Might Also Like', 'solopine'); ?>

		<?php while( $my_query->have_posts() ) {
			$my_query->the_post();?>

					<?php if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) : ?>
					<a href="<?php echo get_permalink() ?>"><?php the_post_thumbnail('misc-thumb'); ?>
					<?php endif; ?>

<a href="<?php echo get_permalink(); ?>"><?php the_title(); ?>

					<?php the_time( get_option('date_format') ); ?>

		<?php
		}
		echo '
';
	}
}
$post = $orig_post;
wp_reset_query();

?>


text:
package io.github.kuyer.jbase.lang.mbean;

import java.util.concurrent.atomic.AtomicLong;

import javax.management.AttributeChangeNotification;
import javax.management.NotificationBroadcasterSupport;

public class Server extends NotificationBroadcasterSupport implements ServerMBean {

	private AtomicLong seq = new AtomicLong(1);
	private String address;

	@Override
	public void setAddress(String address) {
		String oldAddress = this.address;
		this.address = address;
		AttributeChangeNotification notification = new AttributeChangeNotification(this,
				seq.getAndIncrement(),
				System.currentTimeMillis(),
				AttributeChangeNotification.ATTRIBUTE_CHANGE,
				"Server Address Changed",
				"java.lang.String",
				oldAddress,
				this.address);
		super.sendNotification(notification);
	}

	@Override
	public String getAddress() {
		return address;
	}

}


text:
#pragma once

#include "raster/protocol/http/Transport.h"

namespace rdd {

class HTTPSyncTransport : public HTTPTransport {
 public:
  HTTPSyncTransport(const Peer& peer, const TimeoutOption& timeout)
    : HTTPTransport(TransportDirection::UPSTREAM),
      peer_(peer),
      timeout_(timeout) {}

  ~HTTPSyncTransport() override {}

  void open();

  bool isOpen();

  void close();

  void send();

  void recv();

 private:
  Peer peer_;
  TimeoutOption timeout_;
  std::unique_ptr<Socket> socket_;
};

} // namespace rdd


text:
title: "Contract & IT News"
linktitle: "Contract & IT News"
description: "Contract & IT news from PSNC"

date: 2018-09-01
publishdate: 2018-09-01
lastmod: 2018-09-01
categories: ["news", "contract", "IT"]
tags: ["news"]
menu:
  docs:
    parent: "pharmacy-contract"
    weight: 20
weight: 1
sections_weight: 1
draft: false
aliases: []
toc: false
---

# Contract & IT News

We recommend that all community pharmacy contractors [register for the PSNC newsletter](https://psnc.org.uk/latest-news/email-sign-up/) which contains updates from their site, providing subscribers with details and links to the most relevant news articles. The newsletter covers a range of topics relating to NHS community pharmacy such as changes to contractual requirements, Drug Tariff updates and funding arrangements, as well as updates to the wider healthcare landscape. Those signed up to this list also receive [price concession alerts and updates](https://psnc.org.uk/dispensing-supply/supply-chain/generic-shortages/).

<script src="//rss.bloople.net/?url=https%3A%2F%2Fpsnc.org.uk%2Four-latest-news-category%2Fcontract-and-it%2Ffeed%2F&limit=20&showtitle=false&type=js"></script>


text:
import unittest

import numpy

import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
from chainer.utils import array

def _check_forward(e1, e2, f, y_expect):
    e1 = chainer.Variable(e1)
    e2 = chainer.Variable(e2)
    y = f(e1, e2)
    gradient_check.assert_allclose(y_expect, y.data)

def _check_backward(e1, e2, y_grad, f, bias):
    e1 = chainer.Variable(e1)
    e2 = chainer.Variable(e2)
    y = f(e1, e2)
    y.grad = y_grad
    y.backward()

    func = y.creator
    f = lambda: func.forward((e1.data, e2.data))

    ge1, ge2, gW = gradient_check.numerical_grad(
        f, (e1.data, e2.data, func.W), (y.grad,), eps=1e-2)

    gradient_check.assert_allclose(ge1, e1.grad, rtol=1e-3)
    gradient_check.assert_allclose(ge2, e2.grad, rtol=1e-3)
    gradient_check.assert_allclose(gW, func.gW, rtol=1e-3)

    if bias:
        gV1, gV2, gb = gradient_check.numerical_grad(
            f, (func.V1, func.V2, func.b),
            (y.grad,), eps=1e-2)
        gradient_check.assert_allclose(gV1, func.gV1, rtol=1e-3)
        gradient_check.assert_allclose(gV2, func.gV2, rtol=1e-3)
        gradient_check.assert_allclose(gb, func.gb, rtol=1e-3)

def _batch_to_gpu(*xs):
    return tuple(cuda.to_gpu(x) for x in xs)

def _uniform(*shape):
    return numpy.random.uniform(-1, 1, shape).astype(numpy.float32)

class TestBilinear(unittest.TestCase):

    in_shape = (3, 4)
    out_size = 4
    batch_size = 10

    def setUp(self):
        self.f = functions.Bilinear(
            self.in_shape[0], self.in_shape[1], self.out_size)
        self.f.W = _uniform(*self.f.W.shape)
        self.f.V1 = _uniform(*self.f.V1.shape)
        self.f.V2 = _uniform(*self.f.V2.shape)
        self.f.b = _uniform(*self.f.b.shape)
        self.f.zero_grads()

        self.W = self.f.W.copy()
        self.V1 = self.f.V1.copy()
        self.V2 = self.f.V2.copy()
        self.b = self.f.b.copy()

        self.e1 = _uniform(self.batch_size, self.in_shape[0])
        self.e2 = _uniform(self.batch_size, self.in_shape[1])
        self.gy = _uniform(self.batch_size, self.out_size)

        self.y = (
            numpy.einsum('ij,ik,jkl->il', self.e1, self.e2, self.W) +
            self.e1.dot(self.V1) + self.e2.dot(self.V2) + self.b)

    @condition.retry(3)
    def test_forward_cpu(self):
        _check_forward(self.e1, self.e2, self.f, self.y)

    @attr.gpu
    @condition.retry(3)
    def test_forward_gpu(self):
        self.f.to_gpu()
        _check_forward(cuda.to_gpu(self.e1),
                       cuda.to_gpu(self.e2),
                       self.f, self.y)

    @condition.retry(3)
    def test_backward_cpu(self):
        _check_backward(self.e1, self.e2, self.gy, self.f, True)

    @attr.gpu
    @condition.retry(3)
    def test_backward_gpu(self):
        self.f.to_gpu()
        _check_backward(cuda.to_gpu(self.e1),
                        cuda.to_gpu(self.e2),
                        cuda.to_gpu(self.gy),
                        self.f, True)

class TestBilinear2(TestBilinear):

    def setUp(self):
        super(TestBilinear2, self).setUp()

        assert self.in_shape[1] % 2 == 0
        self.e1 = _uniform(self.batch_size, 1, self.in_shape[0])
        self.e2 = _uniform(self.batch_size, self.in_shape[1] // 2, 2)
        self.gy = _uniform(self.batch_size, self.out_size)

        e1 = array.as_mat(self.e1)
        e2 = array.as_mat(self.e2)

        self.y = (
            numpy.einsum('ij,ik,jkl->il', e1, e2, self.W) +
            e1.dot(self.V1) + e2.dot(self.V2) + self.b)

class TestBilinearWOBias(TestBilinear):

    def setUp(self):
        self.f = functions.Bilinear(
            self.in_shape[0], self.in_shape[1], self.out_size, True)
        self.f.W = numpy.random.uniform(
            -1, 1, self.f.W.shape).astype(numpy.float32)
        self.f.zero_grads()

        self.W = self.f.W.copy()

        self.e1 = _uniform(self.batch_size, self.in_shape[0])
        self.e2 = _uniform(self.batch_size, self.in_shape[1])
        self.gy = _uniform(self.batch_size, self.out_size)

        self.y = numpy.einsum('ij,ik,jkl->il', self.e1, self.e2, self.W)

    @condition.retry(3)
    def test_backward_cpu(self):
        _check_backward(self.e1, self.e2, self.gy, self.f, False)

    @attr.gpu
    @condition.retry(3)
    def test_backward_gpu(self):
        self.f.to_gpu()
        _check_backward(cuda.to_gpu(self.e1), cuda.to_gpu(self.e2),
                        cuda.to_gpu(self.gy), self.f, False)

class TestBilinearWOBias2(TestBilinearWOBias):

    def setUp(self):
        super(TestBilinearWOBias2, self).setUp()

        assert self.in_shape[1] % 2 == 0
        self.e1 = _uniform(self.batch_size, 1, self.in_shape[0])
        self.e2 = _uniform(self.batch_size, 2, self.in_shape[1] // 2)
        self.gy = _uniform(self.batch_size, self.out_size)

        e1 = array.as_mat(self.e1)
        e2 = array.as_mat(self.e2)

        self.y = numpy.einsum('ij,ik,jkl->il', e1, e2, self.W)

class InitByInitialParameter(unittest.TestCase):

    in_shape = (2, 3)
    out_size = 4
    batch_size = 10

    def setUp(self):
        self.W = _uniform(self.in_shape[0], self.in_shape[1], self.out_size)
        self.V1 = _uniform(self.in_shape[0], self.out_size)
        self.V2 = _uniform(self.in_shape[1], self.out_size)
        self.b = _uniform(self.out_size,)

class NormalInitialParameter(InitByInitialParameter):

    def check_normal(self, initialW, initial_bias, nobias):
        functions.Bilinear(
            self.in_shape[0], self.in_shape[1], self.out_size, nobias,
            initialW, initial_bias)

    def test_normal_cpu_bias(self):
        self.check_normal(self.W, (self.V1, self.V2, self.b), False)

    def test_normal_cpu_nobias(self):
        self.check_normal(self.W, None, False)

    @attr.gpu
    def test_normal_gpu_bias(self):
        self.check_normal(cuda.to_gpu(self.W),
                          _batch_to_gpu(self.V1, self.V2, self.b), False)

    @attr.gpu
    def test_normal_gpu_nobias(self):
        self.check_normal(cuda.to_gpu(self.W), None, False)

class InvalidInitialParameter(InitByInitialParameter):

    def setUp(self):
        super(InvalidInitialParameter, self).setUp()
        self.invalidW = _uniform(self.in_shape[0] + 1, self.in_shape[1],
                                 self.out_size)
        self.invalidV1 = _uniform(self.in_shape[0] + 1, self.out_size)
        self.invalidV2 = _uniform(self.in_shape[1] + 1, self.out_size)
        self.invalidb = _uniform(self.out_size + 1,)

    def check_invalid(self, initialW, initial_bias, nobias):
        with self.assertRaises(AssertionError):
            functions.Bilinear(
                self.in_shape[0], self.in_shape[1], self.out_size, nobias,
                initialW, initial_bias)

    def test_invalidW_cpu(self):
        self.check_invalid(self.invalidW, (self.V1, self.V2, self.b), False)
        self.check_invalid(self.invalidW, None, True)

    @attr.gpu
    def test_invalidW_gpu(self):
        invalidW = cuda.to_gpu(self.invalidW)
        self.check_invalid(invalidW,
                           _batch_to_gpu(self.V1, self.V2, self.b), False)
        self.check_invalid(invalidW, None, True)

    def test_invalidV1_cpu(self):
        self.check_invalid(self.W, (self.invalidV1, self.V2, self.b), False)

    @attr.gpu
    def test_invaliV1_gpu(self):
        self.check_invalid(cuda.to_gpu(self.W),
                           _batch_to_gpu(self.invalidV1, self.V2, self.b),
                           False)

    def test_invalidV2_cpu(self):
        self.check_invalid(self.W, (self.V1, self.invalidV2, self.b), False)

    @attr.gpu
    def test_invaliV2_gpu(self):
        self.check_invalid(cuda.to_gpu(self.W),
                           _batch_to_gpu(self.V1, self.invalidV2, self.b),
                           False)

    def test_invalidb_cpu(self):
        self.check_invalid(self.W, (self.V1, self.V2, self.invalidb), False)

    @attr.gpu
    def test_invalib_gpu(self):
        self.check_invalid(cuda.to_gpu(self.W),
                           _batch_to_gpu(self.V1, self.V2, self.invalidb),
                           False)

testing.run_module(__name__, __file__)


text:
/*******************************************************************\

Module: Symbolic Execution

Author: Daniel Kroening, kroening@kroening.com

\*******************************************************************/

#include <irep2.h>
#include <migrate.h>
#include <assert.h>

#include <simplify_expr.h>
#include <i2string.h>
#include <cprover_prefix.h>
#include <expr_util.h>
#include <std_expr.h>

#include <ansi-c/c_types.h>

#include "goto_symex.h"
#include "dynamic_allocation.h"
#include "execution_state.h"

goto_symext::goto_symext(const namespacet &_ns, contextt &_new_context,
                         const goto_functionst &_goto_functions,
                         symex_targett *_target, const optionst &opts) :
  guard_identifier_s("goto_symex::guard"),
  total_claims(0),
  remaining_claims(0),
  constant_propagation(true),
  ns(_ns),
  options(opts),
  new_context(_new_context),
  goto_functions(_goto_functions),
  target(_target),
  cur_state(NULL),
  last_throw(NULL),
  inside_unexpected(false),
  unwinding_recursion_assumption(false),
  depth_limit(atol(options.get_option("depth").c_str())),
  break_insn(atol(options.get_option("break-at").c_str())),
  memory_leak_check(options.get_bool_option("memory-leak-check")),
  deadlock_check(options.get_bool_option("deadlock-check")),
  no_assertions(options.get_bool_option("no-assertions")),
  no_simplify(options.get_bool_option("no-simplify")),
  no_unwinding_assertions(options.get_bool_option("no-unwinding-assertions")),
  partial_loops(options.get_bool_option("partial-loops")),
  k_induction(options.get_bool_option("k-induction")
    || options.get_bool_option("k-induction-parallel")),
  base_case(options.get_bool_option("base-case")),
  forward_condition(options.get_bool_option("forward-condition"))
{
  const std::string &set = options.get_option("unwindset");
  unsigned int length = set.length();

  for(unsigned int idx = 0; idx < length; idx++)
  {
    std::string::size_type next = set.find(",", idx);
    std::string val = set.substr(idx, next - idx);
    unsigned long id = atoi(val.substr(0, val.find(":", 0)).c_str());
    unsigned long uw = atol(val.substr(val.find(":", 0) + 1).c_str());
    unwind_set[id] = uw;
    if(next == std::string::npos) break;
    idx = next;
  }

  max_unwind=atol(options.get_option("unwind").c_str());

  art1 = NULL;

  // Work out whether or not we'll be modelling with cpp:: or c:: arrays.
  const symbolt *sp;
  if (!ns.lookup(irep_idt("c::__ESBMC_alloc"), sp)) {
    valid_ptr_arr_name = "c::__ESBMC_alloc";
    alloc_size_arr_name = "c::__ESBMC_alloc_size";
    deallocd_arr_name = "c::__ESBMC_deallocated";
    dyn_info_arr_name = "c::__ESBMC_is_dynamic";
  } else {
    valid_ptr_arr_name = "cpp::__ESBMC_alloc";
    alloc_size_arr_name = "cpp::__ESBMC_alloc_size";
    deallocd_arr_name = "cpp::__ESBMC_deallocated";
    dyn_info_arr_name = "cpp::__ESBMC_is_dynamic";
  }

  symbolt sym;
  sym.name = "symex_throw::thrown_obj";
  sym.base_name = "thrown_obj";
  // Type left deliberately undefined. XXX, is this wise?
  new_context.move(sym);
}

goto_symext::goto_symext(const goto_symext &sym) :
  ns(sym.ns),
  options(sym.options),
  new_context(sym.new_context),
  goto_functions(sym.goto_functions),
  last_throw(NULL),
  inside_unexpected(false),
  unwinding_recursion_assumption(false)
{
  *this = sym;
}

goto_symext& goto_symext::operator=(const goto_symext &sym)
{
  body_warnings = sym.body_warnings;
  unwind_set = sym.unwind_set;
  max_unwind = sym.max_unwind;
  constant_propagation = sym.constant_propagation;
  total_claims = sym.total_claims;
  remaining_claims = sym.remaining_claims;
  guard_identifier_s = sym.guard_identifier_s;
  depth_limit = sym.depth_limit;
  break_insn = sym.break_insn;
  memory_leak_check = sym.memory_leak_check;
  deadlock_check = sym.deadlock_check;
  no_assertions = sym.no_assertions;
  no_simplify = sym.no_simplify;
  no_unwinding_assertions = sym.no_unwinding_assertions;
  partial_loops = sym.partial_loops;
  k_induction = sym.k_induction;
  base_case = sym.base_case;
  forward_condition = sym.forward_condition;

  valid_ptr_arr_name = sym.valid_ptr_arr_name;
  alloc_size_arr_name = sym.alloc_size_arr_name;
  deallocd_arr_name = sym.deallocd_arr_name;
  dyn_info_arr_name = sym.dyn_info_arr_name;

  dynamic_memory = sym.dynamic_memory;

  // Art ptr is shared
  art1 = sym.art1;

  // Symex target is another matter; a higher up class needs to decide
  // whether we're duplicating it or using the same one.
  target = NULL;

  return *this;
}

void goto_symext::do_simplify(exprt &expr)
{
  if(!no_simplify)
    simplify(expr);
}

void goto_symext::do_simplify(expr2tc &expr)
{
  if(!no_simplify) {
    expr2tc tmp = expr->simplify();
    if (!is_nil_expr(tmp))
      expr = tmp;
  }
}

void goto_symext::symex_assign(const expr2tc &code_assign)
{
  //replace_dynamic_allocation(state, lhs);
  //replace_dynamic_allocation(state, rhs);

  const code_assign2t &code = to_code_assign2t(code_assign);

  // Sanity check: if the target has zero size, then we've ended up assigning
  // to/from a C++ POD class with no fields. The rest of the model checker isn't
  // rated for dealing with this concept; perform a NOP.
  try {
    if (is_struct_type(code.target->type) &&
        type_byte_size(*code.target->type) == 0)
      return;
  } catch (array_type2t::dyn_sized_array_excp*foo) {
    delete foo;
  }

  expr2tc lhs = code.target;
  expr2tc rhs = code.source;

  replace_nondet(lhs);
  replace_nondet(rhs);

  if (is_sideeffect2t(rhs))
  {
    const sideeffect2t &effect = to_sideeffect2t(rhs);
    switch (effect.kind) {
    case sideeffect2t::cpp_new:
    case sideeffect2t::cpp_new_arr:
      symex_cpp_new(lhs, effect);
      break;
    case sideeffect2t::malloc:
      symex_malloc(lhs, effect);
      break;
    // No nondet side effect?
    default:
      assert(0 && "unexpected side effect");
    }
  }
  else
  {
    guardt guard; // NOT the state guard!
    symex_assign_rec(lhs, rhs, guard);
  }
}

void goto_symext::symex_assign_rec(
  const expr2tc &lhs,
  expr2tc &rhs,
  guardt &guard)
{

  if (is_symbol2t(lhs)) {
    symex_assign_symbol(lhs, rhs, guard);
  } else if (is_index2t(lhs)) {
    symex_assign_array(lhs, rhs, guard);
  } else if (is_member2t(lhs)) {
    symex_assign_member(lhs, rhs, guard);
  } else if (is_if2t(lhs)) {
    symex_assign_if(lhs, rhs, guard);
  } else if (is_typecast2t(lhs)) {
    symex_assign_typecast(lhs, rhs, guard);
   } else if (is_constant_string2t(lhs) ||
           is_null_object2t(lhs) ||
           is_zero_string2t(lhs))
  {
    // ignore
  } else if (is_byte_extract2t(lhs)) {
    symex_assign_byte_extract(lhs, rhs, guard);
  } else if (is_concat2t(lhs)) {
    symex_assign_concat(lhs, rhs, guard);
  } else if (is_constant_struct2t(lhs)) {
    symex_assign_structure(lhs, rhs, guard);
  } else {
    std::cerr <<  "assignment to " << get_expr_id(lhs) << " not handled"
              << std::endl;
    abort();
  }
}

void goto_symext::symex_assign_symbol(
  const expr2tc &lhs,
  expr2tc &rhs,
  guardt &guard)
{
  // put assignment guard in rhs

  if (!guard.empty())
  {
    rhs = if2tc(rhs->type, guard.as_expr(), rhs, lhs);
  }

  expr2tc orig_name_lhs = lhs;
  cur_state->get_original_name(orig_name_lhs);
  cur_state->rename(rhs);

  do_simplify(rhs);

  expr2tc renamed_lhs = lhs;
  cur_state->assignment(renamed_lhs, rhs, constant_propagation);

  guardt tmp_guard(cur_state->guard);
  tmp_guard.append(guard);

  // do the assignment
  target->assignment(
    tmp_guard.as_expr(),
    renamed_lhs, orig_name_lhs,
    rhs,
    cur_state->source,
    cur_state->gen_stack_trace(),
    symex_targett::STATE);

}

void goto_symext::symex_assign_structure(
  const expr2tc &lhs,
  expr2tc &rhs,
  guardt &guard)
{
  const struct_type2t &structtype = to_struct_type(lhs->type);
  const constant_struct2t &the_structure = to_constant_struct2t(lhs);

  // Explicitly project lhs fields out of structure, assignment will just undo
  // any member operations. If user is assigning to a structure literal, we
  // will croak after recursing. Otherwise, we are assigning to a re-constituted
  // structure, through dereferencing.
  unsigned int i = 0;
  forall_types(it, structtype.members) {
    const expr2tc &lhs_memb = the_structure.datatype_members[i];
    member2tc rhs_memb(*it, rhs, structtype.member_names[i]);
    symex_assign_rec(lhs_memb, rhs_memb, guard);

    i++;
  }
}

void goto_symext::symex_assign_typecast(
  const expr2tc &lhs,
  expr2tc &rhs,
  guardt &guard)
{
  // these may come from dereferencing on the lhs

  const typecast2t &cast = to_typecast2t(lhs);
  expr2tc rhs_typecasted = rhs;
  rhs_typecasted = typecast2tc(cast.from->type, rhs);

  symex_assign_rec(cast.from, rhs_typecasted, guard);
}

void goto_symext::symex_assign_array(
  const expr2tc &lhs,
  expr2tc &rhs,
  guardt &guard)
{
  // lhs must be index operand
  // that takes two operands: the first must be an array
  // the second is the index

  const index2t &index = to_index2t(lhs);

  assert(is_array_type(index.source_value) ||
         is_string_type(index.source_value));

  // turn
  //   a[i]=e
  // into
  //   a'==a WITH [i:=e]

  with2tc new_rhs(index.source_value->type, index.source_value,
                  index.index, rhs);

  symex_assign_rec(index.source_value, new_rhs, guard);
}

void goto_symext::symex_assign_member(
  const expr2tc &lhs,
  expr2tc &rhs,
  guardt &guard)
{
  // symbolic execution of a struct member assignment

  // lhs must be member operand
  // that takes one operands, which must be a structure

  const member2t &member = to_member2t(lhs);

  assert(is_struct_type(member.source_value) ||
         is_union_type(member.source_value));

  const irep_idt &component_name = member.member;
  expr2tc real_lhs = member.source_value;

  // typecasts involved? C++ does that for inheritance.
  if (is_typecast2t(member.source_value))
  {
    const typecast2t &cast = to_typecast2t(member.source_value);
    if (is_null_object2t(cast.from))
    {
      // ignore
    }
    else
    {
      // remove the type cast, we assume that the member is there
      real_lhs = cast.from;
      assert(is_struct_type(real_lhs) || is_union_type(real_lhs));
    }
  }

  // turn
  //   a.c=e
  // into
  //   a'==a WITH [c:=e]

  type2tc str_type =
    type2tc(new string_type2t(component_name.as_string().size()));
  with2tc new_rhs(real_lhs->type, real_lhs,
                       constant_string2tc(str_type, component_name),
                       rhs);

  symex_assign_rec(member.source_value, new_rhs, guard);
}

void goto_symext::symex_assign_if(
  const expr2tc &lhs,
  expr2tc &rhs,
  guardt &guard)
{
  // we have (c?a:b)=e;

  unsigned old_guard_size=guard.size();

  // need to copy rhs -- it gets destroyed
  expr2tc rhs_copy = rhs;
  const if2t &ifval = to_if2t(lhs);

  expr2tc cond = ifval.cond;

  guard.add(cond);
  symex_assign_rec(ifval.true_value, rhs, guard);
  guard.resize(old_guard_size);

  not2tc not_cond(cond);

  guard.add(not_cond);
  symex_assign_rec(ifval.false_value, rhs_copy, guard);
  guard.resize(old_guard_size);
}

void goto_symext::symex_assign_byte_extract(
  const expr2tc &lhs,
  expr2tc &rhs,
  guardt &guard)
{
  // we have byte_extract_X(l, b)=r
  // turn into l=byte_update_X(l, b, r)

  // Grief: multi dimensional arrays.
  const byte_extract2t &extract = to_byte_extract2t(lhs);

  if (is_multi_dimensional_array(extract.source_value)) {
    const array_type2t &arr_type = to_array_type(extract.source_value->type);
    assert(!is_multi_dimensional_array(arr_type.subtype) &&
           "Can't currently byte extract through more than two dimensions of "
           "array right now, sorry");
    constant_int2tc subtype_sz(index_type2(),
                               type_byte_size(*arr_type.subtype));
    expr2tc div = div2tc(index_type2(), extract.source_offset, subtype_sz);
    expr2tc mod = modulus2tc(index_type2(), extract.source_offset, subtype_sz);
    do_simplify(div);
    do_simplify(mod);

    index2tc idx(arr_type.subtype, extract.source_value, div);
    byte_update2tc be2(arr_type.subtype, idx, mod, rhs, extract.big_endian);
    with2tc store(extract.source_value->type, extract.source_value, div, be2);
    symex_assign_rec(extract.source_value, store, guard);
  } else {
    byte_update2tc new_rhs(extract.source_value->type, extract.source_value,
                           extract.source_offset, rhs,
                           extract.big_endian);

    symex_assign_rec(extract.source_value, new_rhs, guard);
  }
}

void goto_symext::symex_assign_concat(
  const expr2tc &lhs,
  expr2tc &rhs,
  guardt &guard)
{
  // Right: generate a series of symex assigns.
  const concat2t &cat = to_concat2t(lhs);
  assert(cat.type->get_width() > 8);
  assert(is_scalar_type(rhs));

  // Ensure we're dealing with a bitvector.
  if (!is_bv_type(rhs))
    rhs = typecast2tc(get_uint_type(rhs->type->get_width()), rhs);

  // Right. To split this up, work out the size that should be being assigned
  // to each part of the contact, and cut up the rhs appropriately.
  unsigned int side1_size = cat.side_1->type->get_width();
  unsigned int side2_size = cat.side_2->type->get_width();

  // Position to split it is side2_size bits up from the zero position. Now,
  // perform this split.
  // Side2 rhs takes the lower bits, so just downcast the rhs to that num of bit
  expr2tc side2_rhs = typecast2tc(get_uint_type(side2_size), rhs);
  // Side1 needs to have that number of lower bits clipped off.
  expr2tc shift_dist = gen_uint(rhs->type, side2_size);
  expr2tc side1_rhs = lshr2tc(rhs->type, rhs, shift_dist);
  // Now downcast it to the desired number of bits.
  side1_rhs = typecast2tc(get_uint_type(side1_size), side1_rhs);

  // And now, perform the new assignments.
  symex_assign_rec(cat.side_1, side1_rhs, guard);
  symex_assign_rec(cat.side_2, side2_rhs, guard);
}

void goto_symext::replace_nondet(expr2tc &expr)
{
  if (is_sideeffect2t(expr) &&
      to_sideeffect2t(expr).kind == sideeffect2t::nondet)
  {
    unsigned int &nondet_count = get_dynamic_counter();
    expr = symbol2tc(expr->type,
                              "nondet$symex::nondet"+i2string(nondet_count++));
  }
  else
  {
    Forall_operands2(it, idx, expr) {
      if (!is_nil_expr(*it))
        replace_nondet(*it);
    }
  }
}


text:
export const aServiceName = 'aService';
export function aService() {
  return {
    getText: () => 'A Directive',
  };
}


text:
package ru.job4j.chess;

/**
 * Исключение о том, что путь занят другой фигурой.
 */
public class OccupiedWayException extends RuntimeException {
	/**
	 * Serial version UID.
	 */
	private static final long serialVersionUID = 9208350358296033910L;

	/**
	 * Конструктор исключения.
	 *
	 * @param message Человекочитаемое сообщение об ошибке.
	 */
	public OccupiedWayException(String message) {
		super(message);
	}
}


text:
kata-perl-minesweeper
=======================

coding practice exercises in Test Driven Design (TDD).

Tests are run using prove

This minesweeper has slightly different requirements
from other online minesweeper katas I have seen.


text:
% Rust Workshop

Rust Romandie meetup + Hackers at EPFL

Dimiter Petrov & Romain Ruetschi

November 12, 2014

# Hello, Rust

Rust is a fairly new systems programming language focused on safety and speed.

```rust
//This is display only code
fn main() {
    println!("Hello, world!");
}
```

# History

* Started as a personal project in 2006 by Graydon Hoare
* First compiler written in OCaml
* Mozilla took over the project 3 years later
* Compiler rewritten in Rust itself in 2010

# Why Rust at Mozilla?

* New experimental, highly parallel browser engine: Servo
* Browsers evolve in a hostile, highly concurrent environment
* Most security problems arise from memory safetey and concurrency issues
* Thus a safer, saner systems language is needed, with built-in concurrency

# Why Rust, for you?

* High-level features
* Low-level control
* Powerful Foreign Function Interface (FFI)
* Direct memory control
* Guaranteed memory safety
* Concurrency without data races
* Zero cost abstractions

# High-level features

* Type inference
* Lambdas
* Closures
* Iterators
* Algebraic data types
* Pattern matching
* Traits (= type classes)
* Macros
* Modules

# Low-level control

* Ability to trade compiler-enforced safety for lower-level control
* Eg. dereferencing raw pointer, pointer arithmetic, calling external code
* Such unsafe code must be surrounded by an `unsafe` block
* Thus easy to spot during code review or when debugging

# Powerful FFI

* Call Rust code from other languages (C, C++, or even GCed languages like Ruby)
* Create bindings for libraries exposing a C interface

# Direct memory control

* No garbage collector
* No runtime overhead
* No unpredictable pauses in execution
* Stack and heap allocations

# But first, the basics

* Primitive types
* Variable bindings
* Functions
* Printing stuff
* Control structures
* Strings
* Arrays, vectors and slices
* Structs and methods

# Numeric types

        Name
        Type
        Example

        Signed integer
        int
        5i

        Unsigned integer
        uint
        5u

        8-bit uint
        u8
        5u8

        16-bit uint
        u16
        5i

        etc.

        32-bit float
        f32
        3.14f32

        64-bit float
        f64
        3.14_f64

# Primitive types

        Name
        Type
        Example

        Unit
        ()
        ()

        Boolean
        bool
        true | false

        Array
        [T]
        [1, 2, 3]
        fixed size, can be allocated on either the stack or the heap

        Slice
        &[T]
        &[1, 2, 3]
        'view' into an array, doesn't own the data it points to, but borrows it

        Tuple
        (A, B, C...)
        ("Rust", 2006i, 'r')
        32-bit unsigned word

# Textual types

        Name
        Type
        Example

        Unicode scalar value
        char
        'a'
        32-bit unsigned word

        Unicode scalar array
        [char]
        ['a', 'b', 'c']
        ~ UTF-32 string

        Unicode string
        str
        "rust is cool"
        array of 8-bit unsigned bytes

            ~ sequence of UTF-8 codepoints

# Variable bindings

# Mutability

# Mutability

```rust
let mut x = 5i;

x = x + 1; // ok
```

# Mutability

```rust
let x = 5i;
let mut y = x;

y = y + 1;
```

# Functions

```rust
fn main() {
    let res = do_stuff(2, 3);
    println!("result is {}", res);
}

fn do_stuff(a: int, b: int) -> int {
    let c = a + b;

    return c * 2;
}
```

# Functions

You can omit `return` if you want to return the last expression.

```rust
fn main() {
    let res = do_stuff(2, 3);
    println!("result is {}", res);
}

fn do_stuff(a: int, b: int) -> int {
    let c = a + b;

    c * 2 // ! no semicolon
}
```

But you also need to omit the last semicolon, otherwise the function will return `()`.

# Printing stuff

```rust
fn main() {
    let name = "John";
    let age = 42;

    println!("{} is {}", name, age);
}
```

> `println!()` is actually a macro, not a function.

# Printing stuff

You can re-order arguments by putting their index inside the braces.

```rust
fn main() {
    let name = "John";
    let age = 42;

    println!("{1} is {0}", age, name);
}
```

# Conditionals

```rust
if age > 16 {
    println!("Have a beer!");
}
else {
    println!("Sorry, no beer for you.");
}
```

> No parenthesis around the condition.

# Conditionals

`if/else` is an expression:

```rust
let message = if health > 0 {
    "Good job"
} else {
    "Game over"
};

println!("{}", message);
```

# While

```rust
while x < 10 {
    // do stuff
}
```

# Loop

Instead of

```rust
while true {
    // do stuff
}
```

use

```rust
loop {
    // do stuff
}
```

> Rust's control-flow analysis treats this construct differently than a `while true`, which leads to better generated code.

# For

```rust
for x in range(0i, 10i) {
    // do stuff
}
```

# For

```rust
for var in expression {
    code
}
```

> `expression` must be an `Iterator` (we'll talk about it later).

# Strings

* Guaranteed to be validly-encoded UTF-8 sequences
* Not null-terminated (can contain null bytes)
* Can be constant strings (`&str`) or growable strings (`String`)

# String slices (`&str`)

A pointer and a length.
String slices are a 'view' into already allocated strings like string literals:

```rust
let hello = "Hello, world!";
```

# Growable strings (`String`)

`String` can grow if defined as `mut`able.

```rust
let mut hello = "Hello".to_string();

hello.push_str(", world!");

// hello now contains "Hello, world!"
```

# Conversions between the two

* Call `as_slice()` on a `String` to convert it to a `&str`
* Call `to_string()` on a `&str` to convert it to a `String`

```rust
let s1: String = "Hello".to_string();
let s2: &str = s1.as_slice();
```

Converting `String` to `&str` is cheap, converting `&str` to `String` involves an allocation.

# Arrays, vectors and slices

* An array is a **fixed-sized** list of elements of the same type
* A vector is a **dynamic, growable** array
* A slice is a reference to an array.

# Arrays

An array is a **fixed-sized** list of elements of the same type.

```rust
// Only the first item needs a type suffix
let a = [1i, 2, 3];

// which you can omit if you specify the type
let a: [int, ..3] = [1, 2, 3];

println!("a has {} elements", a.len());
println!("the first element of a is {}", a[0]);
```

# Vectors

A vector is a **dynamic, growable** array

```rust
let mut participants = vec!["Bob", "Bill"];

participants.push("Joe");

// participants[2] == "Joe";
```

# Slices

A slice is a reference to an array.

A slice allows safe and efficient access to a portion of an array without copying.

```rust
let a: [int, ..5] = [0, 1, 2, 3, 4];
let middle: &[int] = a.slice(1, 4); // just the elements [1, 2, 3]

let a = [0i, 1, 2, 3, 4];
let middle = a.slice(1, 4); // just the elements [1, 2, 3]
```

# Structs and methods

# Structs

```rust
struct Rectangle {
    width: f32,
    height: f32
}
```

# Methods

Methods (static and members) are defined inside an `impl` block.

```rust
struct Rectangle {
    width: f32,
    height: f32
}

impl Rectangle {
    // Methods here.
}

```

# Static methods

Static methods are defined this way, and can be called with `Type::method_name()`.

```rust
struct Rectangle { width: f32, height: f32 }

impl Rectangle {
    fn new(width: f32, height: f32) -> Rectangle {
        Rectangle { width: width, height: height }
    }
}

fn main() {
    let rect = Rectangle::new(1.2, 4.9);
    println!("{}", react.area());
}
```

# Member methods

Member methods take a `&self` parameter, which is a reference to the `struct` the method is called on.

```rust
struct Rectangle { width: f32, height: f32 }

impl Rectangle {
    fn area(&self) -> f32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle::new(1.2, 4.9);
    let area = react.area();

    println!("{}", area);
}
```

# Generics

```rust
struct PairOfInts { first: int, second: int }

fn swap_pair(p: PairOfInts) -> PairOfInts {
  PairOfInts { first: p.second, second: p.first }
}
```

```rust
struct Pair<T> { first: T, second: T }

fn swap_pair<T>(p: Pair<T>) -> Pair<T> {
  Pair { first: p.second, second: p.first }
}

fn main() {
  let p = Pair { first: 1i, second: 2i };
  let swapped = swap_pair(p);
}
```

# Stack and heap allocations

By default, values are allocated on the stack.

```rust
let rect = Rectangle {
    width: 1.0,
    height: 1.0
};
```

> `rect` is of type `Rectangle`

# Stack and heap allocations

You can allocate a value on the heap with the `box` keyword.

# Stack and heap allocations

```rust
{
    let x = box 5i;
    println!("{}", *x); // Prints 5
}
```

```
{
    int *x = (int *)malloc(sizeof(int));
    if (!x) abort();
    *x = 5;
    printf("%d\n", *x);
    free(x);
}
```

# Boxes

```rust
let rect = box Rectangle {
    width: 1.0,
    height: 1.0
};
```

> `rect` is now type `Box<Rectangle>`

# Boxes

Although it's of type `Box<Rectangle>`, you can still call `Rectangle` methods on `rect`.

```rust
let rect = box Rectangle::new(1.0, 1.0);
let area = rect.area();

println!("area = {}", area);
```

# Guaranteed memory safety

* No buffer overflows
* No dangling pointers

# Concurrency without data races

* Only immutable data can be shared
* Shared data must remain live as long as any task might access it

# Zero cost abstractions

Memory safety is enforced during compilation, there is no runtime overhead.

# But how?

Rust is built around 3 concepts:

* Lifetime
* Ownership
* Borrowing

# Lifetime

Time span during which a resource (value) is valid.

# Lifetime

![](http://cl.ly/image/343C1X3o3K1s/Screen%20Shot%202014-11-10%20at%2018.06.58.png)

* You can think of it as a scope.
* At the end of its lifetime, a value will be deallocated.

# Lifetime

```c
{
    int *x = malloc(sizeof(int));

    *x = 5;

    free(x);
}
```

# Lifetime

```rust
{
    let x = box 5i;

    // x gets deallocated here
}
```

# Move & Copy

When you pass data to a function (or even assign it to a variable), that data can be copied, moved, or borrowed (more about it soon).

# Copy

```rust
fn main() {
    let a = 5;
    let b = add_one(a);
    println!("{}", a);
}

fn add_one(x: int) -> int {
    x + 1
}
```

# Move

```rust
struct Person {
    name: String,
    age: uint
}

fn main() {
    let john = Person { name: "John".to_string(), age: 42 };
    show(john);

    // `john` has already been deallocated
}

fn show(person: Person) {
    println!("{} is {}", person.name, person.age);

    // `john` will be deallocated here
}
```

# Move

```rust
struct Person {
    name: String,
    age: uint
}

fn main() {
    let john = Person { name: "John".to_string(), age: 42 };
    show(john);
    show(john);
}

fn show(person: Person) {
    println!("{} is {}", person.name, person.age);

    // `john` will be deallocated here
}
```

# Move

```norust
error: use of moved value: `john`
     show(john);
          ^
note: `john` moved here because it has type `Person`, which is non-copyable
     show(john);
          ^
error: aborting due to previous error
```

# Move

```rust
struct Person { name: String, age: uint }

fn main() {
    let john = Person { name: "John".to_string(), age: 42 };

    // `john` moves into show here
    show(john);
    // `john` is deallocated by now
    // so the next line doesn't compile
    show(john);
}

fn show(person: Person) {
    println!("{} is {}", person.name, person.age);

    // `john` will be deallocated here
}
```

# Move (assignment)

Assigning a value to a variable is similar to passing it to a function.

```rust
struct Person { name: String, age: uint }

fn main() {
    let john = Person { name: "John".to_string(), age: 42 };

    // `john` moves into `john_bis` here
    let john_bis = john;

    // so the next line won't compile
    show(john);
}

fn show(person: Person) {
    println!("{} is {}", person.name, person.age);

    // `john` will be deallocated here
}
```

# Ownership & Borrowing

When you create a resource, you're the **owner** of that resource.

Being an owner gives you some privileges:

* You control when that resource is deallocated.
* You may lend that resource, **immutably**, to **as many** borrowers as you'd like.
* You may lend that resource, **mutably**, to a **single** borrower.

# Ownership & Borrowing

But it also comes with some restrictions:

* If someone is borrowing your resource (either mutably or immutably), you may not mutate the resource or mutably lend it to someone.
* If someone is mutably borrowing your resource, you may not lend it out at all (mutably or immutably) or access it in any way.

# Borrow

> You may lend that resource, **immutably**, to **as many** borrowers as you'd like.

```rust
struct Person { name: String, age: uint }

fn main() {
    let john = Person { name: "John".to_string(), age: 42 };

    // `john` moves into `show`.
    show(&john);

    // `show` hands us `john` back.
    show(&john);
    // the previous line will thus compile.
}

fn show(person: &Person) {
    println!("{} is {}", person.name, person.age);
}
```

# Borrow

```norust
John is 42
John is 42
```

# Mutable borrow

> You may lend that resource, **mutably**, to a **single** borrower.

```rust
struct Person { name: String, age: uint }

fn main() {
    let mut john = Person { name: "John".to_string(), age: 42 };

    grow_older(&mut john);

    show(&john); // John is 43
}

fn grow_older(person: &mut Person) {
    person.age += 1;
}
```

# Mutable borrow

The following will compile too, as `grow_older` gives us `john` back:

```rust
fn main() {
    let mut john = Person { name: "John".to_string(), age: 42 };
    show(&john); // John is 42
    grow_older(&mut john);
    grow_older(&mut john);
    show(&john); // John is 44
}
```

# Mutable borrow

But this won't:

```rust
fn main() {
    let mut john = Person { name: "John".to_string(), age: 42 };

    let mut john_bis = &mut john;

    grow_older(&mut john);

    show(&john);
}
```

# Mutable borrow

```norust
error: cannot borrow `john` as mutable more than once at a time
    grow_older(&mut john);
                    ^
note: previous borrow of `john` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `p` until the borrow ends
    let mut john_bis = &mut john;
                         ^
note: previous borrow ends here
fn main() {
...
}
^
error: aborting due to previous error
```

# Mutable borrow

```rust
fn main() {
    let mut john = Person { name: "John".to_string(),
                            age: 42 };

    // first borrow of `john` as mutable
    let mut john_bis = &mut john;

    // `john` cannot be mutably borrowed again, won't compile
    grow_older(&mut john);

    show(&john);
}
```

# Lifetime annotations

Let's say we want to return a reference to a `struct`'s member field.

```rust
struct Point { x: f64, y: f64 }

fn get_x(point: &Point) -> &f64 {
    &point.x
}
```

# Lifetime annotations

Until a few weeks ago, `get_x()` had to be written this way:

```rust
fn get_x<'a>(point: &'a Point) -> &'a f64 {
    &point.x
}
```

But in that case, those annotations are now optional.

`'a` represents the lifetime of `point`. We hereby specify that the reference we return must have the same lifetime as `point`.

# Lifetime annotations

This means that code such as

```rust
let mut p = Point { x: 2.0, y: 3.0 };
let x = get_x(&p);

p = Point { x: 4.0, y: 6.0 };
```

will not compile, because `x` outlives the value it is reference from.

# Lifetime annotations

```rust
struct Line { start: &Point, end: &Point }

fn make_line(p1: &Point, p2: &Point) -> Line {
    Line { start: p1, end: p2 }
}

fn main() {
    let p1 = Point { x: 1.0, y: 2.3 };
    let p2 = Point { x: 2.0, y: 5.9 };

    let line = make_line(&p1, &p2);
}
```

> error: missing lifetime specifier

# Lifetime annotations

```rust
struct Line<'a> {
    start: &'a Point,
    end: &'a Point
}

fn make_line<'b>(p1: &'b Point, p2: &'b Point) -> Box<Line<'b>> {
    box Line { start: p1, end: p2 }
}

fn main() {
    let p1 = Point { x: 1.0, y: 2.3 };
    let p2 = Point { x: 2.0, y: 5.9 };

    let line = make_line(&p1, &p2);
}
```

# Net result

* You never have to malloc or free
* You never have to retain or release
* Rust will deallocate a value when the current owner is done with it
* The compiler will guarantee that borrowed values are not stolen

# Net result

* In low-level languages, we allocate and free memory, close sockets, etc.
* In high-level languages, we never free memory, but we routinely close sockets and files, and release locks.
* In Rust we do neither :)

# High-level features

# Lambdas

```rust
    let xs = vec!(1i, 2i, 3i);
    let ys = xs.map(|x| x * 2);

    // ys == [2i, 4i, 6i]
```

# Lambdas

```rust
fn add_one(x: int) -> int {
    x + 1
}

fn apply(x: int, adder: |int| -> int) -> int {
    adder(x)
}
```

# Closures

```rust
    let factor = 8;
    let xs = vec!(1i, 2i, 3i);
    let ys = xs.map(|x| x * factor);

    // ys == [8i, 16i, 24i]
```

# Traits

* No inheritance in Rust :)
* No interfaces either…
* Instead Rust provides a mechanism called `traits`.

# Traits

A trait is a sort of interface that defines some behavior.
If a type implements a trait, that means that it supports and implements the behavior the trait describes.

# Traits

You can think of them as (better) Java interfaces. They are in fact very similar to Haskell's typeclasses.

One of the main differences is that you can define a trait implementation separately from the struct definition, even in another module. This means that you can eg. implement a trait you defined yourself for a type provided by a library.

They're also much more powerful (but won't get into too much detail here).

# Traits

```rust
struct Rectangle { width: f32, height: f32 }

trait HasArea {
    fn area(&self) -> f32;
}

impl HasArea for Rectangle {
    fn area(&self) -> f32 {
        self.width * self.height
    }
}
```

# Traits

```rust
fn main() {
    let rect = Rectangle {
        width: 1.2,
        height: 4.9
    };
    println!("{}", react.area());
}
```

# Traits

```rust
struct Circle { radius: f32 }

impl HasArea for Circle {
    fn area(&self) -> f32 {
         std::f32::consts::PI * (self.radius * self.radius)
    }
}
```

# Traits

```rust
fn print_area<T>(shape: T) {
    println!("This shape has an area of {}", shape.area());
}
```

> error: type `T` does not implement any method in scope named `area`

# Traits

```rust
fn print_area<T: HasArea>(shape: T) {
    println!("This shape has an area of {}", shape.area());
}
```

# Traits

```rust
fn print_area<T: HasArea>(shape: T) {
    println!("This shape has an area of {}", shape.area());
}

fn main() {
    let c = Circle { radius: 1.0 }
    let r = Rectangle { width: 3.0, height: 2.0 }

    print_area(c);
    print_area(r);
}
```

> This shape has an area of 3.141592654
> This shape has an area of 6.0

# Traits

```rust
print_area(10i);
```

> error: failed to find an implementation of trait `main::HasArea` for `int`

# Traits

We can implement traits for any type. So this would work, even if it makes no sense:

```rust
impl HasArea for int {
    fn area(&self) -> f64 {
        println!("this is silly");
        *self as f64
    }
}

fn main() {
    10i.area();
    print_area(10i);
}
```

Implementing traits for primitive types should generally be avoided.

# Traits

One restriction:

> Either the trait or the type you're writing the `impl` for must be inside your crate (i.e. your library).

# A few built-in traits

```rust
trait ToString {
    fn to_string(&self) -> String;
}

trait ToJson {
    fn to_json(&self) -> Json;
}

trait Equiv<T> {
    fn equiv(&self, other: &T) -> bool;
}
```

# Enums

* Also called `sum types` in the literature.
* Similar to Haskell's `data` and Scala's `case class`.

```rust
enum Boolean {
    True,
    False
}
```

> Rust's `bool` type is **not** implemented this way as it is a primitive.

# Enums

```rust
enum Boolean {
    True,
    False
}

let b: Boolean = True;
```

A value of type `Boolean` can be either `True` or `False`.

# Enum

From the standard library (almost):

```rust
enum Ordering { Less, Equal, Greater }

fn cmp(a: int, b: int) -> Ordering {
    if      a < b { Less }
    else if a > b { Greater }
    else          { Equal }
}

let ordering = cmp(x, y);

if ordering == Less {
    println!("less");
} else if ordering == Greater {
    println!("greater");
} else if ordering == Equal {
    println!("equal");
}
```

# Pattern matching

Rust provides pattern matching, which lets you rewrite this:

```rust
if ordering == Less {
    println!("less");
} else if ordering == Greater {
    println!("greater");
} else if ordering == Equal {
    println!("equal");
}
```

# Pattern matching

as this:

```rust
match ordering {
    Less    => println!("less"),
    Greater => println!("greater"),
    Equal   => println!("equal")
}
```

# Pattern matching

It also works with primitives:

```rust
let i = 5i;

match i {
    0 => println!("zero"),
    1 => println!("one"),
    _ => println!("> 1")
}
```

# Pattern matching

Patterns must be exhaustive:

```rust
match ordering {
    Less    => println!("less"),
    Greater => println!("greater")
}
```

> error: non-exhaustive patterns: `Equal` not covered [E0004]

# Pattern matching

There's a "catch-all" pattern: `_`.

```rust
match ordering {
    Less => println!("less"),
    _    => println!("not less")
}
```

> error: non-exhaustive patterns: `Equal` not covered [E0004]

# Back to enums

Enums can also store data. One simple example is the built-in `Option` type. Here's how it is defined in the standard library:

```rust
enum Option<T> {
    None,
    Some(T),
}
```

The type `Option<T>` represents an optional value of type `T`.

An `Option` is either

* `Some`, and contains a value of type `T`
* `None`, and does not contain anything

# Option

```rust
let opt: Option<int> = Some(5);

let opt_plus_two = opt + 2;
```

> error: binary operation `+` cannot be applied to type `core::option::Option<int>`

# Option

To make use of the value inside an `Option`, we must pattern-match on it:

```rust
let opt: Option<int> = Some(5);

let opt_plus_two = match opt {
    Some(x) => x + 2,
    None    => -1
}
```

This forces us to handle the case where there might be no value.

# Option

Options have a number of uses in Rust:

* Initial values
* Return values for functions that are not defined over their entire input range (partial functions)
* Return value for otherwise reporting simple errors, where None is returned on error
* Optional struct fields
* Optional function arguments
* Nullable pointers

# Option

`Option` also provides a few convenience methods:

* `fn is_some(&self) -> bool`
* `fn is_none(&self) -> bool`
* `fn unwrap_or(self, def: T) -> T`
* `fn unwrap(self) -> T` **Use with caution**

# Option

A couple more:

* `fn map<U>(self, f: |T| -> U) -> Option<U>`
* `fn and_then<U>(self, f: |T| -> Option<U>) -> Option<U>`

# Option

```rust
fn get_name() -> Option<String> { /* ... */ }

let name: Option<String> = get_name();

let display_name = name.map(|n| format!("My name is {}", n))
                       .unwrap_or("I don't have a name");

println!(display_name);
```

If `get_name()` returns `Some("Marie")`, this will print `My name is Marie`, and if it returns `None`, this will print `I don't have a name`.

# Iterators

```rust
for x in range(0i, 10i) {
    // do stuff
}
```

This works because `range(0, 10)` returns an `Iterator<int>`.

`Iterator<T>` provides a `next()` function that we can call repeatedly to get a sequence of values, each wrapped in `Some`. When no more values are available, `next()` returns `None`.

# Iterators

The `for` loop on the previous slide can be written like this:

```rust
let mut range = range(0i, 10i);

loop {
    match range.next() {
        Some(x) => {
            println!("{}", x);
        },
        None => { break }
    }
}
```

# Iterators

Vectors can be iterated over too. `Vec<T>` provides an `iter()` method which returns an `Iterator<&T>` that we can use to iterate over the elements.

```rust
let nums = vec![1i, 2i, 3i];

for num in nums.iter() {
    println!("{}", num);
}
```

# Iterators

`Iterator` provides methods such as `map`, `filter`, `take`, and friends.

# Consumers

`Iterator`s are not collections, they just allow to iterate over a (potentially infinite) sequence of elements.

It is possible to turn an `Iterator` into a collection with the `collect` method.

```rust
let a = [1i, 2, 3, 4, 5];
let iter = a.iter().map(|&x| x + 1);

let a_plus_one: Vec<int> = iter.collect();
// a_plus_one = [2i, 3, 4, 5, 6];
```

The type annotation is mandatory. `let a_plus_one = iter.collect();` would throw an error.

# Macros

You have already seen them. `println!()` is a macro. They're distinguishable by the `!` at the end of the function name.

We won't get into too much detail here for lack of time.

# Crates and modules

A "crate" in Rust is what you'd call a "package" or "library" in other languages. A crate contains modules (which can contain other modules).

If we have a `greetings` crate that contains a public module `english` that defines a public method `hello()`, we'd use it like this:

```rust
extern crate greetings;

fn main() {
  greetings::english::hello();
}
```
# Modules

The `use` keyword imports names in the local scope.

```rust
extern crate greetings;
use greetings::english;

fn main() {
  english::hello();
}
```

# Cargo

Cargo is Rust's package manager. It:

* gets and compiles external dependencies
* builds your projects
* runs your tests

Use Cargo for all your projects.

# Starting a project

```
$ cargo new hello_world --bin
```

The `--bin` flag indicates you're making a binary, not a library.

This generates a package description file, `Cargo.toml`, where you declare the project's dependencies and metadata.

```
[package]

name = "hello_world"
version = "0.0.1"
authors = ["Your Name <you@example.com>"]
```

# Compiling your project

`src/main.rs`:

```rust
fn main() {
    println!("Hello, world!")
}
```

`cargo build` to build or `cargo run` to build and run your project

```norust
$ cargo run
   Compiling hello_world v0.0.1 (file:///path/to/hello_world)
     Running `target/hello_world`
Hello, world!
```

# Thank you!

Questions?

# References

* http://doc.rust-lang.org/reference.html
* http://www.slideshare.net/saneyuki/rusts-ownership-and-move-semantics
* http://www.infoq.com/news/2012/08/Interview-Rust
* http://theincredibleholk.wordpress.com/2012/05/30/safe-parallelism-in-rust/
* http://blog.skylight.io/rust-means-never-having-to-close-a-socket/
* https://s3.amazonaws.com/f.cl.ly/items/351X3I3z0M1E251x3V1p/Hello%20Rust.pdf
* http://lea-linux.org/documentations/Rust


text:
// IWYU pragma: private, include "src/internal/model/model.h"
// IWYU pragma: friend src/internal/model/*

#ifndef STATE_CHART_INTERNAL_MODEL_STATE_H_
#define STATE_CHART_INTERNAL_MODEL_STATE_H_

#include <string>
#include <vector>

#include "statechart/platform/types.h"
#include "statechart/internal/model/model_element.h"

namespace state_chart {
namespace model {

class ExecutableContent;
class Transition;

// Basic implementation of the State.
class State : public ModelElement {
 public:
  // Params:
  //  id: Unique state id.
  //  is_final: Marks this state as a final state.
  //  is_parallel: Marks this state as a parallel state.
  //  datamodel: The datamodel element.
  //  on_entry: Executable block for onentry.
  //  on_exit: Executable block for onexit.
  State(const string& id, bool is_final, bool is_parallel,
        const ExecutableContent* datamodel, const ExecutableContent* on_entry,
        const ExecutableContent* on_exit);
  State(const State&) = delete;
  State& operator=(const State&) = delete;

  std::vector<const Transition*>* mutable_transitions() {
    return &transitions_;
  }

  // Add the given state as a child state and set this as the parent.
  void AddChild(State* state) {
    child_states_.push_back(state);
    state->SetParent(this);
  }

  // Add all the given child states as children.
  void AddChildren(const std::vector<State*>& child_states);

  string id() const { return id_; }
  bool IsFinal() const { return is_final_; }
  bool IsParallel() const { return is_parallel_; }
  const std::vector<const Transition*>& GetTransitions() const {
    return transitions_;
  }

  const Transition* GetInitialTransition() const { return initial_transition_; }
  // Sets the transition and returns false if IsFinal() or
  // 'initial_transition->GetSourceState() != this'.
  bool SetInitialTransition(const Transition* initial_transition);

  void SetParent(const State* parent) { parent_ = parent; }
  const State* GetParent() const { return parent_; }
  const std::vector<const State*>& GetChildren() const { return child_states_; }
  bool IsAtomic() const { return child_states_.empty(); }
  bool IsCompound() const { return !IsAtomic() && !IsParallel(); }
  const ExecutableContent* GetDatamodelBlock() const { return datamodel_; }
  const ExecutableContent* GetOnEntry() const { return on_entry_; }
  const ExecutableContent* GetOnExit() const { return on_exit_; }

 private:
  const string id_;
  const bool is_final_;
  const bool is_parallel_;
  const State* parent_;
  const Transition* initial_transition_;
  std::vector<const Transition*> transitions_;
  std::vector<const State*> child_states_;
  const ExecutableContent* datamodel_;
  const ExecutableContent* on_entry_;
  const ExecutableContent* on_exit_;
};

}  // namespace model
}  // namespace state_chart

#endif  // STATE_CHART_INTERNAL_MODEL_STATE_H_


text:
from setuptools import setup

setup(
    name='lektor-gae',
    description='Publishes your Lektor site to Google App Engine.',
    url='https://github.com/isotherm/lektor-gae/',
    version='0.1',
    author=u'Kirk Meyer',
    author_email='kirk.meyer@alpaxo.com',
    license='MIT',
    platforms='any',
    py_modules=['lektor_gae'],
    entry_points={
        'lektor.plugins': [
            'gae = lektor_gae:GaePlugin',
        ]
    },
    install_requires=[
        'Lektor',
        'PyYAML',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP :: Site Management',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ],
)


text:
//*********************************************************//
//    Copyright (c) Microsoft. All rights reserved.
//
//    Apache 2.0 License
//
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
//    implied. See the License for the specific language governing
//    permissions and limitations under the License.
//
//*********************************************************//

using System.Collections.Generic;

namespace Microsoft.NodejsTools {
    /// <summary>
    /// Just used for our MEF import to get the metadata in a strongly
    /// typed way.
    /// </summary>
    public interface IClassifierProviderMetadata {
        IEnumerable<string> ContentTypes { get; }
    }
}


text:
package com.readytalk.swt.text.navigation;

import java.net.URL;

import org.eclipse.swt.graphics.Rectangle;

import com.readytalk.swt.text.tokenizer.TextToken;

/**
 * Hyperlink is a class representing a section of clickable text.  It is a
 * composite of a Token, representing a URL, and a rectangular boundary.
 */
public class Hyperlink {
	private TextToken token;
	private Rectangle bounds;

	/**
	 * Creates a Hyperlink with the given token and visual boundary.
	 *
	 * @param token : {@link TextToken}
	 * @param bounds : {@link Rectangle}
	 */
	public Hyperlink(final TextToken token, final Rectangle bounds) {
		this.token = token;
		this.bounds = bounds;
	}

	/**
	 * Gets the URL from the internal Token.
	 * @return {@link URL}
	 */
	public URL getURL() {
		return token.getURL();
	}

	/**
	 * Test whether a coordinate is within the Hyperlink boundary.
	 * @return boolean
	 */
	public boolean contains(final int x, final int y) {
		return bounds.contains(x, y);
	}
}