text:
using System;
using System.Collections.Generic;
using System.Text.Json;
using Azure;
using Azure.Core;
using Azure.ResourceManager.HDInsight;

namespace Azure.ResourceManager.HDInsight.Models
{
    public partial class HDInsightClusterProperties : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(ClusterVersion))
            {
                writer.WritePropertyName("clusterVersion");
                writer.WriteStringValue(ClusterVersion);
            }
            if (Optional.IsDefined(ClusterHdpVersion))
            {
                writer.WritePropertyName("clusterHdpVersion");
                writer.WriteStringValue(ClusterHdpVersion);
            }
            if (Optional.IsDefined(OSType))
            {
                writer.WritePropertyName("osType");
                writer.WriteStringValue(OSType.Value.ToString());
            }
            if (Optional.IsDefined(Tier))
            {
                writer.WritePropertyName("tier");
                writer.WriteStringValue(Tier.Value.ToString());
            }
            if (Optional.IsDefined(ClusterId))
            {
                writer.WritePropertyName("clusterId");
                writer.WriteStringValue(ClusterId);
            }
            writer.WritePropertyName("clusterDefinition");
            writer.WriteObjectValue(ClusterDefinition);
            if (Optional.IsDefined(KafkaRestProperties))
            {
                writer.WritePropertyName("kafkaRestProperties");
                writer.WriteObjectValue(KafkaRestProperties);
            }
            if (Optional.IsDefined(SecurityProfile))
            {
                writer.WritePropertyName("securityProfile");
                writer.WriteObjectValue(SecurityProfile);
            }
            if (Optional.IsDefined(ComputeProfile))
            {
                writer.WritePropertyName("computeProfile");
                writer.WriteObjectValue(ComputeProfile);
            }
            if (Optional.IsDefined(ProvisioningState))
            {
                writer.WritePropertyName("provisioningState");
                writer.WriteStringValue(ProvisioningState.Value.ToString());
            }
            if (Optional.IsDefined(CreatedOn))
            {
                writer.WritePropertyName("createdDate");
                writer.WriteStringValue(CreatedOn.Value, "O");
            }
            if (Optional.IsDefined(ClusterState))
            {
                writer.WritePropertyName("clusterState");
                writer.WriteStringValue(ClusterState);
            }
            if (Optional.IsDefined(QuotaInfo))
            {
                writer.WritePropertyName("quotaInfo");
                writer.WriteObjectValue(QuotaInfo);
            }
            if (Optional.IsCollectionDefined(Errors))
            {
                writer.WritePropertyName("errors");
                writer.WriteStartArray();
                foreach (var item in Errors)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(ConnectivityEndpoints))
            {
                writer.WritePropertyName("connectivityEndpoints");
                writer.WriteStartArray();
                foreach (var item in ConnectivityEndpoints)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(DiskEncryptionProperties))
            {
                writer.WritePropertyName("diskEncryptionProperties");
                writer.WriteObjectValue(DiskEncryptionProperties);
            }
            if (Optional.IsDefined(EncryptionInTransitProperties))
            {
                writer.WritePropertyName("encryptionInTransitProperties");
                writer.WriteObjectValue(EncryptionInTransitProperties);
            }
            if (Optional.IsDefined(StorageProfile))
            {
                writer.WritePropertyName("storageProfile");
                writer.WriteObjectValue(StorageProfile);
            }
            if (Optional.IsDefined(MinSupportedTlsVersion))
            {
                writer.WritePropertyName("minSupportedTlsVersion");
                writer.WriteStringValue(MinSupportedTlsVersion);
            }
            if (Optional.IsDefined(ExcludedServicesConfig))
            {
                writer.WritePropertyName("excludedServicesConfig");
                writer.WriteObjectValue(ExcludedServicesConfig);
            }
            if (Optional.IsDefined(NetworkProperties))
            {
                writer.WritePropertyName("networkProperties");
                writer.WriteObjectValue(NetworkProperties);
            }
            if (Optional.IsDefined(ComputeIsolationProperties))
            {
                writer.WritePropertyName("computeIsolationProperties");
                writer.WriteObjectValue(ComputeIsolationProperties);
            }
            if (Optional.IsCollectionDefined(PrivateLinkConfigurations))
            {
                writer.WritePropertyName("privateLinkConfigurations");
                writer.WriteStartArray();
                foreach (var item in PrivateLinkConfigurations)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
        }

        internal static HDInsightClusterProperties DeserializeHDInsightClusterProperties(JsonElement element)
        {
            Optional<string> clusterVersion = default;
            Optional<string> clusterHdpVersion = default;
            Optional<HDInsightOSType> osType = default;
            Optional<HDInsightTier> tier = default;
            Optional<string> clusterId = default;
            HDInsightClusterDefinition clusterDefinition = default;
            Optional<KafkaRestProperties> kafkaRestProperties = default;
            Optional<HDInsightSecurityProfile> securityProfile = default;
            Optional<ComputeProfile> computeProfile = default;
            Optional<HDInsightClusterProvisioningState> provisioningState = default;
            Optional<DateTimeOffset> createdDate = default;
            Optional<string> clusterState = default;
            Optional<QuotaInfo> quotaInfo = default;
            Optional<IList<ResponseError>> errors = default;
            Optional<IList<ConnectivityEndpoint>> connectivityEndpoints = default;
            Optional<HDInsightDiskEncryptionProperties> diskEncryptionProperties = default;
            Optional<EncryptionInTransitProperties> encryptionInTransitProperties = default;
            Optional<StorageProfile> storageProfile = default;
            Optional<string> minSupportedTlsVersion = default;
            Optional<ExcludedServicesConfig> excludedServicesConfig = default;
            Optional<HDInsightClusterNetworkProperties> networkProperties = default;
            Optional<HDInsightComputeIsolationProperties> computeIsolationProperties = default;
            Optional<IList<HDInsightPrivateLinkConfiguration>> privateLinkConfigurations = default;
            Optional<IReadOnlyList<HDInsightPrivateEndpointConnectionData>> privateEndpointConnections = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("clusterVersion"))
                {
                    clusterVersion = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("clusterHdpVersion"))
                {
                    clusterHdpVersion = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("osType"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    osType = new HDInsightOSType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("tier"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    tier = new HDInsightTier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("clusterId"))
                {
                    clusterId = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("clusterDefinition"))
                {
                    clusterDefinition = HDInsightClusterDefinition.DeserializeHDInsightClusterDefinition(property.Value);
                    continue;
                }
                if (property.NameEquals("kafkaRestProperties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    kafkaRestProperties = KafkaRestProperties.DeserializeKafkaRestProperties(property.Value);
                    continue;
                }
                if (property.NameEquals("securityProfile"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    securityProfile = HDInsightSecurityProfile.DeserializeHDInsightSecurityProfile(property.Value);
                    continue;
                }
                if (property.NameEquals("computeProfile"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    computeProfile = ComputeProfile.DeserializeComputeProfile(property.Value);
                    continue;
                }
                if (property.NameEquals("provisioningState"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    provisioningState = new HDInsightClusterProvisioningState(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("createdDate"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    createdDate = property.Value.GetDateTimeOffset("O");
                    continue;
                }
                if (property.NameEquals("clusterState"))
                {
                    clusterState = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("quotaInfo"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    quotaInfo = QuotaInfo.DeserializeQuotaInfo(property.Value);
                    continue;
                }
                if (property.NameEquals("errors"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<ResponseError> array = new List<ResponseError>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(JsonSerializer.Deserialize<ResponseError>(item.ToString()));
                    }
                    errors = array;
                    continue;
                }
                if (property.NameEquals("connectivityEndpoints"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<ConnectivityEndpoint> array = new List<ConnectivityEndpoint>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(ConnectivityEndpoint.DeserializeConnectivityEndpoint(item));
                    }
                    connectivityEndpoints = array;
                    continue;
                }
                if (property.NameEquals("diskEncryptionProperties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    diskEncryptionProperties = HDInsightDiskEncryptionProperties.DeserializeHDInsightDiskEncryptionProperties(property.Value);
                    continue;
                }
                if (property.NameEquals("encryptionInTransitProperties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    encryptionInTransitProperties = EncryptionInTransitProperties.DeserializeEncryptionInTransitProperties(property.Value);
                    continue;
                }
                if (property.NameEquals("storageProfile"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    storageProfile = StorageProfile.DeserializeStorageProfile(property.Value);
                    continue;
                }
                if (property.NameEquals("minSupportedTlsVersion"))
                {
                    minSupportedTlsVersion = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("excludedServicesConfig"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    excludedServicesConfig = ExcludedServicesConfig.DeserializeExcludedServicesConfig(property.Value);
                    continue;
                }
                if (property.NameEquals("networkProperties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    networkProperties = HDInsightClusterNetworkProperties.DeserializeHDInsightClusterNetworkProperties(property.Value);
                    continue;
                }
                if (property.NameEquals("computeIsolationProperties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    computeIsolationProperties = HDInsightComputeIsolationProperties.DeserializeHDInsightComputeIsolationProperties(property.Value);
                    continue;
                }
                if (property.NameEquals("privateLinkConfigurations"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<HDInsightPrivateLinkConfiguration> array = new List<HDInsightPrivateLinkConfiguration>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(HDInsightPrivateLinkConfiguration.DeserializeHDInsightPrivateLinkConfiguration(item));
                    }
                    privateLinkConfigurations = array;
                    continue;
                }
                if (property.NameEquals("privateEndpointConnections"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<HDInsightPrivateEndpointConnectionData> array = new List<HDInsightPrivateEndpointConnectionData>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(HDInsightPrivateEndpointConnectionData.DeserializeHDInsightPrivateEndpointConnectionData(item));
                    }
                    privateEndpointConnections = array;
                    continue;
                }
            }
            return new HDInsightClusterProperties(clusterVersion.Value, clusterHdpVersion.Value, Optional.ToNullable(osType), Optional.ToNullable(tier), clusterId.Value, clusterDefinition, kafkaRestProperties.Value, securityProfile.Value, computeProfile.Value, Optional.ToNullable(provisioningState), Optional.ToNullable(createdDate), clusterState.Value, quotaInfo.Value, Optional.ToList(errors), Optional.ToList(connectivityEndpoints), diskEncryptionProperties.Value, encryptionInTransitProperties.Value, storageProfile.Value, minSupportedTlsVersion.Value, excludedServicesConfig.Value, networkProperties.Value, computeIsolationProperties.Value, Optional.ToList(privateLinkConfigurations), Optional.ToList(privateEndpointConnections));
        }
    }
}


text:
import React from 'react';

export default class ChipCheckmark extends React.Component<{}, {}> {
  width: number = 0;

  init = (element: HTMLDivElement) => {
    if (!element) {
      return;
    }
    // The checkmark's width may initially be set to 0, so use the checkmark's height as a proxy since the
    // checkmark should always be square.
    this.width = element.getBoundingClientRect().height;
  };

  render() {
    return (
      <div className='mdc-chip__checkmark' ref={this.init}>
        <svg
          className='mdc-chip__checkmark-svg'
          viewBox='-2 -3 30 30'
          focusable='false'
        >
          <path
            className='mdc-chip__checkmark-path'
            fill='none'
            stroke='black'
            d='M1.73,12.91 8.1,19.28 22.79,4.59'
          />
        </svg>
      </div>
    );
  }
}

redpajama_set_name: RedPajamaGithub


text:
import scrapy
from scrapy.shell import inspect_response

from duxiu.items import ExamItem

class ExamSpider(scrapy.Spider):
    name = "exam"
    allowed_domains = ["book.duxiu.com"]
    start_urls = (
        'http://book.duxiu.com/examindex.jsp',
    )

    def parse(self, response):
        for one_level in response.xpath('//ul[@class="treeBd"]/li'):
            one_level_title = one_level.xpath(
                './div/a[contains(@href, "?fenlei=")]/text()').extract_first()
            for two_level in one_level.xpath('./ul/li'):
                two_level_title = two_level.xpath(
                    './div/a[contains(@href, "?fenlei=")]/text()').extract_first()
                for three_level in two_level.xpath('./ul/li'):
                    three_level_title = three_level.xpath(
                        './a[contains(@href, "?fenlei=")]/text()').extract_first()
                    url = three_level.xpath(
                        './a[contains(@href, "?fenlei=")]/@href').extract_first()
                    classification = [one_level_title,
                                      two_level_title, three_level_title]
                    classification = map(
                        lambda x: x.split('(')[0], classification)
                    yield scrapy.Request(response.urljoin(url), self.parse_list, meta={'classification': classification})

    def parse_list(self, response):
        next_page_url = response.xpath(
            u'//div[@id="pageinfo"]/a[text()="下一页"]/@href').extract_first()
        if next_page_url is not None:
            yield scrapy.Request(response.urljoin(next_page_url), self.parse_list, meta=response.meta)

        for download_dom in response.xpath('//ul[@class="searchResult"]/li/div[1]/a[1]'):
            url = download_dom.xpath('./@href').extract_first()
            title = download_dom.xpath('./text()').extract_first()
            yield ExamItem(url=response.urljoin(url),
                           title=title,
                           classification=response.meta['classification'])


text:
from test.util.ports import new as new_port
from test.util.module_disposer import uses_module, case_uses_module
from experiments.ud_xilinx.command_senders import SerialPortCommandSender
from experiments.ud_xilinx.programmers import XilinxImpactProgrammer
import sys
import test.unit.configuration as configuration
import time
import unittest
import voodoo.configuration as ConfigurationManager
import voodoo.gen.coordinator.Access as Access
import voodoo.gen.coordinator.AccessLevel as AccessLevel
import voodoo.gen.coordinator.CoordAddress as CoordAddress
import voodoo.gen.coordinator.CoordinationInformation as CoordInfo
import voodoo.gen.coordinator.CoordinatorServer as CoordinatorServer
import voodoo.gen.generators.ServerSkel as ServerSkel
import voodoo.gen.locator.EasyLocator as EasyLocator
import voodoo.gen.locator.ServerLocator as ServerLocator
import voodoo.gen.locator.ServerTypeHandler as ServerTypeHandler
import voodoo.gen.protocols.Direct.Address as DirectAddress
import voodoo.gen.protocols.Direct.Network as DirectNetwork
import voodoo.gen.protocols.protocols as Protocols
import voodoo.gen.protocols.SOAP.Address as SOAPAddress
import voodoo.gen.protocols.SOAP.Network as SOAPNetwork
import voodoo.gen.protocols.SOAP.ServerSOAP as ServerSOAP
import voodoo.gen.registry.server_registry as ServerRegistry
import voodoo.methods as voodoo_exported_methods
import voodoo.sessions.session_type as SessionType
import weblab.data.client_address as ClientAddress
import weblab.data.command as Command
import weblab.data.server_type as ServerType
import weblab.experiment.util as ExperimentUtil
import experiments.ud_xilinx.server as UdXilinxExperiment
import weblab.lab.server as LaboratoryServer
import weblab.login.server as LoginServer
import weblab.methods as weblab_exported_methods
import weblab.core.alive_users    as AliveUsersCollection
import weblab.core.reservations             as Reservation
import weblab.core.server    as UserProcessingServer
import weblab.core.user_processor           as UserProcessor

from weblab.core.coordinator.gateway import create as coordinator_create, SQLALCHEMY

# Wait that time at most for the board to finish programming before giving up.
XILINX_TIMEOUT = 4

########################################################
# Case 001: a single instance of everything on a       #
# single instance of the WebLab, with two experiments #
########################################################

class FakeUdXilinxExperiment(UdXilinxExperiment.UdXilinxExperiment):
    def __init__(self, coord_address, locator, cfg_manager, fake_xilinx_impact, fake_serial_port, *args, **kwargs):
        super(FakeUdXilinxExperiment,self).__init__(coord_address, locator, cfg_manager, *args, **kwargs)
        self._xilinx_impact = fake_xilinx_impact
        self._programmer = XilinxImpactProgrammer(cfg_manager, fake_xilinx_impact)
        self._programmer._xilinx_impact_device = fake_xilinx_impact
        self._command_sender = SerialPortCommandSender(cfg_manager)
        self._command_sender._serial_port = fake_serial_port

class FakeImpact(object):
    def __init__(self):
        super(FakeImpact,self).__init__()
        self.clear()
    def program_device(self, program_path):
        self._paths.append(open(program_path).read())
    def get_suffix(self):
        return "whatever"
    def clear(self):
        self._paths = []

class FakeSerialPort(object):
    def __init__(self):
        super(FakeSerialPort,self).__init__()
        self.clear()
    def open_serial_port(self, number):
        self.dict['open'].append((self.cycle, number))
        self.cycle += 1
    def send_code(self, n):
        self.dict['send'].append((self.cycle, n))
        self.cycle += 1
    def close_serial_port(self):
        self.dict['close'].append((self.cycle, None))
        self.cycle += 1
    def clear(self):
        self.dict = {'open':[], 'close':[], 'send' : []}
        self.cycle = 0

PORT1 = new_port()
PORT2 = new_port()
PORT3 = new_port()
PORT5 = new_port()
PORT7 = new_port()
PORT8 = new_port()

# Abstract
class Case001TestCase(object):

    def gen_coordination_map(self, protocols):
        map = CoordInfo.CoordinationMap()

        map.add_new_machine('WL_MACHINE1')
        map.add_new_instance('WL_MACHINE1','WL_SERVER1')
        map.add_new_server( 'WL_MACHINE1', 'WL_SERVER1', 'login1',       ServerType.Login, ())
        map.add_new_server( 'WL_MACHINE1', 'WL_SERVER1', 'ups1',         ServerType.UserProcessing, ())
        map.add_new_server( 'WL_MACHINE1', 'WL_SERVER1', 'coordinator1', ServerType.Coordinator, ())
        map.add_new_server( 'WL_MACHINE1', 'WL_SERVER1', 'laboratory1',  ServerType.Laboratory, ())
        map.add_new_server( 'WL_MACHINE1', 'WL_SERVER1', 'experiment1',  ServerType.Experiment, (), ('ud-fpga@FPGA experiments',))
        map.add_new_server( 'WL_MACHINE1', 'WL_SERVER1', 'experiment2',  ServerType.Experiment, (), ('ud-pld@PLD experiments',))

        if len(protocols) == 1 and protocols[0] == Protocols.Direct:
            # They all have Direct

            # 1st: address
            address1 = map['WL_MACHINE1']['WL_SERVER1']['login1'].address
            address2 = map['WL_MACHINE1']['WL_SERVER1']['ups1'].address
            address3 = map['WL_MACHINE1']['WL_SERVER1']['coordinator1'].address
            address5 = map['WL_MACHINE1']['WL_SERVER1']['laboratory1'].address
            address7 = map['WL_MACHINE1']['WL_SERVER1']['experiment1'].address
            address8 = map['WL_MACHINE1']['WL_SERVER1']['experiment2'].address

            # 2nd: network
            direct_network1 = DirectNetwork.DirectNetwork( DirectAddress.from_coord_address(address1))
            direct_network2 = DirectNetwork.DirectNetwork( DirectAddress.from_coord_address(address2))
            direct_network3 = DirectNetwork.DirectNetwork( DirectAddress.from_coord_address(address3))
            direct_network5 = DirectNetwork.DirectNetwork( DirectAddress.from_coord_address(address5))
            direct_network7 = DirectNetwork.DirectNetwork( DirectAddress.from_coord_address(address7))
            direct_network8 = DirectNetwork.DirectNetwork( DirectAddress.from_coord_address(address8))

            # 3rd: accesses
            access_direct1 = Access.Access( Protocols.Direct, AccessLevel.instance,(direct_network1,))
            access_direct2 = Access.Access( Protocols.Direct, AccessLevel.instance,(direct_network2,))
            access_direct3 = Access.Access( Protocols.Direct, AccessLevel.instance,(direct_network3,))
            access_direct5 = Access.Access( Protocols.Direct, AccessLevel.instance,(direct_network5,))
            access_direct7 = Access.Access( Protocols.Direct, AccessLevel.instance,(direct_network7,))
            access_direct8 = Access.Access( Protocols.Direct, AccessLevel.instance,(direct_network8,))

            # 4th: appending accesses
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'login1', ( access_direct1, ))
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'ups1', ( access_direct2, ))
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'coordinator1', ( access_direct3, ))
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'laboratory1', ( access_direct5, ))
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'experiment1', ( access_direct7, ))
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'experiment2', ( access_direct8, ))

        else:
            # They all have SOAP

            # 1st: address
            address1 = SOAPAddress.Address('127.0.0.1:%s@NETWORK' % PORT1)
            address2 = SOAPAddress.Address('127.0.0.1:%s@NETWORK' % PORT2)
            address3 = SOAPAddress.Address('127.0.0.1:%s@NETWORK' % PORT3)
            address5 = SOAPAddress.Address('127.0.0.1:%s@NETWORK' % PORT5)
            address7 = SOAPAddress.Address('127.0.0.1:%s@NETWORK' % PORT7)
            address8 = SOAPAddress.Address('127.0.0.1:%s@NETWORK' % PORT8)

            # 2nd: network
            soap_network1 = SOAPNetwork.SOAPNetwork( address1 )
            soap_network2 = SOAPNetwork.SOAPNetwork( address2 )
            soap_network3 = SOAPNetwork.SOAPNetwork( address3 )
            soap_network5 = SOAPNetwork.SOAPNetwork( address5 )
            soap_network7 = SOAPNetwork.SOAPNetwork( address7 )
            soap_network8 = SOAPNetwork.SOAPNetwork( address8 )

            # 3rd: accesses
            access_soap1 = Access.Access( Protocols.SOAP, AccessLevel.network,(soap_network1,) )
            access_soap2 = Access.Access( Protocols.SOAP, AccessLevel.network,(soap_network2,) )
            access_soap3 = Access.Access( Protocols.SOAP, AccessLevel.network,(soap_network3,) )
            access_soap5 = Access.Access( Protocols.SOAP, AccessLevel.network,(soap_network5,) )
            access_soap7 = Access.Access( Protocols.SOAP, AccessLevel.network,(soap_network7,) )
            access_soap8 = Access.Access( Protocols.SOAP, AccessLevel.network,(soap_network8,) )

            # 4th: appending accesses
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'login1', ( access_soap1, ))
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'ups1', ( access_soap2, ))
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'coordinator1', ( access_soap3, ))
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'laboratory1', ( access_soap5, ))
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'experiment1', ( access_soap7, ))
            map.append_accesses( 'WL_MACHINE1', 'WL_SERVER1', 'experiment2', ( access_soap8, ))

        return map

    def generate_coordinator_server(self, protocol, cfg_manager):
        map = self.gen_coordination_map(protocol)

        protocols = protocol
        if protocol[0] != Protocols.Direct:
            protocols += (Protocols.Direct,)

        generated_coordinator = ServerSkel.factory(
                cfg_manager,
                protocols,
                voodoo_exported_methods.coordinator
            )

        class RealCoordinatorServer(CoordinatorServer.CoordinatorServer,generated_coordinator):
            def __init__(self,cfg_manager,map,*args,**kargs):
                CoordinatorServer.CoordinatorServer.__init__(self,cfg_manager,map, *args, **kargs)

        real_coordinator_server = RealCoordinatorServer(
                cfg_manager,
                map,
                Direct = (map['WL_MACHINE1']['WL_SERVER1']['coordinator1'].address.address,),
                SOAP   = ('',PORT3)
            )
        real_coordinator_server.start()
        self.map = map
        return real_coordinator_server

    def generate_locator(self):
        coordinator_server_address = DirectAddress.Address(
                'WL_MACHINE1',
                'WL_SERVER1',
                'coordinator1'
            )
        server_type_handler = ServerTypeHandler.ServerTypeHandler(
            ServerType,
            {
                ServerType.Coordinator :    voodoo_exported_methods.coordinator,
                ServerType.Login :          weblab_exported_methods.Login,
                ServerType.UserProcessing : weblab_exported_methods.UserProcessing,
                ServerType.Proxy :          weblab_exported_methods.Proxy,
                ServerType.Laboratory :     weblab_exported_methods.Laboratory,
                ServerType.Translator :     weblab_exported_methods.Translator,
                ServerType.Experiment :     weblab_exported_methods.Experiment
            }
        )

        locator = ServerLocator.ServerLocator(
            coordinator_server_address,
            server_type_handler
        )

        easy_locator = EasyLocator.EasyLocator(
                CoordAddress.CoordAddress('WL_MACHINE1','WL_SERVER1','coordinator1'),
                locator
            )

        return easy_locator

    def generate_configuration_server(self):
        cfg_manager= ConfigurationManager.ConfigurationManager()
        cfg_manager.append_module(configuration)
        return cfg_manager

    def generate_login_server(self, protocols, cfg_manager):
        login_coord_address = CoordAddress.CoordAddress.translate_address("login1:WL_SERVER1@WL_MACHINE1")
        locator = self.generate_locator()

        generated_login_server = ServerSkel.factory(
                self.generate_configuration_server(),
                protocols,
                weblab_exported_methods.Login
            )

        class RealLoginServer(LoginServer.LoginServer,generated_login_server):
            def __init__(self, coord_address, locator, cfg_manager, *args,**kargs):
                LoginServer.LoginServer.__init__(self, coord_address, locator, cfg_manager, *args, **kargs)

        real_login_server = RealLoginServer(
                login_coord_address,
                locator,
                cfg_manager,
                Direct = (login_coord_address.address,),
                SOAP   = ('',PORT1)
            )
        real_login_server.start()

        login_client = locator.get_server(ServerType.Login, None)
        return login_client, real_login_server

    def generate_core_server(self, cfg_manager, protocols):
        ups_coord_address = CoordAddress.CoordAddress.translate_address("ups1:WL_SERVER1@WL_MACHINE1")
        locator = self.generate_locator()

        generated_ups = ServerSkel.factory(
                cfg_manager,
                protocols,
                weblab_exported_methods.UserProcessing
            )

        class RealUserProcessingServer(UserProcessingServer.UserProcessingServer,generated_ups):
            def __init__(self, coord_address, locator, cfg_manager, *args,**kargs):
                UserProcessingServer.UserProcessingServer.__init__(
                        self,
                        coord_address,
                        locator,
                        cfg_manager,
                        *args,
                        **kargs
                    )

        coordinator = coordinator_create(SQLALCHEMY, self.locator, self.cfg_manager)
        coordinator._clean()
        coordinator.stop()

        real_core_server = RealUserProcessingServer(
                ups_coord_address,
                locator,
                cfg_manager,
                Direct = (ups_coord_address.address,),
                SOAP   = ('',PORT2)
            )
        real_core_server.start()

        core_client = locator.get_server(ServerType.UserProcessing, None)
        return core_client, real_core_server

    def generate_fake_experiment(self, cfg_manager, fake_xilinx_impact, fake_serial_port, number, experiment_name, experiment_category_name, protocols):
        generated_experiment = ServerSkel.factory(
                cfg_manager,
                protocols,
                weblab_exported_methods.Experiment
            )

        class RealUdXilinxExperiment(FakeUdXilinxExperiment,generated_experiment):
            def __init__(self, coord_address, locator, cfg_manager, fake_xilinx_impact, fake_serial_port, *args,**kargs):
                FakeUdXilinxExperiment.__init__(
                        self,
                        coord_address,
                        locator,
                        cfg_manager,
                        fake_xilinx_impact,
                        fake_serial_port,
                        *args,
                        **kargs
                    )
        locator = self.generate_locator()

        real_experiment = RealUdXilinxExperiment(
                None,
                None,
                cfg_manager,
                fake_xilinx_impact,
                fake_serial_port,
                Direct = ( self.map['WL_MACHINE1']['WL_SERVER1']['experiment' + number].address.address,),
                SOAP   = ('',PORT7 + (int(number)-1))
            )
        real_experiment.start()

        def on_finish():
            experiment_client = locator.get_server(
                            ServerType.Experiment,
                            experiment_name + '@' + experiment_category_name
                        )
            return experiment_client, real_experiment
        return on_finish

    def generate_laboratory_server(self, cfg_manager, protocols):
        generated_laboratory_server = ServerSkel.factory(
                cfg_manager,
                protocols,
                weblab_exported_methods.Laboratory
            )
        locator = self.generate_locator()

        class RealLaboratoryServer(LaboratoryServer.LaboratoryServer,generated_laboratory_server):
            def __init__(self, coord_address, locator, cfg_manager, *args,**kargs):
                LaboratoryServer.LaboratoryServer.__init__(
                        self,
                        coord_address,
                        locator,
                        cfg_manager,
                        *args,
                        **kargs
                    )

        real_laboratory_server = RealLaboratoryServer(
                self.map['WL_MACHINE1']['WL_SERVER1']['laboratory1'].address,
                locator,
                cfg_manager,
                Direct = (self.map['WL_MACHINE1']['WL_SERVER1']['laboratory1'].address.address,),
                SOAP   = ('',PORT5)
            )
        real_laboratory_server.start()

        laboratory_client = locator.get_server(ServerType.Laboratory, None)
        return laboratory_client, real_laboratory_server

    def setUp(self):
        protocols                      = self.get_protocols()

        self.real_servers              = []

        self.fake_impact1              = FakeImpact()
        self.fake_serial_port1         = FakeSerialPort()

        self.fake_impact2              = FakeImpact()
        self.fake_serial_port2         = FakeSerialPort()

        self.cfg_manager               = self.generate_configuration_server()

        self.coordinator_server        = self.generate_coordinator_server(protocols, self.cfg_manager)
        self.real_servers.append(self.coordinator_server)

        self.locator                   = None
        self.login_server, reals       = self.generate_login_server(
                                protocols,
                                self.cfg_manager
                            )
        self.real_login = reals

        self.real_servers.append(reals)
        self.core_server, reals    = self.generate_core_server(
                                self.cfg_manager,
                                protocols
                            )
        self.real_ups = reals
        self.real_servers.append(reals)
        on_finish1                     = self.generate_fake_experiment(
                                self.cfg_manager,
                                self.fake_impact1,
                                self.fake_serial_port1,
                                '1',
                                'ud-fpga',
                                'FPGA experiments',
                                protocols
                            )
        on_finish2                     = self.generate_fake_experiment(
                                self.cfg_manager,
                                self.fake_impact2,
                                self.fake_serial_port2,
                                '2',
                                'ud-pld',
                                'PLD experiments',
                                protocols
                            )
        self.experiment1, reals       = on_finish1()
        self.real_servers.append(reals)
        self.experiment2, reals       = on_finish2()
        self.real_servers.append(reals)

        self.laboratory_server, reals   = self.generate_laboratory_server(
                                self.cfg_manager,
                                protocols
                            )
        self.real_servers.append(reals)

    @uses_module(UserProcessingServer)
    @uses_module(UserProcessor)
    @uses_module(ServerSOAP)
    def test_single_uses_timeout(self):
        backup_poll_time           = configuration.core_experiment_poll_time
        backup_time_between_checks = self.cfg_manager.get_value('core_time_between_checks', AliveUsersCollection.DEFAULT_TIME_BETWEEN_CHECKS)
        try:
            self.cfg_manager._set_value('core_experiment_poll_time',1.5)
            self.cfg_manager._set_value('core_time_between_checks',1.5)
            self._single_use(logout = False, plus_async_use = False)
            time.sleep(self.cfg_manager.get_value('core_experiment_poll_time') + 0.3 + self.cfg_manager.get_value('core_time_between_checks'))
            self._single_use(logout = False, plus_async_use = False)
        finally:
            self.cfg_manager._set_value('core_experiment_poll_time',backup_poll_time)
            self.cfg_manager._set_value('core_time_between_checks',backup_time_between_checks)

    @uses_module(UserProcessingServer)
    @uses_module(UserProcessor)
    @uses_module(ServerSOAP)
    def test_simple_single_uses(self):
        for _ in range(1):
            self._single_use()
        self._single_use()
        self._single_use()

    def _wait_async_done(self, session_id, reqids):
        """
        _wait_async_done(session_id, reqids)
        Helper methods that waits for the specified asynchronous requests to be finished,
        and which asserts that they were successful. Note that it doesn't actually return
        their responses.
        @param reqids Tuple containing the request ids for the commands to check.
        @return Nothing
        """
        # Wait until send_async_file query is actually finished.
        reqsl = list(reqids)
        while len(reqsl) > 0:
            requests = self.real_ups.check_async_command_status(session_id, tuple(reqsl))
            self.assertEquals(len(reqsl), len(requests))
            for rid, req in requests.iteritems():
                status = req[0]
                self.assertTrue(status in ("running", "ok", "error"))
                if status != "running":
                    self.assertEquals("ok", status, "Contents: " + req[1])
                    reqsl.remove(rid)

    def _get_async_response(self, session_id, reqid):
        """
        _get_async_response(reqids)
        Helper method that synchronously gets the response for the specified async request, asserting that
        it was successful.
        @param reqid The request identifier for the async request whose response we want
        @return Response to the request, if successful. None, otherwise.
        """
        # Wait until send_async_file query is actually finished.
        while True:
            requests = self.real_ups.check_async_command_status(session_id, (reqid,))
            self.assertEquals(1, len(requests))
            self.assertTrue(reqid in requests)
            req = requests[reqid]
            status = req[0]
            self.assertTrue(status in ("running", "ok", "error"))
            if status != "running":
                self.assertEquals("ok", status, "Contents: " + req[1])
                return Command.Command(req[1])

    def _single_async_use(self, logout = True):
        self.fake_impact1.clear()
        self.fake_impact2.clear()
        self.fake_serial_port1.clear()
        self.fake_serial_port2.clear()

        session_id = self.real_login.login('student1','password')

        user_information = self.real_ups.get_user_information(session_id)
        self.assertEquals(
                'student1',
                user_information.login
            )

        self.assertEquals(
                'Name of student 1',
                user_information.full_name
            )
        self.assertEquals(
                'weblab@deusto.es',
                user_information.email
            )

        experiments = self.real_ups.list_experiments(session_id)
        self.assertEquals( 5, len(experiments))

        fpga_experiments = [ exp.experiment for exp in experiments if exp.experiment.name == 'ud-fpga' ]
        self.assertEquals(
                len(fpga_experiments),
                1
            )

        # reserve it
        status = self.real_ups.reserve_experiment(
                session_id,
                fpga_experiments[0].to_experiment_id(),
                "{}", "{}",
                ClientAddress.ClientAddress("127.0.0.1")
            )

        reservation_id = status.reservation_id

        # wait until it is reserved
        short_time = 0.1

        # Time extended from 9.0 to 15.0 because at times the test failed, possibly for that reason.
        times      = 15.0 / short_time

        while times > 0:
            time.sleep(short_time)
            new_status = self.real_ups.get_reservation_status(reservation_id)
            if not isinstance(new_status, Reservation.WaitingConfirmationReservation) and not isinstance(new_status, Reservation.WaitingReservation):
                break
            times -= 1
        reservation = self.real_ups.get_reservation_status(
                        reservation_id
                    )
        self.assertTrue(
                isinstance(
                    reservation,
                    Reservation.ConfirmedReservation
                ),
                "Reservation %s is not Confirmed, as expected by this time" % reservation
            )

        # send the program again, but asynchronously. Though this should work, it is not really very customary
        # to send_file more than once in the same session. In fact, it is a feature which might get removed in
        # the future. When/if that happens, this will need to be modified.
        CONTENT = "content of the program FPGA"
        reqid = self.real_ups.send_async_file(reservation_id, ExperimentUtil.serialize(CONTENT), 'program')

        # Wait until send_async_file query is actually finished.
        #self._get_async_response(session_id, reqid)
        self._wait_async_done(reservation_id, (reqid,))

        # We need to wait for the programming to finish, while at the same
        # time making sure that the tests don't dead-lock.
        start_time = time.time()
        response = "STATE=not_ready"
        while response in ("STATE=not_ready", "STATE=programming") and time.time() - start_time < XILINX_TIMEOUT:
            reqid = self.real_ups.send_async_command(reservation_id, Command.Command("STATE"))
            respcmd = self._get_async_response(reservation_id, reqid)
            response = respcmd.get_command_string()
            time.sleep(0.2)

        # Check that the current state is "Ready"
        self.assertEquals("STATE=ready", response)

        reqid = self.real_ups.send_async_command(reservation_id, Command.Command("ChangeSwitch on 0"))
        self._wait_async_done(reservation_id, (reqid,))

        reqid = self.real_ups.send_async_command(reservation_id, Command.Command("ClockActivation on 250"))
        self._wait_async_done(reservation_id, (reqid,))

        # Checking the commands sent
        # Note that the number of paths is 2 now that we send a file twice (sync and async).
        self.assertEquals(
                1,
                len(self.fake_impact1._paths)
            )
        self.assertEquals(
                0,
                len(self.fake_impact2._paths)
            )

        self.assertEquals(
                CONTENT,
                self.fake_impact1._paths[0]
            )

        initial_open = 1
        initial_send = 1
        initial_close = 1
        initial_total = initial_open + initial_send + initial_close

        # ChangeSwitch on 0
        self.assertEquals(
                (0 + initial_total,1),
                self.fake_serial_port1.dict['open'][0 + initial_open]
            )
        self.assertEquals(
                (1 + initial_total,1),
                self.fake_serial_port1.dict['send'][0 + initial_send]
            )
        self.assertEquals(
                (2 + initial_total,None),
                self.fake_serial_port1.dict['close'][0 + initial_close]
            )

        # ClockActivation on 250
        self.assertEquals(
                (3 + initial_total,1),
                self.fake_serial_port1.dict['open'][1 + initial_open]
            )
        self.assertEquals(
                (4 + initial_total,32),
                self.fake_serial_port1.dict['send'][1 + initial_send]
            )

        self.assertEquals(
                (5 + initial_total,None),
                self.fake_serial_port1.dict['close'][1 + initial_close]
            )

        if logout:
            self.real_ups.logout(session_id)

    def _single_use(self, logout = True, plus_async_use = True):
        """
        Will use an experiment.
        @param logout If true, the user will be logged out after the use. Otherwise not.
        @param plus_async_use If true, after using the experiment synchronously, it will use it
        again using the asynchronous versions of the send_command and send_file requests.
        """
        self._single_sync_use(logout)
        if plus_async_use:
            self._single_async_use(logout)

    def _single_sync_use(self, logout = True):

        self.fake_impact1.clear()
        self.fake_impact2.clear()
        self.fake_serial_port1.clear()
        self.fake_serial_port2.clear()

        session_id = self.real_login.login('student1','password')

        user_information = self.real_ups.get_user_information(session_id)
        self.assertEquals(
                'student1',
                user_information.login
            )

        self.assertEquals(
                'Name of student 1',
                user_information.full_name
            )
        self.assertEquals(
                'weblab@deusto.es',
                user_information.email
            )

        experiments = self.real_ups.list_experiments(session_id)
        self.assertEquals( 5, len(experiments))

        fpga_experiments = [ exp.experiment for exp in experiments if exp.experiment.name == 'ud-fpga' ]
        self.assertEquals(
                len(fpga_experiments),
                1
            )

        # reserve it
        status = self.real_ups.reserve_experiment(
                session_id,
                fpga_experiments[0].to_experiment_id(),
                "{}", "{}",
                ClientAddress.ClientAddress("127.0.0.1")
            )

        reservation_id = status.reservation_id

        # wait until it is reserved
        short_time = 0.1
        times      = 13.0 / short_time

        while times > 0:
            new_status = self.real_ups.get_reservation_status(reservation_id)
            if not isinstance(new_status, Reservation.WaitingConfirmationReservation) and not isinstance(new_status, Reservation.WaitingReservation):
                break
            times -= 1
            time.sleep(short_time)
        reservation = self.real_ups.get_reservation_status(
                        reservation_id
                    )
        self.assertTrue(
                isinstance(
                    reservation,
                    Reservation.ConfirmedReservation
                ),
                "Reservation %s is not Confirmed, as expected by this time" % reservation
            )

        # send a program synchronously (the "traditional" way)
        CONTENT = "content of the program FPGA"
        self.real_ups.send_file(reservation_id, ExperimentUtil.serialize(CONTENT), 'program')

        # We need to wait for the programming to finish, while at the same
        # time making sure that the tests don't dead-lock.
        start_time = time.time()
        response = "STATE=not_ready"
        while response in ("STATE=not_ready", "STATE=programming") and time.time() - start_time < XILINX_TIMEOUT:
            respcmd = self.real_ups.send_command(reservation_id, Command.Command("STATE"))
            response = respcmd.get_command_string()
            time.sleep(0.2)

        # Check that the current state is "Ready"
        self.assertEquals("STATE=ready", response)

        # We need to wait for the programming to finish, while at the same
        # time making sure that the tests don't dead-lock.
        start_time = time.time()
        response = "STATE=not_ready"
        while response in ("STATE=not_ready", "STATE=programming") and time.time() - start_time < XILINX_TIMEOUT:
            respcmd = self.real_ups.send_command(reservation_id, Command.Command("STATE"))
            response = respcmd.get_command_string()
            time.sleep(0.2)

        # Check that the current state is "Ready"
        self.assertEquals("STATE=ready", response)

        self.real_ups.send_command(reservation_id, Command.Command("ChangeSwitch on 0"))
        self.real_ups.send_command(reservation_id, Command.Command("ClockActivation on 250"))

        # Checking the commands sent
        # Note that the number of paths is 2 now that we send a file twice (sync and async).
        self.assertEquals(
                1,
                len(self.fake_impact1._paths)
            )
        self.assertEquals(
                0,
                len(self.fake_impact2._paths)
            )

        self.assertEquals(
                CONTENT,
                self.fake_impact1._paths[0]
            )

        initial_open = 1
        initial_send = 1
        initial_close = 1
        initial_total = initial_open + initial_send + initial_close

        # ChangeSwitch on 0
        self.assertEquals(
                (0 + initial_total,1),
                self.fake_serial_port1.dict['open'][0 + initial_open]
            )
        self.assertEquals(
                (1 + initial_total,1),
                self.fake_serial_port1.dict['send'][0 + initial_send]
            )
        self.assertEquals(
                (2 + initial_total,None),
                self.fake_serial_port1.dict['close'][0 + initial_close]
            )

        # ClockActivation on 250
        self.assertEquals(
                (3 + initial_total,1),
                self.fake_serial_port1.dict['open'][1 + initial_open]
            )
        self.assertEquals(
                (4 + initial_total,32),
                self.fake_serial_port1.dict['send'][1 + initial_send]
            )

        self.assertEquals(
                (5 + initial_total,None),
                self.fake_serial_port1.dict['close'][1 + initial_close]
            )

#         end session
#         Note: Before async commands were implemented, this was actually done before
#         checking the commands sent. If it was that way for a reason, it might be
#         necessary to change it in the future.
        if logout:
            self.real_ups.logout(session_id)

    @uses_module(UserProcessingServer)
    @uses_module(UserProcessor)
    @uses_module(ServerSOAP)
    def test_two_multiple_uses_of_different_devices(self):
        user1_session_id = self.real_login.login('student1','password')
        user1_experiments = self.real_ups.list_experiments(user1_session_id)
        self.assertEquals(
                5,
                len(user1_experiments)
            )

        fpga_experiments = [ exp.experiment for exp in user1_experiments if exp.experiment.name == 'ud-fpga' ]
        self.assertEquals(
                len(fpga_experiments),
                1
            )

        # reserve it
        status = self.real_ups.reserve_experiment(
                user1_session_id,
                fpga_experiments[0].to_experiment_id(),
                "{}", "{}",
                ClientAddress.ClientAddress("127.0.0.1")
            )

        user1_reservation_id = status.reservation_id

        user2_session_id = self.real_login.login('student2','password')
        user2_experiments = self.real_ups.list_experiments(user2_session_id)
        self.assertEquals(
                7,
                len(user2_experiments)
            )

        pld_experiments = [ exp.experiment for exp in user2_experiments if exp.experiment.name == 'ud-pld' ]
        self.assertEquals(
                len(pld_experiments),
                1
            )

        # reserve it
        status = self.real_ups.reserve_experiment(
                user2_session_id,
                pld_experiments[0].to_experiment_id(),
                "{}", "{}",
                ClientAddress.ClientAddress("127.0.0.1")
            )

        user2_reservation_id = status.reservation_id

        short_time = 0.1
        times      = 9.0 / short_time

        while times > 0:
            time.sleep(short_time)
            new_status1 = self.real_ups.get_reservation_status(user1_reservation_id)
            new_status2 = self.real_ups.get_reservation_status(user2_reservation_id)
            if not isinstance(new_status1, Reservation.WaitingConfirmationReservation):
                if not isinstance(new_status2, Reservation.WaitingConfirmationReservation):
                    break
            times -= 1

        self.assertTrue(
                isinstance(
                    self.real_ups.get_reservation_status(
                        user1_reservation_id
                    ),
                    Reservation.ConfirmedReservation
                )
            )

        self.assertTrue(
                isinstance(
                    self.real_ups.get_reservation_status(
                        user2_reservation_id
                    ),
                    Reservation.ConfirmedReservation
                )
            )

        # send a program
        CONTENT1 = "content of the program FPGA"
        self.real_ups.send_file(user1_reservation_id, ExperimentUtil.serialize(CONTENT1), 'program')

        # We need to wait for the programming to finish.
        start_time = time.time()
        response = "STATE=not_ready"
        while response in ("STATE=not_ready", "STATE=programming") and time.time() - start_time < XILINX_TIMEOUT:
            respcmd = self.real_ups.send_command(user1_reservation_id, Command.Command("STATE"))
            response = respcmd.get_command_string()
            time.sleep(0.2)

        # Check that the current state is "Ready"
        self.assertEquals("STATE=ready", response)

        self.real_ups.send_command(user1_reservation_id, Command.Command("ChangeSwitch off 1"))
        self.real_ups.send_command(user1_reservation_id, Command.Command("ClockActivation on 250"))

        CONTENT2 = "content of the program PLD"
        self.real_ups.send_file(user2_reservation_id, ExperimentUtil.serialize(CONTENT2), 'program')

        # We need to wait for the programming to finish.
        start_time = time.time()
        response = "STATE=not_ready"
        while response in ("STATE=not_ready", "STATE=programming") and time.time() - start_time < XILINX_TIMEOUT:
            respcmd = self.real_ups.send_command(user1_reservation_id, Command.Command("STATE"))
            response = respcmd.get_command_string()
            time.sleep(0.2)

        # Check that the current state is "Ready"
        self.assertEquals("STATE=ready", response)

        self.real_ups.send_command(user2_reservation_id, Command.Command("ChangeSwitch on 0"))
        self.real_ups.send_command(user2_reservation_id, Command.Command("ClockActivation on 250"))

        # end session
        self.real_ups.logout(user1_session_id)
        self.real_ups.logout(user2_session_id)

        # Checking the commands sent
        self.assertEquals(
                1,
                len(self.fake_impact1._paths)
            )
        self.assertEquals(
                1,
                len(self.fake_impact2._paths)
            )
        self.assertEquals(
                CONTENT1,
                self.fake_impact1._paths[0]
            )
        self.assertEquals(
                CONTENT2,
                self.fake_impact2._paths[0]
            )

        initial_open  = 1
        initial_send  = 1
        initial_close = 1

        initial_total = initial_open + initial_send + initial_close

        # ChangeSwitch off 1
        self.assertEquals(
                (0 + initial_total,1),
                self.fake_serial_port1.dict['open'][0 + initial_open]
            )
        self.assertEquals(
                (1 + initial_total,4),
                self.fake_serial_port1.dict['send'][0 + initial_send]
            )
        self.assertEquals(
                (2 + initial_total,None),
                self.fake_serial_port1.dict['close'][0 + initial_close]
            )

        self.assertEquals(
                (0 + initial_total,1),
                self.fake_serial_port2.dict['open'][0 + initial_open]
            )
        self.assertEquals(
                (1 + initial_total,1),
                self.fake_serial_port2.dict['send'][0 + initial_send]
            )
        self.assertEquals(
                (2 + initial_total,None),
                self.fake_serial_port2.dict['close'][0 + initial_close]
            )

        # ClockActivation on 250
        self.assertEquals(
                (3 + initial_total,1),
                self.fake_serial_port1.dict['open'][1 + initial_open]
            )
        self.assertEquals(
                (4 + initial_total,32),
                self.fake_serial_port1.dict['send'][1 + initial_send]
            )

        self.assertEquals(
                (5 + initial_total,None),
                self.fake_serial_port1.dict['close'][1 + initial_close]
            )

        self.assertEquals(
                (3 + initial_total,1),
                self.fake_serial_port2.dict['open'][1 + initial_open]
            )
        self.assertEquals(
                (4 + initial_total,32),
                self.fake_serial_port2.dict['send'][1 + initial_send]
            )

        self.assertEquals(
                (5 + initial_total,None),
                self.fake_serial_port2.dict['close'][1 + initial_close]
            )

    def tearDown(self):
        ServerRegistry.get_instance().clear()

        for i in self.real_servers:
            i.stop()

@case_uses_module(UserProcessingServer)
class Case001_Direct_Memory_TestCase(Case001TestCase, unittest.TestCase):
    def get_protocols(self):
        return (Protocols.Direct, )
    def get_session_type(self):
        return SessionType.Memory

if ServerSOAP.SOAPPY_AVAILABLE:
    @case_uses_module(UserProcessingServer)
    class Case001_SOAP_MySQL_TestCase(Case001TestCase, unittest.TestCase):
        def get_protocols(self):
            return (Protocols.SOAP, )
        def get_session_type(self):
            return SessionType.sqlalchemy

    @case_uses_module(UserProcessingServer)
    class Case001_SOAP_Memory_TestCase(Case001TestCase, unittest.TestCase):
        def get_protocols(self):
            return (Protocols.SOAP, )
        def get_session_type(self):
            return SessionType.Memory

else:
    print >> sys.stderr, "Case001_SOAP_MySQL_TestCase and Case001_SOAP_Memory_TestCase skipped; SOAPpy not installed"

def suite():
    suites = (unittest.makeSuite(Case001_Direct_Memory_TestCase), )
    if ServerSOAP.SOAPPY_AVAILABLE:
        suites += ( unittest.makeSuite(Case001_SOAP_MySQL_TestCase), unittest.makeSuite(Case001_SOAP_Memory_TestCase) )
    return unittest.TestSuite( suites )

if __name__ == '__main__':
    unittest.main()


text:
// CoderMixer2.h

#ifndef __CODER_MIXER2_H
#define __CODER_MIXER2_H

#include "../../../Common/MyCom.h"
#include "../../../Common/MyVector.h"

#include "../../ICoder.h"

#include "../../Common/CreateCoder.h"

#ifdef _7ZIP_ST
  #define USE_MIXER_ST
#else
  #define USE_MIXER_MT
  #ifndef _SFX
    #define USE_MIXER_ST
  #endif
#endif

#ifdef USE_MIXER_MT
#include "../../Common/StreamBinder.h"
#include "../../Common/VirtThread.h"
#endif

#ifdef USE_MIXER_ST

class CSequentialInStreamCalcSize:
  public ISequentialInStream,
  public CMyUnknownImp
{
public:
  MY_UNKNOWN_IMP1(ISequentialInStream)

  STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
private:
  CMyComPtr<ISequentialInStream> _stream;
  UInt64 _size;
  bool _wasFinished;
public:
  void SetStream(ISequentialInStream *stream) { _stream = stream;  }
  void Init()
  {
    _size = 0;
    _wasFinished = false;
  }
  void ReleaseStream() { _stream.Release(); }
  UInt64 GetSize() const { return _size; }
  bool WasFinished() const { return _wasFinished; }
};

class COutStreamCalcSize:
  public ISequentialOutStream,
  public IOutStreamFinish,
  public CMyUnknownImp
{
  CMyComPtr<ISequentialOutStream> _stream;
  UInt64 _size;
public:
  MY_UNKNOWN_IMP2(ISequentialOutStream, IOutStreamFinish)

  STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
  STDMETHOD(OutStreamFinish)();

  void SetStream(ISequentialOutStream *stream) { _stream = stream; }
  void ReleaseStream() { _stream.Release(); }
  void Init() { _size = 0; }
  UInt64 GetSize() const { return _size; }
};

#endif

namespace NCoderMixer2 {

struct CBond
{
  UInt32 PackIndex;
  UInt32 UnpackIndex;

  UInt32 Get_InIndex(bool encodeMode) const { return encodeMode ? UnpackIndex : PackIndex; }
  UInt32 Get_OutIndex(bool encodeMode) const { return encodeMode ? PackIndex : UnpackIndex; }
};

struct CCoderStreamsInfo
{
  UInt32 NumStreams;
};

struct CBindInfo
{
  CRecordVector<CCoderStreamsInfo> Coders;
  CRecordVector<CBond> Bonds;
  CRecordVector<UInt32> PackStreams;
  unsigned UnpackCoder;

  unsigned GetNum_Bonds_and_PackStreams() const { return Bonds.Size() + PackStreams.Size(); }

  int FindBond_for_PackStream(UInt32 packStream) const
  {
    FOR_VECTOR (i, Bonds)
      if (Bonds[i].PackIndex == packStream)
        return i;
    return -1;
  }

  int FindBond_for_UnpackStream(UInt32 unpackStream) const
  {
    FOR_VECTOR (i, Bonds)
      if (Bonds[i].UnpackIndex == unpackStream)
        return i;
    return -1;
  }

  bool SetUnpackCoder()
  {
    bool isOk = false;
    FOR_VECTOR(i, Coders)
    {
      if (FindBond_for_UnpackStream(i) < 0)
      {
        if (isOk)
          return false;
        UnpackCoder = i;
        isOk = true;
      }
    }
    return isOk;
  }

  bool IsStream_in_PackStreams(UInt32 streamIndex) const
  {
    return FindStream_in_PackStreams(streamIndex) >= 0;
  }

  int FindStream_in_PackStreams(UInt32 streamIndex) const
  {
    FOR_VECTOR(i, PackStreams)
      if (PackStreams[i] == streamIndex)
        return i;
    return -1;
  }

  // that function is used before Maps is calculated

  UInt32 GetStream_for_Coder(UInt32 coderIndex) const
  {
    UInt32 streamIndex = 0;
    for (UInt32 i = 0; i < coderIndex; i++)
      streamIndex += Coders[i].NumStreams;
    return streamIndex;
  }

  // ---------- Maps Section ----------

  CRecordVector<UInt32> Coder_to_Stream;
  CRecordVector<UInt32> Stream_to_Coder;

  void ClearMaps();
  bool CalcMapsAndCheck();

  // ---------- End of Maps Section ----------

  void Clear()
  {
    Coders.Clear();
    Bonds.Clear();
    PackStreams.Clear();

    ClearMaps();
  }

  void GetCoder_for_Stream(UInt32 streamIndex, UInt32 &coderIndex, UInt32 &coderStreamIndex) const
  {
    coderIndex = Stream_to_Coder[streamIndex];
    coderStreamIndex = streamIndex - Coder_to_Stream[coderIndex];
  }
};

class CCoder
{
  CLASS_NO_COPY(CCoder);
public:
  CMyComPtr<ICompressCoder> Coder;
  CMyComPtr<ICompressCoder2> Coder2;
  UInt32 NumStreams;

  UInt64 UnpackSize;
  const UInt64 *UnpackSizePointer;

  CRecordVector<UInt64> PackSizes;
  CRecordVector<const UInt64 *> PackSizePointers;

  CCoder() {}

  void SetCoderInfo(const UInt64 *unpackSize, const UInt64 * const *packSizes);

  IUnknown *GetUnknown() const
  {
    return Coder ? (IUnknown *)Coder : (IUnknown *)Coder2;
  }

  HRESULT QueryInterface(REFGUID iid, void** pp) const
  {
    return GetUnknown()->QueryInterface(iid, pp);
  }
};

class CMixer
{
  bool Is_PackSize_Correct_for_Stream(UInt32 streamIndex);

protected:
  CBindInfo _bi;

  int FindBond_for_Stream(bool forInputStream, UInt32 streamIndex) const
  {
    if (EncodeMode == forInputStream)
      return _bi.FindBond_for_UnpackStream(streamIndex);
    else
      return _bi.FindBond_for_PackStream(streamIndex);
  }

  CBoolVector IsFilter_Vector;
  CBoolVector IsExternal_Vector;
  bool EncodeMode;
public:
  unsigned MainCoderIndex;

  CMixer(bool encodeMode):
      EncodeMode(encodeMode),
      MainCoderIndex(0)
      {}

  /*
  Sequence of calling:

      SetBindInfo();
      for each coder
        AddCoder();
      SelectMainCoder();

      for each file
      {
        ReInit()
        for each coder
          SetCoderInfo();
        Code();
      }
  */

  virtual HRESULT SetBindInfo(const CBindInfo &bindInfo)
  {
    _bi = bindInfo;
    IsFilter_Vector.Clear();
    MainCoderIndex = 0;
    return S_OK;
  }

  virtual void AddCoder(const CCreatedCoder &cod) = 0;
  virtual CCoder &GetCoder(unsigned index) = 0;
  virtual void SelectMainCoder(bool useFirst) = 0;
  virtual void ReInit() = 0;
  virtual void SetCoderInfo(unsigned coderIndex, const UInt64 *unpackSize, const UInt64 * const *packSizes) = 0;
  virtual HRESULT Code(
      ISequentialInStream * const *inStreams,
      ISequentialOutStream * const *outStreams,
      ICompressProgressInfo *progress) = 0;
  virtual UInt64 GetBondStreamSize(unsigned bondIndex) const = 0;

  bool Is_UnpackSize_Correct_for_Coder(UInt32 coderIndex);
  bool Is_PackSize_Correct_for_Coder(UInt32 coderIndex);
  bool IsThere_ExternalCoder_in_PackTree(UInt32 coderIndex);
};

#ifdef USE_MIXER_ST

struct CCoderST: public CCoder
{
  bool CanRead;
  bool CanWrite;

  CCoderST(): CanRead(false), CanWrite(false) {}
};

struct CStBinderStream
{
  CSequentialInStreamCalcSize *InStreamSpec;
  COutStreamCalcSize *OutStreamSpec;
  CMyComPtr<IUnknown> StreamRef;

  CStBinderStream(): InStreamSpec(NULL), OutStreamSpec(NULL) {}
};

class CMixerST:
  public IUnknown,
  public CMixer,
  public CMyUnknownImp
{
  HRESULT GetInStream2(ISequentialInStream * const *inStreams, /* const UInt64 * const *inSizes, */
      UInt32 outStreamIndex, ISequentialInStream **inStreamRes);
  HRESULT GetInStream(ISequentialInStream * const *inStreams, /* const UInt64 * const *inSizes, */
      UInt32 inStreamIndex, ISequentialInStream **inStreamRes);
  HRESULT GetOutStream(ISequentialOutStream * const *outStreams, /* const UInt64 * const *outSizes, */
      UInt32 outStreamIndex, ISequentialOutStream **outStreamRes);

  HRESULT FinishStream(UInt32 streamIndex);
  HRESULT FinishCoder(UInt32 coderIndex);

public:
  CObjectVector<CCoderST> _coders;

  CObjectVector<CStBinderStream> _binderStreams;

  MY_UNKNOWN_IMP

  CMixerST(bool encodeMode);
  ~CMixerST();

  virtual void AddCoder(const CCreatedCoder &cod);
  virtual CCoder &GetCoder(unsigned index);
  virtual void SelectMainCoder(bool useFirst);
  virtual void ReInit();
  virtual void SetCoderInfo(unsigned coderIndex, const UInt64 *unpackSize, const UInt64 * const *packSizes)
    { _coders[coderIndex].SetCoderInfo(unpackSize, packSizes); }
  virtual HRESULT Code(
      ISequentialInStream * const *inStreams,
      ISequentialOutStream * const *outStreams,
      ICompressProgressInfo *progress);
  virtual UInt64 GetBondStreamSize(unsigned bondIndex) const;

  HRESULT GetMainUnpackStream(
      ISequentialInStream * const *inStreams,
      ISequentialInStream **inStreamRes);
};

#endif

#ifdef USE_MIXER_MT

class CCoderMT: public CCoder, public CVirtThread
{
  CLASS_NO_COPY(CCoderMT)
  CRecordVector<ISequentialInStream*> InStreamPointers;
  CRecordVector<ISequentialOutStream*> OutStreamPointers;

private:
  void Execute();
public:
  bool EncodeMode;
  HRESULT Result;
  CObjectVector< CMyComPtr<ISequentialInStream> > InStreams;
  CObjectVector< CMyComPtr<ISequentialOutStream> > OutStreams;

  void Release()
  {
    InStreamPointers.Clear();
    OutStreamPointers.Clear();
    unsigned i;
    for (i = 0; i < InStreams.Size(); i++)
      InStreams[i].Release();
    for (i = 0; i < OutStreams.Size(); i++)
      OutStreams[i].Release();
  }

  class CReleaser
  {
    CLASS_NO_COPY(CReleaser)
    CCoderMT &_c;
  public:
    CReleaser(CCoderMT &c): _c(c) {}
    ~CReleaser() { _c.Release(); }
  };

  CCoderMT(): EncodeMode(false) {}
  ~CCoderMT() { CVirtThread::WaitThreadFinish(); }

  void Code(ICompressProgressInfo *progress);
};

class CMixerMT:
  public IUnknown,
  public CMixer,
  public CMyUnknownImp
{
  CObjectVector<CStreamBinder> _streamBinders;

  HRESULT Init(ISequentialInStream * const *inStreams, ISequentialOutStream * const *outStreams);
  HRESULT ReturnIfError(HRESULT code);

public:
  CObjectVector<CCoderMT> _coders;

  MY_UNKNOWN_IMP

  virtual HRESULT SetBindInfo(const CBindInfo &bindInfo);
  virtual void AddCoder(const CCreatedCoder &cod);
  virtual CCoder &GetCoder(unsigned index);
  virtual void SelectMainCoder(bool useFirst);
  virtual void ReInit();
  virtual void SetCoderInfo(unsigned coderIndex, const UInt64 *unpackSize, const UInt64 * const *packSizes)
    { _coders[coderIndex].SetCoderInfo(unpackSize, packSizes); }
  virtual HRESULT Code(
      ISequentialInStream * const *inStreams,
      ISequentialOutStream * const *outStreams,
      ICompressProgressInfo *progress);
  virtual UInt64 GetBondStreamSize(unsigned bondIndex) const;

  CMixerMT(bool encodeMode): CMixer(encodeMode) {}
};

#endif

}

#endif


text:
package ar.edu.ungs.persistence.dao.impl.stock;

import javax.inject.Named;

import ar.edu.ungs.persistence.dao.impl.JpaEntityDaoImpl;
import ar.edu.ungs.persistence.entities.stock.Proveedor;

@Named
public class ProveedorDao  extends JpaEntityDaoImpl<Integer, Proveedor>{

}


text:
package com.vzome.core.editor;

import org.w3c.dom.Element;

import com.vzome.core.algebra.AlgebraicField;
import com.vzome.core.algebra.AlgebraicMatrix;
import com.vzome.core.algebra.AlgebraicNumber;
import com.vzome.core.algebra.AlgebraicVector;
import com.vzome.core.commands.Command.Failure;
import com.vzome.core.commands.XmlSaveFormat;
import com.vzome.core.construction.MatrixTransformation;
import com.vzome.core.construction.Point;
import com.vzome.core.construction.Scaling;
import com.vzome.core.construction.Segment;
import com.vzome.core.construction.Transformation;
import com.vzome.core.math.symmetry.Axis;
import com.vzome.core.math.symmetry.Direction;
import com.vzome.core.math.symmetry.Symmetry;
import com.vzome.core.model.Connector;
import com.vzome.core.model.Manifestation;
import com.vzome.core.model.Panel;
import com.vzome.core.model.Strut;

public class ScalingTool extends SymmetryTool
{
	private static final String ID = "scaling";
	private static final String LABEL = "Create a scaling tool";
	private static final String TOOLTIP = "
" +
    		"Each tool enlarges or shrinks the selected objects,
" +
    		"relative to a central point.  To create a tool,
" +
    		"select a ball representing the central point, and
" +
    		"two struts from the same orbit (color) with different
" +
    		"sizes.
" +
    		"
" +
    		"The selection order matters.  First select a strut
" +
    		"that you want to enlarge or shrink, then select a
" +
    		"strut that has the desired target size.
" +
		"
";

	public static class Factory extends AbstractToolFactory
	{
		public Factory( ToolsModel tools, Symmetry symmetry )
		{
			super( tools, symmetry, ID, LABEL, TOOLTIP );
		}

		@Override
		protected boolean countsAreValid( int total, int balls, int struts, int panels )
		{
			return ( total == 3 && balls == 1 && struts == 2 );
		}

		@Override
		public Tool createToolInternal( String id )
		{
			ScalingTool tool = new ScalingTool( id, getSymmetry(), this .getToolsModel() );

			int scalePower = 0;;
			switch ( id ) {

			case "scaling.builtin/scale up":
				scalePower = 1;
				break;

			case "scaling.builtin/scale down":
				scalePower = -1;
				break;

			default:
				return tool;  // non-predefined, no scale factor set
			}
			AlgebraicField field = this .getToolsModel() .getEditorModel() .getRealizedModel() .getField();
			tool .setScaleFactor( field .createPower( scalePower ) );
			return tool;
		}

		// This is never called for the predefined tool, so symmetry can be null.
		@Override
		protected boolean bindParameters( Selection selection )
		{
			Symmetry symmetry = getSymmetry();
			AlgebraicVector offset1 = null;
			AlgebraicVector offset2 = null;
        	for ( Manifestation man : selection )
        		if ( man instanceof Strut ) {
        			Strut strut = (Strut) man;
        			if ( offset1 == null )
        				offset1 = strut .getOffset();
        			else
        				offset2 = strut .getOffset();
        		}
        	Axis zone1 = symmetry .getAxis( offset1 );
        	Axis zone2 = symmetry .getAxis( offset2 );
        	if ( zone1 == null || zone2 == null )
        		return false;
        	Direction orbit1 = zone1 .getDirection();
        	Direction orbit2 = zone2 .getDirection();
        	if ( orbit1 != orbit2 )
        		return false;
        	if ( orbit1 .isAutomatic() )
        		return false;
        	AlgebraicNumber l1 = zone1 .getLength( offset1 );
        	AlgebraicNumber l2 = zone2 .getLength( offset2 );
        	if ( l1 .equals( l2 ) )
        		return false;
			return true;
		}
	}

	private AlgebraicNumber scaleFactor;

    @Override
    public String getCategory()
    {
        return ID;
    }

    public ScalingTool( String id, Symmetry symmetry, ToolsModel tools )
    {
        super( id, symmetry, tools );
        this .scaleFactor = null;
    }

    void setScaleFactor( AlgebraicNumber scaleFactor )
    {
		this.scaleFactor = scaleFactor;
    }

    @Override
    protected String checkSelection( boolean prepareTool )
    {
    	if ( this .scaleFactor != null ) {
    		// a predefined tool; does not use this .symmetry
    		AlgebraicField field = this .scaleFactor .getField();
    		this .transforms = new Transformation[ 1 ];
            AlgebraicMatrix transform = new AlgebraicMatrix(
                    field .basisVector( 3, AlgebraicVector.X ) .scale( this .scaleFactor ),
                    field .basisVector( 3, AlgebraicVector.Y ) .scale( this .scaleFactor ),
                    field .basisVector( 3, AlgebraicVector.Z ) .scale( this .scaleFactor ) );
    		transforms[ 0 ] = new MatrixTransformation( transform, this .originPoint .getLocation() );
    		return null;
    	}

        Segment s1 = null, s2 = null;
        Point center = null;
        boolean correct = true;
        boolean hasPanels = false;
        for (Manifestation man : mSelection) {
        	if ( prepareTool )
        		unselect( man );
            if ( man instanceof Connector )
            {
                if ( center != null )
                {
                    correct = false;
                    break;
                }
                center = (Point) ((Connector) man) .getConstructions() .next();
            }
            else if ( man instanceof Strut )
            {
                if ( s2 != null )
                {
                    correct = false;
                    break;
                }
                if ( s1 == null )
                    s1 = (Segment) ((Strut) man) .getConstructions() .next();
                else
                    s2 = (Segment) ((Strut) man) .getConstructions() .next();
            }
            else if ( man instanceof Panel )
            	hasPanels = true;
        }

        if ( center == null ) {
        	if ( prepareTool ) // after validation, or when loading from a file
        		center = originPoint;
        	else // just validating the selection, not really creating a tool
        		return "No symmetry center selected";
        }

        correct = correct && s2 != null;
        if ( !prepareTool && hasPanels )
        	correct = false;  // panels must be allowed when opening legacy files (prepareTool)
        if ( !correct )
            return "scaling tool requires before and after struts, and a single center";

        Axis zone1 = symmetry .getAxis( s1 .getOffset() );
        Axis zone2 = symmetry .getAxis( s2 .getOffset() );
        if(zone1 == null || zone2 == null)
            return "struts cannot be automatic";
        Direction orbit = zone1 .getDirection();
        if ( orbit != zone2 .getDirection() )
            return "before and after struts must be from the same orbit";

    	if ( prepareTool ) {
    		this .transforms = new Transformation[ 1 ];
    		transforms[ 0 ] = new Scaling( s1, s2, center, symmetry );
    	}
        return null;
    }

    @Override
    protected String getXmlElementName()
    {
        return "ScalingTool";
    }

    @Override
    protected void setXmlAttributes( Element element, XmlSaveFormat format ) throws Failure
    {
        String symmName = element .getAttribute( "symmetry" );

        if ( symmName == null || symmName .isEmpty() )
        {
            element .setAttribute( "symmetry", "icosahedral" );
            logBugAccommodation( "scaling tool serialized with no symmetry; assuming icosahedral" );
        }
        super .setXmlAttributes( element, format );
    }
}


text:
SilverStripe has emailing functionality using the built-in mail() function in PHP.
Features include sending plaintext- and HTML emails, sending bulk emails,
subscription, handling bounced back emails.

## Configuration

Your PHP configuration needs to include the SMTP module for sending emails.
If you are not running an SMTP server together with your webserver, you might
need to setup PHP with the credentials for an external SMTP server
(see [PHP documentation for mail()](http://php.net/mail)).

## Usage

### Sending combined HTML and Plaintext

By default, emails are sent in both HTML and Plaintext format.

A plaintext representation is automatically generated from the system by stripping
HTML markup, or transforming it where possible (e.g. `<strong>text</strong>` is
converted to `*text*`).

	:::php
	$email = new Email($from, $to, $subject, $body);
	$email->send();

The default HTML template is located in `sapphire/templates/email/GenericEmail.ss`.

### Sending Plaintext only

	:::php
	$email = new Email($from, $to, $subject, $body);
	$email->sendPlain();

### Custom Template

The emails you create may contain quite a bit of content and perhaps custom elements,
background images and generally be too complex to write out in PHP code.

To support this you can specify a [SilverStripe Template](/topics/templates) to be used
instead of the built in GenericEmail.ss file.

* Create a 'MyEmailTemplate.ss' file inside `mysite/templates/email`.
* Fill MyEmailTemplate.ss with what you need to include. You can use any of the [SilverStripe Template syntax](/topics/templates)
 (e.g. `<% control %>`, `<% if %>`, $FirstName etc). Such as the following:

	:::ss

Hi <% if FirstName %>$FirstName<% end_if %>

$WelcomeMessage

The above is a simple hello email that prints out the first name of the user and
a welcome message. We're not finished quite yet, there is a couple things we need
to do:

*  Before you call `send()` on your email, set the template with `setTemplate()`
*  Populate any custom data into the template with `populateTemplate()` again,
you need to do this before you call `send()`. In this example above, we used 2
fields - `$FirstName` and `$WelcomeMessage` so we need to ensure they are populated:

	:::php
	$email = new Email("from@example.com", "to@example.com", "Welcome to mysite");

	// sets the template to be used - MyEmail.ss.
	$email->setTemplate('MyEmailTemplate');

	// You can call populateTemplate multiple times or bundle everything into an array,
	// including DataSetObjects.

	// Member::currentUser() includes $FirstName
	$email->populateTemplate(Member::currentUser());

	$welcomeMsg = 'Thank you for joining on '.date('Y-m-d').'!';

	$email->populateTemplate(array(
		'WelcomeMessage' => $welcomeMsg,
	));

	$email->send();

### Subclassing

Class definition:

	:::php
	<?php
	class MyEmail extends Email{
	  protected
	    $to = '$Email', // Be sure to encase this in single-quotes, as it is evaluated later by the template parser
	    $from = 'email@email.com',
	    $ss_template = 'MyEmail';
	}

Usage:

	:::php
	$email = new MyEmail();
	$email->send();

### Administrator Emails

The static function `Email::setAdminEmail()` can be called from a `_config.php`
file to set the address that these emails should originate from. This address
is used if the `from` field is empty.

### Redirecting Emails

`Email::send_all_emails_to($address)` will redirect all emails sent to the given
address. We recommend using this in your local development environment. You can
either configure this in your mysite/_config.php:

	:::php
	if(Director::isDev()) Email::send_all_emails_to("me@example.com");

If you use a [SilverStripe Environment](environment-management) file to manage your
configuration then you should include the following in your development copy:

	:::php
	define('SS_SEND_ALL_EMAILS_TO', 'me@example.com');

`Email::cc_all_emails_to()` and `Email::bcc_all_emails_to()` will keep the email
going to  its original recipients, but adds an additional recipient in the BCC/CC
header.

	:::php
	if(Director::isLive()) Email::bcc_all_emails_to("client@example.com");
	else Email::send_all_emails_to("developer@example.com");

### Setting Custom Headers

For email headers which do not have getters or setters (like setTo(), setFrom()) you can use **addCustomHeader($header,
$value)**

	:::php
	$email = new Email(...);
	$email->addCustomHeader('HeaderName', 'HeaderValue');
	..

See [Wikipedia E-mail Message header](http://en.wikipedia.org/wiki/E-mail#Message_header) for a list of header names.

### Newsletters

The [newsletter module](http://silverstripe.org/newsletter-module) provides a UI and logic to send batch emails.

## API Documentation

`[api:Email]`


text:
using ExtendedXmlSerializer.ContentModel;
using ExtendedXmlSerializer.ContentModel.Format;
using ExtendedXmlSerializer.ContentModel.Properties;

namespace ExtendedXmlSerializer.ExtensionModel.References
{
	sealed class ReferenceSerializer : ISerializer
	{
		readonly IReferenceEncounters _encounters;
		readonly IReader              _reader;
		readonly IWriter              _writer;

		public ReferenceSerializer(IReferenceEncounters encounters, IReader reader, IWriter writer)
		{
			_encounters = encounters;
			_reader     = reader;
			_writer     = writer;
		}

		public void Write(IFormatWriter writer, object instance)
		{
			var encounters = _encounters.Get(writer);
			var identifier = encounters.Get(instance);
			if (identifier != null)
			{
				var first  = encounters.IsSatisfiedBy(instance);
				var entity = identifier.Value.Entity;
				if (entity != null)
				{
					if (!first)
					{
						EntityIdentity.Default.Write(writer, entity.Get(instance));
					}
				}
				else
				{
					var property = first
						               ? (IProperty<uint?>)IdentityProperty.Default
						               : ContentModel.Properties.ReferenceIdentity.Default;
					property.Write(writer, identifier.Value.UniqueId);
				}

				if (!first)
				{
					return;
				}
			}

			_writer.Write(writer, instance);
		}

		public object Get(IFormatReader parameter) => _reader.Get(parameter);
	}
}