text:
using NLight.Core;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;

namespace NLight.Text
{
	public class StringValueConverter
	{
		private string[] _expectedDateTimeFormats;

		public StringValueConverter()
		{
			_expectedDateTimeFormats = new string[] { };

			this.DateTimeStyles = DateTimeStyles.None;
			this.DateTimeConversionOption = ConversionOption.Loose;
			this.IntegerNumberStyles = NumberStyles.Integer;
			this.FloatingPointNumberStyles = NumberStyles.Float;
		}

		public ConversionOption DateTimeConversionOption { get; set; }
		public DateTimeStyles DateTimeStyles { get; set; }
		public NumberStyles IntegerNumberStyles { get; set; }
		public NumberStyles FloatingPointNumberStyles { get; set; }

		public string[] GetExpectedDateTimeFormats()
		{
			return _expectedDateTimeFormats == null ? null : (string[]) _expectedDateTimeFormats.Clone();
		}

		public void SetExpectedDateTimeFormats(params string[] formats)
		{
			if (formats == null) throw new ArgumentNullException(nameof(formats));

			var copy = new string[formats.Length];
			Array.Copy(formats, copy, formats.Length);

			Interlocked.Exchange(ref _expectedDateTimeFormats, copy);
		}

		public void SetExpectedDateTimeFormats(IEnumerable<string> formats)
		{
			var list = new List<string>(formats);
			Interlocked.Exchange(ref _expectedDateTimeFormats, list.ToArray());
		}

		private static string TrimWhiteSpaces(string value, TrimmingOptions options)
		{
			if (!string.IsNullOrEmpty(value))
			{
				if ((options & TrimmingOptions.Both) == TrimmingOptions.Both)
					value = value.Trim();
				else if ((options & TrimmingOptions.End) == TrimmingOptions.End)
					value = value.TrimEnd();
				else if ((options & TrimmingOptions.Start) == TrimmingOptions.Start)
					value = value.TrimStart();
			}

			return value;
		}

		#region ConvertFrom

		public string ConvertFrom(object value, string nullString = "", string format = null, IFormatProvider culture = null)
		{
			if (value == null || Convert.IsDBNull(value))
				return nullString;
			else if (value is string)
				return (string) value;
			else
			{
				if (culture == null)
					culture = CultureInfo.CurrentCulture;

				TypeCode typeCode = Type.GetTypeCode(value.GetType());

				switch (typeCode)
				{
					case TypeCode.DateTime:
						if (string.IsNullOrEmpty(format))
							return Convert.ToString((DateTime) value, culture);
						else
							return string.Format(culture, "{0:" + format + "}", value);

					default:
						if (string.IsNullOrEmpty(format))
							return System.Convert.ToString(value, culture);
						else
							return string.Format(culture, "{0:" + format + "}", value);
				}
			}
		}

		#endregion

		#region ConvertTo

		private static object TryOrThrow(bool success, string input, object value, Type dataType)
		{
			return success ? value : throw new FormatException(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionMessages.Text_CannotConvertToDataType, input, dataType));
		}

		private static T TryOrThrow<T>(bool success, string input, T value)
		{
			return success ? value : throw new FormatException(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionMessages.Text_CannotConvertToDataType, input, typeof(T)));
		}

		#region Untyped

		public T ConvertTo<T>(string input, TrimmingOptions trimWhiteSpaces, T defaultValue) => ConvertTo<T>(input, trimWhiteSpaces, defaultValue, null);
		public T ConvertTo<T>(string input, TrimmingOptions trimWhiteSpaces, T defaultValue, IFormatProvider culture) => (T) ConvertTo(input, trimWhiteSpaces, typeof(T), defaultValue, culture);

		public bool TryConvertTo<T>(string input, TrimmingOptions trimWhiteSpaces, T defaultValue, out T value) => TryConvertTo<T>(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertTo<T>(string input, TrimmingOptions trimWhiteSpaces, T defaultValue, IFormatProvider culture, out T value)
		{
			object result;

			if (TryConvertTo(input, trimWhiteSpaces, typeof(T), defaultValue, culture, out result))
			{
				value = (T) result;
				return true;
			}
			else
			{
				value = default(T);
				return false;
			}
		}

		public object ConvertTo(string input, TrimmingOptions trimWhiteSpaces, Type dataType, object defaultValue) => ConvertTo(input, trimWhiteSpaces, dataType, defaultValue, null);
		public object ConvertTo(string input, TrimmingOptions trimWhiteSpaces, Type dataType, object defaultValue, IFormatProvider culture)
		{
			object value;
			return TryOrThrow(TryConvertTo(input, trimWhiteSpaces, dataType, defaultValue, culture, out value), input, value, dataType);
		}

		public bool TryConvertTo(string input, TrimmingOptions trimWhiteSpaces, Type dataType, object defaultValue, out object value) => TryConvertTo(input, trimWhiteSpaces, dataType, defaultValue, null, out value);
		public bool TryConvertTo(string input, TrimmingOptions trimWhiteSpaces, Type dataType, object defaultValue, IFormatProvider culture, out object value)
		{
			if (dataType == null) throw new ArgumentNullException(nameof(dataType));

			if (culture == null)
				culture = CultureInfo.CurrentCulture;

			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (dataType == typeof(string))
			{
				if (string.IsNullOrEmpty(input))
					value = defaultValue;
				else
					value = input;

				return true;
			}

			TypeCode typeCode;

			Type underlyingType = Nullable.GetUnderlyingType(dataType);

			if (underlyingType != null)
			{
				if (string.IsNullOrEmpty(input))
				{
					value = defaultValue;
					return true;
				}

				dataType = underlyingType;
				typeCode = Type.GetTypeCode(dataType);
			}
			else
			{
				if (string.IsNullOrEmpty(input))
					return false;

				typeCode = Type.GetTypeCode(dataType);
			}

			// Handle the case where the provided default value is null,
			// so the casts are not failing when calling the specific conversion methods below.
			// The corner case where the value is empty/null and the default value is also null has been handled already in the code above.
			if (defaultValue == null && dataType.IsValueType)
				defaultValue = Activator.CreateInstance(dataType);

			if (dataType.IsEnum)
				return TryConvertToEnum(dataType, input, trimWhiteSpaces, (Enum) defaultValue, culture, out value);
			else if (dataType == typeof(Guid))
			{
				Guid output;

				if (!TryConvertToGuid(input, trimWhiteSpaces, (Guid) defaultValue, culture, out output))
					return false;

				value = output;
				return true;
			}

			switch (typeCode)
			{
				// TypeCode.String has already been handled earlier

				// most probable conversions first

				case TypeCode.Int32:
					{
						Int32 output;
						if (!TryConvertToInt32(input, trimWhiteSpaces, (Int32) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.Int64:
					{
						Int64 output;
						if (!TryConvertToInt64(input, trimWhiteSpaces, (Int64) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.Double:
					{
						Double output;
						if (!TryConvertToDouble(input, trimWhiteSpaces, (Double) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.Decimal:
					{
						Decimal output;
						if (!TryConvertToDecimal(input, trimWhiteSpaces, (Decimal) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.DateTime:
					{
						DateTime output;
						if (!TryConvertToDateTime(input, trimWhiteSpaces, (DateTime) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.Boolean:
					{
						Boolean output;
						if (!TryConvertToBoolean(input, trimWhiteSpaces, (Boolean) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.Single:
					{
						Single output;
						if (!TryConvertToSingle(input, trimWhiteSpaces, (Single) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.Int16:
					{
						Int16 output;
						if (!TryConvertToInt16(input, trimWhiteSpaces, (Int16) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.Byte:
					{
						Byte output;
						if (!TryConvertToByte(input, trimWhiteSpaces, (Byte) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.SByte:
					{
						SByte output;
						if (!TryConvertToSByte(input, trimWhiteSpaces, (SByte) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.UInt16:
					{
						UInt16 output;
						if (!TryConvertToUInt16(input, trimWhiteSpaces, (UInt16) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.UInt32:
					{
						UInt32 output;
						if (!TryConvertToUInt32(input, trimWhiteSpaces, (UInt32) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.UInt64:
					{
						UInt64 output;
						if (!TryConvertToUInt64(input, trimWhiteSpaces, (UInt64) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				case TypeCode.Char:
					{
						Char output;
						if (!TryConvertToChar(input, trimWhiteSpaces, (Char) defaultValue, culture, out output))
							return false;

						value = output;
						return true;
					}

				// unsupported conversions
				case TypeCode.Object:
				case TypeCode.DBNull:
				case TypeCode.Empty:
				default:
					throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionMessages.Text_ConversionNotSupported, typeof(string), dataType), "dataType");
			}
		}

		#endregion

		#region Typed

		#region Boolean

		public Boolean ConvertToBoolean(string input, TrimmingOptions trimWhiteSpaces, Boolean defaultValue) => ConvertToBoolean(input, trimWhiteSpaces, defaultValue, null);
		public Boolean ConvertToBoolean(string input, TrimmingOptions trimWhiteSpaces, Boolean defaultValue, IFormatProvider culture) { Boolean value; return TryOrThrow(TryConvertToBoolean(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public Boolean? ConvertToNullableBoolean(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableBoolean(input, trimWhiteSpaces, null);
		public Boolean? ConvertToNullableBoolean(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { Boolean? value; return TryOrThrow(TryConvertToNullableBoolean(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToBoolean(string input, TrimmingOptions trimWhiteSpaces, Boolean defaultValue, out Boolean value) => TryConvertToBoolean(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableBoolean(string input, TrimmingOptions trimWhiteSpaces, out Boolean? value) => TryConvertToNullableBoolean(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToBoolean(string input, TrimmingOptions trimWhiteSpaces, Boolean defaultValue, IFormatProvider culture, out Boolean value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else
			{
				int intValue;

				if (Int32.TryParse(input, NumberStyles.None, culture, out intValue))
					value = (intValue != 0);
				else if (!Boolean.TryParse(input, out value))
					return false;
			}

			return true;
		}

		public bool TryConvertToNullableBoolean(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out Boolean? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				Boolean output;
				int intValue;

				if (Int32.TryParse(input, NumberStyles.None, culture, out intValue))
					output = (intValue != 0);
				else if (!Boolean.TryParse(input, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region Char

		public Char ConvertToChar(string input, TrimmingOptions trimWhiteSpaces, Char defaultValue) => ConvertToChar(input, trimWhiteSpaces, defaultValue, null);
		public Char ConvertToChar(string input, TrimmingOptions trimWhiteSpaces, Char defaultValue, IFormatProvider culture) { Char value; return TryOrThrow(TryConvertToChar(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public Char? ConvertToNullableChar(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableChar(input, trimWhiteSpaces, null);
		public Char? ConvertToNullableChar(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { Char? value; return TryOrThrow(TryConvertToNullableChar(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToChar(string input, TrimmingOptions trimWhiteSpaces, Char defaultValue, out Char value) => TryConvertToChar(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableChar(string input, TrimmingOptions trimWhiteSpaces, out Char? value) => TryConvertToNullableChar(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToChar(string input, TrimmingOptions trimWhiteSpaces, Char defaultValue, IFormatProvider culture, out Char value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!Char.TryParse(input, out value))
				return false;

			return true;
		}

		public bool TryConvertToNullableChar(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out Char? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				Char output;
				if (!Char.TryParse(input, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region Enumeration

		public T ConvertToEnum<T>(string input, TrimmingOptions trimWhiteSpaces, T defaultValue) where T : struct => ConvertToEnum<T>(input, trimWhiteSpaces, defaultValue, null);
		public T ConvertToEnum<T>(string input, TrimmingOptions trimWhiteSpaces, T defaultValue, IFormatProvider culture) where T : struct { T value; return TryOrThrow<T>(TryConvertToEnum<T>(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public T ConvertToNullableEnum<T>(string input, TrimmingOptions trimWhiteSpaces, T defaultValue) where T : struct => ConvertToEnum<T>(input, trimWhiteSpaces, defaultValue, null);
		public T ConvertToNullableEnum<T>(string input, TrimmingOptions trimWhiteSpaces, T defaultValue, IFormatProvider culture) where T : struct { T value; return TryOrThrow<T>(TryConvertToEnum<T>(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public bool TryConvertToEnum<T>(string input, TrimmingOptions trimWhiteSpaces, T defaultValue, out T value) where T : struct => TryConvertToEnum<T>(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableEnum<T>(string input, TrimmingOptions trimWhiteSpaces, out T? value) where T : struct => TryConvertToNullableEnum<T>(input, trimWhiteSpaces, null, out value);

		public object ConvertToEnum(Type enumType, string input, TrimmingOptions trimWhiteSpaces, object defaultValue) => ConvertToEnum(enumType, input, trimWhiteSpaces, defaultValue, null);
		public object ConvertToEnum(Type enumType, string input, TrimmingOptions trimWhiteSpaces, object defaultValue, IFormatProvider culture) { object value; return TryOrThrow(TryConvertToEnum(enumType, input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }

		public bool TryConvertToEnum<T>(string input, TrimmingOptions trimWhiteSpaces, T defaultValue, IFormatProvider culture, out T value)
			where T : struct
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!EnumHelper.TryParse(input, true, out value))
				return false;

			return true;
		}

		public bool TryConvertToNullableEnum<T>(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out T? value)
			where T : struct
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				T output;
				if (!EnumHelper.TryParse(input, true, out output))
					return false;

				value = output;
			}

			return true;
		}

		public bool TryConvertToEnum(Type enumType, string input, TrimmingOptions trimWhiteSpaces, object defaultValue, IFormatProvider culture, out object value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!EnumHelper.TryParse(enumType, input, true, out value))
				return false;

			return true;
		}

		#endregion

		#region GUID

		public Guid ConvertToGuid(string input, TrimmingOptions trimWhiteSpaces, Guid defaultValue) => ConvertToGuid(input, trimWhiteSpaces, defaultValue, null);
		public Guid ConvertToGuid(string input, TrimmingOptions trimWhiteSpaces, Guid defaultValue, IFormatProvider culture) { Guid value; return TryOrThrow(TryConvertToGuid(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public Guid? ConvertToNullableGuid(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableGuid(input, trimWhiteSpaces, null);
		public Guid? ConvertToNullableGuid(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { Guid? value; return TryOrThrow(TryConvertToNullableGuid(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToGuid(string input, TrimmingOptions trimWhiteSpaces, Guid defaultValue, out Guid value) => TryConvertToGuid(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableGuid(string input, TrimmingOptions trimWhiteSpaces, out Guid? value) => TryConvertToNullableGuid(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToGuid(string input, TrimmingOptions trimWhiteSpaces, Guid defaultValue, IFormatProvider culture, out Guid value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!Guid.TryParse(input, out value))
				return false;

			return true;
		}

		public bool TryConvertToNullableGuid(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out Guid? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				Guid output;
				if (!TryConvertToGuid(input, TrimmingOptions.None, default(Guid), culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region DateTime

		public DateTime ConvertToDateTime(string input, TrimmingOptions trimWhiteSpaces, DateTime defaultValue) => ConvertToDateTime(input, trimWhiteSpaces, defaultValue, null);
		public DateTime ConvertToDateTime(string input, TrimmingOptions trimWhiteSpaces, DateTime defaultValue, IFormatProvider culture) { DateTime value; return TryOrThrow(TryConvertToDateTime(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public DateTime? ConvertToNullableDateTime(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableDateTime(input, trimWhiteSpaces, null);
		public DateTime? ConvertToNullableDateTime(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { DateTime? value; return TryOrThrow(TryConvertToNullableDateTime(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToDateTime(string input, TrimmingOptions trimWhiteSpaces, DateTime defaultValue, out DateTime value) => TryConvertToDateTime(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableDateTime(string input, TrimmingOptions trimWhiteSpaces, out DateTime? value) => TryConvertToNullableDateTime(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToDateTime(string input, TrimmingOptions trimWhiteSpaces, DateTime defaultValue, IFormatProvider culture, out DateTime value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else
			{
				if (_expectedDateTimeFormats == null || _expectedDateTimeFormats.Length == 0 || !DateTime.TryParseExact(input, _expectedDateTimeFormats, culture, this.DateTimeStyles, out value))
				{
					if (this.DateTimeConversionOption == ConversionOption.Loose)
					{
						if (!DateTime.TryParseExact(input, "G", culture, this.DateTimeStyles, out value))
						{
							if (!DateTime.TryParse(input, culture, this.DateTimeStyles, out value))
								return false;
						}
					}
					else
					{
						value = defaultValue;
						return false;
					}
				}
			}

			return true;
		}

		public bool TryConvertToNullableDateTime(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out DateTime? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				DateTime output;
				if (!TryConvertToDateTime(input, TrimmingOptions.None, DateTime.MinValue, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region DateTimeOffset

		public DateTimeOffset ConvertToDateTimeOffset(string input, TrimmingOptions trimWhiteSpaces, DateTimeOffset defaultValue) => ConvertToDateTimeOffset(input, trimWhiteSpaces, defaultValue, null);
		public DateTimeOffset ConvertToDateTimeOffset(string input, TrimmingOptions trimWhiteSpaces, DateTimeOffset defaultValue, IFormatProvider culture) { DateTimeOffset value; return TryOrThrow(TryConvertToDateTimeOffset(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public DateTimeOffset? ConvertToNullableDateTimeOffset(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableDateTime(input, trimWhiteSpaces, null);
		public DateTimeOffset? ConvertToNullableDateTimeOffset(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { DateTimeOffset? value; return TryOrThrow(TryConvertToNullableDateTimeOffset(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToDateTimeOffset(string input, TrimmingOptions trimWhiteSpaces, DateTimeOffset defaultValue, out DateTimeOffset value) => TryConvertToDateTimeOffset(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableDateTimeOffset(string input, TrimmingOptions trimWhiteSpaces, out DateTimeOffset? value) => TryConvertToNullableDateTimeOffset(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToDateTimeOffset(string input, TrimmingOptions trimWhiteSpaces, DateTimeOffset defaultValue, IFormatProvider culture, out DateTimeOffset value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else
			{
				if (_expectedDateTimeFormats == null || _expectedDateTimeFormats.Length == 0 || !DateTimeOffset.TryParseExact(input, _expectedDateTimeFormats, culture, this.DateTimeStyles, out value))
				{
					if (this.DateTimeConversionOption == ConversionOption.Loose)
					{
						if (!DateTimeOffset.TryParseExact(input, "G", culture, this.DateTimeStyles, out value))
						{
							if (!DateTimeOffset.TryParse(input, culture, this.DateTimeStyles, out value))
								return false;
						}
					}
					else
					{
						value = defaultValue;
						return false;
					}
				}
			}

			return true;
		}

		public bool TryConvertToNullableDateTimeOffset(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out DateTimeOffset? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				DateTimeOffset output;
				if (!TryConvertToDateTimeOffset(input, TrimmingOptions.None, DateTime.MinValue, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region TimeSpan

		public TimeSpan ConvertToTimeSpan(string input, TrimmingOptions trimWhiteSpaces, TimeSpan defaultValue) => ConvertToTimeSpan(input, trimWhiteSpaces, defaultValue, null);
		public TimeSpan ConvertToTimeSpan(string input, TrimmingOptions trimWhiteSpaces, TimeSpan defaultValue, IFormatProvider culture) { TimeSpan value; return TryOrThrow(TryConvertToTimeSpan(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public TimeSpan? ConvertToNullableTimeSpan(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableTimeSpan(input, trimWhiteSpaces, null);
		public TimeSpan? ConvertToNullableTimeSpan(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { TimeSpan? value; return TryOrThrow(TryConvertToNullableTimeSpan(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToTimeSpan(string input, TrimmingOptions trimWhiteSpaces, TimeSpan defaultValue, out TimeSpan value) => TryConvertToTimeSpan(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableTimeSpan(string input, TrimmingOptions trimWhiteSpaces, out TimeSpan? value) => TryConvertToNullableTimeSpan(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToTimeSpan(string input, TrimmingOptions trimWhiteSpaces, TimeSpan defaultValue, IFormatProvider culture, out TimeSpan value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!TimeSpan.TryParse(input, culture, out value))
				return false;

			return true;
		}

		public bool TryConvertToNullableTimeSpan(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out TimeSpan? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				TimeSpan output;
				if (!TimeSpan.TryParse(input, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region SByte

		[CLSCompliant(false)] public SByte ConvertToSByte(string input, TrimmingOptions trimWhiteSpaces, SByte defaultValue) => ConvertToSByte(input, trimWhiteSpaces, defaultValue, null);
		[CLSCompliant(false)] public SByte ConvertToSByte(string input, TrimmingOptions trimWhiteSpaces, SByte defaultValue, IFormatProvider culture) { SByte value; return TryOrThrow(TryConvertToSByte(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		[CLSCompliant(false)] public SByte? ConvertToNullableSByte(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableSByte(input, trimWhiteSpaces, null);
		[CLSCompliant(false)] public SByte? ConvertToNullableSByte(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { SByte? value; return TryOrThrow(TryConvertToNullableSByte(input, trimWhiteSpaces, culture, out value), input, value); }
		[CLSCompliant(false)] public bool TryConvertToSByte(string input, TrimmingOptions trimWhiteSpaces, SByte defaultValue, out SByte value) => TryConvertToSByte(input, trimWhiteSpaces, defaultValue, null, out value);
		[CLSCompliant(false)] public bool TryConvertToNullableSByte(string input, TrimmingOptions trimWhiteSpaces, out SByte? value) => TryConvertToNullableSByte(input, trimWhiteSpaces, null, out value);

		[CLSCompliant(false)]
		public bool TryConvertToSByte(string input, TrimmingOptions trimWhiteSpaces, SByte defaultValue, IFormatProvider culture, out SByte value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!SByte.TryParse(input, this.IntegerNumberStyles, culture, out value))
				return false;

			return true;
		}

		[CLSCompliant(false)]
		public bool TryConvertToNullableSByte(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out SByte? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				SByte output;
				if (!SByte.TryParse(input, this.IntegerNumberStyles, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region Byte

		public Byte ConvertToByte(string input, TrimmingOptions trimWhiteSpaces, Byte defaultValue) => ConvertToByte(input, trimWhiteSpaces, defaultValue, null);
		public Byte ConvertToByte(string input, TrimmingOptions trimWhiteSpaces, Byte defaultValue, IFormatProvider culture) { Byte value; return TryOrThrow(TryConvertToByte(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public Byte? ConvertToNullableByte(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableByte(input, trimWhiteSpaces, null);
		public Byte? ConvertToNullableByte(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { Byte? value; return TryOrThrow(TryConvertToNullableByte(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToByte(string input, TrimmingOptions trimWhiteSpaces, Byte defaultValue, out Byte value) => TryConvertToByte(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableByte(string input, TrimmingOptions trimWhiteSpaces, out Byte? value) => TryConvertToNullableByte(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToByte(string input, TrimmingOptions trimWhiteSpaces, Byte defaultValue, IFormatProvider culture, out Byte value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!Byte.TryParse(input, this.IntegerNumberStyles, culture, out value))
				return false;

			return true;
		}

		public bool TryConvertToNullableByte(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out Byte? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				Byte output;
				if (!Byte.TryParse(input, this.IntegerNumberStyles, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region Int16

		public Int16 ConvertToInt16(string input, TrimmingOptions trimWhiteSpaces, Int16 defaultValue) => ConvertToInt16(input, trimWhiteSpaces, defaultValue, null);
		public Int16 ConvertToInt16(string input, TrimmingOptions trimWhiteSpaces, Int16 defaultValue, IFormatProvider culture) { Int16 value; return TryOrThrow(TryConvertToInt16(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public Int16? ConvertToNullableInt16(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableInt16(input, trimWhiteSpaces, null);
		public Int16? ConvertToNullableInt16(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { Int16? value; return TryOrThrow(TryConvertToNullableInt16(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToInt16(string input, TrimmingOptions trimWhiteSpaces, Int16 defaultValue, out Int16 value) => TryConvertToInt16(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableInt16(string input, TrimmingOptions trimWhiteSpaces, out Int16? value) => TryConvertToNullableInt16(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToInt16(string input, TrimmingOptions trimWhiteSpaces, Int16 defaultValue, IFormatProvider culture, out Int16 value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!Int16.TryParse(input, this.IntegerNumberStyles, culture, out value))
				return false;

			return true;
		}

		public bool TryConvertToNullableInt16(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out Int16? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				Int16 output;
				if (!Int16.TryParse(input, this.IntegerNumberStyles, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region UInt16

		[CLSCompliant(false)] public UInt16 ConvertToUInt16(string input, TrimmingOptions trimWhiteSpaces, UInt16 defaultValue) => ConvertToUInt16(input, trimWhiteSpaces, defaultValue, null);
		[CLSCompliant(false)] public UInt16 ConvertToUInt16(string input, TrimmingOptions trimWhiteSpaces, UInt16 defaultValue, IFormatProvider culture) { UInt16 value; return TryOrThrow(TryConvertToUInt16(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		[CLSCompliant(false)] public UInt16? ConvertToNullableUInt16(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableUInt16(input, trimWhiteSpaces, null);
		[CLSCompliant(false)] public UInt16? ConvertToNullableUInt16(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { UInt16? value; return TryOrThrow(TryConvertToNullableUInt16(input, trimWhiteSpaces, culture, out value), input, value); }
		[CLSCompliant(false)] public bool TryConvertToUInt16(string input, TrimmingOptions trimWhiteSpaces, UInt16 defaultValue, out UInt16 value) => TryConvertToUInt16(input, trimWhiteSpaces, defaultValue, null, out value);
		[CLSCompliant(false)] public bool TryConvertToNullableUInt16(string input, TrimmingOptions trimWhiteSpaces, out UInt16? value) => TryConvertToNullableUInt16(input, trimWhiteSpaces, null, out value);

		[CLSCompliant(false)]
		public bool TryConvertToUInt16(string input, TrimmingOptions trimWhiteSpaces, UInt16 defaultValue, IFormatProvider culture, out UInt16 value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!UInt16.TryParse(input, this.IntegerNumberStyles, culture, out value))
				return false;

			return true;
		}

		[CLSCompliant(false)]
		public bool TryConvertToNullableUInt16(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out UInt16? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				UInt16 output;
				if (!UInt16.TryParse(input, this.IntegerNumberStyles, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region Int32

		public Int32 ConvertToInt32(string input, TrimmingOptions trimWhiteSpaces, Int32 defaultValue) => ConvertToInt32(input, trimWhiteSpaces, defaultValue, null);
		public Int32 ConvertToInt32(string input, TrimmingOptions trimWhiteSpaces, Int32 defaultValue, IFormatProvider culture) { Int32 value; return TryOrThrow(TryConvertToInt32(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public Int32? ConvertToNullableInt32(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableInt32(input, trimWhiteSpaces, null);
		public Int32? ConvertToNullableInt32(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { Int32? value; return TryOrThrow(TryConvertToNullableInt32(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToInt32(string input, TrimmingOptions trimWhiteSpaces, Int32 defaultValue, out Int32 value) => TryConvertToInt32(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableInt32(string input, TrimmingOptions trimWhiteSpaces, out Int32? value) => TryConvertToNullableInt32(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToInt32(string input, TrimmingOptions trimWhiteSpaces, Int32 defaultValue, IFormatProvider culture, out Int32 value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!Int32.TryParse(input, this.IntegerNumberStyles, culture, out value))
				return false;

			return true;
		}

		public bool TryConvertToNullableInt32(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out Int32? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				Int32 output;
				if (!Int32.TryParse(input, this.IntegerNumberStyles, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region UInt32

		[CLSCompliant(false)] public UInt32 ConvertToUInt32(string input, TrimmingOptions trimWhiteSpaces, UInt32 defaultValue) => ConvertToUInt32(input, trimWhiteSpaces, defaultValue, null);
		[CLSCompliant(false)] public UInt32 ConvertToUInt32(string input, TrimmingOptions trimWhiteSpaces, UInt32 defaultValue, IFormatProvider culture) { UInt32 value; return TryOrThrow(TryConvertToUInt32(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		[CLSCompliant(false)] public UInt32? ConvertToNullableUInt32(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableUInt32(input, trimWhiteSpaces, null);
		[CLSCompliant(false)] public UInt32? ConvertToNullableUInt32(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { UInt32? value; return TryOrThrow(TryConvertToNullableUInt32(input, trimWhiteSpaces, culture, out value), input, value); }
		[CLSCompliant(false)] public bool TryConvertToUInt32(string input, TrimmingOptions trimWhiteSpaces, UInt32 defaultValue, out UInt32 value) => TryConvertToUInt32(input, trimWhiteSpaces, defaultValue, null, out value);
		[CLSCompliant(false)] public bool TryConvertToNullableUInt32(string input, TrimmingOptions trimWhiteSpaces, out UInt32? value) => TryConvertToNullableUInt32(input, trimWhiteSpaces, null, out value);

		[CLSCompliant(false)]
		public bool TryConvertToUInt32(string input, TrimmingOptions trimWhiteSpaces, UInt32 defaultValue, IFormatProvider culture, out UInt32 value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!UInt32.TryParse(input, this.IntegerNumberStyles, culture, out value))
				return false;

			return true;
		}

		[CLSCompliant(false)]
		public bool TryConvertToNullableUInt32(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out UInt32? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				UInt32 output;
				if (!UInt32.TryParse(input, this.IntegerNumberStyles, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region Int64

		public Int64 ConvertToInt64(string input, TrimmingOptions trimWhiteSpaces, Int64 defaultValue) => ConvertToInt64(input, trimWhiteSpaces, defaultValue, null);
		public Int64 ConvertToInt64(string input, TrimmingOptions trimWhiteSpaces, Int64 defaultValue, IFormatProvider culture) { Int64 value; return TryOrThrow(TryConvertToInt64(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public Int64? ConvertToNullableInt64(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableInt64(input, trimWhiteSpaces, null);
		public Int64? ConvertToNullableInt64(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { Int64? value; return TryOrThrow(TryConvertToNullableInt64(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToInt64(string input, TrimmingOptions trimWhiteSpaces, Int64 defaultValue, out Int64 value) => TryConvertToInt64(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableInt64(string input, TrimmingOptions trimWhiteSpaces, out Int64? value) => TryConvertToNullableInt64(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToInt64(string input, TrimmingOptions trimWhiteSpaces, Int64 defaultValue, IFormatProvider culture, out Int64 value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!Int64.TryParse(input, this.IntegerNumberStyles, culture, out value))
				return false;

			return true;
		}

		public bool TryConvertToNullableInt64(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out Int64? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				Int64 output;
				if (!Int64.TryParse(input, this.IntegerNumberStyles, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region UInt64

		[CLSCompliant(false)] public UInt64 ConvertToUInt64(string input, TrimmingOptions trimWhiteSpaces, UInt64 defaultValue) => ConvertToUInt64(input, trimWhiteSpaces, defaultValue, null);
		[CLSCompliant(false)] public UInt64 ConvertToUInt64(string input, TrimmingOptions trimWhiteSpaces, UInt64 defaultValue, IFormatProvider culture) { UInt64 value; return TryOrThrow(TryConvertToUInt64(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		[CLSCompliant(false)] public UInt64? ConvertToNullableUInt64(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableUInt64(input, trimWhiteSpaces, null);
		[CLSCompliant(false)] public UInt64? ConvertToNullableUInt64(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { UInt64? value; return TryOrThrow(TryConvertToNullableUInt64(input, trimWhiteSpaces, culture, out value), input, value); }
		[CLSCompliant(false)] public bool TryConvertToUInt64(string input, TrimmingOptions trimWhiteSpaces, UInt64 defaultValue, out UInt64 value) => TryConvertToUInt64(input, trimWhiteSpaces, defaultValue, null, out value);
		[CLSCompliant(false)] public bool TryConvertToNullableUInt64(string input, TrimmingOptions trimWhiteSpaces, out UInt64? value) => TryConvertToNullableUInt64(input, trimWhiteSpaces, null, out value);

		[CLSCompliant(false)]
		public bool TryConvertToUInt64(string input, TrimmingOptions trimWhiteSpaces, UInt64 defaultValue, IFormatProvider culture, out UInt64 value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!UInt64.TryParse(input, this.IntegerNumberStyles, culture, out value))
				return false;

			return true;
		}

		[CLSCompliant(false)]
		public bool TryConvertToNullableUInt64(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out UInt64? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				UInt64 output;
				if (!UInt64.TryParse(input, this.IntegerNumberStyles, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region Single

		public Single ConvertToSingle(string input, TrimmingOptions trimWhiteSpaces, Single defaultValue) => ConvertToSingle(input, trimWhiteSpaces, defaultValue, null);
		public Single ConvertToSingle(string input, TrimmingOptions trimWhiteSpaces, Single defaultValue, IFormatProvider culture) { Single value; return TryOrThrow(TryConvertToSingle(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public Single? ConvertToNullableSingle(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableSingle(input, trimWhiteSpaces, null);
		public Single? ConvertToNullableSingle(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { Single? value; return TryOrThrow(TryConvertToNullableSingle(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToSingle(string input, TrimmingOptions trimWhiteSpaces, Single defaultValue, out Single value) => TryConvertToSingle(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableSingle(string input, TrimmingOptions trimWhiteSpaces, out Single? value) => TryConvertToNullableSingle(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToSingle(string input, TrimmingOptions trimWhiteSpaces, Single defaultValue, IFormatProvider culture, out Single value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!Single.TryParse(input, this.FloatingPointNumberStyles, culture, out value))
				return false;

			return true;
		}

		public bool TryConvertToNullableSingle(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out Single? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				Single output;
				if (!Single.TryParse(input, this.FloatingPointNumberStyles, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region Double

		public Double ConvertToDouble(string input, TrimmingOptions trimWhiteSpaces, Double defaultValue) => ConvertToDouble(input, trimWhiteSpaces, defaultValue, null);
		public Double ConvertToDouble(string input, TrimmingOptions trimWhiteSpaces, Double defaultValue, IFormatProvider culture) { Double value; return TryOrThrow(TryConvertToDouble(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public Double? ConvertToNullableDouble(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableDouble(input, trimWhiteSpaces, null);
		public Double? ConvertToNullableDouble(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { Double? value; return TryOrThrow(TryConvertToNullableDouble(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToDouble(string input, TrimmingOptions trimWhiteSpaces, Double defaultValue, out Double value) => TryConvertToDouble(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableDouble(string input, TrimmingOptions trimWhiteSpaces, out Double? value) => TryConvertToNullableDouble(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToDouble(string input, TrimmingOptions trimWhiteSpaces, Double defaultValue, IFormatProvider culture, out Double value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!Double.TryParse(input, this.FloatingPointNumberStyles, culture, out value))
				return false;

			return true;
		}

		public bool TryConvertToNullableDouble(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out Double? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				Double output;
				if (!Double.TryParse(input, this.FloatingPointNumberStyles, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#region Decimal

		public Decimal ConvertToDecimal(string input, TrimmingOptions trimWhiteSpaces, Decimal defaultValue) => ConvertToDecimal(input, trimWhiteSpaces, defaultValue, null);
		public Decimal ConvertToDecimal(string input, TrimmingOptions trimWhiteSpaces, Decimal defaultValue, IFormatProvider culture) { Decimal value; return TryOrThrow(TryConvertToDecimal(input, trimWhiteSpaces, defaultValue, culture, out value), input, value); }
		public Decimal? ConvertToNullableDecimal(string input, TrimmingOptions trimWhiteSpaces) => ConvertToNullableDecimal(input, trimWhiteSpaces, null);
		public Decimal? ConvertToNullableDecimal(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture) { Decimal? value; return TryOrThrow(TryConvertToNullableDecimal(input, trimWhiteSpaces, culture, out value), input, value); }
		public bool TryConvertToDecimal(string input, TrimmingOptions trimWhiteSpaces, Decimal defaultValue, out Decimal value) => TryConvertToDecimal(input, trimWhiteSpaces, defaultValue, null, out value);
		public bool TryConvertToNullableDecimal(string input, TrimmingOptions trimWhiteSpaces, out Decimal? value) => TryConvertToNullableDecimal(input, trimWhiteSpaces, null, out value);

		public bool TryConvertToDecimal(string input, TrimmingOptions trimWhiteSpaces, Decimal defaultValue, IFormatProvider culture, out Decimal value)
		{
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (string.IsNullOrEmpty(input))
				value = defaultValue;
			else if (!Decimal.TryParse(input, this.FloatingPointNumberStyles, culture, out value))
				return false;

			return true;
		}

		public bool TryConvertToNullableDecimal(string input, TrimmingOptions trimWhiteSpaces, IFormatProvider culture, out Decimal? value)
		{
			value = null;
			input = TrimWhiteSpaces(input, trimWhiteSpaces);

			if (!string.IsNullOrEmpty(input))
			{
				Decimal output;
				if (!Decimal.TryParse(input, this.FloatingPointNumberStyles, culture, out output))
					return false;

				value = output;
			}

			return true;
		}

		#endregion

		#endregion

		#endregion
	}
}


text:
using System;
using System.Runtime.InteropServices;

namespace HelperFramework.PInvoke
{
	public class System
	{
		[DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
		public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);

		[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
		public static extern IntPtr SendMessage(HandleRef hWnd, uint msg, IntPtr wParam, String lParam);

		[DllImport("user32.dll")]
		public static extern int GetSystemMetrics(int smIndex);
	}
}

redpajama_set_name: RedPajamaGithub


text:
#region MIT License

#endregion

using System;
using System.Runtime.InteropServices;

namespace SharpFont.Cache.Internal
{
	[StructLayout(LayoutKind.Sequential)]
	internal class CMapCacheRec
	{
	}
}


text:
export class IngressoModel{
    idevento:number;

}


text:
package com.kb.mylibs.Android.Base;

import android.app.Application;
import android.content.Context;

/**
 * @url https://www.cnblogs.com/hello-studio/p/9640787.html
 * @brief Android 获取静态上下文(Application)
 */
public class MyApplicationTest extends Application
{
    private static Context _Context;
    private static MyApplicationTest _Application;

    @Override
    public void onCreate()
    {
        super.onCreate();
        MyApplicationTest._Context = this.getApplicationContext();
        //Context context = this.getApplicationContext();
        //Ctx.msIns.initNativeContext(context);
        MyApplicationTest._Application = this;
    }

    public static Context getAppContext()
    {
        return MyApplicationTest._Context;
    }

    public static MyApplicationTest getApplication()
    {
        return MyApplicationTest._Application;
    }
}


text:
import asyncio
import aiocouchdb.feeds

from . import utils

class FeedTestCase(utils.TestCase):

    def test_read_chunks(self):
        resp = self.prepare_response(data=[b'foo\r\n', b'bar\r\n'])

        feed = aiocouchdb.feeds.Feed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual(b'foo\r\n', result)

        result = yield from feed.next()
        self.assertEqual(b'bar\r\n', result)

        result = yield from feed.next()
        self.assertEqual(None, result)
        self.assertFalse(feed.is_active())

    def test_ignore_empty_chunks(self):
        resp = self.prepare_response(data=[
            b'foo\r\n', b'\n',  b'\n',
            b'\n',  b'\n', b'bar\r\n'
        ])

        feed = aiocouchdb.feeds.Feed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual(b'foo\r\n', result)

        result = yield from feed.next()
        self.assertEqual(b'bar\r\n', result)

        result = yield from feed.next()
        self.assertEqual(None, result)
        self.assertFalse(feed.is_active())

    def test_read_empty_json_feed(self):
        resp = self.prepare_response()

        feed = aiocouchdb.feeds.Feed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual(None, result)

        self.assertFalse(feed.is_active())

    def test_calling_inactive_feed_returns_none(self):
        resp = self.prepare_response()

        feed = aiocouchdb.feeds.Feed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        yield from feed.next()

        self.assertFalse(feed.is_active())

        result = yield from feed.next()
        self.assertEqual(None, result)

    def test_close_resp_on_feed_end(self):
        resp = self.prepare_response()

        feed = aiocouchdb.feeds.Feed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        yield from feed.next()

        self.assertFalse(feed.is_active())
        self.assertTrue(resp.close.called)

    def test_force_close_resp_on_error(self):
        resp = self.prepare_response(err=ValueError)

        feed = aiocouchdb.feeds.Feed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        with self.assertRaises(ValueError):
            yield from feed.next()

        self.assertFalse(feed.is_active())
        resp.close.assert_called_with(force=True)

    def test_buffer_workflow(self):
        resp = self.prepare_response(data=[
            b'foo\r\n', b'bar\r\n',
            b'baz\r\n', b'boo\r\n'
        ])

        buf_size = 2
        feed = aiocouchdb.feeds.Feed(resp, buffer_size=buf_size, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual(feed._queue.qsize(), buf_size)
        self.assertEqual(b'foo\r\n', result)

        result = yield from feed.next()
        self.assertEqual(feed._queue.qsize(), buf_size)
        self.assertEqual(b'bar\r\n', result)

        result = yield from feed.next()
        self.assertEqual(feed._queue.qsize(), buf_size - 1)
        self.assertEqual(b'baz\r\n', result)

        result = yield from feed.next()
        self.assertEqual(feed._queue.qsize(), 0)
        self.assertEqual(b'boo\r\n', result)

        result = yield from feed.next()
        self.assertEqual(None, result)
        self.assertFalse(feed.is_active())

class JsonFeedTestCase(utils.TestCase):

    def test_read_json_chunks(self):
        resp = self.prepare_response(data=[
            b'{"foo": true}\r\n',
            b'"foo"\r\n',
            b'{"bar": null}\r\n'
        ])

        feed = aiocouchdb.feeds.JsonFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual({'foo': True}, result)

        result = yield from feed.next()
        self.assertEqual('foo', result)

        result = yield from feed.next()
        self.assertEqual({'bar': None}, result)

        result = yield from feed.next()
        self.assertEqual(None, result)
        self.assertFalse(feed.is_active())

class ViewFeedTestCase(utils.TestCase):

    def test_read_empty_view(self):
        resp = self.prepare_response(data=[
            b'{"total_rows": 0, "offset": 0, "rows": [\r\n',
            b'\n',
            b']}\r\n'
        ])

        feed = aiocouchdb.feeds.ViewFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual(None, result)
        self.assertFalse(feed.is_active())

    def test_read_reduced_empty_view(self):
        resp = self.prepare_response(data=[
            b'{"rows": [\r\n',
            b'\r\n]}'
        ])

        feed = aiocouchdb.feeds.ViewFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual(None, result)
        self.assertFalse(feed.is_active())

    def test_read_view(self):
        resp = self.prepare_response(data=[
            b'{"total_rows": 3, "offset": 0, "rows": [\r\n',
            b'{"id": "foo", "key": null, "value": false}',
            b',\r\n{"id": "bar", "key": null, "value": false}',
            b',\r\n{"id": "baz", "key": null, "value": false}',
            b'\r\n]}'
        ])

        feed = aiocouchdb.feeds.ViewFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        for idx in ('foo', 'bar', 'baz'):
            row = yield from feed.next()
            self.assertEqual({'id': idx, 'key': None, 'value': False}, row)
        row = yield from feed.next()
        self.assertEqual(None, row)
        self.assertFalse(feed.is_active())

    def test_view_header(self):
        resp = self.prepare_response(data=[
            b'{"total_rows": 3, "offset": 0, "rows": [\r\n',
            b'{"id": "foo", "key": null, "value": false}',
            b',\r\n{"id": "bar", "key": null, "value": false}',
            b',\r\n{"id": "baz", "key": null, "value": false}',
            b'\r\n]}'
        ])

        feed = aiocouchdb.feeds.ViewFeed(resp, loop=self.loop)

        self.assertIsNone(feed.total_rows)
        self.assertIsNone(feed.offset)
        self.assertIsNone(feed.update_seq)

        yield from feed.next()

        self.assertEqual(3, feed.total_rows)
        self.assertEqual(0, feed.offset)
        self.assertIsNone(feed.update_seq)

    def test_reduced_view_header(self):
        resp = self.prepare_response(data=[
            b'{"rows": [\r\n',
            b'{"key": null, "value": 1}',
            b',\r\n{"key": true, "value": 2}',
            b'\r\n]}'
        ])

        feed = aiocouchdb.feeds.ViewFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        self.assertIsNone(feed.total_rows)
        self.assertIsNone(feed.offset)
        self.assertIsNone(feed.update_seq)

        yield from feed.next()

        self.assertIsNone(feed.total_rows)
        self.assertIsNone(feed.offset)
        self.assertIsNone(feed.update_seq)

class EventSourceFeedTestCase(utils.TestCase):

    def test_read_event(self):
        resp = self.prepare_response(data=[
            b'data: {"type":"updated","db_name":"db"}\n\n',
        ])
        feed = aiocouchdb.feeds.EventSourceFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual({'data': {'db_name': 'db', 'type': 'updated'}}, result)

        result = yield from feed.next()
        self.assertIsNone(result)
        self.assertFalse(feed.is_active())

    def test_read_empty_data(self):
        resp = self.prepare_response(data=[
            b'event: heartbeat\ndata: \n\n'
        ])

        feed = aiocouchdb.feeds.EventSourceFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual({'event': 'heartbeat', 'data': None}, result)

        result = yield from feed.next()
        self.assertIsNone(result)
        self.assertFalse(feed.is_active())

    def test_read_multiple_data(self):
        resp = self.prepare_response(data=[
            b'data: [\ndata:"foo",\ndata: "bar"\ndata:] \n\n'
        ])

        feed = aiocouchdb.feeds.EventSourceFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual({'data': ['foo', 'bar']}, result)

        result = yield from feed.next()
        self.assertIsNone(result)
        self.assertFalse(feed.is_active())

    def test_no_colon(self):
        resp = self.prepare_response(data=[
            b'id\n\n'
        ])

        feed = aiocouchdb.feeds.EventSourceFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual({'id': '', 'data': None}, result)

        result = yield from feed.next()
        self.assertIsNone(result)
        self.assertFalse(feed.is_active())

    def test_leading_colon(self):
        resp = self.prepare_response(data=[
            b':id\n\n'
        ])

        feed = aiocouchdb.feeds.EventSourceFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual({'data': None}, result)

        result = yield from feed.next()
        self.assertIsNone(result)
        self.assertFalse(feed.is_active())

    def test_decode_retry_with_int(self):
        resp = self.prepare_response(data=[
            b'retry: 10\n\n'
        ])

        feed = aiocouchdb.feeds.EventSourceFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual({'retry': 10, 'data': None}, result)

        result = yield from feed.next()
        self.assertIsNone(result)
        self.assertFalse(feed.is_active())

    def test_ignore_unknown_field(self):
        resp = self.prepare_response(data=[
            b'data: "foo"\nfoo: bar\n\n'
        ])

        feed = aiocouchdb.feeds.EventSourceFeed(resp, loop=self.loop)
        self.assertTrue(feed.is_active())

        result = yield from feed.next()
        self.assertEqual({'data': 'foo'}, result)

        result = yield from feed.next()
        self.assertIsNone(result)
        self.assertFalse(feed.is_active())

class ChangesFeedTestCase(utils.TestCase):

    def setUp(self):
        super().setUp()
        self.output = [
            {'seq': 77, 'id': 'foo', 'changes': [{'rev': '9-CDE'}]},
            {'seq': 90, 'id': 'bar', 'changes': [{'rev': '12-ABC'}]},
            {'seq': 91, 'id': 'baz', 'changes': [{'rev': '11-EFG'}],
             'deleted': True}
        ]

    def test_read_changes(self):
        resp = self.prepare_response(data=[
            b'{"results":[\n',
            b'{"seq":77,"id":"foo","changes":[{"rev":"9-CDE"}]}',
            b',\n{"seq":90,"id":"bar","changes":[{"rev":"12-ABC"}]}',
            b',\n{"seq":91,"id":"baz","changes":[{"rev":"11-EFG"}],'
            b'"deleted":true}',
            b'\n],\n"last_seq":91}\n'
        ])
        feed = aiocouchdb.feeds.ChangesFeed(resp, loop=self.loop)
        yield from self.check_feed_output(feed, self.output)

    def test_read_changes_longpoll(self):
        resp = self.prepare_response(data=[
            b'{"results":[\n',
            b'{"seq":77,"id":"foo","changes":[{"rev":"9-CDE"}]}',
            b',\n{"seq":90,"id":"bar","changes":[{"rev":"12-ABC"}]}',
            b',\n{"seq":91,"id":"baz","changes":[{"rev":"11-EFG"}],'
            b'"deleted":true}',
            b'\n],\n"last_seq":91}\n'
        ])
        feed = aiocouchdb.feeds.LongPollChangesFeed(resp, loop=self.loop)
        yield from self.check_feed_output(feed, self.output)

    def test_read_changes_continuous(self):
        resp = self.prepare_response(data=[
            b'{"seq":77,"id":"foo","changes":[{"rev":"9-CDE"}]}\n',
            b'{"seq":90,"id":"bar","changes":[{"rev":"12-ABC"}]}\n',
            b'{"seq":91,"id":"baz","changes":[{"rev":"11-EFG"}],'
            b'"deleted":true}\n',
            b'{"last_seq":91}\n',
        ])
        feed = aiocouchdb.feeds.ContinuousChangesFeed(resp, loop=self.loop)
        yield from self.check_feed_output(feed, self.output)

    def test_read_changes_eventsource(self):
        resp = self.prepare_response(data=[
            b'data: {"seq":77,"id":"foo","changes":[{"rev":"9-CDE"}]}\n'
            b'id: 77\n\n',
            b'event: heartbeat\ndata: \n\n',
            b'data: {"seq":90,"id":"bar","changes":[{"rev":"12-ABC"}]}\n'
            b'id: 90\n\n',
            b'data: {"seq":91,"id":"baz","changes":[{"rev":"11-EFG"}],'
            b'"deleted":true}\nid: 91\n\n',
        ])
        feed = aiocouchdb.feeds.EventSourceChangesFeed(resp, loop=self.loop)
        yield from self.check_feed_output(feed, self.output)

    @asyncio.coroutine
    def check_feed_output(self, feed, output):
        self.assertTrue(feed.is_active())
        self.assertIsNone(feed.last_seq)
        for expected in output:
            event = yield from feed.next()
            self.assertEqual(expected, event)
            self.assertEqual(expected['seq'], feed.last_seq)
        event = yield from feed.next()
        self.assertIsNone(event)
        self.assertFalse(feed.is_active())
        self.assertIsNotNone(feed.last_seq)


text:
<?php

defined('FOF_INCLUDED') or die();

/**
 * Reads and parses the fof.xml file in the back-end of a FOF-powered component,
 * provisioning the data to the rest of the FOF framework
 *
 * @package  FrameworkOnFramework
 * @since    2.1
 */
class FOFConfigProvider
{
	/**
	 * Cache of FOF components' configuration variables
	 *
	 * @var array
	 */
	public static $configurations = array();

	/**
	 * Parses the configuration of the specified component
	 *
	 * @param   string   $component  The name of the component, e.g. com_foobar
	 * @param   boolean  $force      Force reload even if it's already parsed?
	 *
	 * @return  void
	 */
	public function parseComponent($component, $force = false)
	{
		if (!$force && isset(self::$configurations[$component]))
		{
			return;
		}

		if (FOFPlatform::getInstance()->isCli())
		{
			$order = array('cli', 'backend');
		}
		elseif (FOFPlatform::getInstance()->isBackend())
		{
			$order = array('backend');
		}
		else
		{
			$order = array('frontend');
		}

		$order[] = 'common';

		$order = array_reverse($order);
		self::$configurations[$component] = array();

		foreach ($order as $area)
		{
			$config = $this->parseComponentArea($component, $area);
			self::$configurations[$component] = array_merge_recursive(self::$configurations[$component], $config);
		}
	}

	/**
	 * Returns the value of a variable. Variables use a dot notation, e.g.
	 * view.config.whatever where the first part is the domain, the rest of the
	 * parts specify the path to the variable.
	 *
	 * @param   string  $variable  The variable name
	 * @param   mixed   $default   The default value, or null if not specified
	 *
	 * @return  mixed  The value of the variable
	 */
	public function get($variable, $default = null)
	{
		static $domains = null;

		if (is_null($domains))
		{
			$domains = $this->getDomains();
		}

		list($component, $domain, $var) = explode('.', $variable, 3);

		if (!isset(self::$configurations[$component]))
		{
			$this->parseComponent($component);
		}

		if (!in_array($domain, $domains))
		{
			return $default;
		}

		$class = 'FOFConfigDomain' . ucfirst($domain);
		$o = new $class;

		return $o->get(self::$configurations[$component], $var, $default);
	}

	/**
	 * Parses the configuration options of a specific component area
	 *
	 * @param   string  $component  Which component's cionfiguration to parse
	 * @param   string  $area       Which area to parse (frontend, backend, cli)
	 *
	 * @return  array  A hash array with the configuration data
	 */
	protected function parseComponentArea($component, $area)
	{
		// Initialise the return array
		$ret = array();

		// Get the folders of the component
		$componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($component);

		// Check that the path exists
		JLoader::import('joomla.filesystem.folder');
		$path = $componentPaths['admin'];
		$path = JPath::check($path);

		if (!JFolder::exists($path))
		{
			return $ret;
		}

		// Read the filename if it exists
		$filename = $path . '/fof.xml';
		JLoader::import('joomla.filesystem.file');

		if (!JFile::exists($filename))
		{
			return $ret;
		}

		$data = JFile::read($filename);

		// Load the XML data in a SimpleXMLElement object
		$xml = simplexml_load_string($data);

		if (!($xml instanceof SimpleXMLElement))
		{
			return $ret;
		}

		// Get this area's data
		$areaData = $xml->xpath('//' . $area);

		if (empty($areaData))
		{
			return $ret;
		}

		$xml = array_shift($areaData);

		// Parse individual configuration domains
		$domains = $this->getDomains();

		foreach ($domains as $dom)
		{
			$class = 'FOFConfigDomain' . ucfirst($dom);

			if (class_exists($class, true))
			{
				$o = new $class;
				$o->parseDomain($xml, $ret);
			}
		}

		// Finally, return the result
		return $ret;
	}

	/**
	 * Gets a list of the available configuration domain adapters
	 *
	 * @return  array  A list of the available domains
	 */
	protected function getDomains()
	{
		static $domains = array();

		if (empty($domains))
		{
			JLoader::import('joomla.filesystem.folder');
			$files = JFolder::files(__DIR__ . '/domain', '.php');

			if (!empty($files))
			{
				foreach ($files as $file)
				{
					$domain = basename($file, '.php');

					if ($domain == 'interface')
					{
						continue;
					}

					$domain = preg_replace('/[^A-Za-z0-9]/', '', $domain);
					$domains[] = $domain;
				}

				$domains = array_unique($domains);
			}
		}

		return $domains;
	}
}


text:
@interface EmptyCredentialsViewController : ConfirmationAlertViewController
@end

#endif  // IOS_CHROME_CREDENTIAL_PROVIDER_EXTENSION_UI_EMPTY_CREDENTIALS_VIEW_CONTROLLER_H_


text:
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

namespace StyleCop.Analyzers.Lightup
{
    using System;
    using System.Collections.Immutable;
    using Microsoft.CodeAnalysis;

    internal readonly struct IArrayElementReferenceOperationWrapper : IOperationWrapper
    {
        internal const string WrappedTypeName = "Microsoft.CodeAnalysis.Operations.IArrayElementReferenceOperation";
        private static readonly Type WrappedType;
        private static readonly Func<IOperation, IOperation> ArrayReferenceAccessor;
        private static readonly Func<IOperation, ImmutableArray<IOperation>> IndicesAccessor;
        private readonly IOperation operation;
        static IArrayElementReferenceOperationWrapper()
        {
            WrappedType = OperationWrapperHelper.GetWrappedType(typeof(IArrayElementReferenceOperationWrapper));
            ArrayReferenceAccessor = LightupHelpers.CreateOperationPropertyAccessor<IOperation, IOperation>(WrappedType, nameof(ArrayReference));
            IndicesAccessor = LightupHelpers.CreateOperationPropertyAccessor<IOperation, ImmutableArray<IOperation>>(WrappedType, nameof(Indices));
        }

        private IArrayElementReferenceOperationWrapper(IOperation operation)
        {
            this.operation = operation;
        }

        public IOperation WrappedOperation => this.operation;
        public ITypeSymbol Type => this.WrappedOperation.Type;
        public IOperation ArrayReference => ArrayReferenceAccessor(this.WrappedOperation);
        public ImmutableArray<IOperation> Indices => IndicesAccessor(this.WrappedOperation);
        public static IArrayElementReferenceOperationWrapper FromOperation(IOperation operation)
        {
            if (operation == null)
            {
                return default;
            }

            if (!IsInstance(operation))
            {
                throw new InvalidCastException($"Cannot cast '{operation.GetType().FullName}' to '{WrappedTypeName}'");
            }

            return new IArrayElementReferenceOperationWrapper(operation);
        }

        public static bool IsInstance(IOperation operation)
        {
            return operation != null && LightupHelpers.CanWrapOperation(operation, WrappedType);
        }
    }
}


text:
require "spec_helper"

describe ApplicationController do
  # Use the controller method to define an anonymous controller derived from ApplicationController
  # We can request the anonymous controller and test ApplicationController before_filters etc
  controller do
    def index
      render nothing: true
    end
  end

  describe "#set_new_relic_custom_parameters" do
    it "should add remote ip address" do
      parameters = hash_including(remote_ip: request.remote_ip)
      NewRelic::Agent.should_receive(:add_custom_parameters).with(parameters)
    end

    it "should add user agent string" do
      parameters = hash_including(user_agent: request.env["HTTP_USER_AGENT"])
      NewRelic::Agent.should_receive(:add_custom_parameters).with(parameters)
    end

    context "user logged into the site" do
      let(:user) { FactoryGirl.build_stubbed(:user) }
      before(:each) { controller.stub(:current_user).and_return(user) }

      it "should add the logged in users id" do
        parameters = hash_including(user_id: user.id)
        NewRelic::Agent.should_receive(:add_custom_parameters).with(parameters)
      end

      it "should add the logged in users profile username" do
        parameters = hash_including(profile_username: user.profile.username)
        NewRelic::Agent.should_receive(:add_custom_parameters).with(parameters)
      end
    end

    context "user not logged into the site" do
      it "should add an anonymous user id" do
        parameters = hash_including(user_id: 0)
        NewRelic::Agent.should_receive(:add_custom_parameters).with(parameters)
      end

      it "should add an anonymous user profile username" do
        parameters = hash_including(profile_username: "anonymous")
        NewRelic::Agent.should_receive(:add_custom_parameters).with(parameters)
      end
    end

    after(:each) do
      controller.send(:set_new_relic_custom_parameters)
    end
  end
end


text:
<!doctype html>

    <title>Word Power</title>


text:
module AlchemyNodes
  module NodeablesControllerMixin
    def self.included(controller)
      controller.append_view_path 'alchemy_nodes/resources'
    end

  end
end


text: require('../internals/define-well-known-symbol')('hasInstance');


text:
var mongoose = require('mongoose');
var Schema= mongoose.Schema;

var Line = new Schema({
    chords: String,
    words: String
});

var songSchema = new Schema({
    name : String,
    artistsName: String,
    type:String,
    link: String,
    lines: [Line]
});

module.exports = songSchema;


text:
package org.cleanlogic.ol4gwt.showcase.examples;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.*;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.xml.client.Node;
import org.cleanlogic.ol4gwt.showcase.basic.AbstractExample;
import org.cleanlogic.ol4gwt.showcase.components.store.ShowcaseExampleStore;
import org.openlayers.js.XMLSerializer;
import org.openlayers.ol.*;
import org.openlayers.ol.format.GeoJSONFormat;
import org.openlayers.ol.format.WFSFormat;
import org.openlayers.ol.format.filter.EqualToFilter;
import org.openlayers.ol.format.filter.Filter;
import org.openlayers.ol.format.filter.FilterUtils;
import org.openlayers.ol.format.filter.IsLikeFilter;
import org.openlayers.ol.format.options.GetFeatureOptions;
import org.openlayers.ol.layer.BaseLayer;
import org.openlayers.ol.layer.TileLayer;
import org.openlayers.ol.layer.VectorLayer;
import org.openlayers.ol.layer.options.VectorLayerOptions;
import org.openlayers.ol.options.MapOptions;
import org.openlayers.ol.options.ViewOptions;
import org.openlayers.ol.source.BingMapsSource;
import org.openlayers.ol.source.VectorSource;
import org.openlayers.ol.source.options.BingMapsSourceOptions;
import org.openlayers.ol.style.StrokeStyle;
import org.openlayers.ol.style.Style;
import org.openlayers.ol.style.options.StyleOptions;

import javax.inject.Inject;

/**
 * @author Serge Silaev aka iSergio <s.serge.b@gmail.com>
 */
public class VectorWFSGetFeature extends AbstractExample {
    private VectorSource vectorSource = new VectorSource();

    @Inject
    public VectorWFSGetFeature(ShowcaseExampleStore store) {
        super("Vector WFS GetFeature", "OpenStreetMap", new String[]{"Map", "View", "WFS", "GeoJSON", "TileLayer", "VectorLayer", "BingMapsSource", "VectorSource", "StrokeStyle", "Style"}, store);
    }

    @Override
    public void buildPanel() {
        StyleOptions styleOptions = new StyleOptions();
        styleOptions.stroke = StrokeStyle.create(Color.create(0, 0, 255, 1.0), 2);
        VectorLayerOptions vectorLayerOptions = new VectorLayerOptions();
        vectorLayerOptions.source = vectorSource;
//        vectorLayerOptions.style = new Style[] {new Style(styleOptions)};
        VectorLayer vectorLayer = new VectorLayer(vectorLayerOptions);

        BingMapsSourceOptions bingMapsSourceOptions = new BingMapsSourceOptions();
        bingMapsSourceOptions.imagerySet = "Aerial";
        bingMapsSourceOptions.key = "AkGbxXx6tDWf1swIhPJyoAVp06H0s0gDTYslNWWHZ6RoPqMpB9ld5FY1WutX8UoF";
        TileLayer raster = TileLayer.create(new BingMapsSource(bingMapsSourceOptions));

        ViewOptions viewOptions = new ViewOptions();
        viewOptions.center = Coordinate.create(-8908887.277395891, 5381918.072437216);
        viewOptions.maxZoom = 19;
        viewOptions.zoom = 12;

        MapOptions mapOptions = new MapOptions();
        mapOptions.layers = new Collection<>(new BaseLayer[] {raster, vectorLayer});
        mapOptions.view = new View(viewOptions);

        final MapPanel mapPanel = new MapPanel(mapOptions);
        mapPanel.setHeight("400px");

        Filter filter = FilterUtils.and(
                new IsLikeFilter("name", "Mississippi*"),
                new EqualToFilter("waterway", "riverbank")
        );

        GetFeatureOptions getFeatureOptions = new GetFeatureOptions();
        getFeatureOptions.srsName = "EPSG:3857";
        getFeatureOptions.featureNS = "http://openstreemap.org";
        getFeatureOptions.featurePrefix = "osm";
        getFeatureOptions.featureTypes = new String[] {"water_areas"};
        getFeatureOptions.outputFormat = "application/json";
        getFeatureOptions.filter = filter;
        WFSFormat wfsFormat = new WFSFormat();
        Node node = wfsFormat.writeGetFeature(getFeatureOptions);
        RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, "https://ahocevar.com/geoserver/wfs");
        requestBuilder.setRequestData(new XMLSerializer().serializeToString(node));
        requestBuilder.setCallback(new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                GeoJSONFormat format = new GeoJSONFormat();
                Feature[] features = format.readFeatures(response.getText());
                vectorSource.addFeatures(features);
                mapPanel.getMap().getView().fit(vectorSource.getExtent());
            }

            @Override
            public void onError(Request request, Throwable throwable) {
                GWT.log(throwable.toString());
            }
        });

        contentPanel.add(new HTML("
This example generates a GetFeature request which uses a PropertyIsEqualTo and a PropertyIsLike filter, and then posts the request to load the features that match the query.
"));
        contentPanel.add(mapPanel);

        initWidget(contentPanel);
        try {
            requestBuilder.send();
        } catch (RequestException ex) {
            GWT.log(ex.getLocalizedMessage());
        }
    }

    @Override
    public String[] getSourceCodeURLs() {
        String[] sourceCodeURLs = new String[1];
        sourceCodeURLs[0] = GWT.getModuleBaseURL() + "examples/" + "VectorWFSGetFeature.txt";
        return sourceCodeURLs;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<com.larry.widget.PullToExpendScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/top"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:layout_marginTop="-30dp"
            android:orientation="vertical" >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="400dp"
                android:background="#0088CC"
                android:gravity="center"
                android:text="TOP"
                android:textSize="120sp" />
        </LinearLayout>

        <LinearLayout android:id="@+id/bottom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="200dp"
            android:orientation="vertical" >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:background="#00FF00"
                android:gravity="center"
                android:text="@string/hello_world" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:gravity="center"
                android:text="@string/hello_world" />

            <TextView android:layout_width="match_parent"
                android:layout_height="200dp"
                android:gravity="center"
				android:background="#00FF00"
                android:text="@string/hello_world"
                />
        </LinearLayout>
    </FrameLayout>

</com.larry.widget.PullToExpendScrollView>


text:
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule } from 'ionic-angular';
import { BlocksPage, HomePage, PagesModule } from '../pages';
import { AddressProvider } from '../providers/address/address';
import { ApiProvider } from '../providers/api/api';
import { BlocksProvider } from '../providers/blocks/blocks';
import { CurrencyProvider } from '../providers/currency/currency';
import { DefaultProvider } from '../providers/default/default';
import { HttpErrorInterceptor } from '../providers/error-handler/error-handler';
import { Logger } from '../providers/logger/logger';
import { PriceProvider } from '../providers/price/price';
import { RedirProvider } from '../providers/redir/redir';
import { SearchProvider } from '../providers/search/search';
import { TxsProvider } from '../providers/transactions/transactions';
import { InsightApp } from './app.component';

@NgModule({
  declarations: [InsightApp],
  imports: [
    BrowserModule,
    HttpClientModule,
    PagesModule,
    IonicModule.forRoot(InsightApp, {
      mode: 'md',
      animate: false
    })
  ],
  bootstrap: [IonicApp],
  entryComponents: [InsightApp, HomePage, BlocksPage],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpErrorInterceptor,
      multi: true
    },
    ApiProvider,
    CurrencyProvider,
    BlocksProvider,
    TxsProvider,
    DefaultProvider,
    PriceProvider,
    SearchProvider,
    RedirProvider,
    Logger,
    AddressProvider
  ]
})
export class AppModule {}


text: Rails.application.config.session_store :cookie_store, key: '_PauHanaChi_session'


text:
This is still a work in progress.

##### How to run

.1 Checkout WordPress dev suite

```
$ mkdir /tmp/wordpress-tests
$ cd /tmp/wordpress-tests
$ svn co http://svn.automattic.com/wordpress-tests/trunk/
```

.2 Install WordPress site.

    rename wp-tests-config-sample.php to wp-tests-config.php
    edit wp-tests-config.php and set a test database

.3 Install PHPunit

```
$ wget https://phar.phpunit.de/phpunit.phar
$ php phpunit.phar
```

.4 Setup and run WSL tests

```
$ export WP_TESTS_DIR=/tmp/wordpress-tests
$ cd wp-content/plugins/wordpress-social-login
$ phpunit
```


text:
package software.amazon.awssdk.core.internal.http.async;

import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;

import java.nio.ByteBuffer;
import java.util.Optional;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
import software.amazon.awssdk.utils.IoUtils;

/**
 * Implementation of {@link SdkHttpContentPublisher} that provides all it's data at once. Useful for
 * non streaming operations that are already marshalled into memory.
 */
@SdkInternalApi
public final class SimpleHttpContentPublisher implements SdkHttpContentPublisher {

    private final byte[] content;
    private final int length;

    public SimpleHttpContentPublisher(SdkHttpFullRequest request) {
        this.content = request.contentStreamProvider().map(p -> invokeSafely(() -> IoUtils.toByteArray(p.newStream())))
                                                      .orElseGet(() -> new byte[0]);
        this.length = content.length;
    }

    @Override
    public Optional<Long> contentLength() {
        return Optional.of((long) length);
    }

    @Override
    public void subscribe(Subscriber<? super ByteBuffer> s) {
        s.onSubscribe(new SubscriptionImpl(s));
    }

    private class SubscriptionImpl implements Subscription {
        private boolean running = true;
        private final Subscriber<? super ByteBuffer> s;

        private SubscriptionImpl(Subscriber<? super ByteBuffer> s) {
            this.s = s;
        }

        @Override
        public void request(long n) {
            if (running) {
                running = false;
                if (n <= 0) {
                    s.onError(new IllegalArgumentException("Demand must be positive"));
                } else {
                    s.onNext(ByteBuffer.wrap(content));
                    s.onComplete();
                }
            }
        }

        @Override
        public void cancel() {
            running = false;
        }
    }
}


text:
<?php

class TextTextCork extends TextCorkAppModel
{
	var $actsAs = array(
		'Cascata.AguaCascata',
		'Tradutore.TradTradutore',
		'Containable',
		'Corktile.CorkAttachable' => array('type' => 'text_cork'),
	);

	var $hasOne = array('TextTextCorkTranslation' => array('className' => 'TextCork.TextTextCorkTranslation'));

	/** saveCorkContent
	 *
	 *  This function is demanded by the Corktile contract. Basically, it must
	 *  insert the data in a table row. If an 'id' is given in the content, it
	 *  should update the data.
	 *
	 *  @param array $content The data that must be saved. If empty it should be filled with
	 *                        the default content.
	 *  @param array $options Special options related to this type of Cork. In the
	 *						  case of the TextCork this data can be:
	 *						    - 'maxLenght' => maximum lenght of chars it must have
	 *							- 'minLenght' => minimum lenght of chars it should have
	 *                          - 'textile' => if set to true it should
	 *  @param boolean $fromForm It should be set from true, if the data sent is being
	 *							 sent directly from the Form.
	 *  @return The saved data ID on success. False on failure.
	 */
	function saveCorkContent($content = array(), $options = array(), $fromForm = false)
	{
		//@todo: Treat multiple languages right. Now it creates content only for the
		//used language.
		if (empty($content)) // sets the default content.
		{
			$content['TextTextCork']['text'] = __("TextTextCork Model: This text hasn't been written yet. It's up to the site content editor to write it.", true);
			$content['TextTextCork']['cake_fooler_field'] = "Cake, you're fooled";
		}
		// @todo Treat the validation options, in order for it to work properly.
		if ($this->save($content)){
			//debug($content);
			return $this->id;
		}
		else
			return false;
	}

	/** getCorkContent
	 *
	 *  This function is demanded by the Corktile contract. Basically, it must
	 *  return the Model data for a given id.
	 *
	 *  @param $id The id of the row to be retrieved
	 *  @param Array $options If it should be variations on the regular behavior,
	 *                        these options should be passed to this array.
	 *                        In the special case of the text_cork there aren't
	 *  @return The data ID on success. False on failure.
	 */

	function getCorkContent($id, $options = array())
	{
		return array_merge_recursive(
			array('TextTextCork' => array('languages' => $this->getLanguages($id))),
			$this->find('first', array('emptyTranslation' => true, 'conditions' => array('TextTextCork.id' => $id), 'contain' => array()))
		);
	}

	/**
	 *  This function is an optional function of the Burocrata contract. It will be
	 *  called by a form of the type ('cork').
	 *
	 *  @param $data The data to be saved.
	 *  @return The same as save's.
	 */

	function saveBurocrataCork($data)
	{
		return $this->save($data);
	}
}

?>