text:
using Microsoft.Extensions.Logging;
using OmniSharp.Eventing;
using OmniSharp.MSBuild;
using OmniSharp.MSBuild.Logging;
using OmniSharp.Options;
using OmniSharp.Services;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using MSB = Microsoft.Build;

namespace Mef
{
    // OmniSharp.MsBuild part:  SDK .csproj loader

    public class ProjectLoader
    {
        #region ctor

        private readonly Dictionary<string, string> _globalProperties;
        private readonly MSBuildOptions _options;
        private readonly SdksPathResolver _sdksPathResolver;

        public static ProjectLoader Load(string solutionDirectory)
        {
            IEventEmitter mevent = NullEventEmitter.Instance;
            ILoggerFactory factory = new NullLoggerFactory();

            var dot = new DotNetCliService(factory, mevent);
            SdksPathResolver sdksPathResolver = new SdksPathResolver(dot);

            ImmutableDictionary<string, string> propertyOverrides = ImmutableDictionary<string, string>.Empty;
            var loader = new ProjectLoader(new MSBuildOptions(), solutionDirectory, propertyOverrides, sdksPathResolver);
            return loader;
        }

        public ProjectLoader(MSBuildOptions options, string solutionDirectory,
            ImmutableDictionary<string, string> propertyOverrides, // ILoggerFactory loggerFactory,
            SdksPathResolver sdksPathResolver)
        {
            // _logger = loggerFactory.CreateLogger<ProjectLoader>();
            _options = options ?? new MSBuildOptions();
            _sdksPathResolver = sdksPathResolver ?? throw new ArgumentNullException(nameof(sdksPathResolver));
            _globalProperties = CreateGlobalProperties(_options, solutionDirectory, propertyOverrides); // , _logger);
        }

        private static Dictionary<string, string> CreateGlobalProperties(
            MSBuildOptions options, string solutionDirectory, ImmutableDictionary<string, string> propertyOverrides) // , ILogger logger)
        {
            var globalProperties = new Dictionary<string, string>
            {
                { PropertyNames.DesignTimeBuild, "true" },
                { PropertyNames.BuildingInsideVisualStudio, "true" },
                { PropertyNames.BuildProjectReferences, "false" },
                { PropertyNames._ResolveReferenceDependencies, "true" },
                { PropertyNames.SolutionDir, solutionDirectory + Path.DirectorySeparatorChar },

                // This properties allow the design-time build to handle the Compile target without actually invoking the compiler.
                // See https://github.com/dotnet/roslyn/pull/4604 for details.
                { PropertyNames.ProvideCommandLineArgs, "true" },
                { PropertyNames.SkipCompilerExecution, "true" }
            };

            object logger = null;
            globalProperties.AddPropertyOverride(PropertyNames.MSBuildExtensionsPath, options.MSBuildExtensionsPath,
                propertyOverrides, logger);
            globalProperties.AddPropertyOverride(PropertyNames.TargetFrameworkRootPath, options.TargetFrameworkRootPath,
                propertyOverrides, logger);
            globalProperties.AddPropertyOverride(PropertyNames.RoslynTargetsPath, options.RoslynTargetsPath, propertyOverrides, logger);
            globalProperties.AddPropertyOverride(PropertyNames.CscToolPath, options.CscToolPath, propertyOverrides, logger);
            globalProperties.AddPropertyOverride(PropertyNames.CscToolExe, options.CscToolExe, propertyOverrides, logger);
            globalProperties.AddPropertyOverride(PropertyNames.VisualStudioVersion, options.VisualStudioVersion,
                propertyOverrides, logger);
            globalProperties.AddPropertyOverride(PropertyNames.Configuration, options.Configuration, propertyOverrides, logger);
            globalProperties.AddPropertyOverride(PropertyNames.Platform, options.Platform, propertyOverrides, logger);

            return globalProperties;
        }

        #endregion

        public // (MSB.Execution.ProjectInstance projectInstance, ImmutableArray<MSBuildDiagnostic> diagnostics)
            Tuple<MSB.Execution.ProjectInstance, ImmutableArray<MSBuildDiagnostic>>
            BuildProject(string filePath)
        {
            using (_sdksPathResolver.SetSdksPathEnvironmentVariable(filePath))
            {
                var evaluatedProject = EvaluateProjectFileCore(filePath);

                //  SetTargetFrameworkIfNeeded(evaluatedProject);
                var projectInstance = evaluatedProject.CreateProjectInstance();
                //  var msbuildLogger = new MSBuildLogger(_logger);
                var buildResult = false;
                //projectInstance.Build(
                //  targets: new string[] { TargetNames.Compile, TargetNames.CoreCompile },
                //  loggers: new[] { msbuildLogger });

                ImmutableArray<MSBuildDiagnostic> diagnostics = ImmutableArray<MSBuildDiagnostic>.Empty;
                // msbuildLogger.GetDiagnostics();

                return buildResult
                    ? new Tuple<MSB.Execution.ProjectInstance, ImmutableArray<MSBuildDiagnostic>>(projectInstance, diagnostics)
                    : new Tuple<MSB.Execution.ProjectInstance, ImmutableArray<MSBuildDiagnostic>>(null, diagnostics);
            }
        }

        public MSB.Evaluation.Project EvaluateProjectFile(string filePath)
        {
            using (_sdksPathResolver.SetSdksPathEnvironmentVariable(filePath))
            {
                return EvaluateProjectFileCore(filePath);
            }
        }

        private MSB.Evaluation.Project EvaluateProjectFileCore(string filePath)
        {
            // Evaluate the MSBuild project
            var projectCollection = new MSB.Evaluation.ProjectCollection(_globalProperties);

            var toolsVersion = _options.ToolsVersion;
            if (string.IsNullOrEmpty(toolsVersion) || Version.TryParse(toolsVersion, out _))
            {
                toolsVersion = projectCollection.DefaultToolsVersion;
            }

            toolsVersion = GetLegalToolsetVersion(toolsVersion, projectCollection.Toolsets);

            var vsV = Environment.GetEnvironmentVariable("VisualStudioVersion"); // @"14.0");
            if (toolsVersion == "2.0") //  && !string.IsNullOrWhiteSpace(vsV))
                toolsVersion = vsV ?? "14.0";

            return projectCollection.LoadProject(filePath, toolsVersion);
        }

        //private static void SetTargetFrameworkIfNeeded(MSB.Evaluation.Project evaluatedProject)
        //{
        //    var targetFramework = evaluatedProject.GetPropertyValue(PropertyNames.TargetFramework);
        //    var targetFrameworks = PropertyConverter.SplitList(evaluatedProject.GetPropertyValue(PropertyNames.TargetFrameworks), ';');

        //    // If the project supports multiple target frameworks and specific framework isn't
        //    // selected, we must pick one before execution. Otherwise, the ResolveReferences
        //    // target might not be available to us.
        //    if (string.IsNullOrWhiteSpace(targetFramework) && targetFrameworks.Length > 0)
        //    {
        //        // For now, we'll just pick the first target framework. Eventually, we'll need to
        //        // do better and potentially allow OmniSharp hosts to select a target framework.
        //        targetFramework = targetFrameworks[0];
        //        evaluatedProject.SetProperty(PropertyNames.TargetFramework, targetFramework);
        //    }
        //    else if (!string.IsNullOrWhiteSpace(targetFramework) && targetFrameworks.Length == 0)
        //    {
        //        targetFrameworks = ImmutableArray.Create(targetFramework);
        //    }
        //}

        private static string GetLegalToolsetVersion(string toolsVersion, ICollection<MSB.Evaluation.Toolset> toolsets)
        {
            // It's entirely possible the the toolset specified does not exist. In that case, we'll try to use
            // the highest version available.
            var version = new Version(toolsVersion);

            bool exists = false;
            Version highestVersion = null;

            var legalToolsets = new SortedList<Version, MSB.Evaluation.Toolset>(toolsets.Count);
            foreach (var toolset in toolsets)
            {
                // Only consider this toolset if it has a legal version, we haven't seen it, and its path exists.
                if (Version.TryParse(toolset.ToolsVersion, out var toolsetVersion) &&
                    !legalToolsets.ContainsKey(toolsetVersion) &&
                    Directory.Exists(toolset.ToolsPath))
                {
                    legalToolsets.Add(toolsetVersion, toolset);

                    if (highestVersion == null ||
                        toolsetVersion > highestVersion)
                    {
                        highestVersion = toolsetVersion;
                    }

                    if (toolsetVersion == version)
                    {
                        exists = true;
                    }
                }
            }

            if (highestVersion == null)
            {
                throw new InvalidOperationException("No legal MSBuild toolsets available.");
            }

            if (!exists)
            {
                toolsVersion = legalToolsets[highestVersion].ToolsPath;
            }

            return toolsVersion;
        }
    }

    internal static class Extensions
    {
        public static void AddPropertyOverride(
            this Dictionary<string, string> properties,
            string propertyName,
            string userOverrideValue,
            ImmutableDictionary<string, string> propertyOverrides,
            object logger)
        {
            var overrideValue = propertyOverrides.GetValueOrDefault(propertyName);

            if (!string.IsNullOrEmpty(userOverrideValue))
            {
                // If the user set the option, we should use that.
                properties.Add(propertyName, userOverrideValue);
                // logger.LogDebug($"'{propertyName}' set to '{userOverrideValue}' (user override)");
            }
            else if (!string.IsNullOrEmpty(overrideValue))
            {
                // If we have a custom environment value, we should use that.
                properties.Add(propertyName, overrideValue);
                // logger.LogDebug($"'{propertyName}' set to '{overrideValue}'");
            }
        }
    }

    internal static class PropertyNames
    {
        public const string DesignTimeBuild = nameof(DesignTimeBuild);
        public const string BuildingInsideVisualStudio = nameof(BuildingInsideVisualStudio);
        public const string BuildProjectReferences = nameof(BuildProjectReferences);
        public const string _ResolveReferenceDependencies = nameof(_ResolveReferenceDependencies);
        public const string SolutionDir = nameof(SolutionDir);
        public const string ProvideCommandLineArgs = nameof(ProvideCommandLineArgs);
        public const string SkipCompilerExecution = nameof(SkipCompilerExecution);

        public const string MSBuildExtensionsPath = nameof(MSBuildExtensionsPath);
        public const string TargetFrameworkRootPath = nameof(TargetFrameworkRootPath);
        public const string RoslynTargetsPath = nameof(RoslynTargetsPath);
        public const string CscToolPath = nameof(CscToolPath);
        public const string CscToolExe = nameof(CscToolExe);
        public const string VisualStudioVersion = nameof(VisualStudioVersion);
        public const string Configuration = nameof(Configuration);
        public const string Platform = nameof(Platform);
    }

    public class NullEventEmitter : IEventEmitter
    {
        public static IEventEmitter Instance { get; } = new NullEventEmitter();

        private NullEventEmitter() { }

        public void Emit(string kind, object args)
        {
            // nothing
        }
    }

    public class NullLoggerFactory : ILoggerFactory
    {
        public void AddProvider(ILoggerProvider provider) { }
        public ILogger CreateLogger(string categoryName) => new TraceLogger();

        public void Dispose() { }
    }

    public class TraceLogger : ILogger, IDisposable
    {
        public TraceLogger()
        {
        }

        public IDisposable BeginScope<TState>(TState state) => this;
        public void Dispose() { }

        public bool IsEnabled(LogLevel logLevel) => true;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
            Exception exception, Func<TState, Exception, string> formatter)
        {
            Trace.WriteLine(exception?.Message ?? "");
        }
    }
}


text:
using Anotar.NLog;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace DeVi.Models.TvDbApi
{
	internal class TvDB : ITvDB
	{
		public TvDB()
		{
			ApiUrlBase = $"{MirrorPath}/api/{ApiKeys.TvDbApiKey}";
		}

		public IEnumerable<Language> FetchLanguageList()
		{
			var doc = XDocument.Load( $"{ApiUrlBase}/languages.xml" );
			var root = doc.Element( "Languages" );
			if( root == null )
			{
				LogTo.Warn( "Failed to retrieve language list: Languages-Tag not found" );
				yield break;
			}

			foreach( var lang in root.Elements( "Language" ) )
			{
				var strId = lang.Element( "id" )?.Value;
				if( string.IsNullOrEmpty( strId ) )
				{
					continue;
				}

				uint id = uint.Parse( strId );
				string code = lang.Element( "abbreviation" )?.Value;

				yield return new Language
				{
					Id = id,
					Code = code
				};
			}
		}

		/// <summary>
		///     Retrieve information about an episode.
		/// </summary>
		/// <param name="episodeId">The identifier of the episode</param>
		/// <param name="language">Language to use when retrieving data.</param>
		/// <returns>Information about the episode</returns>
		public Episode GetBaseEpisodeRecord( uint episodeId, string language = "en" )
		{
			string url = $"{ApiUrlBase}/episodes/{episodeId}/{language}.xml";

			var doc = XDocument.Load( url );
			var root = doc.Element( "Data" )?.Element( "Episode" );
			if( root == null )
			{
				LogTo.Warn( "Failed to load episode information - Episode-Tag not found" );
				return null;
			}

			return ReadBaseEpisodeRecord( root );
		}

		/// <summary>
		///     Retrieve basic information about a series
		/// </summary>
		/// <param name="seriesId">The show identifier.</param>
		/// <param name="language">Language to use when retrieving data.</param>
		/// <returns>Information about the series</returns>
		public Series GetBaseSeriesRecord( uint seriesId, string language = "en" )
		{
			string url = $"{ApiUrlBase}/series/{seriesId}/{language}.xml";

			var doc = XDocument.Load( url );
			var root = doc.Element( "Data" )?.Element( "Series" );
			if( root == null )
			{
				LogTo.Warn( "Failed to load series information - Series-Tag not found" );
				return null;
			}

			return ReadBaseSeriesRecord( root );
		}

		/// <summary>
		/// Retrieve information about a series.
		/// </summary>
		/// <param name="seriesId">The series identifier.</param>
		/// <param name="language">Language to use while searching.</param>
		/// <returns></returns>
		public async Task<Series> GetFullSeriesRecord( uint seriesId, string language = "en" )
		{
			string url = $"{ApiUrlBase}/series/{seriesId}/all/{language}.zip";
			string tempFileName = Path.GetTempFileName();

			using( var client = new WebClient() )
			{
				await client.DownloadFileTaskAsync( url, tempFileName );

				try
				{
					using( var archive = ZipFile.OpenRead( tempFileName ) )
					{
						Series series;
						using( var stream = archive.GetEntry( $"{language}.xml" ).Open() )
						{
							var doc = XDocument.Load( stream );
							var root = doc.Element( "Data" );
							if( root == null )
							{
								LogTo.Warn( "Failed to load series information - Data-Tag not found" );
								return null;
							}

							series = ReadBaseSeriesRecord( root.Element( "Series" ) );
							foreach( var element in root.Elements( "Episode" ) )
							{
								series.Episodes.Add( ReadBaseEpisodeRecord( element ) );
							}
						}

						return series;
					}
				}
				finally
				{
					try
					{
						File.Delete( tempFileName );
					}
					catch( IOException )
					{
						// Don't care. It's a temporary file
					}
				}
			}
		}

		/// <summary>
		/// Retrieve updates for series and episodes.
		/// </summary>
		/// <param name="lastUpdate">Date and time of the last performed update.</param>
		/// <returns>List of updated series and episodes.</returns>
		public async Task<UpdateData> GetUpdates( DateTime lastUpdate )
		{
			string timeframe = "day";
			var diff = DateTime.Now - lastUpdate;
			if( diff.TotalDays > 30 )
			{
				timeframe = "all";
			}
			else if( diff.TotalDays > 7 )
			{
				timeframe = "month";
			}
			else if( diff.TotalDays > 1 )
			{
				timeframe = "week";
			}

			string url = $"{ApiUrlBase}/updates/updates_{timeframe}.zip";
			string tempFileName = Path.GetTempFileName();

			using( var client = new WebClient() )
			{
				await client.DownloadFileTaskAsync( url, tempFileName );

				try
				{
					using( var archive = ZipFile.OpenRead( tempFileName ) )
					{
						using( var stream = archive.GetEntry( $"updates_{timeframe}.xml" ).Open() )
						{
							var doc = XDocument.Load( stream );
							var root = doc.Element( "Data" );
							if( root == null )
							{
								LogTo.Warn( "Failed to load updates - Data-Tag not found" );
								return null;
							}

							List<uint> series = new List<uint>();
							List<uint> episodes = new List<uint>();

							foreach( var element in root.Elements( "Series" ) )
							{
								uint id;
								if( uint.TryParse( element.Element( "id" )?.Value, out id ) )
								{
									series.Add( id );
								}
							}

							foreach( var element in root.Elements( "Episode" ) )
							{
								uint id;
								if( uint.TryParse( element.Element( "id" )?.Value, out id ) )
								{
									episodes.Add( id );
								}
							}

							return new UpdateData( series, episodes );
						}
					}
				}
				finally
				{
					try
					{
						File.Delete( tempFileName );
					}
					catch( IOException )
					{
						// Don't care. It's a temporary file
					}
				}
			}
		}

		/// <summary>
		/// Searches for serieses.
		/// </summary>
		/// <param name="query">The query to search for.</param>
		/// <param name="language">Language to use when retrieving data.</param>
		/// <returns></returns>
		public IEnumerable<SeriesSearchResult> SearchSeries( string query, string language = "en" )
		{
			var doc = XDocument.Load( $"{MirrorPath}/api/GetSeries.php?seriesname={query}&language={language}" );
			var root = doc.Element( "Data" );
			if( root == null )
			{
				LogTo.Warn( "Failed to search series: Data-Tag not found" );
				yield break;
			}

			foreach( var element in root.Elements( "Series" ) )
			{
				var str = element.Element( "seriesid" )?.Value;
				if( string.IsNullOrEmpty( str ) )
				{
					continue;
				}

				uint id = uint.Parse( str );
				string name = element.Element( "SeriesName" )?.Value;
				string overview = element.Element( "Overview" )?.Value;
				string banner = element.Element( "banner" )?.Value;

				DateTime firstAired = DateTime.MinValue;
				str = element.Element( "FirstAired" )?.Value;
				if( !string.IsNullOrWhiteSpace( str ) )
				{
					firstAired = DateTime.ParseExact( str, "yyyy-MM-dd", CultureInfo.InvariantCulture );
				}

				yield return new SeriesSearchResult( id, name, overview, firstAired, banner );
			}
		}

		private static AirDay ParseAirDay( string value )
		{
			switch( value )
			{
			case "Daily":
				return AirDay.Daily;

			case "Monday":
				return AirDay.Monday;

			case "Tuesday":
				return AirDay.Thursday;

			case "Wednesday":
				return AirDay.Wednesday;

			case "Thursday":
				return AirDay.Thursday;

			case "Friday":
				return AirDay.Friday;

			case "Saturday":
				return AirDay.Saturday;

			case "Sunday":
				return AirDay.Sunday;

			default:
				return AirDay.Unknown;
			}
		}

		private static ContentRating ParseContentRating( string value )
		{
			switch( value )
			{
			case "TV-PG":
				return ContentRating.TVPG;

			case "TV-G":
				return ContentRating.TVG;

			case "TV-MA":
				return ContentRating.TVMA;

			case "TV-Y":
				return ContentRating.TVY;

			case "TV-Y7":
				return ContentRating.TVY7;

			case "TV-14":
				return ContentRating.TV14;

			default:
				return ContentRating.Unknown;
			}
		}

		private static SeriesStatus ParseSeriesStatus( string value )
		{
			switch( value )
			{
			case "Ended":
				return SeriesStatus.Ended;

			default:
				return SeriesStatus.Continuing;
			}
		}

		private static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
		{
			DateTime dtDateTime = new DateTime( 1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc );
			dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
			return dtDateTime;
		}

		private Episode ReadBaseEpisodeRecord( XElement parent )
		{
			Episode episode = new Episode();

			string str = parent.Element( "id" )?.Value;
			if( string.IsNullOrWhiteSpace( str ) )
			{
				LogTo.Warn( "Failed to read BaseSeriesRecord - id tag not found" );
				return null;
			}

			episode.Id = uint.Parse( str );
			episode.ImdbId = parent.Element( "IMDB_ID" )?.Value;
			episode.Overview = parent.Element( "Overview" )?.Value;
			episode.ProductionCode = parent.Element( "ProductionCode" )?.Value;
			episode.Name = parent.Element( "EpisodeName" )?.Value;

			str = parent.Element( "EpisodeNumber" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				episode.EpisodeNumber = uint.Parse( str, CultureInfo.InvariantCulture );
			}

			str = parent.Element( "absolute_number" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				episode.AbsoluteNumber = uint.Parse( str, CultureInfo.InvariantCulture );
			}

			str = parent.Element( "lastupdated" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				uint stamp = uint.Parse( str );
				episode.LastUpdated = UnixTimeStampToDateTime( stamp );
			}

			str = parent.Element( "FirstAired" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				episode.FirstAired = DateTime.ParseExact( str, "yyyy-MM-dd", CultureInfo.InvariantCulture );
			}

			str = parent.Element( "SeasonNumber" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				episode.SeasonNumber = uint.Parse( str, CultureInfo.InvariantCulture );
			}

			str = parent.Element( "GuestStars" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				foreach( var person in str.Split( SplitChars, StringSplitOptions.RemoveEmptyEntries ) )
				{
					episode.GuestStars.Add( new Person { Name = person } );
				}
			}

			str = parent.Element( "Writer" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				foreach( var person in str.Split( SplitChars, StringSplitOptions.RemoveEmptyEntries ) )
				{
					episode.Writers.Add( new Person { Name = person } );
				}
			}

			str = parent.Element( "Director" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				foreach( var person in str.Split( SplitChars, StringSplitOptions.RemoveEmptyEntries ) )
				{
					episode.Directors.Add( new Person { Name = person } );
				}
			}

			str = parent.Element( "Rating" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				episode.Rating = double.Parse( str, CultureInfo.InvariantCulture );
			}

			str = parent.Element( "RatingCount" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				episode.Ratings = int.Parse( str, CultureInfo.InvariantCulture );
			}

			str = parent.Element( "filename" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				episode.BannerLocation = new Uri( $"http://thetvdb.com/banners/{str}" );
			}

			return episode;
		}

		private Series ReadBaseSeriesRecord( XElement parent )
		{
			Series series = new Series();

			var element = parent.Element( "id" );
			if( element == null )
			{
				throw new InvalidDataException( "BaseSeriesRecord does not contain series id" );
			}

			series.Id = uint.Parse( element.Value );
			series.Name = parent.Element( "SeriesName" )?.Value;
			series.Overview = parent.Element( "Overview" )?.Value;
			series.ContentRating = ParseContentRating( parent.Element( "ContentRating" )?.Value );
			series.ImdbId = parent.Element( "IMDB_ID" )?.Value;
			series.AirDays = ParseAirDay( parent.Element( "Airs_DayOfWeek" )?.Value );
			series.Status = ParseSeriesStatus( parent.Element( "Status" )?.Value );

			series.Network = new Network
			{
				Name = parent.Element( "Network" )?.Value
			};

			series.Language = new Language
			{
				Code = parent.Element( "Language" )?.Value
			};

			string str = parent.Element( "Airs_Time" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				DateTime date;
				bool valid = true;

				if( !DateTime.TryParseExact( str, "h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date ) )
				{
					if( !DateTime.TryParseExact( str, "hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date ) )
					{
						valid = false;
					}
                }

				if( valid )
				{
					series.AirTime = date.TimeOfDay;
				}
			}

			str = parent.Element( "added" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				series.Added = DateTime.ParseExact( str, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture );
			}

			str = parent.Element( "addedBy" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				series.AddedBy = uint.Parse( str, CultureInfo.InvariantCulture );
			}

			str = parent.Element( "banner" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				series.BannerLocation = new Uri( $"http://thetvdb.com/banners/{str}" );
			}

			str = parent.Element( "lastupdated" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				uint stamp = uint.Parse( str );
				series.LastUpdated = UnixTimeStampToDateTime( stamp );
			}

			str = parent.Element( "Genre" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				foreach( var actor in str.Split( SplitChars, StringSplitOptions.RemoveEmptyEntries ) )
				{
					series.Genres.Add( new Genre { Name = actor } );
				}
			}

			str = parent.Element( "FirstAired" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				series.FirstAired = DateTime.ParseExact( str, "yyyy-MM-dd", CultureInfo.InvariantCulture );
			}

			str = parent.Element( "Actors" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				foreach( var actor in str.Split( SplitChars, StringSplitOptions.RemoveEmptyEntries ) )
				{
					series.Actors.Add( new Person { Name = actor } );
				}
			}

			str = parent.Element( "Runtime" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				series.Runtime = uint.Parse( str, CultureInfo.InvariantCulture );
			}

			str = parent.Element( "Rating" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				series.Rating = double.Parse( str, CultureInfo.InvariantCulture );
			}

			str = parent.Element( "RatingCount" )?.Value;
			if( !string.IsNullOrWhiteSpace( str ) )
			{
				series.Ratings = int.Parse( str, CultureInfo.InvariantCulture );
			}
			return series;
		}

		private const string MirrorPath = "http://thetvdb.com";
		private static readonly char[] SplitChars = { '|', ',', '&' };
		private readonly string ApiUrlBase;
	}
}

redpajama_set_name: RedPajamaGithub


text:
module Mat
    ( M44
    , V3 (..)
    , makePerspective
    , makeView
    , makeRotate
    , normalMatrix
    , identity
    , inv44
    ) where

import           Linear.Matrix     (M44, fromQuaternion, identity, inv44,
                                    m33_to_m44, transpose)
import qualified Linear.Projection as Proj
import           Linear.Quaternion (axisAngle)
import           Linear.V3         (V3 (..))

-- | Construct a perspective matrix.
makePerspective :: M44 Float
makePerspective =
    Proj.perspective (pi / 4) (800 / 600) 0.1 100

-- | Construct a view matrix.
makeView :: M44 Float
makeView =
    Proj.lookAt (V3 0 0 20) (V3 0 0 0) (V3 0 1 0)

makeRotate :: V3 Float -> Float -> M44 Float
makeRotate v = m33_to_m44 . fromQuaternion . axisAngle v

-- | Make a normal matrix.
normalMatrix :: M44 Float -> M44 Float
normalMatrix = transpose . inv44


text:
package io.github.cjstehno.ersatz.impl.matchers;

import io.github.cjstehno.ersatz.server.ClientRequest;
import io.github.cjstehno.ersatz.server.MockClientRequest;
import lombok.val;
import org.hamcrest.StringDescription;
import org.junit.jupiter.api.Test;

import static io.github.cjstehno.ersatz.cfg.HttpMethod.PUT;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.IsIterableContaining.hasItem;
import static org.junit.jupiter.api.Assertions.*;

class MappedValuesMatcherTest {

    @Test void mappedValues() {
        val request = new MockClientRequest(PUT, "/testing")
            .query("alpha", "one")
            .query("bravo", "two", "three");

        var matcher = new MappedValuesMatcher("Query param", equalTo("alpha"), hasItem("one"), ClientRequest::getQueryParams);
        assertTrue(matcher.matches(request));

        matcher = new MappedValuesMatcher("Query param", equalTo("bravo"), hasItem("three"), ClientRequest::getQueryParams);
        assertTrue(matcher.matches(request));

        matcher = new MappedValuesMatcher("Query param", equalTo("bravo"), hasItem("four"), ClientRequest::getQueryParams);
        assertFalse(matcher.matches(request));

        val desc = new StringDescription();
        matcher.describeTo(desc);
        assertEquals("Query param name is \"bravo\" and values are a collection containing \"four\"", desc.toString());
    }
}


text:
export type widthHeightObject = { width: number, height: number };
export class ResizeUtils {
	public static getScaleToFill(objSize: widthHeightObject, sizeToFill: widthHeightObject): number {
		var scale = (sizeToFill.height / sizeToFill.width) > (objSize.height / objSize.width) ? (sizeToFill.height / objSize.height) : (sizeToFill.width / objSize.width);
	    return scale;
	}

	public static getScaleToFit(objSize: widthHeightObject, sizeToFit: widthHeightObject): number {
		return Math.min(sizeToFit.width / objSize.width, sizeToFit.height / objSize.height);
	}
};


text: Use this plugin to setup your machine for android development.


text:
<!DOCTYPE html>

Bug 106538: Top layer fails for inline elements

This tests that position 'static' computes to 'absolute' in the top layer. The test passes if you see a single green box.

<dialog id="middle-dialog" class="green-box" data-offset-x="150" data-offset-y="100"></dialog>
<dialog id="right-dialog" class="green-box" data-offset-x="200" data-offset-y="100"></dialog>


text:
package com.aspose.email.examples.email;

import com.aspose.email.MailAddress;
import com.aspose.email.MailMessage;
import com.aspose.email.MailMessageLoadOptions;
import com.aspose.email.SaveOptions;
import com.aspose.email.examples.Utils;

public class ExtractingEmailHeaders
{
    public static void main(String[] args) throws Exception
    {
        // The path to the documents directory.
        String dataDir = Utils.getDataDir(ExtractingEmailHeaders.class);

        MailMessage message;

        //Create MailMessage instance by loading an EML file
        message = MailMessage.load(dataDir + "Message.eml", MailMessageLoadOptions.getDefaultEml());

        System.out.println("Printing all Headers:\n\n");

        //print out all the headers
        for (int i=0; i< message.getHeaders().getCount();i++)
        {
            System.out.println(message.getHeaders().get(i));
        }

        // Display status
        System.out.println("\nEmail message header printed successfully.");
    }
}


text:
module RSpec
  module Core
    module Formatters
      # @api private
      #
      # Extracts code snippets by looking at the backtrace of the passed error and applies synax highlighting and line numbers using html.
      class SnippetExtractor
        # @private
        class NullConverter
          def convert(code)
            %Q(#{code}\n# Install the coderay gem to get syntax highlighting)
          end
        end

        # @private
        class CoderayConverter
          def convert(code)
            CodeRay.scan(code, :ruby).html(:line_numbers => false)
          end
        end

        begin
          require 'coderay'
          @@converter = CoderayConverter.new
        rescue LoadError
          @@converter = NullConverter.new
        end

        # @api private
        #
        # Extract lines of code corresponding to  a backtrace.
        #
        # @param backtrace [String] the backtrace from a spec failure
        # @return [String] highlighted code snippet indicating where the spec failure occured
        #
        # @see #post_process
        def snippet(backtrace)
          raw_code, line = snippet_for(backtrace[0])
          highlighted = @@converter.convert(raw_code)
          post_process(highlighted, line)
        end

        # @api private
        #
        # Create a snippet from a line of code.
        #
        # @param error_line [String] file name with line number (i.e. 'foo_spec.rb:12')
        # @return [String] lines around the target line within the file
        #
        # @see #lines_around
        def snippet_for(error_line)
          if error_line =~ /(.*):(\d+)/
            file = $1
            line = $2.to_i
            [lines_around(file, line), line]
          else
            ["# Couldn't get snippet for #{error_line}", 1]
          end
        end

        # @api private
        #
        # Extract lines of code centered around a particular line within a source file.
        #
        # @param file [String] filename
        # @param line [Fixnum] line number
        # @return [String] lines around the target line within the file (2 above and 1 below).
        def lines_around(file, line)
          if File.file?(file)
            lines = File.read(file).split("\n")
            min = [0, line-3].max
            max = [line+1, lines.length-1].min
            selected_lines = []
            selected_lines.join("\n")
            lines[min..max].join("\n")
          else
            "# Couldn't get snippet for #{file}"
          end
        rescue SecurityError
          "# Couldn't get snippet for #{file}"
        end

        # @api private
        #
        # Adds line numbers to all lines and highlights the line where the failure occurred using html `span` tags.
        #
        # @param highlighted [String] syntax-highlighted snippet surrounding the offending line of code
        # @param offending_line [Fixnum] line where failure occured
        # @return [String] completed snippet
        def post_process(highlighted, offending_line)
          new_lines = []
          highlighted.split("\n").each_with_index do |line, i|
            new_line = "#{offending_line+i-2}#{line}"
            new_line = "#{new_line}" if i == 2
            new_lines << new_line
          end
          new_lines.join("\n")
        end

      end
    end
  end
end


text:
package ledger

import (
	"bytes"
	"encoding/binary"
	"math/big"

	"github.com/ethereum/go-ethereum/rlp"

	"github.com/wojtechnology/glacier/meddb"
)

type BlockHeader struct {
	ParentHash Hash
	Number     *big.Int
	Dt         *big.Int
	Nonce      BlockNonce
}

type BlockBody struct {
	Transactions []*Transaction
}

type Block struct {
	Header *BlockHeader
	Body   *BlockBody
}

// ----------------------
// Block database helpers
// ----------------------

// Returns big-endian encoded block number for header
func encodeBlockHeaderNumber(number uint64) []byte {
	enc := make([]byte, 8)
	binary.BigEndian.PutUint64(enc, number)
	return enc
}

// Concatenates elements to build key for storing block parts in database
func buildBlockHeaderKey(prefix string, hash Hash, number uint64) []byte {
	encNum := encodeBlockHeaderNumber(number)
	return append(append([]byte(prefix), hash.Bytes()...), encNum...)
}

// ----------------
// Block Header API
// ----------------

// Returns Sha256 hash of block header in rlp format
func (h *BlockHeader) Hash() Hash {
	// TODO: Cache this value
	return rlpHash(h)
}

// Writes block header to provided database in rlp format
func (h *BlockHeader) Write(db meddb.Database) error {
	key := buildBlockHeaderKey(blockHeaderPrefix, h.Hash(), h.Number.Uint64())
	return writeRlp(db, key, h)
}

// Writes head block header to provided database in rlp format
func (h *BlockHeader) WriteHead(db meddb.Database) error {
	key := []byte(headKey)
	return writeRlp(db, key, h)
}

// Gets block header from database in rlp format, constructs object and returns
func GetBlockHeader(db meddb.Database, hash Hash, number uint64) (*BlockHeader, error) {
	// TODO: Think about the error handling in this function
	key := buildBlockHeaderKey(blockHeaderPrefix, hash, number)
	data, err := db.Get(key)
	if err != nil {
		return nil, err
	}

	h := new(BlockHeader)
	if err := rlp.Decode(bytes.NewReader(data), h); err != nil {
		return nil, err
	}
	return h, nil
}

// Gets head block header from database in rlp format, constructs objects and returns
func GetHeadBlockHeader(db meddb.Database) (*BlockHeader, error) {
	// TODO: Think about the error handling in this function
	key := []byte(headKey)
	data, err := db.Get(key)
	if err != nil {
		return nil, err
	}

	h := new(BlockHeader)
	if err := rlp.Decode(bytes.NewReader(data), h); err != nil {
		return nil, err
	}
	return h, nil
}

// --------------
// Block Body API
// --------------

// Writes block to provided database in rlp format
func (b *BlockBody) Write(db meddb.Database, hash Hash, number uint64) error {
	key := buildBlockHeaderKey(blockBodyPrefix, hash, number)
	return writeRlp(db, key, b)
}

func GetBlockBody(db meddb.Database, hash Hash, number uint64) (*BlockBody, error) {
	// TODO: think about the error handling in this function
	key := buildBlockHeaderKey(blockBodyPrefix, hash, number)
	data, err := db.Get(key)
	if err != nil {
		return nil, err
	}

	b := new(BlockBody)
	if err = rlp.Decode(bytes.NewReader(data), b); err != nil {
		return nil, err
	}
	return b, nil
}

// ---------
// Block API
// ---------

func (b *Block) writeBody(db meddb.Database) error {
	err := b.Body.Write(db, b.Header.Hash(), b.Header.Number.Uint64())
	if err != nil {
		return err
	}
	return nil
}

// Writes block header and body to the database
func (b *Block) Write(db meddb.Database) error {
	err := b.Header.Write(db)
	if err != nil {
		return err
	}
	err = b.writeBody(db)
	if err != nil {
		return err
	}
	return nil
}

// Writes block header and body to the database using the head block key
func (b *Block) WriteHead(db meddb.Database) error {
	err := b.Header.WriteHead(db)
	if err != nil {
		return err
	}
	err = b.writeBody(db)
	if err != nil {
		return err
	}
	return nil
}

// Adds transaction to block body
func (b *Block) AddTransaction(t *Transaction) error {
	if b.Body == nil {
		return &MissingBodyError{B: b}
	}
	b.Body.Transactions = append(b.Body.Transactions, t)
	return nil
}

// Gets whole block from database
func GetBlock(db meddb.Database, hash Hash, number uint64) (*Block, error) {
	header, err := GetBlockHeader(db, hash, number)
	if err != nil {
		return nil, err
	}

	body, err := GetBlockBody(db, hash, number)
	if err != nil {
		return nil, err
	}

	b := &Block{
		Header: header,
		Body:   body,
	}
	return b, nil
}

// Gets whole head block from database
func GetHeadBlock(db meddb.Database) (*Block, error) {
	header, err := GetHeadBlockHeader(db)
	if err != nil {
		return nil, err
	}

	body, err := GetBlockBody(db, header.Hash(), header.Number.Uint64())
	if err != nil {
		return nil, err
	}

	b := &Block{
		Header: header,
		Body:   body,
	}
	return b, nil
}

// Gets and returns the genesis block if it exists in the database
// Otherwise, creates the genesis block, commits it to the database and returns it
func GetOrCreateGenesisBlock(db meddb.Database) (*Block, error) {
	// TODO: test
	gen := genesis()
	curGen, err := GetBlock(db, gen.Header.Hash(), gen.Header.Number.Uint64())
	if err != nil {
		// Means that we haven't found the genesis block
		err = gen.Write(db)
		if err != nil {
			return nil, err
		}
	} else {
		gen = curGen
	}
	return gen, nil
}

// Creates and returns genesis block
func genesis() *Block {
	header := &BlockHeader{
		ParentHash: StringToHash(genesisParentHash),
		Number:     big.NewInt(0),
		Dt:         big.NewInt(0),
		Nonce:      EncodeNonce(0),
	}
	body := &BlockBody{
		Transactions: make([]*Transaction, 0),
	}
	genesis := &Block{
		Header: header,
		Body:   body,
	}
	return genesis
}


text:
package io.github.greyp9.arwo.core.resource;

import io.github.greyp9.arwo.core.http.Http;
import io.github.greyp9.arwo.core.value.Value;

public final class PathU {

    private PathU() {
    }

    public static String toPath(final String basePath, final String... tokens) {
        final StringBuilder buffer = new StringBuilder();
        buffer.append(basePath);
        for (final String token : tokens) {
            if (!Value.isEmpty(token)) {
                buffer.append(token.startsWith(Http.Token.SLASH) ? "" : Http.Token.SLASH);
                buffer.append(token);
            }
        }
        return buffer.toString();
    }

    public static String toDir(final String prefix, final String... tokens) {
        return toPath(prefix, tokens) + Http.Token.SLASH;
    }

    public static String toParent(final String path) {
        final boolean endsSlash = path.endsWith(Http.Token.SLASH);
        return path + (endsSlash ? "" : Http.Token.SLASH) + "..";
    }
}


text:
package org.springframework.hateoas.config;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.hateoas.RelProvider;
import org.springframework.hateoas.config.EnableHypermediaSupport.HypermediaType;

/**
 * Integration tests for using {@link EnableHypermediaSupport} from within XML documents.
 *
 * @author Oliver Gierke
 */
public class XmlConfigurationIntegrationTest {

	/**
	 * @see #259
	 */
	@Test
	public void enablesHyperMediaSupportFromXml() {

		ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml", getClass());

		assertThat(context.getBean(RelProvider.class), is(notNullValue()));

		context.close();
	}

	@Configuration
	@EnableHypermediaSupport(type = HypermediaType.HAL)
	static class HypermediaConfiguration {}
}


text:
#pragma once

#include "common/Common.h"                           // for uint32
#include "decompressors/AbstractLJpegDecompressor.h" // for AbstractLJpegDe...
#include "io/Buffer.h"                               // for Buffer, Buffer:...
#include "io/ByteStream.h"                           // for ByteStream

namespace rawspeed {

class RawImage;

// Decompresses Lossless JPEGs, with 2-4 components

class LJpegDecompressor final : public AbstractLJpegDecompressor
{
  void decodeScan() override;
  template<int N_COMP> void decodeN();

  uint32 offX = 0;
  uint32 offY = 0;

public:
  LJpegDecompressor(const ByteStream& bs, const RawImage& img)
      : AbstractLJpegDecompressor(bs, img) {}

  void decode(uint32 offsetX, uint32 offsetY, bool fixDng16Bug);
};

} // namespace rawspeed


text:
<?php

namespace OpenConext\AttributeAggregationApiClientBundle\Tests\DependencyInjection;

use Matthias\SymfonyConfigTest\PhpUnit\ConfigurationTestCaseTrait;
use OpenConext\AttributeAggregationApiClientBundle\DependencyInjection\Configuration;
use OpenConext\AttributeAggregationApiClientBundle\Tests\DataProvider;
use PHPUnit\Framework\TestCase;

final class ConfigurationTest extends TestCase
{
    use ConfigurationTestCaseTrait;
    use DataProvider;

    private $validConfig = [
        'base_url' => 'http://aa.invalid/',
        'username' => 'test user',
        'password' => 'test password',
    ];

    /**
     * @test
     * @group eb_api_config
     * @dataProvider nonStringScalarProvider
     */
    public function base_url_cannot_be_other_than_string($value)
    {
        $config = $this->validConfig;
        $config["base_url"] = $value;

        $this->assertPartialConfigurationIsInvalid(
            [['http_client' => $config]],
            'http_client',
            "The Attribute Aggregation API base URL should be a string"
        );
    }

    /**
     * @test
     * @group eb_api_config
     */
    public function base_url_has_to_be_valid_url()
    {
        $config = $this->validConfig;
        $config["base_url"] = "not a valid URL";

        $this->assertPartialConfigurationIsInvalid(
            [['http_client' => $config]],
            'http_client',
            "The Attribute Aggregation API base URL should be a valid URL"
        );
    }

    /**
     * @test
     * @group eb_api_config
     */
    public function base_url_must_end_in_forward_slash()
    {
        $config = $this->validConfig;
        $config["base_url"] = "https://aa.invalid";

        $this->assertPartialConfigurationIsInvalid(
            [['http_client' => $config]],
            'http_client',
            "The Attribute Aggregation API base URL must end in a forward slash"
        );
    }

    /**
     * @test
     * @group eb_api_config
     * @dataProvider nonStringScalarProvider
     */
    public function username_cannot_be_other_than_string($value)
    {
        $config = $this->validConfig;
        $config["username"] = $value;

        $this->assertPartialConfigurationIsInvalid(
            [['http_client' => $config]],
            'http_client',
            "The Attribute Aggregation API username should be a string"
        );
    }

    /**
     * @test
     * @group eb_api_config
     * @dataProvider nonStringScalarProvider
     */
    public function password_cannot_be_other_than_string($value)
    {
        $config = $this->validConfig;
        $config["password"] = $value;

        $this->assertPartialConfigurationIsInvalid(
            [['http_client' => $config]],
            'http_client',
            "The Attribute Aggregation API password should be a string"
        );
    }

    protected function getConfiguration()
    {
        return new Configuration();
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

		<title>background() \ Language (API) \ Processing 2+</title>

		<link rel="icon" href="/favicon.ico" type="image/x-icon" />

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta name="Author" content="Processing Foundation" />
		<meta name="Publisher" content="Processing Foundation" />
		<meta name="Keywords" content="Processing, Sketchbook, Programming, Coding, Code, Art, Design" />
		<meta name="Description" content="Processing is a flexible software sketchbook and a language for learning how to code within the context of the visual arts. Since 2001, Processing has promoted software literacy within the visual arts and visual literacy within technology." />
		<meta name="Copyright" content="All contents copyright the Processing Foundation, Ben Fry, Casey Reas, and the MIT Media Laboratory" />

		<link href="css/style.css" rel="stylesheet" type="text/css" />

Processing

p5.js

Processing.py

Processing Foundation

				<form name="search" method="get" action="http://www.google.com/search">

<input type="hidden" name="as_sitesearch" value="processing.org" />
				       <input type="text" name="as_q" value="" size="20" class="text" />
				       <input type="submit" value=" " />

				</form>

	Language

	Libraries

	Tools

	Environment

This reference is for Processing 3.0+. If you have a previous version, use the reference included with your software. If you see any errors or have suggestions, please let us know. If you prefer a more technical reference, visit the Processing Javadoc.

		Name

background()

Examples

background(51);

background(255, 204, 0);

PImage img;
img = loadImage("laDefense.jpg");
background(img);

		Description

The background() function sets the color used for the background of the Processing window. The default background is light gray. This function is typically used within draw() to clear the display window at the beginning of each frame, but it can be used inside setup() to set the background on the first frame of animation or if the backgound need only be set once.

An image can also be used as the background for a sketch, although the image's width and height must match that of the sketch window. Images used with background() will ignore the current tint() setting. To resize an image to the size of the sketch window, use image.resize(width, height).

It is not possible to use the transparency alpha parameter with background colors on the main drawing surface. It can only be used along with a PGraphics object and createGraphics().

Syntax
background(rgb)
background(rgb, alpha)
background(gray)
background(gray, alpha)
background(v1, v2, v3)
background(v1, v2, v3, alpha)
background(image)

	Parameters

rgb
int: any value of the color datatype

alpha
float: opacity of the background

gray
float: specifies a value between white and black

v1
float: red or hue value (depending on the current color mode)

v2
float: green or saturation value (depending on the current color mode)

v3
float: blue or brightness value (depending on the current color mode)

image
PImage: PImage to set as background (must be same size as the sketch window)

Returns	void

Related	stroke()

fill()

tint()

colorMode()

Updated on June 20, 2015 10:37:37pm UTC

Processing is an open project intiated by Ben Fry and Casey Reas. It is developed by a team of volunteers.

                    © Info


text:
/**
 * Created by qhr66_000 on 2015-10-27.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    Sequelize = require('sequelize');

var review = function (sequelize) {
    var reviewModel = sequelize.define('Review', {
        author: {
            type: Sequelize.STRING,
            allowNull: false
        },
        score: {
            type: Sequelize.INTEGER,
            allowNull: false,
            validate: {
                //for some reason does not accept zero
                min: {args: 1, msg: "must be value from between 1 and 100"},
                max: {args: 100, msg: "must be value from between 1 and 100"}
            }
        },
        comment: Sequelize.STRING
    });
    return reviewModel;
};

module.exports = review;

//var reviewSchema = new Schema({
//    author: {type: String, required: true},
//    score: {type: Number, min: 0, max: 100, required: true},
//    comment: String,
//});
//
//exports.Model = mongoose.model('Review', reviewSchema);
//
//exports.schema = reviewSchema;


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_practical_test02_var03_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="practicaltest02var03.eim.systems.cs.pub.ro.practicaltest02var03.PracticalTest02Var03MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <EditText
        android:id="@+id/port"
        android:layout_width="match_parent"
        android:layout_height="50dp" />
    <Button
        android:text="Start"
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="50dp" />
        <EditText
            android:id="@+id/word"
            android:layout_width="match_parent"
            android:layout_height="50dp" />
        <Button
            android:text="Get"
            android:id="@+id/get"
            android:layout_width="match_parent"
            android:layout_height="50dp" />
        <TextView
            android:id="@+id/result"
            android:layout_width="match_parent"
            android:layout_height="200dp" />
    </LinearLayout>
</RelativeLayout>


text:
Write a program that finds in given array of integers a sequence of given sum `S` (if present).

_Example:_

|        array            |  S |  result |
|-------------------------|----|---------|
| 4, 3, 1, **4, 2, 5**, 8 | 11 | 4, 2, 5 |

_You do not have to submit anything for this problem._


text:
from CIM14.ENTSOE.Dynamics.IEC61970.Core.CoreIdentifiedObject import CoreIdentifiedObject

class CoreTerminal(CoreIdentifiedObject):

    def __init__(self, ConductingEquipment=None, *args, **kw_args):
        """Initialises a new 'CoreTerminal' instance.

        @param ConductingEquipment:
        """
        self._ConductingEquipment = None
        self.ConductingEquipment = ConductingEquipment

        super(CoreTerminal, self).__init__(*args, **kw_args)

    _attrs = []
    _attr_types = {}
    _defaults = {}
    _enums = {}
    _refs = ["ConductingEquipment"]
    _many_refs = []

    def getConductingEquipment(self):
        """
        """
        return self._ConductingEquipment

    def setConductingEquipment(self, value):
        if self._ConductingEquipment is not None:
            filtered = [x for x in self.ConductingEquipment.Terminals if x != self]
            self._ConductingEquipment._Terminals = filtered

        self._ConductingEquipment = value
        if self._ConductingEquipment is not None:
            if self not in self._ConductingEquipment._Terminals:
                self._ConductingEquipment._Terminals.append(self)

    ConductingEquipment = property(getConductingEquipment, setConductingEquipment)


text:
package cn.cerc.mis.core;

public interface SupportScriptFile {

    void addScriptFile(String fileName);

    void addScriptCode(HtmlContent scriptCode);
}


text:
package io.paradoxical.cassieq.clustering.allocation;

import com.godaddy.logging.Logger;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import io.paradoxical.cassieq.configurations.AllocationConfig;
import org.jooq.lambda.Seq;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;

import static com.godaddy.logging.LoggerFactory.getLogger;

public class ManualResourceAllocater implements ResourceAllocator {

    private Logger logger = getLogger(ManualResourceAllocater.class);

    private final AllocationConfig allocationConfig;
    private final ResourceConfig config;
    private final Supplier<Set<ResourceIdentity>> inputSupplier;
    private final Consumer<Set<ResourceIdentity>> onDistributed;

    @Inject
    public ManualResourceAllocater(
            AllocationConfig allocationConfig,
            @Assisted ResourceConfig config,
            @Assisted Supplier<Set<ResourceIdentity>> inputSupplier,
            @Assisted Consumer<Set<ResourceIdentity>> onDistributed) {
        this.allocationConfig = allocationConfig;
        this.config = config;
        this.inputSupplier = inputSupplier;
        this.onDistributed = onDistributed;
        logger = logger.with("allocation-group", config.getGroup());
    }

    @Override
    public void claim() {
        final List<ResourceIdentity> resourceIdentities = new ArrayList<>(inputSupplier.get());

        resourceIdentities.sort((a, b) -> a.get().compareTo(b.get()));

        final Integer manualAllocatorInstanceNumber = allocationConfig.getManualAllocatorInstanceNumber();

        final Integer manualAllocatorsCount = allocationConfig.getManualAllocatorsCount();

        if (manualAllocatorInstanceNumber == null || manualAllocatorsCount == null) {
            logger.warn("Manual allocation strategy selected but alloctor count and allocator instance are not set! Cannot allocate resources");
            return;
        }

        if (manualAllocatorInstanceNumber > manualAllocatorsCount) {
            logger.with("instance-num", manualAllocatorInstanceNumber)
                  .with("allocator-count", manualAllocatorsCount)
                  .warn("Instance number is greater than total allocators. Not allocating");

            return;
        }

        long sliceSize = Double.valueOf(Math.ceil((resourceIdentities.size() / manualAllocatorsCount))).longValue();

        long start = sliceSize * manualAllocatorInstanceNumber;

        long end;

        if(manualAllocatorsCount - 1 == manualAllocatorInstanceNumber){
            end = resourceIdentities.size();
        }
        else{
            end = sliceSize * (manualAllocatorInstanceNumber + 1);
        }

        final Seq<ResourceIdentity> slice = Seq.seq(resourceIdentities).slice(start, end);

        onDistributed.accept(slice.toSet());
    }

    @Override
    public void close() throws Exception {

    }
}


text:
package com.google.wave.prototype.dataflow.transform;

import java.util.Arrays;
import java.util.List;

import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;

import com.google.cloud.dataflow.sdk.Pipeline;
import com.google.cloud.dataflow.sdk.testing.DataflowAssert;
import com.google.cloud.dataflow.sdk.testing.TestPipeline;
import com.google.cloud.dataflow.sdk.transforms.Create;
import com.google.cloud.dataflow.sdk.transforms.DoFnTester;
import com.google.cloud.dataflow.sdk.values.KV;
import com.google.cloud.dataflow.sdk.values.PCollection;
import com.google.wave.prototype.dataflow.coder.AggregateDataCoder;
import com.google.wave.prototype.dataflow.model.AggregatedData;
import com.google.wave.prototype.dataflow.transform.AggregateEvents;
import com.google.wave.prototype.dataflow.transform.AggregateEvents.CountEvents;
import com.google.wave.prototype.dataflow.transform.AggregateEvents.FilterRawData;

/**
 * Unit tester for AggregateEvents PTransform and the DoFn present in it
 */
public class AggregateEventsTest {

    @SuppressWarnings("unchecked")
    @Test
    public void filterRawDataTest() {
        FilterRawData filterRawDataDoFn = new AggregateEvents.FilterRawData();
        DoFnTester<String, KV<String, String>> doFnTester = DoFnTester.of(filterRawDataDoFn);

        // getAdDataSampleCSVRows() will return raw AdData csv rows
        // FilterRawData DoFn will extract ProposalId and event from it
        List<KV<String, String>> results = doFnTester.processBatch(getAdDataSampleCSVRows());

        // Based on the input following KV are expected
        KV<String, String> expectedValue1 = KV.of("101", "Impression");
        KV<String, String> expectedValue2 = KV.of("102", "Click");
        KV<String, String> expectedValue3 = KV.of("101", "Click");
        Assert.assertThat(results, CoreMatchers.hasItems(expectedValue1, expectedValue2, expectedValue3));
    }

    @SuppressWarnings("unchecked")
    @Test
    public void countEventsDoFnTest() {
        CountEvents countEventsDoFn = new AggregateEvents.CountEvents();
        DoFnTester<KV<String, Iterable<String>>, AggregatedData> countEventDoFnTester = DoFnTester.of(countEventsDoFn);

        // Input to AggregateEvents.CountEvents
        KV<String, Iterable<String>> kvPropsalIdEvents1 = KV.of("101", (Iterable<String>) Arrays.asList("Impression", "Click", "Impression"));
        KV<String, Iterable<String>> kvPropsalIdEvents2 = KV.of("102", (Iterable<String>) Arrays.asList("Click", "Impression"));
        KV<String, Iterable<String>> kvPropsalIdEvents3 = KV.of("103", (Iterable<String>) Arrays.asList("Click"));

        List<AggregatedData> results = countEventDoFnTester.processBatch(kvPropsalIdEvents1, kvPropsalIdEvents2, kvPropsalIdEvents3);

        // Expected results
        // For proposalId 101, there are 1 Click and 2 Impressions in the input
        // Hence the expected in new AggregatedData("101", 1, 2)
        // For proposalId 102, there are 1 Click and 1 Impression in the input
        // For proposalId 103, there are 1 Click and 0 Impression in the input
        AggregatedData expectedValue1 = new AggregatedData("101", 1, 2);
        AggregatedData expectedValue2 = new AggregatedData("102", 1, 1);
        AggregatedData expectedValue3 = new AggregatedData("103", 1, 0);
        Assert.assertThat(results, CoreMatchers.hasItems(expectedValue1, expectedValue2, expectedValue3));
    }

    @Test
    public void aggregateEventsTransformTest() {
        Pipeline p = TestPipeline.create();

        PCollection<String> inPCol = p.apply(Create.of(getAdDataSampleCSVRows()));
        PCollection<AggregatedData> result = inPCol.apply(new AggregateEvents())
                .setCoder(AggregateDataCoder.getInstance());

        // Input data contains 3 rows
        // 2 proposal Id present in input 101 and 102
        // And proposal Id 101 has 1 Impression and 1 Click
        // Proposal Id 102 has 1 Click
        // So expected values are new AggregatedData("101", 1, 1) and new AggregatedData("102", 1, 0)
        AggregatedData expectedValue1 = new AggregatedData("101", 1, 1);
        AggregatedData expectedValue2 = new AggregatedData("102", 1, 0);
        DataflowAssert.that(result).containsInAnyOrder(Arrays.asList(expectedValue1, expectedValue2));

        p.run();
    }

    private String[] getAdDataSampleCSVRows() {
        String[] adDataSampleCSVRows = new String[3];
        adDataSampleCSVRows[0] = "1,01-01-14 9:00,ip-10-150-38-122/10.150.38.122,0,70.209.198.223,http://sample.com,3232,Impression,3,1,101";
        adDataSampleCSVRows[1] = "2,01-01-14 9:01,ip-10-150-38-122/10.150.38.123,0,70.209.198.223,http://sample.com,3232,Click,3,1,102";
        adDataSampleCSVRows[2] = "3,01-01-14 9:00,ip-10-150-38-122/10.150.38.122,0,70.209.198.223,http://sample.com,3232,Click,3,1,101";

        return adDataSampleCSVRows;
    }

}


text:
<?php

namespace Fannan\TransactionModule\Test\Unit\Transaction;

class TransactionSeederTest extends \TestCase
{

}


text:
/**
 * @add jQuery.Drag.prototype
 */

steal.plugins('jquery/event/drag', 'jquery/dom/cur_styles').then(function( $ ) {
	var round = function( x, m ) {
		return Math.round(x / m) * m;
	}

	$.Drag.prototype.
	/**
	 * @function step
	 * @plugin jquery/event/drag/step
	 * @download  http://jmvcsite.heroku.com/pluginify?plugins[]=jquery/event/drag/step/step.js
	 * makes the drag move in steps of amount pixels.
	 * @codestart
	 * drag.step({x: 5}, $('foo'))
	 * @codeend
	 * @param {number} amount
	 * @param {jQuery} container
	 * @return {jQuery.Drag} the drag
	 */
	step = function( amount, container ) {
		//on draws ... make sure this happens
		if ( typeof amount == 'number' ) {
			amount = {
				x: amount,
				y: amount
			}
		}
		container = container || $(document.body);
		this._step = amount;

		var styles = container.curStyles("borderTopWidth", "paddingTop", "borderLeftWidth", "paddingLeft");
		var left = parseInt(styles.borderTopWidth) + parseInt(styles.paddingTop),
			top = parseInt(styles.borderLeftWidth) + parseInt(styles.paddingLeft);

		this._step.offset = container.offsetv().plus(left, top);
		return this;
	};

	var oldPosition = $.Drag.prototype.position;
	$.Drag.prototype.position = function( offsetPositionv ) {
		//adjust required_css_position accordingly
		if ( this._step ) {
			var movingSize = this.movingElement.dimensionsv('outer'),
				lot = this._step.offset.top(),
				lof = this._step.offset.left();

			if ( this._step.x ) {
				offsetPositionv.left(Math.round(lof + round(offsetPositionv.left() - lof, this._step.x)))
			}
			if ( this._step.y ) {
				offsetPositionv.top(Math.round(lot + round(offsetPositionv.top() - lot, this._step.y)))
			}
		}

		oldPosition.call(this, offsetPositionv)
	}

})


text:
<?php

/**
 * Social Login Global Functions
 *
 * @version 1.1.0
 * @since 1.0
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

if ( ! function_exists( 'woocommerce_social_login_buttons' ) ) :

/**
 * Pluggable function to render social login buttons
 *
 * @since 1.0
 * @param string $return_url Return url, defaults to the current url
 */
function woocommerce_social_login_buttons( $return_url = null ) {

	if ( is_user_logged_in() ) {
		return;
	}

	// If no return_url, use the current URL
	if ( ! $return_url ) {
		$return_url = home_url( add_query_arg( array() ) );
	}

	// Enqueue styles and scripts
	wc_social_login()->frontend->load_styles_scripts();

	// load the template
	wc_get_template(
		'global/social-login.php',
		array(
			'providers'  => wc_social_login()->get_available_providers(),
			'return_url' => $return_url,
			'login_text' => get_option( 'wc_social_login_text' ),
		),
		'',
		wc_social_login()->get_plugin_path() . '/templates/'
	);
}

endif;

if ( ! function_exists( 'woocommerce_social_login_link_account_buttons' ) ) :

	/**
	 * Pluggable function to render social login "link your account" buttons
	 *
	 * @since 1.1.0
	 * @param string $return_url Return url, defaults my account page
	 */
	function woocommerce_social_login_link_account_buttons( $return_url = null ) {

		if ( ! is_user_logged_in() ) {
			return;
		}

		// If no return_url, use the my account page
		if ( ! $return_url ) {
			$return_url = SV_WC_Plugin_Compatibility::wc_get_page_permalink( 'myaccount' );
		}

		// Enqueue styles and scripts
		wc_social_login()->frontend->load_styles_scripts();

		$available_providers = array();

		// determine available providers for user
		foreach ( wc_social_login()->get_available_providers() as $provider ) {

			if ( ! get_user_meta( get_current_user_id(), '_wc_social_login_' . $provider->get_id() . '_profile', true ) ) {
				$available_providers[] = $provider;
			}
		}

		// load the template
		wc_get_template(
			'global/social-login-link-account.php',
			array(
				'available_providers'  => $available_providers,
				'return_url'           => $return_url,
			),
			'',
			wc_social_login()->get_plugin_path() . '/templates/'
		);
	}

endif;


text:
var setting = require('../../../utils/nativeSetting');
module.exports = {
	process : function(ctx, step, next) {
		ctx.vars[step.var] = setting.getString(step.name, step.value);
		setTimeout(next, 1);
	}
}


text:
package com.google.android.exoplayer.upstream;

import com.google.android.exoplayer.C;
import com.google.android.exoplayer.util.Assertions;

import android.content.Context;
import android.content.res.AssetManager;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

/**
 * A local asset {@link UriDataSource}.
 */
public final class AssetDataSource implements UriDataSource {

  /**
   * Thrown when an {@link IOException} is encountered reading a local asset.
   */
  public static final class AssetDataSourceException extends IOException {

    public AssetDataSourceException(IOException cause) {
      super(cause);
    }

  }

  private final AssetManager assetManager;
  private final TransferListener listener;

  private String uriString;
  private InputStream inputStream;
  private long bytesRemaining;
  private boolean opened;

  /**
   * Constructs a new {@link DataSource} that retrieves data from a local asset.
   */
  public AssetDataSource(Context context) {
    this(context, null);
  }

  /**
   * Constructs a new {@link DataSource} that retrieves data from a local asset.
   *
   * @param listener An optional listener. Specify {@code null} for no listener.
   */
  public AssetDataSource(Context context, TransferListener listener) {
    this.assetManager = context.getAssets();
    this.listener = listener;
  }

  @Override
  public long open(DataSpec dataSpec) throws AssetDataSourceException {
    try {
      uriString = dataSpec.uri.toString();
      String path = dataSpec.uri.getPath();
      if (path.startsWith("/android_asset/")) {
        path = path.substring(15);
      } else if (path.startsWith("/")) {
        path = path.substring(1);
      }
      uriString = dataSpec.uri.toString();
      inputStream = assetManager.open(path, AssetManager.ACCESS_RANDOM);
      long skipped = inputStream.skip(dataSpec.position);
      Assertions.checkState(skipped == dataSpec.position);
      bytesRemaining = dataSpec.length == C.LENGTH_UNBOUNDED ? inputStream.available()
          : dataSpec.length;
      if (bytesRemaining < 0) {
        throw new EOFException();
      }
    } catch (IOException e) {
      throw new AssetDataSourceException(e);
    }

    opened = true;
    if (listener != null) {
      listener.onTransferStart();
    }
    return bytesRemaining;
  }

  @Override
  public int read(byte[] buffer, int offset, int readLength) throws AssetDataSourceException {
    if (bytesRemaining == 0) {
      return -1;
    } else {
      int bytesRead = 0;
      try {
        bytesRead = inputStream.read(buffer, offset, (int) Math.min(bytesRemaining, readLength));
      } catch (IOException e) {
        throw new AssetDataSourceException(e);
      }

      if (bytesRead > 0) {
        bytesRemaining -= bytesRead;
        if (listener != null) {
          listener.onBytesTransferred(bytesRead);
        }
      }

      return bytesRead;
    }
  }

  @Override
  public String getUri() {
    return uriString;
  }

  @Override
  public void close() throws AssetDataSourceException {
    uriString = null;
    if (inputStream != null) {
      try {
        inputStream.close();
      } catch (IOException e) {
        throw new AssetDataSourceException(e);
      } finally {
        inputStream = null;
        if (opened) {
          opened = false;
          if (listener != null) {
            listener.onTransferEnd();
          }
        }
      }
    }
  }

}


text:
import * as angular from 'angular';
import * as _ from 'underscore';
import {PreviewFileDataSet} from "../model/preview-file-data-set";
import {FileMetadataTransformResponse} from "../model/file-metadata-transform-response"
import {Node} from "../../../api/models/node";
import {Observable} from "rxjs/Observable";
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/map';
import {DataSource} from "../../../api/models/datasource";
import {HttpClient} from "@angular/common/http";
import {Injectable} from "@angular/core";

export interface DetectionResult {
    filePaths ?: string[];
    result ?: FileMetadataTransformResponse;
}

@Injectable()
export class FileMetadataTransformService  {

    /**
     * Array of the selected file paths that have been detected
     */
   private detectionResult:DetectionResult;

    cache:  {[key: string]: FileMetadataTransformResponse} = {}

    constructor(private http: HttpClient) {

    }

    detectFormatForNode(node:Node, datasource:DataSource): Observable<FileMetadataTransformResponse> {
        let paths = this.getSelectedItems(node,datasource);
        //return if the paths are the same
        if (this.detectionResult && this.detectionResult.filePaths != undefined) {
            let selectedFilePathsString = this.detectionResult.filePaths.toString();
            let pathsString = paths.toString();
            if (selectedFilePathsString == pathsString) {
                return Observable.of(this.detectionResult.result);
            }
        }

        return this.detectFormat(paths, datasource);
    }

    detectFormatForPaths(paths:string[], datasource:DataSource): Observable<FileMetadataTransformResponse> {
        //return if the paths are the same
        if (this.detectionResult && this.detectionResult.filePaths != undefined) {
            let selectedFilePathsString = this.detectionResult.filePaths.toString();
            let pathsString = paths.toString();
            if (selectedFilePathsString == pathsString) {
                return Observable.of(this.detectionResult.result);
            }
        }
        return this.detectFormat(paths, datasource);
    }

    getSelectedItems(node:Node, datasource:DataSource) :string[] {
        let paths = node.getSelectedDescendants().map((node) => {
            let path = node.getBrowserObject().getPath();
            if (datasource.connector.id == "local-file-system") {
                //ensure the path starts with file://
                if (path.indexOf("file:/") != 0) {
                    path = "file://" + path;
                }
            }
            return path;
        });
        return paths;
    }

    detectFormat(paths:string[], datasource:DataSource) :Observable<FileMetadataTransformResponse>{
        let observable =null;
        let cacheKey = datasource.id+"_"+paths.sort().toString();
        if(this.cache[cacheKey]){
            observable = Observable.of(this.cache[cacheKey]);

        }
        else {
            observable = new Observable<FileMetadataTransformResponse>((observer) => {

                let request: any = {
                    dataSource: datasource,
                    paths: paths
                }
                let statusCheckTime = 300

                let formatDetected = (data: FileMetadataTransformResponse): void => {

                    this.detectionResult = {}

                    this.detectionResult.filePaths = paths;
                    this.detectionResult.result = new FileMetadataTransformResponse(data)
                    if (this.detectionResult.result.results) {
                        _.each(this.detectionResult.result.results.datasets, (dataset: PreviewFileDataSet, key: string) => {
                            dataset.dataSource = datasource;
                        })
                    }
                    this.cache[cacheKey] = this.detectionResult.result
                    observer.next(this.detectionResult.result);
                }

                let formatError = (data: FileMetadataTransformResponse): void => {
                    console.log('FORMAT ERROR ', data);
                    observer.error(data)
                }

                formatError.bind(this)
                formatDetected.bind(this)

                let checkProgress = (data: FileMetadataTransformResponse): void => {

                    if (data.status == "PENDING") {
                        setTimeout(() => fileMetadataProgress(data.table), statusCheckTime)
                    }
                    else if (data.status == "SUCCESS") {
                        formatDetected(data);
                    }
                    else if (data.status == "ERROR") {
                        formatError(data);
                    }
                }

                let fileMetadataProgress = (id: string) => {

                    this.http.get("/proxy/v1/spark/shell/file-metadata/" + id).subscribe((data: any) => {
                        checkProgress(data);
                    }, error1 => {
                        formatError(error1)
                    })
                }

                this.http.post("/proxy/v1/spark/shell/file-metadata", request)
                    .subscribe((data: any) => {

                        checkProgress(data);
                    });

            });
        }
        return observable;

    }
}


text:
package uk.co.real_logic.aeron.driver;

import uk.co.real_logic.agrona.status.PositionIndicator;

/**
 * Consumption position a subscriber has got to within a {@link DriverSubscription}.
 */
public final class SubscriberPosition
{
    private final DriverSubscription subscription;
    private final int positionCounterId;
    private final PositionIndicator positionIndicator;

    public SubscriberPosition(
        final DriverSubscription subscription, final int positionCounterId, final PositionIndicator positionIndicator)
    {
        this.subscription = subscription;
        this.positionCounterId = positionCounterId;
        this.positionIndicator = positionIndicator;
    }

    public PositionIndicator positionIndicator()
    {
        return positionIndicator;
    }

    public int positionCounterId()
    {
        return positionCounterId;
    }

    public DriverSubscription subscription()
    {
        return subscription;
    }
}


text:
package info.dgjones.abora.ug2java.transform.method.intra;

import java.util.List;

import info.dgjones.abora.ug2java.JavaMethod;
import info.dgjones.abora.ug2java.javatoken.JavaAssignment;
import info.dgjones.abora.ug2java.javatoken.JavaCallEnd;
import info.dgjones.abora.ug2java.javatoken.JavaCallStart;
import info.dgjones.abora.ug2java.javatoken.JavaIdentifier;
import info.dgjones.abora.ug2java.transform.method.AbstractMethodBodyTransformation;
import info.dgjones.abora.ug2java.transform.tokenmatcher.TokenMatcher;
import info.dgjones.abora.ug2java.transform.tokenmatcher.TokenMatcherFactory;

public class TransformReceiverReceiveIntegerVar extends AbstractMethodBodyTransformation {

	public TransformReceiverReceiveIntegerVar() {
		super();
	}
	public TransformReceiverReceiveIntegerVar(TokenMatcherFactory factory) {
		super(factory);
	}

	protected TokenMatcher matchers(TokenMatcherFactory factory) {
		return factory.seq(
				factory.token(JavaIdentifier.class),
				factory.token(JavaAssignment.class),
				factory.token(JavaIdentifier.class),
				factory.token(JavaCallStart.class, "receiveIntegerVar"),
				factory.token(JavaCallEnd.class));
	}

	protected int transform(JavaMethod javaMethod, List tokens, int i) {
		JavaIdentifier variable = (JavaIdentifier)tokens.get(i);
		String type = javaMethod.findTypeOfVariable(variable.value);
		if (type != null && type.equals("boolean")) {
			JavaCallStart call = (JavaCallStart)tokens.get(i+3);
			call.value="receiveBooleanVar";
		}

		return i;
	}

}


text:
![Build Status](https://ahdde.visualstudio.com/_apis/public/build/definitions/c46377a0-ba14-4eb7-9145-b950c0883320/2/badge)

## Synopsis

Client library for submitting data to and querying from [graphite](https://github.com/graphite-project/graphite-web)

## Code Example
### Submit metrics
```csharp
var client = new CarbonClient("example.com");

var datapoints = new[]
    {
        new Datapoint("data.server1.cpuUsage", 10, DateTime.Now),
        new Datapoint("data.server2.cpuUsage", 15, DateTime.Now),
        new Datapoint("data.server3.cpuUsage", 20, DateTime.Now),
    };

await client.SendAsync(datapoints);
```

### Query metrics
```csharp
//dynamically build targets - 'data.*.server[0-9].{cpu,ram,disk}.Usage'
var path = new GraphitePath("data")
    .WildcardPath()
    .Path("server").Range('0', '9')
    .ValuePath("cpu", "ram", "disk").Path("Usage");

//invoke functions on targets - alias(sum(data.*.server[0-9].{cpu,ram,disk}.Usage),"usage")
var function = path.Sum().Alias("usage");

//retrieve data from graphite
var client = new GraphiteClient("http://example.com");
var data = await client.GetMetricsDataAsync(function, "-1d")
```

For details take a look at the [tests](https://github.com/ahdde/graphite.net/blob/master/Graphite.Test/GraphitePathTest.cs)

## Motivation

All existing libraries we found supported only string parameters for querying graphite. To fix this we wrote our own statically typed client.

This client also supports sending batch data via the python pickle protocol (in addition to the plaintext protocol) (many thanks to [Razorvine](https://github.com/irmen/pickle)).

## Installation

Install via [nuget](https://www.nuget.org/packages/ahd.Graphite).

## Known Issues

Please be aware that this library might include functions which are not yet stable or miss functions from the latest stable release. To work around unsupported features you can always call .ToString() and use the inappropriately named function `GraphitePath.Parse()`. Depending on your build configuration you may also use the obsolete method `.Function("functionName", params)`.

## Contributing

We are happily accepting pull requests for any missing feature or enhancement. If anything is unclear, do not hesitate to open an [issue](https://github.com/ahdde/graphite.net/issues/new).

## License

Licensed under [MIT License](https://github.com/ahdde/graphite.net/blob/master/LICENSE.md)


text:
package org.keycloak.testsuite.pages;

import org.keycloak.testsuite.util.DroneUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

/**
 * Page shown during processing of the PushButtonAuthenticator
 *
 * @author Marek Posolda
 */
public class PushTheButtonPage extends AbstractPage {

    @FindBy(name = "submit1")
    private WebElement submitButton;

    @Override
    public void open() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isCurrent() {
        return DroneUtils.getCurrentDriver().getTitle().equals("PushTheButton")
                && !driver.findElements(By.name("submit1")).isEmpty();
    }

    public void submit() {
        submitButton.click();
    }
}


text:
var pomelo = require('pomelo');
/**
 * Init app for client.
 */
var app = pomelo.createApp();
app.set('name', 'cityofpomelo');

// app configuration
app.configure('production|development', 'connector', function(){
  app.set('connectorConfig',
    {
      connector : pomelo.connectors.hybridconnector,
      heartbeat : 3
    });
});

app.configure('production|development', 'gate', function(){
  app.set('connectorConfig',
    {
      connector : pomelo.connectors.hybridconnector,
      useProtobuf : true
    });
});

// start app
app.start();

process.on('uncaughtException', function(err) {
  console.error(' Caught exception: ' + err.stack);
});


text:
package bwyap.utility.logging;

/**
 * A concrete logger class that prints log messages to the System output stream
 * @author bwyap
 *
 */
public class SystemLogger extends Logger {

	protected SystemLogger() { }

	@Override
	public void printMessage(String msg) {
		System.out.println(msg);
	}

	@Override
	public void logMessage(String msg) {
		System.out.println("[MSG] " + msg);
	}

	@Override
	public void logInfo(String msg) {
		System.out.println("[INF] " + msg);
	}

	@Override
	public void logErr(String msg) {
		System.err.println("[ERR] " + msg);
	}

	@Override
	public void logWarning(String msg) {
		System.out.println("[WRN] " + msg);
	}

}


text:
<root>
    <scripts>
        <include src="file://{resources}/scripts/selection/selection.js" />
        <include src="file://{resources}/scripts/selection/selection_filter.js" />
    </scripts>
    <Panel></Panel>
</root>


text:
.class Lcom/android/internal/app/ResolverActivity$ResolverComparator;
.super Ljava/lang/Object;
.source "ResolverActivity.java"

# interfaces
.implements Ljava/util/Comparator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/app/ResolverActivity;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "ResolverComparator"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Ljava/util/Comparator",
        "<",
        "Landroid/content/pm/ResolveInfo;",
        ">;"
    }
.end annotation

# instance fields
.field private final mCollator:Ljava/text/Collator;

.field private final mHttp:Z

.field final synthetic this$0:Lcom/android/internal/app/ResolverActivity;

# direct methods
.method public constructor <init>(Lcom/android/internal/app/ResolverActivity;Landroid/content/Context;Landroid/content/Intent;)V
    .locals 2
    .param p2, "context"    # Landroid/content/Context;
    .param p3, "intent"    # Landroid/content/Intent;

    .prologue
    .line 1331
    iput-object p1, p0, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->this$0:Lcom/android/internal/app/ResolverActivity;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 1332
    invoke-virtual {p2}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;

    move-result-object v1

    invoke-virtual {v1}, Landroid/content/res/Resources;->getConfiguration()Landroid/content/res/Configuration;

    move-result-object v1

    iget-object v1, v1, Landroid/content/res/Configuration;->locale:Ljava/util/Locale;

    invoke-static {v1}, Ljava/text/Collator;->getInstance(Ljava/util/Locale;)Ljava/text/Collator;

    move-result-object v1

    iput-object v1, p0, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->mCollator:Ljava/text/Collator;

    .line 1333
    invoke-virtual {p3}, Landroid/content/Intent;->getScheme()Ljava/lang/String;

    move-result-object v0

    .line 1334
    .local v0, "scheme":Ljava/lang/String;
    const-string v1, "http"

    invoke-virtual {v1, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_0

    const-string v1, "https"

    invoke-virtual {v1, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_1

    :cond_0
    const/4 v1, 0x1

    :goto_0
    iput-boolean v1, p0, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->mHttp:Z

    .line 1335
    return-void

    .line 1334
    :cond_1
    const/4 v1, 0x0

    goto :goto_0
.end method

.method private getPackageTimeSpent(Ljava/lang/String;)J
    .locals 4
    .param p1, "packageName"    # Ljava/lang/String;

    .prologue
    .line 1374
    iget-object v1, p0, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->this$0:Lcom/android/internal/app/ResolverActivity;

    # getter for: Lcom/android/internal/app/ResolverActivity;->mStats:Ljava/util/Map;
    invoke-static {v1}, Lcom/android/internal/app/ResolverActivity;->access$1100(Lcom/android/internal/app/ResolverActivity;)Ljava/util/Map;

    move-result-object v1

    if-eqz v1, :cond_0

    .line 1375
    iget-object v1, p0, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->this$0:Lcom/android/internal/app/ResolverActivity;

    # getter for: Lcom/android/internal/app/ResolverActivity;->mStats:Ljava/util/Map;
    invoke-static {v1}, Lcom/android/internal/app/ResolverActivity;->access$1100(Lcom/android/internal/app/ResolverActivity;)Ljava/util/Map;

    move-result-object v1

    invoke-interface {v1, p1}, Ljava/util/Map;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/app/usage/UsageStats;

    .line 1376
    .local v0, "stats":Landroid/app/usage/UsageStats;
    if-eqz v0, :cond_0

    .line 1377
    invoke-virtual {v0}, Landroid/app/usage/UsageStats;->getTotalTimeInForeground()J

    move-result-wide v2

    .line 1381
    .end local v0    # "stats":Landroid/app/usage/UsageStats;
    :goto_0
    return-wide v2

    :cond_0
    const-wide/16 v2, 0x0

    goto :goto_0
.end method

# virtual methods
.method public compare(Landroid/content/pm/ResolveInfo;Landroid/content/pm/ResolveInfo;)I
    .locals 10
    .param p1, "lhs"    # Landroid/content/pm/ResolveInfo;
    .param p2, "rhs"    # Landroid/content/pm/ResolveInfo;

    .prologue
    .line 1340
    iget v6, p1, Landroid/content/pm/ResolveInfo;->targetUserId:I

    const/4 v7, -0x2

    if-eq v6, v7, :cond_0

    .line 1341
    const/4 v6, 0x1

    .line 1370
    :goto_0
    return v6

    .line 1344
    :cond_0
    iget-boolean v6, p0, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->mHttp:Z

    if-eqz v6, :cond_2

    .line 1348
    iget v6, p1, Landroid/content/pm/ResolveInfo;->match:I

    invoke-static {v6}, Lcom/android/internal/app/ResolverActivity;->isSpecificUriMatch(I)Z

    move-result v0

    .line 1349
    .local v0, "lhsSpecific":Z
    iget v6, p2, Landroid/content/pm/ResolveInfo;->match:I

    invoke-static {v6}, Lcom/android/internal/app/ResolverActivity;->isSpecificUriMatch(I)Z

    move-result v1

    .line 1350
    .local v1, "rhsSpecific":Z
    if-eq v0, v1, :cond_2

    .line 1351
    if-eqz v0, :cond_1

    const/4 v6, -0x1

    goto :goto_0

    :cond_1
    const/4 v6, 0x1

    goto :goto_0

    .line 1355
    .end local v0    # "lhsSpecific":Z
    .end local v1    # "rhsSpecific":Z
    :cond_2
    iget-object v6, p0, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->this$0:Lcom/android/internal/app/ResolverActivity;

    # getter for: Lcom/android/internal/app/ResolverActivity;->mStats:Ljava/util/Map;
    invoke-static {v6}, Lcom/android/internal/app/ResolverActivity;->access$1100(Lcom/android/internal/app/ResolverActivity;)Ljava/util/Map;

    move-result-object v6

    if-eqz v6, :cond_4

    .line 1356
    iget-object v6, p2, Landroid/content/pm/ResolveInfo;->activityInfo:Landroid/content/pm/ActivityInfo;

    iget-object v6, v6, Landroid/content/pm/ActivityInfo;->packageName:Ljava/lang/String;

    invoke-direct {p0, v6}, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->getPackageTimeSpent(Ljava/lang/String;)J

    move-result-wide v6

    iget-object v8, p1, Landroid/content/pm/ResolveInfo;->activityInfo:Landroid/content/pm/ActivityInfo;

    iget-object v8, v8, Landroid/content/pm/ActivityInfo;->packageName:Ljava/lang/String;

    invoke-direct {p0, v8}, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->getPackageTimeSpent(Ljava/lang/String;)J

    move-result-wide v8

    sub-long v4, v6, v8

    .line 1360
    .local v4, "timeDiff":J
    const-wide/16 v6, 0x0

    cmp-long v6, v4, v6

    if-eqz v6, :cond_4

    .line 1361
    const-wide/16 v6, 0x0

    cmp-long v6, v4, v6

    if-lez v6, :cond_3

    const/4 v6, 0x1

    goto :goto_0

    :cond_3
    const/4 v6, -0x1

    goto :goto_0

    .line 1365
    .end local v4    # "timeDiff":J
    :cond_4
    iget-object v6, p0, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->this$0:Lcom/android/internal/app/ResolverActivity;

    # getter for: Lcom/android/internal/app/ResolverActivity;->mPm:Landroid/content/pm/PackageManager;
    invoke-static {v6}, Lcom/android/internal/app/ResolverActivity;->access$700(Lcom/android/internal/app/ResolverActivity;)Landroid/content/pm/PackageManager;

    move-result-object v6

    invoke-virtual {p1, v6}, Landroid/content/pm/ResolveInfo;->loadLabel(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;

    move-result-object v2

    .line 1366
    .local v2, "sa":Ljava/lang/CharSequence;
    if-nez v2, :cond_5

    iget-object v6, p1, Landroid/content/pm/ResolveInfo;->activityInfo:Landroid/content/pm/ActivityInfo;

    iget-object v2, v6, Landroid/content/pm/ActivityInfo;->name:Ljava/lang/String;

    .line 1367
    :cond_5
    iget-object v6, p0, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->this$0:Lcom/android/internal/app/ResolverActivity;

    # getter for: Lcom/android/internal/app/ResolverActivity;->mPm:Landroid/content/pm/PackageManager;
    invoke-static {v6}, Lcom/android/internal/app/ResolverActivity;->access$700(Lcom/android/internal/app/ResolverActivity;)Landroid/content/pm/PackageManager;

    move-result-object v6

    invoke-virtual {p2, v6}, Landroid/content/pm/ResolveInfo;->loadLabel(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;

    move-result-object v3

    .line 1368
    .local v3, "sb":Ljava/lang/CharSequence;
    if-nez v3, :cond_6

    iget-object v6, p2, Landroid/content/pm/ResolveInfo;->activityInfo:Landroid/content/pm/ActivityInfo;

    iget-object v3, v6, Landroid/content/pm/ActivityInfo;->name:Ljava/lang/String;

    .line 1370
    :cond_6
    iget-object v6, p0, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->mCollator:Ljava/text/Collator;

    invoke-interface {v2}, Ljava/lang/CharSequence;->toString()Ljava/lang/String;

    move-result-object v7

    invoke-interface {v3}, Ljava/lang/CharSequence;->toString()Ljava/lang/String;

    move-result-object v8

    invoke-virtual {v6, v7, v8}, Ljava/text/Collator;->compare(Ljava/lang/String;Ljava/lang/String;)I

    move-result v6

    goto :goto_0
.end method

.method public bridge synthetic compare(Ljava/lang/Object;Ljava/lang/Object;)I
    .locals 1
    .param p1, "x0"    # Ljava/lang/Object;
    .param p2, "x1"    # Ljava/lang/Object;

    .prologue
    .line 1327
    check-cast p1, Landroid/content/pm/ResolveInfo;

    .end local p1    # "x0":Ljava/lang/Object;
    check-cast p2, Landroid/content/pm/ResolveInfo;

    .end local p2    # "x1":Ljava/lang/Object;
    invoke-virtual {p0, p1, p2}, Lcom/android/internal/app/ResolverActivity$ResolverComparator;->compare(Landroid/content/pm/ResolveInfo;Landroid/content/pm/ResolveInfo;)I

    move-result v0

    return v0
.end method


text:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name="index"),
    url(r'^episodes/', views.episodes, name="episodes"),
]


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Describes a series of key/value pairs that encapsulate aspects of a browser.
 */
public interface Capabilities {

  default String getBrowserName() {
    return String.valueOf(Optional.ofNullable(getCapability("browserName")).orElse(""));
  }

  default Platform getPlatform() {
    Object rawPlatform = getCapability("platform");

    if (rawPlatform == null) {
      return null;
    }

    if (rawPlatform instanceof String) {
      return Platform.valueOf((String) rawPlatform);
    } else if (rawPlatform instanceof Platform) {
      return (Platform) rawPlatform;
    }

    throw new IllegalStateException("Platform was neither a string or a Platform: " + rawPlatform);
  }

  default String getVersion() {
    return String.valueOf(Optional.ofNullable(getCapability("version")).orElse(""));
  }

  /**
   * @deprecated Use is(SUPPORTS_JAVASCRIPT) instead
   * @see #is(String)
   * @see org.openqa.selenium.remote.CapabilityType#SUPPORTS_JAVASCRIPT
   */
  @Deprecated
  default boolean isJavascriptEnabled() {
    return is("javascriptEnabled");
  }

  /**
   * @return The capabilities as a Map
   */
  Map<String, ?> asMap();

  /**
   * @see org.openqa.selenium.remote.CapabilityType
   * @param capabilityName The capability to return.
   * @return The value, or null if not set.
   */
  Object getCapability(String capabilityName);

  /**
   * @see org.openqa.selenium.remote.CapabilityType
   * @param capabilityName The capability to check.
   * @return Whether or not the value is not null and not false.
   */
  default boolean is(String capabilityName) {
    Object cap = getCapability(capabilityName);
    if (cap == null) {
      // javascriptEnabled is true if not set explicitly
      return "javascriptEnabled".equals(capabilityName);
    }
    return cap instanceof Boolean ? (Boolean) cap : Boolean.parseBoolean(String.valueOf(cap));
  }

  /**
   * Merge two {@link Capabilities} together and return the union of the two as a new
   * {@link Capabilities} instance. Capabilities from {@code other} will override those in
   * {@code this}.
   */
  default Capabilities merge(Capabilities other) {
    HashMap<String, Object> map = new HashMap<>();
    map.putAll(asMap());
    if (other != null) {
      map.putAll(other.asMap());
    }
    return new ImmutableCapabilities(map);
  }
}