text:
using System;
using System.CodeDom;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Workflow.ComponentModel.Compiler;

namespace System.Workflow.Activities.Rules
{
    #region RuleException
    /// <summary>
    /// Represents the base class for all rule engine exception classes
    /// </summary>
    [Serializable]
    public class RuleException : Exception, ISerializable
    {
        /// <summary>
        /// Initializes a new instance of the RuleException class
        /// </summary>
        public RuleException()
            : base()
        {
        }

        /// <summary>
        /// Initializes a new instance of the RuleException class
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception</param>
        public RuleException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the RuleException class
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception</param>
        /// <param name="ex">The inner exception</param>
        public RuleException(string message, Exception ex)
            : base(message, ex)
        {
        }

        /// <summary>
        /// Constructor required by for Serialization - initialize a new instance from serialized data
        /// </summary>
        /// <param name="serializeInfo">Reference to the object that holds the data needed to deserialize the exception</param>
        /// <param name="context">Provides the means for deserializing the exception data</param>
        protected RuleException(SerializationInfo serializeInfo, StreamingContext context)
            : base(serializeInfo, context)
        {
        }
    }
    #endregion

    #region RuleEvaluationException
    /// <summary>
    /// Represents the the exception thrown when an error is encountered during evaluation
    /// </summary>
    [Serializable]
    public class RuleEvaluationException : RuleException, ISerializable
    {
        /// <summary>
        /// Initializes a new instance of the RuleRuntimeException class
        /// </summary>
        public RuleEvaluationException()
            : base()
        {
        }

        /// <summary>
        /// Initializes a new instance of the RuleRuntimeException class
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception</param>
        public RuleEvaluationException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the RuleRuntimeException class
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception</param>
        /// <param name="ex">The inner exception</param>
        public RuleEvaluationException(string message, Exception ex)
            : base(message, ex)
        {
        }

        /// <summary>
        /// Constructor required by for Serialization - initialize a new instance from serialized data
        /// </summary>
        /// <param name="serializeInfo">Reference to the object that holds the data needed to deserialize the exception</param>
        /// <param name="context">Provides the means for deserializing the exception data</param>
        protected RuleEvaluationException(SerializationInfo serializeInfo, StreamingContext context)
            : base(serializeInfo, context)
        {
        }
    }
    #endregion

    #region RuleEvaluationIncompatibleTypesException
    /// <summary>
    /// Represents the exception thrown when types are incompatible
    /// </summary>
    [Serializable]
    public class RuleEvaluationIncompatibleTypesException : RuleException, ISerializable
    {
        private Type m_leftType;
        private CodeBinaryOperatorType m_op;
        private Type m_rightType;

        /// <summary>
        /// Type on the left of the operator
        /// </summary>
        public Type Left
        {
            get { return m_leftType; }
            set { m_leftType = value; }
        }

        /// <summary>
        /// Arithmetic operation that failed
        /// </summary>
        public CodeBinaryOperatorType Operator
        {
            get { return m_op; }
            set { m_op = value; }
        }

        /// <summary>
        /// Type on the right of the operator
        /// </summary>
        public Type Right
        {
            get { return m_rightType; }
            set { m_rightType = value; }
        }

        /// <summary>
        /// Initializes a new instance of the RuleEvaluationIncompatibleTypesException class
        /// </summary>
        public RuleEvaluationIncompatibleTypesException()
            : base()
        {
        }

        /// <summary>
        /// Initializes a new instance of the RuleEvaluationIncompatibleTypesException class
        /// </summary>
        /// <param name="message"></param>
        public RuleEvaluationIncompatibleTypesException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the RuleEvaluationIncompatibleTypesException class
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ex"></param>
        public RuleEvaluationIncompatibleTypesException(string message, Exception ex)
            : base(message, ex)
        {
        }

        /// <summary>
        /// Initializes a new instance of the RuleEvaluationIncompatibleTypesException class
        /// </summary>
        /// <param name="message"></param>
        /// <param name="left"></param>
        /// <param name="op"></param>
        /// <param name="right"></param>
        public RuleEvaluationIncompatibleTypesException(
            string message,
            Type left,
            CodeBinaryOperatorType op,
            Type right)
            : base(message)
        {
            m_leftType = left;
            m_op = op;
            m_rightType = right;
        }

        /// <summary>
        /// Initializes a new instance of the RuleEvaluationIncompatibleTypesException class
        /// </summary>
        /// <param name="message"></param>
        /// <param name="left"></param>
        /// <param name="op"></param>
        /// <param name="right"></param>
        /// <param name="ex"></param>
        public RuleEvaluationIncompatibleTypesException(
            string message,
            Type left,
            CodeBinaryOperatorType op,
            Type right,
            Exception ex)
            : base(message, ex)
        {
            m_leftType = left;
            m_op = op;
            m_rightType = right;
        }

        /// <summary>
        /// Constructor required by for Serialization - initialize a new instance from serialized data
        /// </summary>
        /// <param name="serializeInfo">Reference to the object that holds the data needed to deserialize the exception</param>
        /// <param name="context">Provides the means for deserializing the exception data</param>
        protected RuleEvaluationIncompatibleTypesException(SerializationInfo serializeInfo, StreamingContext context)
            : base(serializeInfo, context)
        {
            if (serializeInfo == null)
                throw new ArgumentNullException("serializeInfo");
            string qualifiedTypeString = serializeInfo.GetString("left");
            if (qualifiedTypeString != "null")
                m_leftType = Type.GetType(qualifiedTypeString);
            m_op = (CodeBinaryOperatorType)serializeInfo.GetValue("op", typeof(CodeBinaryOperatorType));
            qualifiedTypeString = serializeInfo.GetString("right");
            if (qualifiedTypeString != "null")
                m_rightType = Type.GetType(qualifiedTypeString);
        }

        /// <summary>
        /// Implements the ISerializable interface
        /// </summary>
        /// <param name="info">Reference to the object that holds the data needed to serialize/deserialize the exception</param>
        /// <param name="context">Provides the means for serialiing the exception data</param>
        [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new ArgumentNullException("info");
            base.GetObjectData(info, context);
            info.AddValue("left", (m_leftType != null) ? m_leftType.AssemblyQualifiedName : "null");
            info.AddValue("op", m_op);
            info.AddValue("right", (m_rightType != null) ? m_rightType.AssemblyQualifiedName : "null");
        }
    }
    #endregion

    #region RuleSetValidationException
    /// <summary>
    /// Represents the exception thrown when a ruleset can not be validated
    /// </summary>
    [Serializable]
    public class RuleSetValidationException : RuleException, ISerializable
    {
        private ValidationErrorCollection m_errors;

        /// <summary>
        /// Collection of validation errors that occurred while validating the RuleSet
        /// </summary>
        public ValidationErrorCollection Errors
        {
            get { return m_errors; }
        }

        /// <summary>
        /// Initializes a new instance of the RuleSetValidationException class
        /// </summary>
        public RuleSetValidationException()
            : base()
        {
        }

        /// <summary>
        /// Initializes a new instance of the RuleSetValidationException class
        /// </summary>
        /// <param name="message"></param>
        public RuleSetValidationException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the RuleSetValidationException class
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ex"></param>
        public RuleSetValidationException(string message, Exception ex)
            : base(message, ex)
        {
        }

        /// <summary>
        /// Initializes a new instance of the RuleSetValidationException class
        /// </summary>
        /// <param name="message"></param>
        /// <param name="errors"></param>
        public RuleSetValidationException(
            string message,
            ValidationErrorCollection errors)
            : base(message)
        {
            m_errors = errors;
        }

        /// <summary>
        /// Constructor required by for Serialization - initialize a new instance from serialized data
        /// </summary>
        /// <param name="serializeInfo">Reference to the object that holds the data needed to deserialize the exception</param>
        /// <param name="context">Provides the means for deserializing the exception data</param>
        protected RuleSetValidationException(SerializationInfo serializeInfo, StreamingContext context)
            : base(serializeInfo, context)
        {
            if (serializeInfo == null)
                throw new ArgumentNullException("serializeInfo");
            m_errors = (ValidationErrorCollection)serializeInfo.GetValue("errors", typeof(ValidationErrorCollection));
        }

        /// <summary>
        /// Implements the ISerializable interface
        /// </summary>
        /// <param name="info">Reference to the object that holds the data needed to serialize/deserialize the exception</param>
        /// <param name="context">Provides the means for serialiing the exception data</param>
        [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new ArgumentNullException("info");
            base.GetObjectData(info, context);
            info.AddValue("errors", m_errors);
        }
    }
    #endregion
}


text:
AthenaPDF is a drop-in replacement for wkhtmltopdf

Usage:

```bash
$ curl http://athenapdf:8080/convert\?auth\=wodby-athenapdf\&url\=http://google.com/ |> out.pdf
```

## Configuration

Configuration is possible via environment variables. See the full list of variables on [GitHub](https://github.com/arachnys/athenapdf/blob/master/weaver/conf/sample.env).

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 25: 450 (1927)

#### Original name
Meliola sepulta Pat.

### Remarks
null


text:
public class Rules {

	public int howManyNumbersMatch(Ticket aTicket, int[] winningNumbers) {
		int numberFound = 0;
		for (int i = 0; i < aTicket.numbers().length; i++)
			for (int j = 0; j < winningNumbers.length; j++)
				if (aTicket.numbers()[i] == winningNumbers[j])
					numberFound++;
		return numberFound;
	}

	public int prizeFor(int numbersMatched) {
		if (numbersMatched == 3)
			return 2;
		if (numbersMatched == 4)
			return 50;
		if (numbersMatched == 5)
			return 2500;
		if (numbersMatched == 6)
			return 1000000;
		return 0;
	}

}


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

namespace ODataValidator.Rule
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Xml;
    using System.Xml.Linq;
    using System.Xml.XPath;
    using ODataValidator.Rule.Helper;
    using ODataValidator.RuleEngine;
    using ODataValidator.RuleEngine.Common;

    /// <summary>
    /// Class of extension rule for Metadata.Core.4056
    /// </summary>
    [Export(typeof(ExtensionRule))]
    public class MetadataCore4056 : ExtensionRule
    {
        /// <summary>
        /// Gets Category property
        /// </summary>
        public override string Category
        {
            get
            {
                return "core";
            }
        }

        /// <summary>
        /// Gets rule name
        /// </summary>
        public override string Name
        {
            get
            {
                return "Metadata.Core.4056";
            }
        }

        /// <summary>
        /// Gets rule description
        /// </summary>
        public override string Description
        {
            get
            {
                return @"The name of the structural property MUST be unique within the set of structural and navigation properties of the containing structured type and any of its base types.";
            }
        }

        /// <summary>
        /// Gets rule specification in OData document
        /// </summary>
        public override string SpecificationSection
        {
            get
            {
                return "6.1.1";
            }
        }

        /// <summary>
        /// Gets location of help information of the rule
        /// </summary>
        public override string HelpLink
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Gets the error message for validation failure
        /// </summary>
        public override string ErrorMessage
        {
            get
            {
                return this.Description;
            }
        }

        /// <summary>
        /// Gets the requirement level.
        /// </summary>
        public override RequirementLevel RequirementLevel
        {
            get
            {
                return RequirementLevel.Must;
            }
        }

        /// <summary>
        /// Gets the payload type to which the rule applies.
        /// </summary>
        public override PayloadType? PayloadType
        {
            get
            {
                return RuleEngine.PayloadType.Metadata;
            }
        }

        /// <summary>
        /// Gets the offline context to which the rule applies
        /// </summary>
        public override bool? IsOfflineContext
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Gets the payload format to which the rule applies.
        /// </summary>
        public override PayloadFormat? PayloadFormat
        {
            get
            {
                return RuleEngine.PayloadFormat.Xml;
            }
        }

        /// <summary>
        /// Gets the OData version
        /// </summary>
        public override ODataVersion? Version
        {
            get
            {
                return ODataVersion.V4;
            }
        }

        /// <summary>
        /// Verify Metadata.Core.4056
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out parameter to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;
            info = null;

            XmlDocument metadata = new XmlDocument();

            metadata.LoadXml(context.MetadataDocument);
            string entityTypeXpath = @"/*[local-name()='Edmx']/*[local-name()='DataServices']/*[local-name()='Schema']/*[local-name()='EntityType' or local-name()='ComplexType']";

            XmlNodeList structuredTypeCollection = metadata.SelectNodes(entityTypeXpath, ODataNamespaceManager.Instance);

            if (structuredTypeCollection.Count > 0)
            {
                passed = true;
                string wholeMetadata = context.ContainsExternalSchema ? context.MergedMetadataDocument : context.MetadataDocument;
                string ns;
                foreach (XmlNode node in structuredTypeCollection)
                {
                    ns = node.ParentNode.Attributes["Namespace"] != null ? node.ParentNode.Attributes["Namespace"].Value : null;
                    List<string> properties = MetadataHelper.GetAllPropertiesNamesOfStructuredType(wholeMetadata, ns,
                        node.Attributes["Name"].Value, MatchPropertyType.All);

                    if (properties.Count != properties.Distinct().Count<string>())
                    {
                        passed = false; break;
                    }
                }
            }

            info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
            return passed;
        }
    }
}


text:
using dtPolyRef = uint64_t;
#else
using dtPolyRef = unsigned int;
#endif

class dtCrowd;
class dtQueryFilter;
struct dtCrowdAgent;

namespace Urho3D
{

class CrowdAgent;
class NavigationMesh;

/// Parameter structure for obstacle avoidance params (copied from DetourObstacleAvoidance.h in order to hide Detour header from Urho3D library users).
/// @pod
struct CrowdObstacleAvoidanceParams
{
    float velBias;
    float weightDesVel;
    float weightCurVel;
    float weightSide;
    float weightToi;
    float horizTime;
    unsigned char gridSize;         ///< grid
    unsigned char adaptiveDivs;     ///< adaptive
    unsigned char adaptiveRings;    ///< adaptive
    unsigned char adaptiveDepth;    ///< adaptive
};

/// Crowd manager scene component. Should be added only to the root scene node.
class URHO3D_API CrowdManager : public Component
{
    URHO3D_OBJECT(CrowdManager, Component);

    friend class CrowdAgent;

public:
    /// Construct.
    explicit CrowdManager(Context* context);
    /// Destruct.
    ~CrowdManager() override;
    /// Register object factory.
    /// @nobind
    static void RegisterObject(Context* context);
    /// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
    void ApplyAttributes() override;

    /// Draw the agents' pathing debug data.
    void DrawDebugGeometry(DebugRenderer* debug, bool depthTest) override;
    /// Add debug geometry to the debug renderer.
    void DrawDebugGeometry(bool depthTest);

    /// Set the crowd target position. The target position is set to all crowd agents found in the specified node. Defaulted to scene node.
    void SetCrowdTarget(const Vector3& position, Node* node = nullptr);
    /// Set the crowd move velocity. The move velocity is applied to all crowd agents found in the specified node. Defaulted to scene node.
    void SetCrowdVelocity(const Vector3& velocity, Node* node = nullptr);
    /// Reset any crowd target for all crowd agents found in the specified node. Defaulted to scene node.
    void ResetCrowdTarget(Node* node = nullptr);
    /// Set the maximum number of agents.
    /// @property
    void SetMaxAgents(unsigned maxAgents);
    /// Set the maximum radius of any agent.
    /// @property
    void SetMaxAgentRadius(float maxAgentRadius);
    /// Assigns the navigation mesh for the crowd.
    /// @property{set_navMesh}
    void SetNavigationMesh(NavigationMesh* navMesh);
    /// Set all the query filter types configured in the crowd based on the corresponding attribute.
    void SetQueryFilterTypesAttr(const VariantVector& value);
    /// Set the include flags for the specified query filter type.
    void SetIncludeFlags(unsigned queryFilterType, unsigned short flags);
    /// Set the exclude flags for the specified query filter type.
    void SetExcludeFlags(unsigned queryFilterType, unsigned short flags);
    /// Set the cost of an area for the specified query filter type.
    void SetAreaCost(unsigned queryFilterType, unsigned areaID, float cost);
    /// Set all the obstacle avoidance types configured in the crowd based on the corresponding attribute.
    void SetObstacleAvoidanceTypesAttr(const VariantVector& value);
    /// Set the params for the specified obstacle avoidance type.
    void SetObstacleAvoidanceParams(unsigned obstacleAvoidanceType, const CrowdObstacleAvoidanceParams& params);

    /// Get all the crowd agent components in the specified node hierarchy. If the node is not specified then use scene node. When inCrowdFilter is set to true then only get agents that are in the crowd.
    PODVector<CrowdAgent*> GetAgents(Node* node = nullptr, bool inCrowdFilter = true) const;
    /// Find the nearest point on the navigation mesh to a given point using the crowd initialized query extent (based on maxAgentRadius) and the specified query filter type.
    Vector3 FindNearestPoint(const Vector3& point, int queryFilterType, dtPolyRef* nearestRef = nullptr);
    /// Try to move along the surface from one point to another using the crowd initialized query extent (based on maxAgentRadius) and the specified query filter type.
    Vector3 MoveAlongSurface(const Vector3& start, const Vector3& end, int queryFilterType, int maxVisited = 3);
    /// Find a path between world space points using the crowd initialized query extent (based on maxAgentRadius) and the specified query filter type. Return non-empty list of points if successful.
    void FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, int queryFilterType);
    /// Return a random point on the navigation mesh using the crowd initialized query extent (based on maxAgentRadius) and the specified query filter type.
    Vector3 GetRandomPoint(int queryFilterType, dtPolyRef* randomRef = nullptr);
    /// Return a random point on the navigation mesh within a circle using the crowd initialized query extent (based on maxAgentRadius) and the specified query filter type. The circle radius is only a guideline and in practice the returned point may be further away.
    Vector3 GetRandomPointInCircle(const Vector3& center, float radius, int queryFilterType, dtPolyRef* randomRef = nullptr);
    /// Return distance to wall from a point using the crowd initialized query extent (based on maxAgentRadius) and the specified query filter type. Maximum search radius must be specified.
    float GetDistanceToWall(const Vector3& point, float radius, int queryFilterType, Vector3* hitPos = nullptr, Vector3* hitNormal = nullptr);
    /// Perform a walkability raycast on the navigation mesh between start and end using the crowd initialized query extent (based on maxAgentRadius) and the specified query filter type. Return the point where a wall was hit, or the end point if no walls.
    Vector3 Raycast(const Vector3& start, const Vector3& end, int queryFilterType, Vector3* hitNormal = nullptr);

    /// Get the maximum number of agents.
    /// @property
    unsigned GetMaxAgents() const { return maxAgents_; }

    /// Get the maximum radius of any agent.
    /// @property
    float GetMaxAgentRadius() const { return maxAgentRadius_; }

    /// Get the Navigation mesh assigned to the crowd.
    /// @property{get_navMesh}
    NavigationMesh* GetNavigationMesh() const { return navigationMesh_; }

    /// Get the number of configured query filter types.
    /// @property
    unsigned GetNumQueryFilterTypes() const { return numQueryFilterTypes_; }

    /// Get the number of configured area in the specified query filter type.
    /// @property
    unsigned GetNumAreas(unsigned queryFilterType) const;
    /// Return all the filter types configured in the crowd as attribute.
    VariantVector GetQueryFilterTypesAttr() const;
    /// Get the include flags for the specified query filter type.
    unsigned short GetIncludeFlags(unsigned queryFilterType) const;
    /// Get the exclude flags for the specified query filter type.
    unsigned short GetExcludeFlags(unsigned queryFilterType) const;
    /// Get the cost of an area for the specified query filter type.
    float GetAreaCost(unsigned queryFilterType, unsigned areaID) const;

    /// Get the number of configured obstacle avoidance types.
    /// @property
    unsigned GetNumObstacleAvoidanceTypes() const { return numObstacleAvoidanceTypes_; }

    /// Return all the obstacle avoidance types configured in the crowd as attribute.
    VariantVector GetObstacleAvoidanceTypesAttr() const;
    /// Get the params for the specified obstacle avoidance type.
    const CrowdObstacleAvoidanceParams& GetObstacleAvoidanceParams(unsigned obstacleAvoidanceType) const;

protected:
    /// Create and initialized internal Detour crowd object. When it is a recreate, it preserves the configuration and attempts to re-add existing agents in the previous crowd back to the newly created crowd.
    bool CreateCrowd();
    /// Create and adds an detour crowd agent, Agent's radius and height is set through the navigation mesh. Return -1 on error, agent ID on success.
    int AddAgent(CrowdAgent* agent, const Vector3& pos);
    /// Removes the detour crowd agent.
    void RemoveAgent(CrowdAgent* agent);

protected:
    /// Handle scene being assigned.
    void OnSceneSet(Scene* scene) override;
    /// Update the crowd simulation.
    void Update(float delta);
    /// Get the detour crowd agent.
    const dtCrowdAgent* GetDetourCrowdAgent(int agent) const;
    /// Get the detour query filter.
    const dtQueryFilter* GetDetourQueryFilter(unsigned queryFilterType) const;

    /// Get the internal detour crowd component.
    dtCrowd* GetCrowd() const { return crowd_; }

private:
    /// Handle the scene subsystem update event.
    void HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData);
    /// Handle navigation mesh changed event. It can be navmesh being rebuilt or being removed from its node.
    void HandleNavMeshChanged(StringHash eventType, VariantMap& eventData);
    /// Handle component added in the scene to check for late addition of the navmesh.
    void HandleComponentAdded(StringHash eventType, VariantMap& eventData);

    /// Internal Detour crowd object.
    dtCrowd* crowd_{};
    /// NavigationMesh for which the crowd was created.
    WeakPtr<NavigationMesh> navigationMesh_;
    /// The NavigationMesh component Id for pending crowd creation.
    unsigned navigationMeshId_{};
    /// The maximum number of agents the crowd can manage.
    unsigned maxAgents_{};
    /// The maximum radius of any agent that will be added to the crowd.
    float maxAgentRadius_{};
    /// Number of query filter types configured in the crowd. Limit to DT_CROWD_MAX_QUERY_FILTER_TYPE.
    unsigned numQueryFilterTypes_{};
    /// Number of configured area in each filter type. Limit to DT_MAX_AREAS.
    PODVector<unsigned> numAreas_;
    /// Number of obstacle avoidance types configured in the crowd. Limit to DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS.
    unsigned numObstacleAvoidanceTypes_{};
};

}


text:
module Player where

import Board

data Player = Player { playerType :: String
                     , playerSymbol :: Symbol
                     } deriving (Show)

currentPlayerType :: (Player, Player) -> String
currentPlayerType players = (playerType (fst players))

currentPlayerSymbol :: (Player, Player) -> Symbol
currentPlayerSymbol players = (playerSymbol (fst players))

createPlayers :: String -> Symbol -> String -> Symbol -> (Player, Player)
createPlayers playerType1 playerSymbol1 playerType2 playerSymbol2 =
  ( Player {playerType=playerType1, playerSymbol=playerSymbol1}
  , Player {playerType=playerType2, playerSymbol=playerSymbol2}
  )

humanVsHuman :: (Player, Player)
humanVsHuman = createPlayers "human" x "human" o

humanVsComputer :: (Player, Player)
humanVsComputer = createPlayers "human" x "computer" o

computerVsComputer :: (Player, Player)
computerVsComputer = createPlayers "computer" x "computer" o


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE Reply SYSTEM "http://217.206.100.98:8080/iComNew205/hostConnect_2_05_006.dtd">
<Reply>
  <OptionInfoReply>
    <Option>
      <Opt>LONACHOINKCSTDBEB</Opt>
      <OptionNumber>15</OptionNumber>
      <OptGeneral>
        <SupplierId>11</SupplierId>
        <SupplierName>Holiday Inn Kings Cross</SupplierName>
        <Description>Bed & Full English Breakfast</Description>
        <Comment>Standard Room</Comment>
        <Locality>KGX</Locality>
        <LocalityDescription>Kings Cross</LocalityDescription>
        <Class>3*</Class>
        <ClassDescription>3 Star</ClassDescription>
        <SType>Y</SType>
        <SCU>Night</SCU>
        <MinSCU>1</MinSCU>
        <MaxSCU>99</MaxSCU>
        <OptExtras>
          <OptExtra>
            <SequenceNumber>1</SequenceNumber>
            <Description>Porterage</Description>
            <IsPricePerPerson>Y</IsPricePerPerson>
          </OptExtra>
        </OptExtras>
        <VoucherName>Holiday Inn Kings Cross</VoucherName>
        <Address1>21 Fleet St</Address1>
        <Address2>London</Address2>
        <Address3></Address3>
        <Address4></Address4>
        <Address5></Address5>
        <PostCode>W1 4TG</PostCode>
        <Single_Avail>Y</Single_Avail>
        <Single_Ad_Max>1</Single_Ad_Max>
        <Twin_Avail>Y</Twin_Avail>
        <Twin_Ad_Max>2</Twin_Ad_Max>
        <Double_Avail>Y</Double_Avail>
        <Double_Ad_Max>2</Double_Ad_Max>
        <Triple_Avail>Y</Triple_Avail>
        <Triple_Ad_Max>3</Triple_Ad_Max>
        <Quad_Avail>N</Quad_Avail>
        <InfantsAllowed>Y</InfantsAllowed>
        <Infant_From>0</Infant_From>
        <Infant_To>3</Infant_To>
        <ChildrenAllowed>Y</ChildrenAllowed>
        <Child_From>4</Child_From>
        <Child_To>12</Child_To>
        <AdultsAllowed>Y</AdultsAllowed>
        <Adult_From>13</Adult_From>
        <Adult_To>99</Adult_To>
        <ButtonName>Accommodation</ButtonName>
      </OptGeneral>
      <OptStayResults>
        <Availability>RQ</Availability>
        <Currency>GBP</Currency>
        <TotalPrice>67200</TotalPrice>
        <RateName>Standard</RateName>
        <RateText>Standard</RateText>
      </OptStayResults>
    </Option>
    <Option>
      <Opt>LONACHOINKCROOMON</Opt>
      <OptionNumber>14</OptionNumber>
      <OptGeneral>
        <SupplierId>11</SupplierId>
        <SupplierName>Holiday Inn Kings Cross</SupplierName>
        <Description>Room Only</Description>
        <Comment>Standard Room</Comment>
        <Locality>KGX</Locality>
        <LocalityDescription>Kings Cross</LocalityDescription>
        <Class>3*</Class>
        <ClassDescription>3 Star</ClassDescription>
        <SType>Y</SType>
        <SCU>Night</SCU>
        <MinSCU>1</MinSCU>
        <MaxSCU>99</MaxSCU>
        <OptExtras>
          <OptExtra>
            <SequenceNumber>1</SequenceNumber>
            <Description>Porterage</Description>
            <IsPricePerPerson>Y</IsPricePerPerson>
          </OptExtra>
        </OptExtras>
        <VoucherName>Holiday Inn Kings Cross</VoucherName>
        <Address1>21 Fleet St</Address1>
        <Address2>London</Address2>
        <Address3></Address3>
        <Address4></Address4>
        <Address5></Address5>
        <PostCode>W1 4TG</PostCode>
        <Single_Avail>Y</Single_Avail>
        <Single_Ad_Max>1</Single_Ad_Max>
        <Twin_Avail>Y</Twin_Avail>
        <Twin_Ad_Max>2</Twin_Ad_Max>
        <Double_Avail>Y</Double_Avail>
        <Double_Ad_Max>2</Double_Ad_Max>
        <Triple_Avail>Y</Triple_Avail>
        <Triple_Ad_Max>3</Triple_Ad_Max>
        <Quad_Avail>N</Quad_Avail>
        <InfantsAllowed>Y</InfantsAllowed>
        <Infant_From>0</Infant_From>
        <Infant_To>3</Infant_To>
        <ChildrenAllowed>Y</ChildrenAllowed>
        <Child_From>4</Child_From>
        <Child_To>12</Child_To>
        <AdultsAllowed>Y</AdultsAllowed>
        <Adult_From>13</Adult_From>
        <Adult_To>99</Adult_To>
        <ButtonName>Accommodation</ButtonName>
      </OptGeneral>
      <OptStayResults>
        <Availability>RQ</Availability>
        <Currency>GBP</Currency>
        <TotalPrice>48000</TotalPrice>
        <RateName>Standard</RateName>
        <RateText>Standard</RateText>
      </OptStayResults>
    </Option>
    <Option>
      <Opt>LONACHOINKCSTDBCB</Opt>
      <OptionNumber>13</OptionNumber>
      <OptGeneral>
        <SupplierId>11</SupplierId>
        <SupplierName>Holiday Inn Kings Cross</SupplierName>
        <Description>Bed & Continental Breakfast</Description>
        <Comment>Standard Room</Comment>
        <Locality>KGX</Locality>
        <LocalityDescription>Kings Cross</LocalityDescription>
        <Class>3*</Class>
        <ClassDescription>3 Star</ClassDescription>
        <SType>Y</SType>
        <SCU>Night</SCU>
        <MinSCU>1</MinSCU>
        <MaxSCU>99</MaxSCU>
        <OptExtras>
          <OptExtra>
            <SequenceNumber>1</SequenceNumber>
            <Description>Porterage</Description>
            <IsPricePerPerson>Y</IsPricePerPerson>
          </OptExtra>
        </OptExtras>
        <VoucherName>Holiday Inn Kings Cross</VoucherName>
        <Address1>21 Fleet St</Address1>
        <Address2>London</Address2>
        <Address3></Address3>
        <Address4></Address4>
        <Address5></Address5>
        <PostCode>W1 4TG</PostCode>
        <Single_Avail>Y</Single_Avail>
        <Single_Ad_Max>1</Single_Ad_Max>
        <Twin_Avail>Y</Twin_Avail>
        <Twin_Ad_Max>2</Twin_Ad_Max>
        <Double_Avail>Y</Double_Avail>
        <Double_Ad_Max>2</Double_Ad_Max>
        <Triple_Avail>Y</Triple_Avail>
        <Triple_Ad_Max>3</Triple_Ad_Max>
        <Quad_Avail>N</Quad_Avail>
        <InfantsAllowed>Y</InfantsAllowed>
        <Infant_From>0</Infant_From>
        <Infant_To>3</Infant_To>
        <ChildrenAllowed>Y</ChildrenAllowed>
        <Child_From>4</Child_From>
        <Child_To>12</Child_To>
        <AdultsAllowed>Y</AdultsAllowed>
        <Adult_From>13</Adult_From>
        <Adult_To>99</Adult_To>
        <ButtonName>Accommodation</ButtonName>
      </OptGeneral>
      <OptStayResults>
        <Availability>RQ</Availability>
        <Currency>GBP</Currency>
        <TotalPrice>57600</TotalPrice>
        <RateName>Standard</RateName>
        <RateText>Standard</RateText>
      </OptStayResults>
    </Option>
    <Option>
      <Opt>LONACBAILONSTDFUB</Opt>
      <OptionNumber>12</OptionNumber>
      <OptGeneral>
        <SupplierId>10</SupplierId>
        <SupplierName>Baileys London</SupplierName>
        <Description>Full Board</Description>
        <Comment>Standard Room</Comment>
        <Locality>PAD</Locality>
        <LocalityDescription>Paddington</LocalityDescription>
        <Class>4*</Class>
        <ClassDescription>4 Star</ClassDescription>
        <SType>Y</SType>
        <SCU>Night</SCU>
        <MinSCU>1</MinSCU>
        <MaxSCU>99</MaxSCU>
        <OptExtras>
          <OptExtra>
            <SequenceNumber>1</SequenceNumber>
            <Description>Porterage</Description>
            <IsPricePerPerson>Y</IsPricePerPerson>
          </OptExtra>
        </OptExtras>
        <VoucherName>Baileys London</VoucherName>
        <Address1>21 Fleet St</Address1>
        <Address2>London</Address2>
        <Address3></Address3>
        <Address4></Address4>
        <Address5></Address5>
        <PostCode>W1 4TG</PostCode>
        <Single_Avail>Y</Single_Avail>
        <Single_Ad_Max>1</Single_Ad_Max>
        <Twin_Avail>Y</Twin_Avail>
        <Twin_Ad_Max>2</Twin_Ad_Max>
        <Double_Avail>Y</Double_Avail>
        <Double_Ad_Max>2</Double_Ad_Max>
        <Triple_Avail>Y</Triple_Avail>
        <Triple_Ad_Max>3</Triple_Ad_Max>
        <Quad_Avail>N</Quad_Avail>
        <InfantsAllowed>Y</InfantsAllowed>
        <Infant_From>0</Infant_From>
        <Infant_To>3</Infant_To>
        <ChildrenAllowed>Y</ChildrenAllowed>
        <Child_From>4</Child_From>
        <Child_To>12</Child_To>
        <AdultsAllowed>Y</AdultsAllowed>
        <Adult_From>13</Adult_From>
        <Adult_To>99</Adult_To>
        <ButtonName>Accommodation</ButtonName>
      </OptGeneral>
      <OptStayResults>
        <Availability>RQ</Availability>
        <Currency>GBP</Currency>
        <TotalPrice>124800</TotalPrice>
        <RateName>Standard</RateName>
        <RateText>Standard</RateText>
      </OptStayResults>
    </Option>
    <Option>
      <Opt>LONACBAILONSTDBCB</Opt>
      <OptionNumber>10</OptionNumber>
      <OptGeneral>
        <SupplierId>10</SupplierId>
        <SupplierName>Baileys London</SupplierName>
        <Description>Bed & Continental Breakfast</Description>
        <Comment>Standard Room</Comment>
        <Locality>PAD</Locality>
        <LocalityDescription>Paddington</LocalityDescription>
        <Class>4*</Class>
        <ClassDescription>4 Star</ClassDescription>
        <SType>Y</SType>
        <SCU>Night</SCU>
        <MinSCU>1</MinSCU>
        <MaxSCU>99</MaxSCU>
        <OptExtras>
          <OptExtra>
            <SequenceNumber>1</SequenceNumber>
            <Description>Porterage</Description>
            <IsPricePerPerson>Y</IsPricePerPerson>
          </OptExtra>
        </OptExtras>
        <VoucherName>Baileys London</VoucherName>
        <Address1>21 Fleet St</Address1>
        <Address2>London</Address2>
        <Address3></Address3>
        <Address4></Address4>
        <Address5></Address5>
        <PostCode>W1 4TG</PostCode>
        <Single_Avail>Y</Single_Avail>
        <Single_Ad_Max>1</Single_Ad_Max>
        <Twin_Avail>Y</Twin_Avail>
        <Twin_Ad_Max>2</Twin_Ad_Max>
        <Double_Avail>Y</Double_Avail>
        <Double_Ad_Max>2</Double_Ad_Max>
        <Triple_Avail>Y</Triple_Avail>
        <Triple_Ad_Max>3</Triple_Ad_Max>
        <Quad_Avail>N</Quad_Avail>
        <InfantsAllowed>Y</InfantsAllowed>
        <Infant_From>0</Infant_From>
        <Infant_To>3</Infant_To>
        <ChildrenAllowed>Y</ChildrenAllowed>
        <Child_From>4</Child_From>
        <Child_To>12</Child_To>
        <AdultsAllowed>Y</AdultsAllowed>
        <Adult_From>13</Adult_From>
        <Adult_To>99</Adult_To>
        <ButtonName>Accommodation</ButtonName>
      </OptGeneral>
      <OptStayResults>
        <Availability>RQ</Availability>
        <Currency>GBP</Currency>
        <TotalPrice>98400</TotalPrice>
        <RateName>Midweek</RateName>
        <RateText>Mon-Fri</RateText>
      </OptStayResults>
    </Option>
    <Option>
      <Opt>LONACCUMLONSUITE </Opt>
      <OptionNumber>9</OptionNumber>
      <OptGeneral>
        <SupplierId>1</SupplierId>
        <SupplierName>Cumberland Hotel</SupplierName>
        <Description>Bed & Continental Breakfast</Description>
        <Comment>Suite</Comment>
        <Locality>PAD</Locality>
        <LocalityDescription>Paddington</LocalityDescription>
        <Class>4*</Class>
        <ClassDescription>4 Star</ClassDescription>
        <SType>Y</SType>
        <SCU>Night</SCU>
        <MinSCU>1</MinSCU>
        <MaxSCU>99</MaxSCU>
        <OptExtras>
          <OptExtra>
            <SequenceNumber>1</SequenceNumber>
            <Description>Porterage</Description>
            <IsPricePerPerson>Y</IsPricePerPerson>
          </OptExtra>
        </OptExtras>
        <VoucherName>Cumberland Hotel</VoucherName>
        <Address1>21 Fleet St</Address1>
        <Address2>London</Address2>
        <Address3></Address3>
        <Address4></Address4>
        <Address5></Address5>
        <PostCode>W1 4TG</PostCode>
        <Single_Avail>Y</Single_Avail>
        <Single_Ad_Max>1</Single_Ad_Max>
        <Twin_Avail>Y</Twin_Avail>
        <Twin_Ad_Max>2</Twin_Ad_Max>
        <Double_Avail>Y</Double_Avail>
        <Double_Ad_Max>2</Double_Ad_Max>
        <Triple_Avail>Y</Triple_Avail>
        <Triple_Ad_Max>3</Triple_Ad_Max>
        <Quad_Avail>N</Quad_Avail>
        <InfantsAllowed>Y</InfantsAllowed>
        <Infant_From>0</Infant_From>
        <Infant_To>3</Infant_To>
        <ChildrenAllowed>Y</ChildrenAllowed>
        <Child_From>4</Child_From>
        <Child_To>12</Child_To>
        <AdultsAllowed>Y</AdultsAllowed>
        <Adult_From>13</Adult_From>
        <Adult_To>99</Adult_To>
        <ButtonName>Accommodation</ButtonName>
      </OptGeneral>
      <OptStayResults>
        <Availability>RQ</Availability>
        <Currency>GBP</Currency>
        <TotalPrice>105600</TotalPrice>
        <RateName>Standard</RateName>
        <RateText>Standard</RateText>
      </OptStayResults>
    </Option>
    <Option>
      <Opt>LONACCUMLONROOMON</Opt>
      <OptionNumber>8</OptionNumber>
      <OptGeneral>
        <SupplierId>1</SupplierId>
        <SupplierName>Cumberland Hotel</SupplierName>
        <Description>Room Only</Description>
        <Comment>Standard Room</Comment>
        <Locality>PAD</Locality>
        <LocalityDescription>Paddington</LocalityDescription>
        <Class>4*</Class>
        <ClassDescription>4 Star</ClassDescription>
        <SType>Y</SType>
        <SCU>Night</SCU>
        <MinSCU>1</MinSCU>
        <MaxSCU>99</MaxSCU>
        <OptExtras>
          <OptExtra>
            <SequenceNumber>1</SequenceNumber>
            <Description>Porterage</Description>
            <IsPricePerPerson>Y</IsPricePerPerson>
          </OptExtra>
        </OptExtras>
        <VoucherName>Cumberland Hotel</VoucherName>
        <Address1>21 Fleet St</Address1>
        <Address2>London</Address2>
        <Address3></Address3>
        <Address4></Address4>
        <Address5></Address5>
        <PostCode>W1 4TG</PostCode>
        <Single_Avail>Y</Single_Avail>
        <Single_Ad_Max>1</Single_Ad_Max>
        <Twin_Avail>Y</Twin_Avail>
        <Twin_Ad_Max>2</Twin_Ad_Max>
        <Double_Avail>Y</Double_Avail>
        <Double_Ad_Max>2</Double_Ad_Max>
        <Triple_Avail>Y</Triple_Avail>
        <Triple_Ad_Max>3</Triple_Ad_Max>
        <Quad_Avail>N</Quad_Avail>
        <InfantsAllowed>Y</InfantsAllowed>
        <Infant_From>0</Infant_From>
        <Infant_To>3</Infant_To>
        <ChildrenAllowed>Y</ChildrenAllowed>
        <Child_From>4</Child_From>
        <Child_To>12</Child_To>
        <AdultsAllowed>Y</AdultsAllowed>
        <Adult_From>13</Adult_From>
        <Adult_To>99</Adult_To>
        <ButtonName>Accommodation</ButtonName>
      </OptGeneral>
      <OptStayResults>
        <Availability>RQ</Availability>
        <Currency>GBP</Currency>
        <TotalPrice>57600</TotalPrice>
        <RateName>Standard</RateName>
        <RateText>Standard</RateText>
      </OptStayResults>
    </Option>
    <Option>
      <Opt>LONACCUMLONSTDBCB</Opt>
      <OptionNumber>1</OptionNumber>
      <OptGeneral>
        <SupplierId>1</SupplierId>
        <SupplierName>Cumberland Hotel</SupplierName>
        <Description>Bed & Continental Breakfast</Description>
        <Comment>Standard Room</Comment>
        <Locality>PAD</Locality>
        <LocalityDescription>Paddington</LocalityDescription>
        <Class>4*</Class>
        <ClassDescription>4 Star</ClassDescription>
        <SType>Y</SType>
        <SCU>Night</SCU>
        <MinSCU>1</MinSCU>
        <MaxSCU>99</MaxSCU>
        <OptExtras>
          <OptExtra>
            <SequenceNumber>1</SequenceNumber>
            <Description>Porterage</Description>
            <IsPricePerPerson>Y</IsPricePerPerson>
          </OptExtra>
        </OptExtras>
        <VoucherName>Cumberland Hotel</VoucherName>
        <Address1>21 Fleet St</Address1>
        <Address2>London</Address2>
        <Address3></Address3>
        <Address4></Address4>
        <Address5></Address5>
        <PostCode>W1 4TG</PostCode>
        <Single_Avail>Y</Single_Avail>
        <Single_Ad_Max>1</Single_Ad_Max>
        <Twin_Avail>Y</Twin_Avail>
        <Twin_Ad_Max>2</Twin_Ad_Max>
        <Double_Avail>Y</Double_Avail>
        <Double_Ad_Max>2</Double_Ad_Max>
        <Triple_Avail>Y</Triple_Avail>
        <Triple_Ad_Max>3</Triple_Ad_Max>
        <Quad_Avail>N</Quad_Avail>
        <InfantsAllowed>Y</InfantsAllowed>
        <Infant_From>0</Infant_From>
        <Infant_To>3</Infant_To>
        <ChildrenAllowed>Y</ChildrenAllowed>
        <Child_From>4</Child_From>
        <Child_To>12</Child_To>
        <AdultsAllowed>Y</AdultsAllowed>
        <Adult_From>13</Adult_From>
        <Adult_To>99</Adult_To>
        <ButtonName>Accommodation</ButtonName>
      </OptGeneral>
      <OptStayResults>
        <Availability>RQ</Availability>
        <Currency>GBP</Currency>
        <TotalPrice>67200</TotalPrice>
        <RateName>Standard</RateName>
        <RateText>Standard</RateText>
      </OptStayResults>
    </Option>
  </OptionInfoReply>
</Reply>


text:
exports.why = function() {
    if(Math.random() < 0.1) {
        return special();
    } else if(Math.random() < 0.333) {
        return phrase();
    }
    return sentence();
}

function randi(n) {
    return ~~(Math.random()*n);
}

function randc(A) {
    return A[randi(A.length)];
}

function special() {
    return randc([
            'why not?',
            'woof woof!',
            'why indeed?',
            'THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER',
            'some mysteries are never meant to be solved',
            "I'm not telling you",
            'you know why',
            'instead of asking me why, how about let\'s play chess?'
            ]);
}

function phrase() {
    return randc([
            function() {return 'for the ' + nouned_verb() + ' ' + prepositional_phrase()},
            function() {return 'because ' + sentence()},
            function() {return 'so as to ' + present_verb() + ' ' + object()},
            function() {return 'to ' + present_verb() + ' ' + object()},
            ])();
}

function preposition() {
    return randc(['of', 'from']);
}

function prepositional_phrase() {
    return preposition() + ' ' + randc([
            function() {return article() + ' ' + noun_phrase()},
            function() {return proper_noun()},
            function() {return accusative_pronoun()},
            ])();
}

function sentence() {
    return subject() + ' ' + predicate();
}

function subject() {
    return randc([
            function() {return proper_noun()},
            function() {return nominative_pronoun()},
            function() {return article() + ' ' + noun_phrase()}
            ])();
}

function proper_noun() {
    return randc([
            'Purple Puppy',
            'Hatsune Miku',
            'Donald Trump',
            'Woofer',
            'Purple Puppies\' Porpoise'
            ]);
}

function noun_phrase() {
    return randc([
            function() {return noun();},
            function() {return noun();},
            function() {return noun();},
            function() {return adjective_phrase() + ' ' + noun_phrase()},
            function() {return adjective_phrase() + ' ' + noun_phrase()},
            function() {return adjective_phrase() + ' ' + noun_phrase()},
            function() {return noun_phrase() + ' and ' + noun_phrase()}
            ])();
}

function noun() {
    return randc([
            'puppy',
            'cat',
            'kitten',
            'dog',
            'stalker',
            'siege tank',
            'marine',
            'marauder',
            'zealot',
            'zergling',
            'baneling',
            'roach',
            'queen',
            'hydralisk',
            'ultralisk',
            'adept',
            'immortal',
            'sentry',
            'high templar',
            'dark templar',
            'archon',
            'liberator',
            'raven',
            'banshee',
            'viking',
            'battlecruiser',
            'phoenix',
            'void ray',
            'carrier',
            'tempest',
            'oracle',
            'mutalisk',
            'viper',
            'corruptor',
            'brood lord',
            'overlord',
            'overseer',
            'high school student'
            ]);
}

function nominative_pronoun() {
    return randc([
            'I',
            'you',
            'he',
            'she',
            'they',
            'we'
            ]);
}

function accusative_pronoun() {
    return randc([
            'me',
            'everyone',
            'her',
            'him',
            'them',
            'us'
            ]);
}

function nouned_verb() {
    return randc([
            'love',
            'approval',
            'satisfaction',
            ]);
}

function adjective_phrase() {
    return randc([
            adjective,
            adjective,
            adjective,
            adjective,
            adjective,
            function() {return adjective_phrase() + ' and ' + adjective_phrase();},
            function() {return intensifier() + ' ' + adjective();},
            function() {return intensifier() + ' ' + adjective();},
            function() {return intensifier() + ' ' + adjective();}
            ])();
}

function pos_intensifier() {
    return randc(['very', 'really', 'somewhat', 'moderately', 'mildly', 'quite']);
}

function intensifier() {
    return randc(['', '', 'not ']) + pos_intensifier();
}

function adjective() {
    return randc([
            'purple',
            'green',
            'orange',
            'red',
            'blue',
            'yellow',
            'pink',
            'ultraviolet',
            'infrared',
            'spotted',
            'fluffy',
            'adorable',
            'terrified',
            'excited',
            'acceptable',
            'catlike',
            'doglike',
            'playful',
            'friendly',
            'spiky',
            'pointy',
            'aerodynamic',
            'checkered',
            'mottled',
            'two-dimensional',
            'tetrahedral',
            'triangular',
            'aggressive',
            'spherical',
            'cute',
            'African American',
            'differentiable',
            'open-source',
            'agreeable',
            'disagreeable',
            'tubular',
            'simply connected',
            ]);
}

function article() {
    return randc(['the', 'some', 'a']);
}

function predicate() {
    return randc([
            function() {return transitive_verb() + ' ' + object();},
            intransitive_verb
            ])();
}

function present_verb() {
    return randc([
            function() {return 'defeat';},
            function() {return 'counter';},
            function() {return 'neutralize';},
            function() {return 'fool';},
            function() {return 'please';},
            function() {return 'satisfy';},
            function() {return 'outwit';},
            function() {return 'obtain ' + object() + ' from';}
            ])();
}

function transitive_verb() {
    return randc([
            'threatened',
            'told',
            'asked',
            'begged',
            'helped',
            'obeyed',
            'commanded',
            'confessed to',
            'hugged',
            'betrayed',
            'attacked',
            'advanced upon',
            ]);
}

function intransitive_verb() {
    return randc([
            'insisted on it',
            'suggested it',
            'told me to',
            'wanted it',
            'knew it was a good idea',
            'had a good feeling about it',
            'demanded it be this way',
            'exploded',
            ]);
}

function object() {
    return randc([
            accusative_pronoun,
            function() {
                var n = noun_phrase();
                var a = article();
                var re = /(a|e|i|o|u)/i;
                if (a == 'a' && n[0].match(re)) {
                    a = 'an';
                }
                return a + ' ' +  n;
            }
            ])();
}


text:
package views.templatemodels

import play.api.i18n.Messages

case class PageTitle(title: String, formErrorsExist: Boolean = false) {
  def fullTitle()(implicit messages: Messages): String = {
    val standardTitle = s"$title - ${messages("Service.title")} - GOV.UK"
    val errorTitle    = s"${messages("Service.error")}: $standardTitle"

    if (formErrorsExist) errorTitle else standardTitle
  }
}


text:
<?php

namespace Zimbra\Admin\Tests\Request;

use Zimbra\Admin\Tests\ZimbraAdminApiTestCase;
use Zimbra\Admin\Request\GetAllXMPPComponents;

/**
 * Testcase class for GetAllXMPPComponents.
 */
class GetAllXMPPComponentsTest extends ZimbraAdminApiTestCase
{
    public function testGetAllXMPPComponentsRequest()
    {
        $req = new \Zimbra\Admin\Request\GetAllXMPPComponents();
        $this->assertInstanceOf('Zimbra\Admin\Request\Base', $req);

        $xml = '<?xml version="1.0"?>' . "\n"
            . '<GetAllXMPPComponentsRequest />';
        $this->assertXmlStringEqualsXmlString($xml, (string) $req);

        $array = [
            'GetAllXMPPComponentsRequest' => [
                '_jsns' => 'urn:zimbraAdmin',
            ],
        ];
        $this->assertEquals($array, $req->toArray());
    }

    public function testGetAllXMPPComponentsApi()
    {
        $this->api->getAllXMPPComponents();

        $client = $this->api->getClient();
        $req = $client->lastRequest();
        $xml = '<?xml version="1.0"?>' . "\n"
            . '<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:urn="urn:zimbra" xmlns:urn1="urn:zimbraAdmin">'
                . '<env:Body>'
                    . '<urn1:GetAllXMPPComponentsRequest />'
                . '</env:Body>'
            . '</env:Envelope>';
        $this->assertXmlStringEqualsXmlString($xml, (string) $req);
    }
}


text:
package edu.currencyconv.dto;

/**
 * Created by m1s on 11/19/15.
 */
public class AddressDto extends AbsDto {
    private String country;
    private String city;
    private String street;
    private String houseNumber;
    private Integer zip;

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getHouseNumber() {
        return houseNumber;
    }

    public void setHouseNumber(String houseNumber) {
        this.houseNumber = houseNumber;
    }

    public Integer getZip() {
        return zip;
    }

    public void setZip(Integer zip) {
        this.zip = zip;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "AddressDto{"
                + "country='" + country + '\''
                + ", city='" + city + '\''
                + ", street='" + street + '\''
                + ", houseNumber='" + houseNumber + '\''
                + ", zip=" + zip
                + '}';
    }
}


text:
/*
 *
 * A magic index in an array A[0...n-1] is defined to be an index such that A[i] = i.
 *
 * Given a sorted array of distinct integers, write a method to find a magic index, if one exists,
 * in array A. Return the magic index or -1 if there isn't one.
 *
 * Extra credit: What if the values are not distinct?
 *
 */

var magicIndex = function magicIndex(array) {

};


text:
Description
===========
This cookbook makes it easy to install arbitrary system packages. This mayb be useful
when you want to install some libraries, but don't necessarily want to do any configuration.

Attributes
==========
This cookbook defines the following attributes:

* `default[:system_packages][:packages]` - A string listing the packages that you want installed, separated by a space. Unless you're trying to install from source packages, this is probably the only attribute you need to set.

The following attributes are used when installing from source archives. This is experimental and subject to change.

* `default[:system_packages][:package_name]` - The name of a package that's typically provided by the OS. We use this to disable installation, so our source-installed version doesn't get clobbered (we only do this for Debian/Ubuntu right now).
* `default[:system_packages][:command]` - this should be a command provided by the package. We'll check for the existance of this to see if the installation worked.
* `default[:system_packages][:checksum]` - An SHA checksum to make sure our downloaded file is OK.
* `default[:system_packages][:url]` - A URL to a source tarball; e.g. `http://example.com/foo.tar.gz`
* `default[:system_packages][:archive_type]` - This is a kludge to remove the extension so we can know what directory the package gets extracted into. Defaults to `.tar.gz`
* `default[:system_packages][:configure_options]` - Addition options passed to `./configure`

Usage
=====
The `default` recipe allows you to install arbitrary system packages. To use it, create
a role, and list the packages that you want to install in the
`default[:system_packages][:packages]` attribute.

Here's a sample role:

    name "sample_system_packages"
    description "Sample Role to install some system packages"
    run_list "recipe[system_packages]"

    default_attributes(
      "system_packages" => {
        "packages" => "git-core git-doc git-svn gitstats gitweb"
      }
    )

The `source` recipe allows you to download and install a package from a source tarball. This
recipe is currently experimental, and may change in the future. Here's an example role that
uses this recip to install ImageMagick from source, with RSVG support:

    name "imagemagick_with_rsvg"
    description "Installs ImageMagick from source with RSVG support"
    run_list(
      "recipe[system_packages]",
      "recipe[system_packages::source]"
    )

    default_attributes(
      "system_packages" => {
        "packages" => "librsvg2-2 librsvg2-bin librsvg2-dev libfontconfig libfontconfig-dev libxml2-dev libmagickcore-dev libmagickcore2 libmagickcore2-extra libmagickwand-dev libmagick++-dev libmagick++2",
        "package_name" => "imagemagick",
        "command" => "convert", # command that should be made available by installing the package.
        "checksum" => "9ee0684fb05dae545a0877cbb3d3dc9ec654c3836f886007c85e65305f14fb08",
        "url" => "http://www.imagemagick.org/download/ImageMagick-6.7.6-0.tar.gz",
        "configure_options" => ""
      }
    )

License and Author
==================

Author:: Brad Montgomery (<bmontgomery@coroutine.com>)

Copyright 2012, Coroutine LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the 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.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Entities;
using Exceptions;
using ItsaRepository.interfaces;
using ServiceInterfaces;

namespace Services
{
    public class MediaService : IMediaService
    {
        private readonly IMediaRepository _mediaRepository;

        public MediaService(IMediaRepository mediaRepository)
        {
            _mediaRepository = mediaRepository;
        }

        #region IMediaService Members

        public Media GetMedia(int year, int month, int day, string linkKey)
        {
            return _mediaRepository
                .Entities
                .FirstOrDefault(e => e.Year == year && e.Month == month && e.Day == day && e.LinkKey == linkKey);
        }

        public IEnumerable<Media> GetMedia(int pageNumber, int pageItems)
        {
            try
            {
                return _mediaRepository.Entities
                                       .OrderBy(e => e.Year)
                                       .ThenBy(e => e.Month)
                                       .ThenBy(e => e.Day)
                                       .Skip((pageNumber - 1)*pageItems)
                                       .Take(pageItems)
                                       .ToList();
            }
            catch
            {
                throw new ItsaException("Unable to get media");
            }
        }

        public Media CreateMedia(string fileName, string contentType, Stream inputStream, int contentLength)
        {
            var mediaToCreate = new Media(fileName, contentType, inputStream, contentLength);

            try
            {
                Media media = (from e in _mediaRepository.Entities
                               where e.FileName == mediaToCreate.FileName
                               select e).FirstOrDefault();

                if (media == null)
                {
                    mediaToCreate = _mediaRepository.Create(mediaToCreate);
                    return mediaToCreate;
                }
                throw new ItsaException("Unable to add media. The media already exists in the database");
            }
            catch (ItsaException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new ItsaException("Could not create media", e);
            }
        }

        public void UpdateMedia(string fileName, string title, string caption, string description, string alternate,
                               string contentType, int alignment, int size, Stream inputStream,
                               int contentLength)
        {
            byte[] bytes = ReadBytes(inputStream, contentLength);

            // todo: url?
            var media = new Media(fileName, title, caption, description, alternate, contentType, alignment, size,
                                  bytes);
            try
            {
                _mediaRepository.Update(media);
            }
            catch (Exception e)
            {
                throw new ItsaException("Could not create media", e);
            }
        }

        public Media UpdateMediaDetails(Guid mediaId, string title, string caption, string description, string alternate)
        {
            Media medium = (from i in _mediaRepository.Entities
                            where i.Id == mediaId
                            select i).FirstOrDefault();
            if (medium == null)
            {
                throw new ItsaException("Unable to find media");
            }

            medium.Title = title;
            medium.Caption = caption;
            medium.Description = description;
            medium.Alternate = alternate;

            try
            {
                _mediaRepository.Update(medium);
            }
            catch (Exception e)
            {
                throw new ItsaException("Could not update media", e);
            }
            return medium;
        }

        public void DeleteMedia(Guid mediaId)
        {
            Media medium = (from i in _mediaRepository.Entities
                            where i.Id == mediaId
                            select i).FirstOrDefault();
            try
            {
                _mediaRepository.Delete(medium);
            }
            catch (Exception)
            {
                throw new ItsaException("Unable to delete media");
            }
        }

        public Media GetMedia(Guid mediaId)
        {
            Media medium = (from i in _mediaRepository.Entities
                            where i.Id == mediaId
                            select i).FirstOrDefault();
            return medium;
        }

        #endregion

        private static byte[] ReadBytes(Stream inputStream, int contentLength)
        {
            var bytes = new byte[contentLength];
            inputStream.Read(bytes, 0, contentLength);
            return bytes;
        }
    }
}


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\PostOrder\Enums;

class RefundStatusEnum
{
    const C_FAILED = 'FAILED';
    const C_OTHER = 'OTHER';
    const C_PENDING = 'PENDING';
    const C_SUCCESS = 'SUCCESS';
}


text:
<?php

class AdminDashgoalsController extends ModuleAdminController
{
	public function ajaxProcessChangeConfYear()
	{
		$year = (int)Tools::getValue('year');
		Configuration::updateValue('PS_DASHGOALS_CURRENT_YEAR', $year);
		$months = $this->module->setMonths($year);

		$this->context->smarty->assign(
			array(
				'currency' => $this->context->currency,
				'goals_year' => $year,
				'goals_months' => $months,
				'link' => $this->context->link
			)
		);

		echo $this->module->display(_PS_MODULE_DIR_.$this->module->name.DIRECTORY_SEPARATOR.$this->module->name.'.php', 'config.tpl');
	}
}


text:
package org.jboss.resteasy.test.nextgen.finegrain;

import junit.framework.Assert;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.core.MessageBodyParameterInjector;
import org.jboss.resteasy.spi.BadRequestException;
import org.jboss.resteasy.spi.InternalDispatcher;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.test.EmbeddedContainer;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.Stack;

import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;

/**
 * Test for InternalDispatcher
 *
 * @author Solomon Duskis
 * @version $Revision: 1 $
 */

public class InternalDispatcherTest
{

   private static Dispatcher dispatcher;
   private static ForwardingResource forwardingResource;
   private static ResteasyClient client;

   @Path("/")
   public interface Client
   {
      @GET
      @Path("basic")
      @Produces("text/plain")
      String getBasic();

      @PUT
      @Path("basic")
      @Consumes("text/plain")
      void putBasic(String body);

      @GET
      @Path("forward/basic")
      @Produces("text/plain")
      String getForwardBasic();

      @PUT
      @Path("forward/basic")
      @Consumes("text/plain")
      void putForwardBasic(String body);

      @POST
      @Path("forward/basic")
      @Consumes("text/plain")
      void postForwardBasic(String body);

      @DELETE
      @Path("/forward/basic")
      void deleteForwardBasic();

      @GET
      @Produces("text/plain")
      @Path("/forward/object/{id}")
      Response getForwardedObject(@PathParam("id") Integer id);

      @GET
      @Produces("text/plain")
      @Path("/object/{id}")
      Response getObject(@PathParam("id") Integer id);

      @GET
      @Produces("text/plain")
      @Path("/infinite-forward")
      int infiniteForward();

   }

   @Path("/")
   public static class ForwardingResource
   {
      public Stack<String> uriStack = new Stack<String>();
      String basic = "basic";
      @Context
      UriInfo uriInfo;

      @GET
      @Produces("text/plain")
      @Path("/basic")
      public String getBasic()
      {
         uriStack.push(uriInfo.getAbsolutePath().toString());
         return basic;
      }

      @GET
      @Produces("text/plain")
      @Path("/forward/basic")
      public String forwardBasic(@Context InternalDispatcher dispatcher)
      {
         uriStack.push(uriInfo.getAbsolutePath().toString());
         return (String) dispatcher.getEntity("/basic");
      }

      @PUT
      @POST
      @Consumes("text/plain")
      @Path("/basic")
      public void putBasic(String basic)
      {
         uriStack.push(uriInfo.getAbsolutePath().toString());
         this.basic = basic;
      }

      @DELETE
      @Path("/basic")
      public void deleteBasic()
      {
         uriStack.push(uriInfo.getAbsolutePath().toString());
         this.basic = "basic";
      }

      @PUT
      @Consumes("text/plain")
      @Path("/forward/basic")
      public void putForwardBasic(String basic,
                                  @Context InternalDispatcher dispatcher)
      {
         uriStack.push(uriInfo.getAbsolutePath().toString());
         dispatcher.putEntity("/basic", basic);
      }

      @POST
      @Consumes("text/plain")
      @Path("/forward/basic")
      public void postForwardBasic(String basic,
                                   @Context InternalDispatcher dispatcher)
      {
         uriStack.push(uriInfo.getAbsolutePath().toString());
         dispatcher.postEntity("/basic", basic);
      }

      @DELETE
      @Path("/forward/basic")
      public void deleteForwardBasic(@Context InternalDispatcher dispatcher)
      {
         uriStack.push(uriInfo.getAbsolutePath().toString());
         dispatcher.delete("/basic");
      }

      @GET
      @Produces("text/plain")
      @Path("/object/{id}")
      public Response getObject(@PathParam("id") Integer id)
      {
         uriStack.push(uriInfo.getAbsolutePath().toString());
         if (id == 0)
            return Response.noContent().build();
         else
            return Response.ok("object" + id).build();
      }

      @GET
      @Path("/forward/object/{id}")
      public Response forwardObject(@PathParam("id") Integer id,
                                    @Context InternalDispatcher dispatcher)
      {
         uriStack.push(uriInfo.getAbsolutePath().toString());
         return dispatcher.getResponse("/object/" + id);
      }

      @GET
      @Path("/infinite-forward")
      @Produces("text/plain")
      public int infinitFoward(@Context InternalDispatcher dispatcher,
                               @QueryParam("count") @DefaultValue("0") int count)
      {
         uriStack.push(uriInfo.getAbsolutePath().toString());
         try
         {
            dispatcher.getEntity("/infinite-forward?count=" + (count + 1));
            // we'll never reach 20, since the max count of times through the
            // system is 20, and first time through is 0
            Assert.assertNotSame(20, count);
         }
         catch (BadRequestException e)
         {

         }
         finally
         {
            Assert
                    .assertEquals(count, MessageBodyParameterInjector.bodyCount());
            Assert.assertEquals(count + 1, ResteasyProviderFactory
                    .getContextDataLevelCount());
         }
         return ResteasyProviderFactory.getContextDataLevelCount();
      }
   }

   @BeforeClass
   public static void before() throws Exception
   {
      dispatcher = EmbeddedContainer.start().getDispatcher();
            forwardingResource = new ForwardingResource();
            dispatcher.getRegistry().addSingletonResource(forwardingResource);
      client = new ResteasyClientBuilder().build();
   }

   @Before
   public void setup() {
       forwardingResource.uriStack.clear();
   }

   @AfterClass
   public static void after() throws Exception
   {
      client.close();
      EmbeddedContainer.stop();
   }

   @Test
   public void testClientResponse() throws Exception
   {
      Client proxy = client.target(generateBaseUrl()).proxy(Client.class);

      Assert.assertEquals("basic", proxy.getBasic());
      Assert.assertEquals("basic", proxy.getForwardBasic());
      Assert.assertEquals("object1", proxy.getObject(1).readEntity(String.class));
      Assert.assertEquals("object1", proxy.getForwardedObject(1).readEntity(String.class));
      Response cr = proxy.getObject(0);
      Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), cr.getStatus());
      cr.close();
      cr = proxy.getForwardedObject(0);
      Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), cr.getStatus());
      cr.close();

      proxy.putForwardBasic("testBasic");
      Assert.assertEquals("testBasic", proxy.getBasic());
      proxy.postForwardBasic("testBasic1");
      Assert.assertEquals("testBasic1", proxy.getBasic());
      proxy.deleteForwardBasic();
      Assert.assertEquals("basic", proxy.getBasic());

   }

   @Test
   public void testInfinitForward()
   {
      Client proxy = client.target(generateBaseUrl()).proxy(Client.class);
      // assert that even though there were infinite forwards, there still was
      // only 1 level of "context" data and that clean up occurred correctly.
      // This should not spin forever, since RESTEasy stops the recursive loop
      // after 20 internal dispatches
      Assert.assertEquals(1, proxy.infiniteForward());
   }

      @Test
   public void testUriInfoBasic() {
       String baseUrl = generateBaseUrl();
       Client proxy = client.target(generateBaseUrl()).proxy(Client.class);

       proxy.getBasic();
       Assert.assertEquals(baseUrl + "/basic", forwardingResource.uriStack.pop());
       Assert.assertTrue(forwardingResource.uriStack.isEmpty());

   }

   @Test
   public void testUriInfoForwardBasic() {
      String baseUrl = generateBaseUrl();
       Client proxy = client.target(generateBaseUrl()).proxy(Client.class);

      proxy.getForwardBasic();
       Assert.assertEquals(baseUrl + "/basic", forwardingResource.uriStack.pop());
       Assert.assertEquals(baseUrl + "/forward/basic", forwardingResource.uriStack.pop());
       Assert.assertTrue(forwardingResource.uriStack.isEmpty());
   }

}