text:
package gojsonschema

import (
	"encoding/json"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"unicode/utf8"
)

func Validate(ls JSONLoader, ld JSONLoader) (*Result, error) {

	var err error

	// load schema

	schema, err := NewSchema(ls)
	if err != nil {
		return nil, err
	}

	// begine validation

	return schema.Validate(ld)

}

func (v *Schema) Validate(l JSONLoader) (*Result, error) {

	// load document

	root, err := l.LoadJSON()
	if err != nil {
		return nil, err
	}

	// begin validation

	result := &Result{}
	context := newJsonContext(STRING_CONTEXT_ROOT, nil)
	v.rootSchema.validateRecursive(v.rootSchema, root, result, context)

	return result, nil

}

func (v *subSchema) subValidateWithContext(document interface{}, context *jsonContext) *Result {
	result := &Result{}
	v.validateRecursive(v, document, result, context)
	return result
}

// Walker function to validate the json recursively against the subSchema
func (v *subSchema) validateRecursive(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *jsonContext) {

	if internalLogEnabled {
		internalLog("validateRecursive %s", context.String())
		internalLog(" %v", currentNode)
	}

	// Handle referenced schemas, returns directly when a $ref is found
	if currentSubSchema.refSchema != nil {
		v.validateRecursive(currentSubSchema.refSchema, currentNode, result, context)
		return
	}

	// Check for null value
	if currentNode == nil {
		if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_NULL) {
			result.addError(
				new(InvalidTypeError),
				context,
				currentNode,
				ErrorDetails{
					"expected": currentSubSchema.types.String(),
					"given":    TYPE_NULL,
				},
			)
			return
		}

		currentSubSchema.validateSchema(currentSubSchema, currentNode, result, context)
		v.validateCommon(currentSubSchema, currentNode, result, context)

	} else { // Not a null value

		if isJsonNumber(currentNode) {

			value := currentNode.(json.Number)

			_, isValidInt64, _ := checkJsonNumber(value)

			validType := currentSubSchema.types.Contains(TYPE_NUMBER) || (isValidInt64 && currentSubSchema.types.Contains(TYPE_INTEGER))

			if currentSubSchema.types.IsTyped() && !validType {

				givenType := TYPE_INTEGER
				if !isValidInt64 {
					givenType = TYPE_NUMBER
				}

				result.addError(
					new(InvalidTypeError),
					context,
					currentNode,
					ErrorDetails{
						"expected": currentSubSchema.types.String(),
						"given":    givenType,
					},
				)
				return
			}

			currentSubSchema.validateSchema(currentSubSchema, value, result, context)
			v.validateNumber(currentSubSchema, value, result, context)
			v.validateCommon(currentSubSchema, value, result, context)
			v.validateString(currentSubSchema, value, result, context)

		} else {

			rValue := reflect.ValueOf(currentNode)
			rKind := rValue.Kind()

			switch rKind {

			// Slice => JSON array

			case reflect.Slice:

				if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_ARRAY) {
					result.addError(
						new(InvalidTypeError),
						context,
						currentNode,
						ErrorDetails{
							"expected": currentSubSchema.types.String(),
							"given":    TYPE_ARRAY,
						},
					)
					return
				}

				castCurrentNode := currentNode.([]interface{})

				currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context)

				v.validateArray(currentSubSchema, castCurrentNode, result, context)
				v.validateCommon(currentSubSchema, castCurrentNode, result, context)

			// Map => JSON object

			case reflect.Map:
				if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_OBJECT) {
					result.addError(
						new(InvalidTypeError),
						context,
						currentNode,
						ErrorDetails{
							"expected": currentSubSchema.types.String(),
							"given":    TYPE_OBJECT,
						},
					)
					return
				}

				castCurrentNode, ok := currentNode.(map[string]interface{})
				if !ok {
					castCurrentNode = convertDocumentNode(currentNode).(map[string]interface{})
				}

				currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context)

				v.validateObject(currentSubSchema, castCurrentNode, result, context)
				v.validateCommon(currentSubSchema, castCurrentNode, result, context)

				for _, pSchema := range currentSubSchema.propertiesChildren {
					nextNode, ok := castCurrentNode[pSchema.property]
					if ok {
						subContext := newJsonContext(pSchema.property, context)
						v.validateRecursive(pSchema, nextNode, result, subContext)
					}
				}

			// Simple JSON values : string, number, boolean

			case reflect.Bool:

				if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_BOOLEAN) {
					result.addError(
						new(InvalidTypeError),
						context,
						currentNode,
						ErrorDetails{
							"expected": currentSubSchema.types.String(),
							"given":    TYPE_BOOLEAN,
						},
					)
					return
				}

				value := currentNode.(bool)

				currentSubSchema.validateSchema(currentSubSchema, value, result, context)
				v.validateNumber(currentSubSchema, value, result, context)
				v.validateCommon(currentSubSchema, value, result, context)
				v.validateString(currentSubSchema, value, result, context)

			case reflect.String:

				if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_STRING) {
					result.addError(
						new(InvalidTypeError),
						context,
						currentNode,
						ErrorDetails{
							"expected": currentSubSchema.types.String(),
							"given":    TYPE_STRING,
						},
					)
					return
				}

				value := currentNode.(string)

				currentSubSchema.validateSchema(currentSubSchema, value, result, context)
				v.validateNumber(currentSubSchema, value, result, context)
				v.validateCommon(currentSubSchema, value, result, context)
				v.validateString(currentSubSchema, value, result, context)

			}

		}

	}

	result.incrementScore()
}

// Different kinds of validation there, subSchema / common / array / object / string...
func (v *subSchema) validateSchema(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *jsonContext) {

	if internalLogEnabled {
		internalLog("validateSchema %s", context.String())
		internalLog(" %v", currentNode)
	}

	if len(currentSubSchema.anyOf) > 0 {

		validatedAnyOf := false
		var bestValidationResult *Result

		for _, anyOfSchema := range currentSubSchema.anyOf {
			if !validatedAnyOf {
				validationResult := anyOfSchema.subValidateWithContext(currentNode, context)
				validatedAnyOf = validationResult.Valid()

				if !validatedAnyOf && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) {
					bestValidationResult = validationResult
				}
			}
		}
		if !validatedAnyOf {

			result.addError(new(NumberAnyOfError), context, currentNode, ErrorDetails{})

			if bestValidationResult != nil {
				// add error messages of closest matching subSchema as
				// that's probably the one the user was trying to match
				result.mergeErrors(bestValidationResult)
			}
		}
	}

	if len(currentSubSchema.oneOf) > 0 {

		nbValidated := 0
		var bestValidationResult *Result

		for _, oneOfSchema := range currentSubSchema.oneOf {
			validationResult := oneOfSchema.subValidateWithContext(currentNode, context)
			if validationResult.Valid() {
				nbValidated++
			} else if nbValidated == 0 && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) {
				bestValidationResult = validationResult
			}
		}

		if nbValidated != 1 {

			result.addError(new(NumberOneOfError), context, currentNode, ErrorDetails{})

			if nbValidated == 0 {
				// add error messages of closest matching subSchema as
				// that's probably the one the user was trying to match
				result.mergeErrors(bestValidationResult)
			}
		}

	}

	if len(currentSubSchema.allOf) > 0 {
		nbValidated := 0

		for _, allOfSchema := range currentSubSchema.allOf {
			validationResult := allOfSchema.subValidateWithContext(currentNode, context)
			if validationResult.Valid() {
				nbValidated++
			}
			result.mergeErrors(validationResult)
		}

		if nbValidated != len(currentSubSchema.allOf) {
			result.addError(new(NumberAllOfError), context, currentNode, ErrorDetails{})
		}
	}

	if currentSubSchema.not != nil {
		validationResult := currentSubSchema.not.subValidateWithContext(currentNode, context)
		if validationResult.Valid() {
			result.addError(new(NumberNotError), context, currentNode, ErrorDetails{})
		}
	}

	if currentSubSchema.dependencies != nil && len(currentSubSchema.dependencies) > 0 {
		if isKind(currentNode, reflect.Map) {
			for elementKey := range currentNode.(map[string]interface{}) {
				if dependency, ok := currentSubSchema.dependencies[elementKey]; ok {
					switch dependency := dependency.(type) {

					case []string:
						for _, dependOnKey := range dependency {
							if _, dependencyResolved := currentNode.(map[string]interface{})[dependOnKey]; !dependencyResolved {
								result.addError(
									new(MissingDependencyError),
									context,
									currentNode,
									ErrorDetails{"dependency": dependOnKey},
								)
							}
						}

					case *subSchema:
						dependency.validateRecursive(dependency, currentNode, result, context)

					}
				}
			}
		}
	}

	result.incrementScore()
}

func (v *subSchema) validateCommon(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) {

	if internalLogEnabled {
		internalLog("validateCommon %s", context.String())
		internalLog(" %v", value)
	}

	// enum:
	if len(currentSubSchema.enum) > 0 {
		has, err := currentSubSchema.ContainsEnum(value)
		if err != nil {
			result.addError(new(InternalError), context, value, ErrorDetails{"error": err})
		}
		if !has {
			result.addError(
				new(EnumError),
				context,
				value,
				ErrorDetails{
					"allowed": strings.Join(currentSubSchema.enum, ", "),
				},
			)
		}
	}

	result.incrementScore()
}

func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface{}, result *Result, context *jsonContext) {

	if internalLogEnabled {
		internalLog("validateArray %s", context.String())
		internalLog(" %v", value)
	}

	nbValues := len(value)

	// TODO explain
	if currentSubSchema.itemsChildrenIsSingleSchema {
		for i := range value {
			subContext := newJsonContext(strconv.Itoa(i), context)
			validationResult := currentSubSchema.itemsChildren[0].subValidateWithContext(value[i], subContext)
			result.mergeErrors(validationResult)
		}
	} else {
		if currentSubSchema.itemsChildren != nil && len(currentSubSchema.itemsChildren) > 0 {

			nbItems := len(currentSubSchema.itemsChildren)

			// while we have both schemas and values, check them against each other
			for i := 0; i != nbItems && i != nbValues; i++ {
				subContext := newJsonContext(strconv.Itoa(i), context)
				validationResult := currentSubSchema.itemsChildren[i].subValidateWithContext(value[i], subContext)
				result.mergeErrors(validationResult)
			}

			if nbItems < nbValues {
				// we have less schemas than elements in the instance array,
				// but that might be ok if "additionalItems" is specified.

				switch currentSubSchema.additionalItems.(type) {
				case bool:
					if !currentSubSchema.additionalItems.(bool) {
						result.addError(new(ArrayNoAdditionalItemsError), context, value, ErrorDetails{})
					}
				case *subSchema:
					additionalItemSchema := currentSubSchema.additionalItems.(*subSchema)
					for i := nbItems; i != nbValues; i++ {
						subContext := newJsonContext(strconv.Itoa(i), context)
						validationResult := additionalItemSchema.subValidateWithContext(value[i], subContext)
						result.mergeErrors(validationResult)
					}
				}
			}
		}
	}

	// minItems & maxItems
	if currentSubSchema.minItems != nil {
		if nbValues < int(*currentSubSchema.minItems) {
			result.addError(
				new(ArrayMinItemsError),
				context,
				value,
				ErrorDetails{"min": *currentSubSchema.minItems},
			)
		}
	}
	if currentSubSchema.maxItems != nil {
		if nbValues > int(*currentSubSchema.maxItems) {
			result.addError(
				new(ArrayMaxItemsError),
				context,
				value,
				ErrorDetails{"max": *currentSubSchema.maxItems},
			)
		}
	}

	// uniqueItems:
	if currentSubSchema.uniqueItems {
		var stringifiedItems []string
		for _, v := range value {
			vString, err := marshalToJsonString(v)
			if err != nil {
				result.addError(new(InternalError), context, value, ErrorDetails{"err": err})
			}
			if isStringInSlice(stringifiedItems, *vString) {
				result.addError(
					new(ItemsMustBeUniqueError),
					context,
					value,
					ErrorDetails{"type": TYPE_ARRAY},
				)
			}
			stringifiedItems = append(stringifiedItems, *vString)
		}
	}

	result.incrementScore()
}

func (v *subSchema) validateObject(currentSubSchema *subSchema, value map[string]interface{}, result *Result, context *jsonContext) {

	if internalLogEnabled {
		internalLog("validateObject %s", context.String())
		internalLog(" %v", value)
	}

	// minProperties & maxProperties:
	if currentSubSchema.minProperties != nil {
		if len(value) < int(*currentSubSchema.minProperties) {
			result.addError(
				new(ArrayMinPropertiesError),
				context,
				value,
				ErrorDetails{"min": *currentSubSchema.minProperties},
			)
		}
	}
	if currentSubSchema.maxProperties != nil {
		if len(value) > int(*currentSubSchema.maxProperties) {
			result.addError(
				new(ArrayMaxPropertiesError),
				context,
				value,
				ErrorDetails{"max": *currentSubSchema.maxProperties},
			)
		}
	}

	// required:
	for _, requiredProperty := range currentSubSchema.required {
		_, ok := value[requiredProperty]
		if ok {
			result.incrementScore()
		} else {
			result.addError(
				new(RequiredError),
				context,
				value,
				ErrorDetails{"property": requiredProperty},
			)
		}
	}

	// additionalProperty & patternProperty:
	if currentSubSchema.additionalProperties != nil {

		switch currentSubSchema.additionalProperties.(type) {
		case bool:

			if !currentSubSchema.additionalProperties.(bool) {

				for pk := range value {

					found := false
					for _, spValue := range currentSubSchema.propertiesChildren {
						if pk == spValue.property {
							found = true
						}
					}

					pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context)

					if found {

						if pp_has && !pp_match {
							result.addError(
								new(AdditionalPropertyNotAllowedError),
								context,
								value[pk],
								ErrorDetails{"property": pk},
							)
						}

					} else {

						if !pp_has || !pp_match {
							result.addError(
								new(AdditionalPropertyNotAllowedError),
								context,
								value[pk],
								ErrorDetails{"property": pk},
							)
						}

					}
				}
			}

		case *subSchema:

			additionalPropertiesSchema := currentSubSchema.additionalProperties.(*subSchema)
			for pk := range value {

				found := false
				for _, spValue := range currentSubSchema.propertiesChildren {
					if pk == spValue.property {
						found = true
					}
				}

				pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context)

				if found {

					if pp_has && !pp_match {
						validationResult := additionalPropertiesSchema.subValidateWithContext(value[pk], context)
						result.mergeErrors(validationResult)
					}

				} else {

					if !pp_has || !pp_match {
						validationResult := additionalPropertiesSchema.subValidateWithContext(value[pk], context)
						result.mergeErrors(validationResult)
					}

				}

			}
		}
	} else {

		for pk := range value {

			pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context)

			if pp_has && !pp_match {

				result.addError(
					new(InvalidPropertyPatternError),
					context,
					value[pk],
					ErrorDetails{
						"property": pk,
						"pattern":  currentSubSchema.PatternPropertiesString(),
					},
				)
			}

		}
	}

	result.incrementScore()
}

func (v *subSchema) validatePatternProperty(currentSubSchema *subSchema, key string, value interface{}, result *Result, context *jsonContext) (has bool, matched bool) {

	if internalLogEnabled {
		internalLog("validatePatternProperty %s", context.String())
		internalLog(" %s %v", key, value)
	}

	has = false

	validatedkey := false

	for pk, pv := range currentSubSchema.patternProperties {
		if matches, _ := regexp.MatchString(pk, key); matches {
			has = true
			subContext := newJsonContext(key, context)
			validationResult := pv.subValidateWithContext(value, subContext)
			result.mergeErrors(validationResult)
			if validationResult.Valid() {
				validatedkey = true
			}
		}
	}

	if !validatedkey {
		return has, false
	}

	result.incrementScore()

	return has, true
}

func (v *subSchema) validateString(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) {

	// Ignore JSON numbers
	if isJsonNumber(value) {
		return
	}

	// Ignore non strings
	if !isKind(value, reflect.String) {
		return
	}

	if internalLogEnabled {
		internalLog("validateString %s", context.String())
		internalLog(" %v", value)
	}

	stringValue := value.(string)

	// minLength & maxLength:
	if currentSubSchema.minLength != nil {
		if utf8.RuneCount([]byte(stringValue)) < int(*currentSubSchema.minLength) {
			result.addError(
				new(StringLengthGTEError),
				context,
				value,
				ErrorDetails{"min": *currentSubSchema.minLength},
			)
		}
	}
	if currentSubSchema.maxLength != nil {
		if utf8.RuneCount([]byte(stringValue)) > int(*currentSubSchema.maxLength) {
			result.addError(
				new(StringLengthLTEError),
				context,
				value,
				ErrorDetails{"max": *currentSubSchema.maxLength},
			)
		}
	}

	// pattern:
	if currentSubSchema.pattern != nil {
		if !currentSubSchema.pattern.MatchString(stringValue) {
			result.addError(
				new(DoesNotMatchPatternError),
				context,
				value,
				ErrorDetails{"pattern": currentSubSchema.pattern},
			)

		}
	}

	// format
	if currentSubSchema.format != "" {
		if !FormatCheckers.IsFormat(currentSubSchema.format, stringValue) {
			result.addError(
				new(DoesNotMatchFormatError),
				context,
				value,
				ErrorDetails{"format": currentSubSchema.format},
			)
		}
	}

	result.incrementScore()
}

func (v *subSchema) validateNumber(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) {

	// Ignore non numbers
	if !isJsonNumber(value) {
		return
	}

	if internalLogEnabled {
		internalLog("validateNumber %s", context.String())
		internalLog(" %v", value)
	}

	number := value.(json.Number)
	float64Value, _ := number.Float64()

	// multipleOf:
	if currentSubSchema.multipleOf != nil {

		if !isFloat64AnInteger(float64Value / *currentSubSchema.multipleOf) {
			result.addError(
				new(MultipleOfError),
				context,
				resultErrorFormatJsonNumber(number),
				ErrorDetails{"multiple": *currentSubSchema.multipleOf},
			)
		}
	}

	//maximum & exclusiveMaximum:
	if currentSubSchema.maximum != nil {
		if currentSubSchema.exclusiveMaximum {
			if float64Value >= *currentSubSchema.maximum {
				result.addError(
					new(NumberLTError),
					context,
					resultErrorFormatJsonNumber(number),
					ErrorDetails{
						"max": resultErrorFormatNumber(*currentSubSchema.maximum),
					},
				)
			}
		} else {
			if float64Value > *currentSubSchema.maximum {
				result.addError(
					new(NumberLTEError),
					context,
					resultErrorFormatJsonNumber(number),
					ErrorDetails{
						"max": resultErrorFormatNumber(*currentSubSchema.maximum),
					},
				)
			}
		}
	}

	//minimum & exclusiveMinimum:
	if currentSubSchema.minimum != nil {
		if currentSubSchema.exclusiveMinimum {
			if float64Value <= *currentSubSchema.minimum {
				result.addError(
					new(NumberGTError),
					context,
					resultErrorFormatJsonNumber(number),
					ErrorDetails{
						"min": resultErrorFormatNumber(*currentSubSchema.minimum),
					},
				)
			}
		} else {
			if float64Value < *currentSubSchema.minimum {
				result.addError(
					new(NumberGTEError),
					context,
					resultErrorFormatJsonNumber(number),
					ErrorDetails{
						"min": resultErrorFormatNumber(*currentSubSchema.minimum),
					},
				)
			}
		}
	}

	result.incrementScore()
}


text:
/**
 * Fake implementations of bindings used with runners-core.
 */
package org.apache.beam.fn.harness.fake;

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE CPP, DefaultSignatures, FlexibleContexts #-}

-- |
-- Module:      Data.Aeson.Types.Class
-- Copyright:   (c) 2011-2015 Bryan O'Sullivan
--              (c) 2011 MailRank, Inc.
-- License:     Apache
-- Maintainer:  Bryan O'Sullivan <bos@serpentine.com>
-- Stability:   experimental
-- Portability: portable
--
-- Types for working with JSON data.

module Data.Aeson.Types.Class
    (
    -- * Core JSON classes
      FromJSON(..)
    , ToJSON(..)
    -- * Generic JSON classes
    , GFromJSON(..)
    , GToJSON(..)
    , genericToJSON
    , genericToEncoding
    , genericParseJSON
    -- * Object key-value pairs
    , KeyValue(..)
    -- * Functions needed for documentation
    , typeMismatch
    ) where

import Data.Aeson.Types.Internal
import Data.Text (Text)
import GHC.Generics (Generic, Rep, from, to)
import qualified Data.Aeson.Encode.Builder as E

-- | Class of generic representation types ('Rep') that can be converted to
-- JSON.
class GToJSON f where
    -- | This method (applied to 'defaultOptions') is used as the
    -- default generic implementation of 'toJSON'.
    gToJSON :: Options -> f a -> Value

    -- | This method (applied to 'defaultOptions') can be used as the
    -- default generic implementation of 'toEncoding'.
    gToEncoding :: Options -> f a -> Encoding

-- | Class of generic representation types ('Rep') that can be converted from JSON.
class GFromJSON f where
    -- | This method (applied to 'defaultOptions') is used as the
    -- default generic implementation of 'parseJSON'.
    gParseJSON :: Options -> Value -> Parser (f a)

-- | A configurable generic JSON creator. This function applied to
-- 'defaultOptions' is used as the default for 'toJSON' when the type
-- is an instance of 'Generic'.
genericToJSON :: (Generic a, GToJSON (Rep a)) => Options -> a -> Value
genericToJSON opts = gToJSON opts . from

-- | A configurable generic JSON encoder. This function applied to
-- 'defaultOptions' is used as the default for 'toEncoding' when the type
-- is an instance of 'Generic'.
genericToEncoding :: (Generic a, GToJSON (Rep a)) => Options -> a -> Encoding
genericToEncoding opts = gToEncoding opts . from

-- | A configurable generic JSON decoder. This function applied to
-- 'defaultOptions' is used as the default for 'parseJSON' when the
-- type is an instance of 'Generic'.
genericParseJSON :: (Generic a, GFromJSON (Rep a)) => Options -> Value -> Parser a
genericParseJSON opts = fmap to . gParseJSON opts

-- | A type that can be converted to JSON.
--
-- An example type and instance:
--
-- @
-- \-- Allow ourselves to write 'Text' literals.
-- {-\# LANGUAGE OverloadedStrings #-}
--
-- data Coord = Coord { x :: Double, y :: Double }
--
-- instance ToJSON Coord where
--   toJSON (Coord x y) = 'object' [\"x\" '.=' x, \"y\" '.=' y]
--
--   toEncoding (Coord x y) = 'pairs' (\"x\" '.=' x '<>' \"y\" '.=' y)
-- @
--
-- Instead of manually writing your 'ToJSON' instance, there are two options
-- to do it automatically:
--
-- * "Data.Aeson.TH" provides Template Haskell functions which will derive an
-- instance at compile time. The generated instance is optimized for your type
-- so will probably be more efficient than the following two options:
--
-- * The compiler can provide a default generic implementation for
-- 'toJSON'.
--
-- To use the second, simply add a @deriving 'Generic'@ clause to your
-- datatype and declare a 'ToJSON' instance for your datatype without giving
-- definitions for 'toJSON' or 'toEncoding'.
--
-- For example, the previous example can be simplified to a more
-- minimal instance:
--
-- @
-- {-\# LANGUAGE DeriveGeneric \#-}
--
-- import "GHC.Generics"
--
-- data Coord = Coord { x :: Double, y :: Double } deriving 'Generic'
--
-- instance ToJSON Coord where
--     toEncoding = 'genericToEncoding' 'defaultOptions'
-- @
--
-- Why do we provide an implementation for 'toEncoding' here?  The
-- 'toEncoding' function is a relatively new addition to this class.
-- To allow users of older versions of this library to upgrade without
-- having to edit all of their instances or encounter surprising
-- incompatibilities, the default implementation of 'toEncoding' uses
-- 'toJSON'.  This produces correct results, but since it performs an
-- intermediate conversion to a 'Value', it will be less efficient
-- than directly emitting an 'Encoding'.  Our one-liner definition of
-- 'toEncoding' above bypasses the intermediate 'Value'.
--
-- If @DefaultSignatures@ doesn't give exactly the results you want,
-- you can customize the generic encoding with only a tiny amount of
-- effort, using 'genericToJSON' and 'genericToEncoding' with your
-- preferred 'Options':
--
-- @
-- instance ToJSON Coord where
--     toJSON     = 'genericToJSON' 'defaultOptions'
--     toEncoding = 'genericToEncoding' 'defaultOptions'
-- @
class ToJSON a where
    -- | Convert a Haskell value to a JSON-friendly intermediate type.
    toJSON     :: a -> Value
    {-# MINIMAL toJSON #-}

    default toJSON :: (Generic a, GToJSON (Rep a)) => a -> Value
    toJSON = genericToJSON defaultOptions

    -- | Encode a Haskell value as JSON.
    --
    -- The default implementation of this method creates an
    -- intermediate 'Value' using 'toJSON'.  This provides
    -- source-level compatibility for people upgrading from older
    -- versions of this library, but obviously offers no performance
    -- advantage.
    --
    -- To benefit from direct encoding, you /must/ provide an
    -- implementation for this method.  The easiest way to do so is by
    -- having your types implement 'Generic' using the @DeriveGeneric@
    -- extension, and then have GHC generate a method body as follows.
    --
    -- @
    -- instance ToJSON Coord where
    --     toEncoding = 'genericToEncoding' 'defaultOptions'
    -- @

    toEncoding :: a -> Encoding
    toEncoding = Encoding . E.encodeToBuilder . toJSON
    {-# INLINE toEncoding #-}

-- | A type that can be converted from JSON, with the possibility of
-- failure.
--
-- In many cases, you can get the compiler to generate parsing code
-- for you (see below).  To begin, let's cover writing an instance by
-- hand.
--
-- There are various reasons a conversion could fail.  For example, an
-- 'Object' could be missing a required key, an 'Array' could be of
-- the wrong size, or a value could be of an incompatible type.
--
-- The basic ways to signal a failed conversion are as follows:
--
-- * 'empty' and 'mzero' work, but are terse and uninformative
--
-- * 'fail' yields a custom error message
--
-- * 'typeMismatch' produces an informative message for cases when the
-- value encountered is not of the expected type
--
-- An example type and instance:
--
-- @
-- \-- Allow ourselves to write 'Text' literals.
-- {-\# LANGUAGE OverloadedStrings #-}
--
-- data Coord = Coord { x :: Double, y :: Double }
--
-- instance FromJSON Coord where
--   parseJSON ('Object' v) = Coord    '<$>'
--                          v '.:' \"x\" '<*>'
--                          v '.:' \"y\"
--
--   \-- We do not expect a non-'Object' value here.
--   \-- We could use 'mzero' to fail, but 'typeMismatch'
--   \-- gives a much more informative error message.
--   parseJSON invalid    = 'typeMismatch' \"Coord\" invalid
-- @
--
-- Instead of manually writing your 'FromJSON' instance, there are two options
-- to do it automatically:
--
-- * "Data.Aeson.TH" provides Template Haskell functions which will derive an
-- instance at compile time. The generated instance is optimized for your type
-- so will probably be more efficient than the following two options:
--
-- * The compiler can provide a default generic implementation for
-- 'parseJSON'.
--
-- To use the second, simply add a @deriving 'Generic'@ clause to your
-- datatype and declare a 'FromJSON' instance for your datatype without giving
-- a definition for 'parseJSON'.
--
-- For example, the previous example can be simplified to just:
--
-- @
-- {-\# LANGUAGE DeriveGeneric \#-}
--
-- import "GHC.Generics"
--
-- data Coord = Coord { x :: Double, y :: Double } deriving 'Generic'
--
-- instance FromJSON Coord
-- @
--
-- If @DefaultSignatures@ doesn't give exactly the results you want,
-- you can customize the generic decoding with only a tiny amount of
-- effort, using 'genericParseJSON' with your preferred 'Options':
--
-- @
-- instance FromJSON Coord where
--     parseJSON = 'genericParseJSON' 'defaultOptions'
-- @

class FromJSON a where
    parseJSON :: Value -> Parser a

    default parseJSON :: (Generic a, GFromJSON (Rep a)) => Value -> Parser a
    parseJSON = genericParseJSON defaultOptions

-- | A key-value pair for encoding a JSON object.
class KeyValue kv where
    (.=) :: ToJSON v => Text -> v -> kv
    infixr 8 .=

-- | Fail parsing due to a type mismatch, with a descriptive message.
--
-- Example usage:
--
-- @
-- instance FromJSON Coord where
--   parseJSON ('Object' v) = {- type matches, life is good -}
--   parseJSON wat        = 'typeMismatch' \"Coord\" wat
-- @
typeMismatch :: String -- ^ The name of the type you are trying to parse.
             -> Value  -- ^ The actual value encountered.
             -> Parser a
typeMismatch expected actual =
    fail $ "expected " ++ expected ++ ", encountered " ++ name
  where
    name = case actual of
             Object _ -> "Object"
             Array _  -> "Array"
             String _ -> "String"
             Number _ -> "Number"
             Bool _   -> "Boolean"
             Null     -> "Null"


text:
netuitive_rails_agent 1.2.0 (2016-10-21)
-------------------------
* Added whitelist for tuning action controller collection.

netuitive_rails_agent 1.0.4 (2016-10-21)
-------------------------
* Build improvements, including automatic deployment.
* Added docker example.

netuitive_rails_agent 1.0.3 (2016-10-21)
-------------------------
* error proofing

netuitive_rails_agent 1.0.2 (2016-10-17)
-------------------------
* turning request wrapping off by default
* more fault tolerant if a queue time header isn't included when request wrapping is enabled
* fixed a bug where error metric aren't sent if error events are disabled

netuitive_rails_agent 1.0.1 (2016-10-17)
-------------------------
* refactoring of classes into gem namespace to avoid collisions
* External event support
* Action controller error metrics and events
* Sidekiq metrics and events
* Queue time metrics
* Configurable log properties
* Configurable feature flags
* Request time metrics on the controller and global levels


text:
#include "stdafx.h"
#include "ddCheckBox.h"

// ddCheckBox

IMPLEMENT_DYNAMIC(ddCheckBox, CButton)

ddCheckBox::ddCheckBox()
{

}

ddCheckBox::~ddCheckBox()
{
	m_font.DeleteObject();
}

BOOL ddCheckBox::Create( CString str,DWORD dw,CRect rect,CWnd *p,UINT n)
{

	DWORD dw_ = BS_AUTOCHECKBOX | dw;

	return CButton::Create( str, dw_,rect,p,n);//|ES_WANTRETURN|ES_MULTILINE|ES_AUTOVSCROLL
}

BEGIN_MESSAGE_MAP(ddCheckBox, CButton)
	ON_WM_CREATE()
END_MESSAGE_MAP()

// ddCheckBox message handlers

UINT ddCheckBox::WhoAmI()
{
	return this->GetDlgCtrlID();
}

int ddCheckBox::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CButton::OnCreate(lpCreateStruct) == -1)
		return -1;

	m_font.CreatePointFont( 90,"Tahoma");
	SetFont(&m_font);

	return 0;
}


text:
@interface WarnDescribleFaultReasonCell : UITableViewCell

@property(nonatomic,copy)void(^tapActionBlock)(NSString*);

-(void)setCellWithData:(NSDictionary*)dic isManula:(BOOL)ismannual;

@end


text:
/**
 * JS supplement to the Sked PHP calendar library.
 *
 * @see https://github.com/CampusUnion/Sked
 */
(function($) {

    $(document).ready(function(){

        // Pluralize intervals (days, weeks, etc.) based on frequency
        $('.sked-form select[name="frequency"], .sked-form select[name="lead_time_num"]').change(function(){
            var bPlural = $(this).val() !== '1';
            var fnPluralString = function(){
                var strText = $(this).text();
                if (bPlural && strText !== '-' && !strText.match('s$'))
                    $(this).text(strText + 's');
                else if (!bPlural && strText.match('s$'))
                    $(this).text(strText.slice(0, -1));
            };
            $(this).siblings('select').children('option').each(fnPluralString);
        }).change();

        // Only show weekdays for weekly & monthly intervals
        $('.sked-form select[name="interval"]').change(function(){
            var bHide = ($(this).val() === '1' || $(this).val() === '');
            $('[name="weekdays[]"]').prop('disabled', bHide)
                .parents('.sked-input-wrapper')[bHide ? 'hide' : 'show']();
        }).change();

        // Toggle recurring-event fields based on "repeats" checkbox
        $('.sked-form input[name="repeats"]').change(function(){
            if ($(this).is(':checked'))
                $('.sked-input-recurring').show();
            else
                $('.sked-input-recurring').hide();
        }).change();

    });

})(jQuery);

// Tell dependency loaders we're here.
window.skedJsLoaded = true;


text:
#ifndef CHARACTERWIDGET_H
#define CHARACTERWIDGET_H

#include <QFont>
#include <QPoint>
#include <QSize>
#include <QString>
#include <QWidget>

QT_BEGIN_NAMESPACE
class QMouseEvent;
class QPaintEvent;
QT_END_NAMESPACE

//! [0]
class CharacterWidget : public QWidget
{
    Q_OBJECT

public:
    CharacterWidget(QWidget *parent = 0);
    QSize sizeHint() const;

public slots:
    void updateFont(const QFont &font);
    void updateSize(const QString &fontSize);
    void updateStyle(const QString &fontStyle);
    void updateFontMerging(bool enable);

signals:
    void characterSelected(const QString &character);

protected:
    void mouseMoveEvent(QMouseEvent *event);
    void mousePressEvent(QMouseEvent *event);
    void paintEvent(QPaintEvent *event);

private:
    QFont displayFont;
    int columns;
    int lastKey;
    int squareSize;
};
//! [0]

#endif


text:
<?php

namespace Splash\Local\Objects\Invoice;

use ArrayObject;
use Paiement;
use PaiementFourn;
use Splash\Core\SplashCore      as Splash;
use Splash\Local\Local;
use Splash\Local\Services\PaymentManager;

/**
 * Dolibarr Customer/Supplier Invoice Payments Fields
 */
trait PaymentsTrait
{
    //====================================================================//
    // General Class Variables
    //====================================================================//

    /**
     * @var array
     */
    protected $payments = array();

    /**
     * Build Address Fields using FieldFactory
     *
     * @return void
     */
    protected function buildPaymentsFields()
    {
        global $langs;

        $listName = "" ;

        //====================================================================//
        // Payment Line Payment Method
        $this->fieldsFactory()->create(SPL_T_VARCHAR)
            ->identifier("mode")
            ->inList("payments")
            ->name($listName.$langs->trans("PaymentMode"))
            ->microData("http://schema.org/Invoice", "PaymentMethod")
            ->addChoice("ByBankTransferInAdvance", "By bank transfer in advance")
            ->addChoice("CheckInAdvance", "Check in advance")
            ->addChoice("COD", "Cash On Delivery")
            ->addChoice("Cash", "Cash")
            ->addChoice("PayPal", "Online Payments (PayPal, more..)")
            ->addChoice("DirectDebit", "Credit Card")
            ->association("date@payments", "mode@payments", "amount@payments")
        ;
        //====================================================================//
        // Payment Line Date
        $this->fieldsFactory()->create(SPL_T_DATE)
            ->identifier("date")
            ->inList("payments")
            ->name($listName.$langs->trans("Date"))
            ->microData("http://schema.org/PaymentChargeSpecification", "validFrom")
            ->association("date@payments", "mode@payments", "amount@payments")
        ;
        //====================================================================//
        // Payment Line Payment Identifier
        $this->fieldsFactory()->create(SPL_T_VARCHAR)
            ->identifier("number")
            ->inList("payments")
            ->name($listName.$langs->trans('Numero'))
            ->microData("http://schema.org/Invoice", "paymentMethodId")
            ->association("date@payments", "mode@payments", "amount@payments")
        ;
        //====================================================================//
        // Payment Line Amount
        $this->fieldsFactory()->create(SPL_T_DOUBLE)
            ->identifier("amount")
            ->inList("payments")
            ->name($listName.$langs->trans("PaymentAmount"))
            ->microData("http://schema.org/PaymentChargeSpecification", "price")
            ->association("date@payments", "mode@payments", "amount@payments")
        ;
    }

    /**
     * Fetch Invoice Payments List (Done after Load)
     *
     * @param mixed $invoiceId
     * @param bool  $isSupplier
     *
     * @return bool
     */
    protected function loadPayments($invoiceId, bool $isSupplier = false): bool
    {
        global $db;

        //====================================================================//
        // Detect Supplier Invoices Mode
        $isSupplier |= is_a($this, Local::CLASS_SUPPLIER_INVOICE);
        //====================================================================//
        // Prepare SQL Request
        // Payments already done (from payment on this invoice)
        $sql = 'SELECT p.datep as date, p.num_paiement as number, p.rowid as id, p.fk_bank,';
        $sql .= ' c.code as code, c.libelle as payment_label,';
        $sql .= ' pf.amount as amount,';
        $sql .= ' ba.rowid as baid, ba.ref, ba.label';
        $sql .= ' FROM '.MAIN_DB_PREFIX.'c_paiement as c, ' ;
        $sql .= $isSupplier
            ? MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'paiementfourn as p'
            : MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p'
        ;
        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
        $sql .= $isSupplier
            ? ' WHERE pf.fk_facturefourn = '.$invoiceId.' AND p.fk_paiement = c.id AND pf.fk_paiementfourn = p.rowid'
            : ' WHERE pf.fk_facture = '.$invoiceId.' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'
        ;
        $sql .= ' ORDER BY p.rowid';

        //====================================================================//
        // Execute SQL Request
        $result = $db->query($sql);
        if (!$result) {
            $this->catchDolibarrErrors();

            return false;
        }
        //====================================================================//
        // Count Results
        $count = $db->num_rows($result);
        if (0 == $count) {
            return true;
        }
        //====================================================================//
        // Fetch Results
        $index = 0;
        while ($index < $count) {
            $this->payments[$index] = $db->fetch_object($result);
            //====================================================================//
            // Detect Payment Method Type from Default Payment "known" methods
            $this->payments[$index]->method = $this->identifySplashPaymentMethod($this->payments[$index]->code);
            $index ++;
        }
        $db->free($result);

        return true;
    }

    /**
     * Read requested Field
     *
     * @param string $key       Input List Key
     * @param string $fieldName Field Identifier / Name
     *
     * @return void
     */
    protected function getPaymentsFields(string $key, string $fieldName): void
    {
        //====================================================================//
        // Check if List field & Init List Array
        $fieldId = self::lists()->initOutput($this->out, "payments", $fieldName);
        if (!$fieldId) {
            return;
        }
        //====================================================================//
        // Fill List with Data
        foreach ($this->payments as $index => $paymentLine) {
            //====================================================================//
            // READ Fields
            switch ($fieldName) {
                //====================================================================//
                // Payment Line - Payment Mode
                case 'mode@payments':
                    $value = $paymentLine->method;

                    break;
                    //====================================================================//
                    // Payment Line - Payment Date
                case 'date@payments':
                    $value = !empty($paymentLine->date)?dol_print_date($paymentLine->date, '%Y-%m-%d'):null;

                    break;
                    //====================================================================//
                    // Payment Line - Payment Identification Number
                case 'number@payments':
                    $value = $paymentLine->number;

                    break;
                    //====================================================================//
                    // Payment Line - Payment Amount
                case 'amount@payments':
                    $value = self::parsePrice($paymentLine->amount);

                    break;
                default:
                    return;
            }
            //====================================================================//
            // Insert Data in List
            self::lists()->insert($this->out, "payments", $fieldName, $index, $value);
        }
        unset($this->in[$key]);
    }

    /**
     * Write Given Fields
     *
     * @param string $fieldName Field Identifier / Name
     * @param mixed  $fieldData Field Data
     *
     * @return void
     */
    protected function setPaymentLineFields(string $fieldName, $fieldData)
    {
        //====================================================================//
        // Safety Check
        if ("payments" !== $fieldName) {
            return;
        }
        //====================================================================//
        // Verify Lines List & Update if Needed
        if (is_array($fieldData) || is_a($fieldData, "ArrayObject")) {
            foreach ($fieldData as $lineData) {
                $this->setPaymentLineData($lineData);
            }
        }
        //====================================================================//
        // Delete Remaining Lines
        foreach ($this->payments as $paymentData) {
            //====================================================================//
            // Fetch Payment Line Entity
            $payment = $this->newPayment();
            $payment->fetch($paymentData->id);
            //====================================================================//
            // Check If Payment impact another Bill
            if (count($payment->getBillsArray()) > 1) {
                continue;
            }
            //====================================================================//
            // Try to delete Payment Line
            $payment->delete();
        }

        unset($this->in[$fieldName]);
    }

    /**
     * Delete All Invoices Payments (Only Used for Debug in PhpUnit)
     *
     * @param int $invoiceId Invoice Object ID
     *
     * @return void
     */
    protected function clearPayments(int $invoiceId): void
    {
        //====================================================================//
        // Load Invoice Payments
        $this->loadPayments($invoiceId);
        //====================================================================//
        // Delete Remaining Lines
        foreach ($this->payments as $paymentData) {
            //====================================================================//
            // Fetch Payment Line Entity
            $payment = $this->newPayment();
            $payment->fetch($paymentData->id);
            //====================================================================//
            // Check If Payment impact another Bill
            $billArray = $payment->getBillsArray();
            if (is_array($billArray) && count($billArray) > 1) {
                continue;
            }
            //====================================================================//
            // Try to delete Payment Line
            if ($payment->delete() <= 0) {
                $this->catchDolibarrErrors($payment);

                Splash::log()->errTrace("Unable to Delete Invoice Payment (".$paymentData->id.")");
            }
        }
    }

    /**
     * Update a Payment line Data
     *
     * @param array|ArrayObject $lineData Line Data Array
     *
     * @return bool
     */
    private function setPaymentLineData($lineData): bool
    {
        //====================================================================//
        // Read Next Payment Line
        $paymentData = array_shift($this->payments);

        //====================================================================//
        // Existing Line
        //
        // => Update Date & Payment reference (Number)
        // => If Amount is Different, delete Payment & Re-Create
        // => If Payment method is different => Do nothing!!
        //====================================================================//
        if ($paymentData) {
            //====================================================================//
            // Update Payment Infos, If No Need to Re-Create => EXIT
            if (!$this->updatePaymentItem($paymentData->id, $lineData)) {
                return false;
            }
        }

        //====================================================================//
        // Try Multi Invoice Payments Identification
        //====================================================================//
        if ($this->identifyExistingPayment((array) $lineData)) {
            return true;
        }

        //====================================================================//
        // Create New Line
        //====================================================================//
        return $this->createPaymentItem($lineData);
    }

    /**
     * Update an Exiting Payment
     *
     * @param int               $paymentId Payment Item ID
     * @param array|ArrayObject $lineData  Line Data Array
     *
     * @return bool Re-Create Payment Item or Exit?
     */
    private function updatePaymentItem(int $paymentId, $lineData): bool
    {
        //====================================================================//
        // Load Payment Item
        $payment = $this->newPayment();
        $payment->fetch($paymentId);

        //====================================================================//
        // Update Payment Values
        $this->updatePaymentItemDatas($payment, $lineData);

        //====================================================================//
        // Check If Payment impact another Bill => Too Late to Delete & recreate this payment
        if (count($payment->getBillsArray()) > 1) {
            // Payment is Used by Another Bill => No Recreate
            return false;
        }
        //====================================================================//
        // Safety Check => Amount is Defined
        if (!isset($lineData["amount"])) {
            return false;
        }
        //====================================================================//
        // Check If Payment Amount are Different
        if (abs($payment->amount - self::parsePrice($lineData["amount"])) < 1E-6) {
            // Amounts are Similar => No Recreate
            return false;
        }
        //====================================================================//
        // Try to delete Payment
        if ($payment->delete() <= 0) {
            $this->catchDolibarrErrors($payment);

            // Unable to Delete Payment => No Recreate
            return false;
        }
        //====================================================================//
        // Payment Was Deleted => Recreate
        return true;
    }

    /**
     * Update an Exiting Payment Datas
     *
     * @param Paiement|PaiementFourn $payment  Payment Item ID
     * @param array|ArrayObject      $lineData Line Data Array
     *
     * @return void
     */
    private function updatePaymentItemDatas($payment, $lineData)
    {
        //====================================================================//
        // Update Payment Date
        if (isset($lineData["date"])
            && (dol_print_date($payment->datepaye, 'standard') !== $lineData["date"])) {
            $payment->update_date($lineData["date"]);
            $this->catchDolibarrErrors($payment);
        }

        //====================================================================//
        // Update Payment Number
        /** @since V13.0 Field Renamed  */
        $number = (Local::dolVersionCmp("13.0.0") < 0)
            ? $payment->num_paiement
            : $payment->num_payment;
        if (isset($lineData["number"]) && ($number !== $lineData["number"])) {
            $payment->update_num($lineData["number"]);
            $this->catchDolibarrErrors($payment);
        }

        //====================================================================//
        // Update Payment Method
        if (isset($lineData["mode"])) {
            //====================================================================//
            // Detect Payment Method Id
            $newMethodId = $this->identifyPaymentMethod($lineData["mode"]);
            $currentMethodId = $this->identifyPaymentType($payment->type_code);
            if ($newMethodId && ($currentMethodId !== $newMethodId)) {
                $payment->setValueFrom("fk_paiement", $newMethodId);
                $this->catchDolibarrErrors($payment);
            }
        }
    }

    /**
     * Update an Exiting Payment
     *
     * @param array|ArrayObject $lineData Line Data Array
     *
     * @return bool Re-Create Payment Item or Exit?
     */
    private function createPaymentItem($lineData)
    {
        global $user;
        //====================================================================//
        // Verify Minimal Fields Ar available
        if (!isset($lineData["mode"])
            || !isset($lineData["date"])
            || !isset($lineData["amount"])
            || empty((double) $lineData["amount"])) {
            return false;
        }
        $payment = $this->newPayment();
        //====================================================================//
        // Setup Payment Invoice Id
        $payment->facid = $this->object->id;
        //====================================================================//
        // Setup Payment Date
        $payment->datepaye = (new \DateTime($lineData["date"]))->getTimestamp();
        //====================================================================//
        // Setup Payment Method
        $payment->paiementid = $this->identifyPaymentMethod($lineData["mode"]);
        //====================================================================//
        // Setup Payment Reference
        /** @since V13.0 Field Renamed  */
        if (Local::dolVersionCmp("13.0.0") < 0) {
            $payment->num_paiement = $lineData["number"] ?? "";
        } else {
            $payment->num_payment = $lineData["number"] ?? "";
        }
        //====================================================================//
        // Setup Payment Amount
        $payment->amounts[$payment->facid] = self::parsePrice($lineData["amount"]);
        //====================================================================//
        // Take Care of Payment Currency
        if (property_exists($payment, "multicurrency_code")) {
            $payment->multicurrency_code[$payment->facid] = $this->object->multicurrency_code;
        }
        //====================================================================//
        // Create Payment Line
        if ($payment->create($user) <= 0) {
            Splash::log()->errTrace("Unable to create Invoice Payment. ");

            return $this->catchDolibarrErrors($payment);
        }

        //====================================================================//
        // Setup Payment Account Id
        $result = $payment->addPaymentToBank(
            $user,
            'payment',
            '(Payment)',
            $this->identifyBankAccountId($this->identifyPaymentMethod($lineData["mode"])),
            "",
            ""
        );

        if ($result < 0) {
            Splash::log()->errTrace("Unable to add Invoice Payment to Bank Account.");

            return $this->catchDolibarrErrors($payment);
        }

        return true;
    }

    /**
     * Create a New Payment Object
     *
     * @return Paiement|PaiementFourn
     */
    private function newPayment()
    {
        global $db;
        static $isInitDone;

        if (!isset($isInitDone)) {
            //====================================================================//
            // Include Object Dolibarr Class
            require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
            require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
            require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
            $isInitDone = true;
        }

        return is_a($this, Local::CLASS_SUPPLIER_INVOICE) ? new PaiementFourn($db) : new Paiement($db);
    }

    /**
     * Write Given Fields
     *
     * @param string $methodType
     *
     * @return string
     *
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    private function identifySplashPaymentMethod(string $methodType)
    {
        //====================================================================//
        // Detect Payment Method Type from Default Payment "known" methods
        switch ($methodType) {
            case "PRE":
            case "PRO":
            case "TIP":
            case "VIR":
                return "ByBankTransferInAdvance";
            case "CHQ":
                return "CheckInAdvance";
            case "FAC":
                return "COD";
            case "LIQ":
                return "Cash";
            case "CB":
                return "DirectDebit";
            case "VAD":
                return "PayPal";
            default:
                return "Unknown";
        }
    }

    /**
     * Write Given Fields
     *
     * @param string $methodType
     *
     * @return int
     *
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    private function identifyPaymentMethod(string $methodType)
    {
        global $conf;

        //====================================================================//
        // Detect Payment Method Type from Default Payment "known/standard" methods
        switch ($methodType) {
            case "ByBankTransferInAdvance":
                return $this->identifyPaymentType("VIR");
            case "CheckInAdvance":
                return $this->identifyPaymentType("CHQ");
            case "COD":
                return $this->identifyPaymentType("FAC");
            case "Cash":
                return $this->identifyPaymentType("LIQ");
            case "PayPal":
                return $this->identifyPaymentType("VAD");
            case "CreditCard":
            case "DirectDebit":
                return $this->identifyPaymentType("CB");
        }

        //====================================================================//
        // Return Default Payment Method or 0 (Default)
        if (isset($conf->global->SPLASH_DEFAULT_PAYMENT) && !empty($conf->global->SPLASH_DEFAULT_PAYMENT)) {
            return $this->identifyPaymentType($conf->global->SPLASH_DEFAULT_PAYMENT);
        }

        return $this->identifyPaymentType("VAD");
    }

    /**
     * Identify Payment Method ID using Payment Method Code
     *
     * @param string $paymentTypeCode Payment Method Code
     *
     * @return int
     */
    private function identifyPaymentType(string $paymentTypeCode)
    {
        global $db;

        //====================================================================//
        // Include Object Dolibarr Class
        require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
        $form = new \Form($db);
        $form->load_cache_types_paiements();
        //====================================================================//
        // Safety Check
        if (empty($form->cache_types_paiements)) {
            return 0;
        }
        //====================================================================//
        // Detect Payment Method Id From Method Code
        foreach ($form->cache_types_paiements as $key => $paymentMethod) {
            if ($paymentMethod["code"] === $paymentTypeCode) {
                return $key;
            }
        }
        //====================================================================//
        // Default Payment Method Id
        return 0;
    }

    /**
     * Identify Bank Account ID using Splash Configuration
     *
     * @param int $paymentTypeId Payment Method ID
     *
     * @return int
     */
    private function identifyBankAccountId(int $paymentTypeId)
    {
        global $conf;

        //====================================================================//
        // Detect Bank Account Id From Method Code
        $parameterName = "SPLASH_BANK_FOR_".$paymentTypeId;
        if (isset($conf->global->{$parameterName}) && !empty($conf->global->{$parameterName})) {
            return $conf->global->{$parameterName};
        }

        //====================================================================//
        // Default Payment Account Id
        return $conf->global->SPLASH_BANK;
    }

    /**
     * Identify Bank Account ID using Splash Configuration
     *
     * @param array $lineData Payment Line data
     *
     * @return null|Paiement
     */
    private function identifyExistingPayment($lineData): ?Paiement
    {
        //====================================================================//
        // Search for Similar Payment in Database
        $payment = $this->getSimilarPayment($lineData);
        if (!$payment) {
            return null;
        }
        //====================================================================//
        // Collect Payment Invoice/Credit Paid Totals
        $paymentDetails = PaymentManager::getPaymentInvoicesTotals($payment);
        if (!$paymentDetails || isset($paymentDetails[$this->object->id])) {
            return null;
        }
        //====================================================================//
        // Attach Payment to this Invoice/Credit Note
        Splash::log()->war("An Existing Payment was Identified: ".$payment->ref);
        //====================================================================//
        // Update Payment Amounts for All Invoice/Credit Note
        $consumed = $payment->amount;
        foreach ($paymentDetails as $paymentDetail) {
            PaymentManager::updatePaymentInvoiceAmount(
                $payment,
                $paymentDetail['invoice'],
                (float) $paymentDetail['invoiced']
            );
            $consumed -= (float) $paymentDetail['invoiced'];
        }
        //====================================================================//
        // Add Remaining Amount to Current Invoice
        PaymentManager::addPaymentInvoiceAmount(
            $payment,
            $this->object,
            (float) $consumed
        );
        //====================================================================//
        // Return Identified Payment
        return $payment;
    }

    /**
     * Search for Similar Payment based on Inputs
     *
     * @param array $lineData Payment Line data
     *
     * @return null|Paiement
     */
    private function getSimilarPayment(array $lineData): ?Paiement
    {
        //====================================================================//
        // Safety Checks
        if (is_a($this, Local::CLASS_SUPPLIER_INVOICE)
            || empty($lineData["mode"])
            || empty($lineData["date"])
            || empty($lineData["number"])
            || empty($lineData["amount"])) {
            return null;
        }
        //====================================================================//
        // Return Identified Payment
        return PaymentManager::searchForSimilarPayment(
            $lineData["date"],
            $lineData["number"],
            (float) $lineData["amount"],
            $this->identifyPaymentMethod($lineData["mode"])
        );
    }
}


text:
namespace Homework_Defining_Classes___Part_1
{
    public class Battery
    {
        private string model;
        private string hoursIdle;
        private decimal hoursTalk;
        private enum BatteryType
        {
            LiIon,
            NiMH,
            NiCd
        }
        public Battery(string model,string hoursIdle,decimal hoursTalk)
        {
            this.model = model;
            this.hoursIdle = hoursIdle;
            this.hoursTalk = hoursTalk;
        }
        public string Model
        {
            get
            {
                return this.model;
            }
            set
            {
                this.model = value;
            }
        }
        public string HoursIdle
        {
            get
            {
                return this.HoursIdle;
            }
            set
            {
                this.HoursIdle = value;
            }
        }

    }
}


text:
<!DOCTYPE html>

    <title>W5 - Sync Promises Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="../bower_components/w5/dist/css/w5.min.css">


text:
<?php

/**
 * Doctrine_Ticket_1524_TestCase
 *
 * @package     Doctrine
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @category    Object Relational Mapping
 * @link        www.doctrine-project.org
 * @since       1.0
 * @version     $Revision$
 */
class Doctrine_Ticket_1524_TestCase extends Doctrine_UnitTestCase
{
    public function testTest()
    {
        $manager = Doctrine_Manager::getInstance();
        $manager->registerValidators('MyValidator');
        $this->assertTrue(in_array('MyValidator', $manager->getValidators()));
    }
}

class MyValidator extends Doctrine_Validator
{
    public function validate($value)
    {
        return true;
    }
}


text:
/**@file tmsrp_event.c
 * @brief MSRP/MSRPS Event.
 *
 * @author Mamadou Diop <diopmamadou(at)doubango.org>
 *

 */
#include "tinymsrp/tmsrp_event.h"

#include "tsk_debug.h"

tmsrp_event_t* tmsrp_event_create(const void* callback_data, tsk_bool_t outgoing, tmsrp_event_type_t type, tmsrp_message_t* message)
{
	tmsrp_event_t* _event;
	if((_event = tsk_object_new(tmsrp_event_def_t))){
		_event->callback_data = callback_data;
		_event->outgoing = outgoing;
		_event->type = type;
		_event->message = tsk_object_ref(message);
	}
	else{
		TSK_DEBUG_ERROR("Faile to create new MSRP event");
	}

	return _event;
}

//========================================================
//	MSRP Event definition
//

/**@ingroup tmsrp_event_group
*/
static tsk_object_t* tmsrp_event_ctor(tsk_object_t *self, va_list * app)
{
	tmsrp_event_t *_event = self;
	if(_event){
	}
	else{
		TSK_DEBUG_ERROR("Failed to create new MSRP Event");
	}
	return self;
}

/**@ingroup tmsrp_event_group
*/
static tsk_object_t* tmsrp_event_dtor(tsk_object_t *self)
{
	tmsrp_event_t *_event = self;
	if(_event){
		TSK_OBJECT_SAFE_FREE(_event->message);
	}
	else{
		TSK_DEBUG_ERROR("Null MSRP Event");
	}

	return self;
}

static const tsk_object_def_t tmsrp_event_def_s =
{
	sizeof(tmsrp_event_t),
	tmsrp_event_ctor,
	tmsrp_event_dtor,
	tsk_null
};
const tsk_object_def_t *tmsrp_event_def_t = &tmsrp_event_def_s;


text:
/**
 * @author TristanVALCKE / https://github.com/Itee
 */
/* global QUnit */

import { NumberKeyframeTrack } from '../../../../../src/animation/tracks/NumberKeyframeTrack';

export default QUnit.module( 'Animation', () => {

	QUnit.module( 'Tracks', () => {

		QUnit.module( 'NumberKeyframeTrack', () => {

			QUnit.todo( 'write me !', ( assert ) => {

				assert.ok( false, "everything's gonna be alright" );

			} );

		} );

	} );

} );


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Runtime.InteropServices;

namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop
{
    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("93615958-1FA4-4d6a-AA14-CB3B9A6B08AC")]
    internal interface ICSCompileProgress
    {
        // members not ported
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: stas
 * Date: 11.04.16
 * Time: 22:15
 */
namespace CoreBundle\Model\Tournament;

use CoreBundle\Entity\Tournament;

/**
 * Class SwissService
 * @package CoreBundle\Service
 */
interface TournamentDrawInterface
{
    /**
     * @param Tournament $tournament
     * @param int $round
     * @return void
     */
    public function makeDraw(Tournament $tournament, int $round);

    /**
     * @param Tournament $tournament
     * @return void
     */
    public function makeDrawForNextRound(Tournament $tournament);
}


text:
package org.jboss.mass.mat.xml.dependencyscriptor;

public class Inbound {

	private String type;
	private String confirmed;
	private String value;

	public Inbound(String type, String confirmed) {
		this.type = type;
		this.confirmed = confirmed;
	}

	public String getType() {
		return type;
	}

	public String getConfirmed() {
		return confirmed;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
}


text:
<?php

declare(strict_types=1);

namespace Doctrine\Migrations;

use Doctrine\DBAL\Connection;
use Doctrine\Migrations\Metadata\MigrationPlanList;
use Doctrine\Migrations\Query\Query;
use Doctrine\Migrations\Tools\BytesFormatter;
use Doctrine\Migrations\Version\Executor;
use Psr\Log\LoggerInterface;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\Stopwatch\StopwatchEvent;
use Throwable;
use function count;
use const COUNT_RECURSIVE;

/**
 * The DbalMigrator class is responsible for generating and executing the SQL for a migration.
 *
 * @internal
 */
class DbalMigrator implements Migrator
{
    /** @var Stopwatch */
    private $stopwatch;

    /** @var LoggerInterface */
    private $logger;

    /** @var Executor */
    private $executor;

    /** @var Connection */
    private $connection;

    /** @var EventDispatcher */
    private $dispatcher;

    public function __construct(
        Connection $connection,
        EventDispatcher $dispatcher,
        Executor $executor,
        LoggerInterface $logger,
        Stopwatch $stopwatch
    ) {
        $this->stopwatch  = $stopwatch;
        $this->logger     = $logger;
        $this->executor   = $executor;
        $this->connection = $connection;
        $this->dispatcher = $dispatcher;
    }

    /**
     * @return array<string, Query[]>
     */
    private function executeMigrations(
        MigrationPlanList $migrationsPlan,
        MigratorConfiguration $migratorConfiguration
    ) : array {
        $allOrNothing = $migratorConfiguration->isAllOrNothing();

        if ($allOrNothing) {
            $this->connection->beginTransaction();
        }

        try {
            $this->dispatcher->dispatchMigrationEvent(Events::onMigrationsMigrating, $migrationsPlan, $migratorConfiguration);

            $sql = $this->executePlan($migrationsPlan, $migratorConfiguration);

            $this->dispatcher->dispatchMigrationEvent(Events::onMigrationsMigrated, $migrationsPlan, $migratorConfiguration);
        } catch (Throwable $e) {
            if ($allOrNothing) {
                $this->connection->rollBack();
            }

            throw $e;
        }

        if ($allOrNothing) {
            $this->connection->commit();
        }

        return $sql;
    }

    /**
     * @return array<string, Query[]>
     */
    private function executePlan(MigrationPlanList $migrationsPlan, MigratorConfiguration $migratorConfiguration) : array
    {
        $sql  = [];
        $time = 0;

        foreach ($migrationsPlan->getItems() as $plan) {
            $versionExecutionResult = $this->executor->execute($plan, $migratorConfiguration);

            // capture the to Schema for the migration so we have the ability to use
            // it as the from Schema for the next migration when we are running a dry run
            // $toSchema may be null in the case of skipped migrations
            if (! $versionExecutionResult->isSkipped()) {
                $migratorConfiguration->setFromSchema($versionExecutionResult->getToSchema());
            }

            $sql[(string) $plan->getVersion()] = $versionExecutionResult->getSql();
            $time                             += $versionExecutionResult->getTime();
        }

        return $sql;
    }

    /**
     * @param array<string, Query[]> $sql
     */
    private function endMigrations(
        StopwatchEvent $stopwatchEvent,
        MigrationPlanList $migrationsPlan,
        array $sql
    ) : void {
        $stopwatchEvent->stop();

        $this->logger->notice(
            'finished in {duration}ms, used {memory} memory, {migrations_count} migrations executed, {queries_count} sql queries',
            [
                'duration' => $stopwatchEvent->getDuration(),
                'memory' => BytesFormatter::formatBytes($stopwatchEvent->getMemory()),
                'migrations_count' => count($migrationsPlan),
                'queries_count' => count($sql, COUNT_RECURSIVE) - count($sql),
            ]
        );
    }

    /**
     * {@inheritDoc}
     */
    public function migrate(MigrationPlanList $migrationsPlan, MigratorConfiguration $migratorConfiguration) : array
    {
        if (count($migrationsPlan) === 0) {
            $this->logger->notice('No migrations to execute.');

            return [];
        }

        $stopwatchEvent = $this->stopwatch->start('migrate');

        $sql = $this->executeMigrations($migrationsPlan, $migratorConfiguration);

        $this->endMigrations($stopwatchEvent, $migrationsPlan, $sql);

        return $sql;
    }
}


text:
/*
 * Exemplo 8.1
 * Livro: Aprenda a programar com C#
 * Autores: Antonio Trigo e Jorge Henriques
 * Disponível em: http://www.silabo.pt
*/

using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = new int[] { 10, 20, 30, 40, 50 };
            Console.WriteLine(a[3]); //Mostra o elemento 40
            Console.Write("Insira um valor para a terceira posicao:");
            a[2] = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(a[2]); //Mostra o valor inserido
        }
    }
}


text:
/**
 * CLIs for administering OFAgents.
 */
package org.onosproject.ofagent.cli;


text:
layout: default
---

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

        <meta name="viewport" content="width=device-width">

<link href="{{ site.baseurl }}/css/lightbox.css" rel="stylesheet" />

{% assign post = page %}

{{ page.title }}

                    {% if page.subtitle %}

{{ page.subtitle }}

                    {% endif %}
                    Posted on {{ page.date | date: "%B %-d, %Y" }} by {{ post.author }}

{% assign minutes = content | number_of_words | divided_by: 180 %}
 {% if minutes == 0 %}{% assign minutes = 1 %}{% endif %}
{{ minutes }} minute read

 {% if post.tags.size > 0 %}
  ∼ Tagged with {% if post.tags.size == 1 %} {% else %}{% endif %} :
{% for tag in page.tags %}{{ tag }}{% unless forloop.last %} • {% endunless %}{% endfor %}{% endif %}

          {% if post.categories.size > 0 %}

                           ∼ Filed in {% if post.categories.size == 1 %} {% else %}{% endif %} : {% for tag in page.categories %}{{ tag }}{% unless forloop.last %} • {% endunless %}{% endfor %%}{% endif %}

               				{{ content }}

               {% include signoff.html %}

 {% if site.share %}{% include share.html %}{% endif %}

{% if site.comments %}{% include disqus_comments.html %}{% endif %}

                    {% if page.previous.url %}

                        ← Previous Post

                    {% endif %}
                    {% if page.next.url %}

                        Next Post →

                    {% endif %}


text:
<?php

// Check to ensure this file is included in Joomla!
defined ( '_JEXEC' ) or die ( 'Restricted access' );

	if ($this->category->haschildren) {
	    $iCol = 1;
	    $iCategory = 1;
	    $categories_per_row = VmConfig::get('categories_per_row', 3);
	    $category_cellwidth = ' width' . floor(100 / $categories_per_row);
	    $verticalseparator = " vertical-separator";
	    ?>

		<?php
		// Start the Output
		if (!empty($this->category->children)) {
		    foreach ($this->category->children as $category) {

			// Show the horizontal seperator
			if ($iCol == 1 && $iCategory > $categories_per_row) {
			    ?>

			    <?php
			}

			// this is an indicator whether a row needs to be opened or not
			if ($iCol == 1) {
			    ?>

				<?php
			    }

			    // Show the vertical seperator
			    if ($iCategory == $categories_per_row or $iCategory % $categories_per_row == 0) {
				$show_vertical_separator = ' ';
			    } else {
				$show_vertical_separator = $verticalseparator;
			    }

			    // Category Link
			    $caturl = JRoute::_('index.php?option=com_virtuemart&view=category&virtuemart_category_id=' . $category->virtuemart_category_id, FALSE);

			    // Show Category
			    ?>
			    <div class="category floatleft<?php echo $category_cellwidth . $show_vertical_separator ?>">

					<a href="<?php echo $caturl ?>" title="<?php echo vmText::_($category->category_name) ?>">
					    <?php echo vmText::_($category->category_name) ?>

					    <?php
					    // if ($category->ids) {
					    echo $category->images[0]->displayMediaThumb("", false);
					    //}
					    ?>

			    <?php
			    $iCategory++;

			    // Do we need to close the current row now?
			    if ($iCol == $categories_per_row) {
				?>

			    <?php
			    $iCol = 1;
			} else {
			    $iCol++;
			}
		    }
		}
		// Do we need a final closing row tag?
		if ($iCol != 1) {
		    ?>

	<?php } ?>

    <?php }


text:
package com.junjun.myblog.domain;

import java.util.List;

/**
 * 博客类型
 *
 * @author jun
 *
 */
public class BlogType {

	private Integer id;//博客类型id
	private String typeName;//类型名
	private String orderNum;//排序

	//数据库中没有的字段
	private Integer blogTypeCount;// 每个类型所拥有的博客数量

	private List<Blog> blogs;//一个博客类型可对应多篇博客

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getTypeName() {
		return typeName;
	}

	public void setTypeName(String typeName) {
		this.typeName = typeName;
	}

	public String getOrderNum() {
		return orderNum;
	}

	public void setOrderNum(String orderNum) {
		this.orderNum = orderNum;
	}

	public Integer getBlogTypeCount() {
		return blogTypeCount;
	}

	public void setBlogTypeCount(Integer blogTypeCount) {
		this.blogTypeCount = blogTypeCount;
	}

	public List<Blog> getBlogs() {
		return blogs;
	}

	public void setBlogs(List<Blog> blogs) {
		this.blogs = blogs;
	}

	@Override
	public String toString() {
		return "BlogType [id=" + id + ", typeName=" + typeName + ", orderNum=" + orderNum + ", blogTypeCount="
				+ blogTypeCount + "]";
	}

}


text:
#ifndef SIDECAR_GUI_STREAMITEM_H // -*- C++ -*-
#define SIDECAR_GUI_STREAMITEM_H

#include "IO/StreamStatus.h"

#include "CollectionItem.h"

namespace Logger {
class Log;
}
namespace XmlRpc {
class XmlRpcValue;
}

namespace SideCar {
namespace GUI {
namespace Master {

class RunnerItem;
class TaskItem;

/** TreeViewItem that represents an IO::Stream object of a runner process. An IO::Stream contains IO::Modules,
    which is a simple container for an IO::Task object.
*/
class StreamItem : public CollectionItem {
    Q_OBJECT
    using Super = CollectionItem;

public:
    static Logger::Log& Log();

    /** Constructor.

        \param status initial status value of the item

        \param parent parent node for this item
    */
    StreamItem(const IO::StreamStatus& status, RunnerItem* parent);

    /** Obtain the item's RunnerItem parent.

        \return RunnerItem object
    */
    RunnerItem* getParent() const;

    /** Obtain a TaskItem child.

        \param index which TaskItem to fetch

        \return TaskItem object
    */
    TaskItem* getChild(int index) const;

    /** Obtain an XML description of the runtime parameter values for a particular child TaskItem.

        \param taskIndex which TaskItem to work with

        \param definition XML container update with the XML description

        \return true if successful
    */
    bool getParameters(int taskIndex, XmlRpc::XmlRpcValue& definition) const;

    /** Change one or more runtime parameter values of a particular child TaskItem.

        \param taskIndex which TaskItem to work with

        \param definition XML container containing the parameter changes to
        apply

        \return true if successful
    */
    bool setParameters(int taskIndex, const XmlRpc::XmlRpcValue& updates) const;

    void formatChangedParameters(const XmlRpc::XmlRpcValue& definitions, QStringList& changes) const;

private:
    /** Obtain the type-cast status container sent by a IO::Streams object.

        \return read-only IO::StreamStatus reference
    */
    const IO::StreamStatus& getStatus() const { return static_cast<const IO::StreamStatus&>(Super::getStatus()); }

    /** Update the status for the tasks managed by the stream.
     */
    void updateChildren();

    int streamIndex_;
};

} // end namespace Master
} // end namespace GUI
} // end namespace SideCar

/** \file
 */

#endif


text:
export function Foo(props) {
  props.foo;
  return <div />;
}
Foo.propTypes = {
  foo: React.PropTypes.string.isRequired
};


text:
* Do not use `CoreObject`
* Derive from broccoli-plugin base class

# 0.2.3

* Make `new` operator optional
* Use [new `.rebuild` API](https://github.com/broccolijs/broccoli/blob/master/docs/new-rebuild-api.md)
* Avoid mutating array arguments

# 0.2.2

No changelog beyond this point. Here be dragons.


text:
!
! This file is released under terms of BSD license
! See LICENSE file for more information
!

module imaginary_module
end module imaginary_module


text:
<?php

namespace Mvc\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Message
 *
 * @ORM\Table(name="messages")
 * @ORM\Entity(repositoryClass="Mvc\BlogBundle\Entity\MessageRepository")
 */
class Message
{

    /*---------------------------
    -----------------------------
        PROPERTIES
    -----------------------------
    ---------------------------*/

    /**
     * @ORM\ManyToOne(targetEntity="Mvc\UserBundle\Entity\User", inversedBy="messages")
     * @ORM\JoinColumn(nullable=false)
     */
    private $user;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="message", type="string", length=140)
     * @Assert\NotBlank()
     * @Assert\Length(max=140)
     */
    private $message;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="createdAt", type="datetime")
     */
    private $createdAt;

    /*---------------------------
    -----------------------------
        CONSTRUCTOR
    -----------------------------
    ---------------------------*/
    public function __construct()
    {
        $this->createdAt = new \Datetime();
    }

    /*---------------------------
    -----------------------------
        GETTERS & SETTERS
    -----------------------------
    ---------------------------*/

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set message
     *
     * @param string $message
     * @return Message
     */
    public function setMessage($message)
    {
        $this->message = $message;

        return $this;
    }

    /**
     * Get message
     *
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return Message
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set user
     *
     * @param \Mvc\UserBundle\Entity\User $user
     * @return Message
     */
    public function setUser(\Mvc\UserBundle\Entity\User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \Mvc\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}