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

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Common.Core;
using Microsoft.Common.Core.Services;
using Microsoft.R.Host.Client.Session;
using Microsoft.R.Host.Client.Test.Fixtures;
using Microsoft.R.Host.Client.Test.Script;
using Microsoft.R.Platform.IO;
using Microsoft.UnitTests.Core.XUnit;
using Microsoft.UnitTests.Core.XUnit.MethodFixtures;

namespace Microsoft.R.Host.Client.Test {
    [ExcludeFromCodeCoverage]
    public class IdeGraphicsDeviceTest {
        private readonly IServiceContainer _services;
        private readonly GraphicsDeviceTestFilesFixture _files;
        private readonly TestMethodFixture _testMethod;

        private const int DefaultWidth = 360;
        private const int DefaultHeight = 360;

        private const int DefaultExportWidth = 480;
        private const int DefaultExportHeight = 480;
        private const int DefaultExportResolution = 96;

        public List<string> PlotFilePaths { get; } = new List<string>();
        public List<PlotMessage> OriginalPlotMessages { get; } = new List<PlotMessage>();

        private PlotDeviceProperties DefaultDeviceProperties = new PlotDeviceProperties(DefaultWidth, DefaultHeight, 96);

        public IdeGraphicsDeviceTest(IServiceContainer services, GraphicsDeviceTestFilesFixture files, TestMethodFixture testMethod) {
            _services = services;
            _files = files;
            _testMethod = testMethod;
        }

        private int X(double percentX) {
            return (int)(DefaultWidth * percentX);
        }

        private int Y(double percentY) {
            return (int)(DefaultHeight - DefaultHeight * percentY - 1);
        }

        [Test]
        [Category.Plots]
        public async Task GridLine() {
            var code = @"
library(grid)
grid.newpage()
grid.segments(.01, .1, .99, .1)
";
            var inputs = Batch(code);
            var actualPlotFilePaths = await GraphicsTestAsync(inputs);
            var plotFilePath = actualPlotFilePaths.Should().ContainSingle().Which;

            var bmp = (Bitmap)Image.FromFile(plotFilePath);
            bmp.Width.Should().Be(DefaultWidth);
            bmp.Height.Should().Be(DefaultHeight);
            var startX = X(0.01);
            var endX = X(0.99);
            var y = Y(0.1);

            var fg = Color.FromArgb(255, 0, 0, 0);
            var bg = Color.FromArgb(255, 255, 255, 255);

            // Check extremities on the line
            bmp.GetPixel(startX, y).Should().Be(fg);
            bmp.GetPixel(endX, y).Should().Be(fg);

            // Check extremities outside of line
            bmp.GetPixel(startX - 1, y).Should().Be(bg);
            bmp.GetPixel(endX + 1, y).Should().Be(bg);

            // Check above and below line
            bmp.GetPixel(startX, y - 1).Should().Be(bg);
            bmp.GetPixel(startX, y + 1).Should().Be(bg);
        }

        [Test]
        [Category.Plots]
        public async Task MultiplePagesTwoBatchesInteractive() {
            var inputs = new[] {
                @"
library(grid)
redGradient <- matrix(hcl(0, 80, seq(50, 80, 10)), nrow = 4, ncol = 5)

# interpolated
grid.newpage()
grid.raster(redGradient)
",
                @"
# blocky
grid.newpage()
grid.raster(redGradient, interpolate = FALSE)
"
            };

            var actualPlotFilePaths = await GraphicsTestAsync(inputs);
            actualPlotFilePaths.Should().HaveCount(2);
        }

        [Test]
        [Category.Plots]
        public async Task MultiplePlotsInteractive() {
            var code = @"
plot(0:10)
plot(5:15)
";
            var inputs = Interactive(code);
            var actualPlotFilePaths = await GraphicsTestAsync(inputs);
            actualPlotFilePaths.Should().HaveCount(2);
        }

        [Test]
        [Category.Plots]
        public async Task MultiplePlotsBatch() {
            var code = @"
plot(0:10)
plot(5:15)
";
            var inputs = Batch(code);
            var actualPlotFilePaths = await GraphicsTestAsync(inputs);
            actualPlotFilePaths.Should().HaveCount(2);
        }

        [Test]
        [Category.Plots]
        public async Task PlotCars() {
            var expectedPath = await WriteExpectedImageAsync("png", 360, 360, 96, "Expected", "plot(cars)");

            var code = @"
plot(cars)
";
            var inputs = Batch(code);
            var actualPlotPaths = (await GraphicsTestAsync(inputs)).ToArray();
            var expectedPlotPaths = new string[] { expectedPath };
            CompareImages(actualPlotPaths, expectedPlotPaths);
        }

        [Test]
        [Category.Plots]
        public async Task SetInitialSize() {
            DefaultDeviceProperties = new PlotDeviceProperties(600, 600, 96);

            var code = @"
plot(0:10)
";
            var inputs = Batch(code);
            var actualPlotFilePaths = await GraphicsTestAsync(inputs);
            var plotFilePath = actualPlotFilePaths.Should().ContainSingle().Which;

            var bmp = (Bitmap)Image.FromFile(plotFilePath);
            bmp.Width.Should().Be(600);
            bmp.Height.Should().Be(600);
        }

        [Test]
        [Category.Plots]
        public async Task ResizeNonInteractive() {
            var code = @"
plot(0:10)
rtvs:::graphics.ide.resize(rtvs:::graphics.ide.getactivedeviceid(), 600, 600, 96)
";
            var inputs = Batch(code);
            var actualPlotFilePaths = await GraphicsTestAsync(inputs);
            var plotFilePath = actualPlotFilePaths.Should().ContainSingle().Which;

            var bmp = (Bitmap)Image.FromFile(plotFilePath);
            bmp.Width.Should().Be(600);
            bmp.Height.Should().Be(600);
        }

        [Test]
        [Category.Plots]
        public async Task ResizeInteractive() {
            var code = @"
plot(0:10)
rtvs:::graphics.ide.resize(rtvs:::graphics.ide.getactivedeviceid(), 600, 600, 96)
";
            var inputs = Interactive(code);
            var actualPlotFilePaths = (await GraphicsTestAsync(inputs)).ToArray();
            actualPlotFilePaths.Should().HaveCount(2);

            var bmp1 = (Bitmap)Image.FromFile(actualPlotFilePaths[0]);
            var bmp2 = (Bitmap)Image.FromFile(actualPlotFilePaths[1]);
            bmp1.Width.Should().Be(DefaultWidth);
            bmp1.Height.Should().Be(DefaultHeight);
            bmp2.Width.Should().Be(600);
            bmp2.Height.Should().Be(600);
        }

        [Test]
        [Category.Plots]
        public async Task ResizeInteractiveNoTempFilesLeak() {
            //https://github.com/Microsoft/RTVS/issues/1568
            var code = @"
plot(0:10)
rtvs:::graphics.ide.resize(rtvs:::graphics.ide.getactivedeviceid(), 600, 600, 96)
";
            var tmpFilesBefore = Directory.GetFiles(Path.GetTempPath(), "rhost-ide-plot-*.png");
            var inputs = Interactive(code);
            var actualPlotFilePaths = (await GraphicsTestAsync(inputs)).ToArray();
            actualPlotFilePaths.Should().HaveCount(2);
            var tmpFilesAfter = Directory.GetFiles(Path.GetTempPath(), "rhost-ide-plot-*.png");
            tmpFilesAfter.ShouldAllBeEquivalentTo(tmpFilesBefore);
        }

        [Test]
        [Category.Plots]
        public async Task ExportToImage() {
            var exportedBmpFilePath = _files.ExportToBmpResultPath;
            var exportedPngFilePath = _files.ExportToPngResultPath;
            var exportedJpegFilePath = _files.ExportToJpegResultPath;
            var exportedTiffFilePath = _files.ExportToTiffResultPath;

            var code = string.Format(@"
plot(0:10)
"
            );

            string[] format = { "bmp", "png", "jpeg", "tiff" };
            string[] paths = { exportedBmpFilePath, exportedPngFilePath, exportedJpegFilePath, exportedTiffFilePath };
            var inputs = Interactive(code);
            var actualPlotFilePaths = await ExportToImageAsync(inputs, format, paths, DefaultExportWidth, DefaultExportHeight, DefaultExportResolution);
            var plotFilePath = actualPlotFilePaths.Should().ContainSingle().Which;

            var bmp = (Bitmap)Image.FromFile(plotFilePath);
            bmp.Width.Should().Be(DefaultWidth);
            bmp.Height.Should().Be(DefaultHeight);

            var exportedBmp = (Bitmap)Image.FromFile(exportedBmpFilePath);
            exportedBmp.Width.Should().Be(DefaultExportWidth);
            exportedBmp.Height.Should().Be(DefaultExportHeight);

            var exportedPng = (Bitmap)Image.FromFile(exportedPngFilePath);
            exportedPng.Width.Should().Be(DefaultExportWidth);
            exportedPng.Height.Should().Be(DefaultExportHeight);

            var exportedJpeg = (Bitmap)Image.FromFile(exportedJpegFilePath);
            exportedJpeg.Width.Should().Be(DefaultExportWidth);
            exportedJpeg.Height.Should().Be(DefaultExportHeight);

            var exportedTiff = (Bitmap)Image.FromFile(exportedTiffFilePath);
            exportedTiff.Width.Should().Be(DefaultExportWidth);
            exportedTiff.Height.Should().Be(DefaultExportHeight);
        }

        [Test]
        [Category.Plots]
        public async Task ExportPreviousPlotToImage() {
            var expectedExportedBmpFilePath = await WriteExpectedImageAsync("bmp", DefaultExportWidth, DefaultExportHeight, DefaultExportResolution, "Expected", "plot(0:10)");

            var actualExportedBmpFilePath = _files.GetDestinationPath("ExportPreviousPlotToImageExpected1.bmp");
            var code = string.Format(@"
plot(0:10)
plot(10:20)
rtvs:::graphics.ide.previousplot(rtvs:::graphics.ide.getactivedeviceid())
"
            );

            var inputs = Interactive(code);
            string[] format = { "bmp"};
            string[] paths = { actualExportedBmpFilePath };
            var actualPlotFilePaths = await ExportToImageAsync(inputs, format, paths, DefaultExportWidth, DefaultExportHeight, DefaultExportResolution);
            actualPlotFilePaths.Should().HaveCount(3);

            CompareImages(new string[] { actualExportedBmpFilePath }, new string[] { expectedExportedBmpFilePath });
        }

        [Test]
        [Category.Plots]
        public async Task ExportToPdf() {
            var exportedFilePath = _files.ExportToPdfResultPath;

            var code = string.Format(@"
plot(0:10)
"
            );

            var inputs = Interactive(code);
            var actualPlotFilePaths = await ExportToPdfAsync(inputs, exportedFilePath, 7, 7);
            var plotFilePath = actualPlotFilePaths.Should().ContainSingle().Which;

            var bmp = (Bitmap)Image.FromFile(plotFilePath);
            bmp.Width.Should().Be(DefaultWidth);
            bmp.Height.Should().Be(DefaultHeight);

            PdfComparer.ComparePdfFiles(exportedFilePath, _files.ExpectedExportToPdfPath);
        }

        [Test]
        [Category.Plots]
        public async Task ResizeInteractiveMultiPlots() {
            // Resize a graph with multiple plots, where the
            // code is executed one line at a time interactively
            // Make sure that all parts of the graph are present
            // We used to have a bug where the resized image only had
            // the top left plot, and the others were missing
            var expected1Path = await WriteExpectedImageAsync("png", 360, 360, 96, "Expected1", "par(mfrow=c(2,2));plot(0:1)");
            var expected2Path = await WriteExpectedImageAsync("png", 360, 360, 96, "Expected2", "par(mfrow=c(2,2));plot(0:1);plot(1:2)");
            var expected3Path = await WriteExpectedImageAsync("png", 360, 360, 96, "Expected3", "par(mfrow=c(2,2));plot(0:1);plot(1:2);plot(2:3)");
            var expected4Path = await WriteExpectedImageAsync("png", 360, 360, 96, "Expected4", "par(mfrow=c(2,2));plot(0:1);plot(1:2);plot(2:3);plot(3:4)");
            var expected5Path = await WriteExpectedImageAsync("png", 600, 600, 96, "Expected5", "par(mfrow=c(2,2));plot(0:1);plot(1:2);plot(2:3);plot(3:4)");

            var code = @"
par(mfrow = c(2, 2))
plot(0:1)
plot(1:2)
plot(2:3)
plot(3:4)
rtvs:::graphics.ide.resize(rtvs:::graphics.ide.getactivedeviceid(), 600, 600, 96)
";
            var inputs = Interactive(code);
            var actualPlotPaths = (await GraphicsTestAsync(inputs)).ToArray();
            var expectedPlotPaths = new string[] { expected1Path, expected2Path, expected3Path, expected4Path, expected5Path };
            CompareImages(actualPlotPaths, expectedPlotPaths);
        }

        [Test]
        [Category.Plots]
        public async Task ResizeNonInteractiveMultiPlots() {
            // Resize a graph with multiple plots, where the
            // code is executed all at once
            // Make sure that all parts of the graph are present
            // We used to have a bug where the resized image only had
            // the top left plot, and the others were missing
            var expected1Path = await WriteExpectedImageAsync("png", 360, 360, 96, "Expected1", "par(mfrow=c(2,2));plot(0:1);plot(1:2);plot(2:3);plot(3:4)");
            var expected2Path = await WriteExpectedImageAsync("png", 600, 600, 96, "Expected2", "par(mfrow=c(2,2));plot(0:1);plot(1:2);plot(2:3);plot(3:4)");

            var inputs = new [] {
                @"
par(mfrow = c(2, 2))
plot(0:1)
plot(1:2)
plot(2:3)
plot(3:4)
",
"rtvs:::graphics.ide.resize(rtvs:::graphics.ide.getactivedeviceid(), 600, 600, 96)",
            };
            var actualPlotPaths = (await GraphicsTestAsync(inputs)).ToArray();
            var expectedPlotPaths = new string[] { expected1Path, expected2Path };
            CompareImages(actualPlotPaths, expectedPlotPaths);
        }

        [Test]
        [Category.Plots]
        public async Task Previous() {
            var code = @"
plot(0:10)
plot(5:15)
rtvs:::graphics.ide.previousplot(rtvs:::graphics.ide.getactivedeviceid())
";

            var inputs = Interactive(code);
            var actualPlotFilePaths = (await GraphicsTestAsync(inputs)).ToArray();
            actualPlotFilePaths.Should().HaveCount(3);

            File.ReadAllBytes(actualPlotFilePaths[2]).Should().Equal(File.ReadAllBytes(actualPlotFilePaths[0]));
            File.ReadAllBytes(actualPlotFilePaths[1]).Should().NotEqual(File.ReadAllBytes(actualPlotFilePaths[0]));

            OriginalPlotMessages.Last().ActivePlotIndex.Should().Be(0);
            OriginalPlotMessages.Last().PlotCount.Should().Be(2);
        }

        [Test]
        [Category.Plots]
        public async Task ClearPlots() {
            var code = @"
plot(0:10)
plot(0:15)
rtvs:::graphics.ide.clearplots(rtvs:::graphics.ide.getactivedeviceid())
";

            var inputs = Interactive(code);
            var actualPlotFilePaths = await GraphicsTestAsync(inputs);
            actualPlotFilePaths.Should().HaveCount(2);

            OriginalPlotMessages.Last().ActivePlotIndex.Should().Be(-1);
            OriginalPlotMessages.Last().PlotCount.Should().Be(0);
        }

        [Test]
        [Category.Plots]
        public async Task RemovePlotFirst() {
            var code = @"
plot(0:10)
plot(0:20)
plot(0:30)
device_id <- rtvs:::graphics.ide.getactivedeviceid()
rtvs:::graphics.ide.previousplot(device_id)
rtvs:::graphics.ide.previousplot(device_id)
rtvs:::graphics.ide.removeplot(device_id, rtvs:::graphics.ide.getactiveplotid(device_id))
";

            var inputs = Interactive(code);
            var actualPlotFilePaths = await GraphicsTestAsync(inputs);
            actualPlotFilePaths.Should().HaveCount(6);

            OriginalPlotMessages.Last().ActivePlotIndex.Should().Be(0);
            OriginalPlotMessages.Last().PlotCount.Should().Be(2);
        }

        [Test]
        [Category.Plots]
        public async Task RemovePlotLast() {
            var code = @"
plot(0:10)
plot(0:20)
plot(0:30)
device_id <- rtvs:::graphics.ide.getactivedeviceid()
rtvs:::graphics.ide.removeplot(device_id, rtvs:::graphics.ide.getactiveplotid(device_id))
";

            var inputs = Interactive(code);
            var actualPlotFilePaths = await GraphicsTestAsync(inputs);
            actualPlotFilePaths.Should().HaveCount(4);

            OriginalPlotMessages.Last().ActivePlotIndex.Should().Be(1);
            OriginalPlotMessages.Last().PlotCount.Should().Be(2);
        }

        [Test]
        [Category.Plots]
        public async Task RemovePlotMiddle() {
            var code = @"
plot(0:10)
plot(0:20)
plot(0:30)
device_id <- rtvs:::graphics.ide.getactivedeviceid()
rtvs:::graphics.ide.previousplot(device_id)
rtvs:::graphics.ide.removeplot(device_id, rtvs:::graphics.ide.getactiveplotid(device_id))
";

            var inputs = Interactive(code);
            var actualPlotFilePaths = await GraphicsTestAsync(inputs);
            actualPlotFilePaths.Should().HaveCount(5);

            OriginalPlotMessages.Last().ActivePlotIndex.Should().Be(1);
            OriginalPlotMessages.Last().PlotCount.Should().Be(2);
        }

        [Test]
        [Category.Plots]
        public async Task RemovePlotSingle() {
            var code = @"
plot(0:10)
device_id <- rtvs:::graphics.ide.getactivedeviceid()
rtvs:::graphics.ide.removeplot(device_id, rtvs:::graphics.ide.getactiveplotid(device_id))
";

            var inputs = Interactive(code);
            var actualPlotFilePaths = await GraphicsTestAsync(inputs);
            actualPlotFilePaths.Should().HaveCount(1);

            OriginalPlotMessages.Last().ActivePlotIndex.Should().Be(-1);
            OriginalPlotMessages.Last().PlotCount.Should().Be(0);
        }

        [Test]
        [Category.Plots]
        public async Task HistoryResizeOldPlot() {
            var expected1Path = await WriteExpectedImageAsync("png", 360, 360, 96, "Expected1", "plot(0:10)");
            var expected2Path = await WriteExpectedImageAsync("png", 360, 360, 96, "Expected2", "plot(5:15)");
            var expected3Path = await WriteExpectedImageAsync("png", 600, 600, 96, "Expected3", "plot(5:15)");
            var expected4Path = await WriteExpectedImageAsync("png", 600, 600, 96, "Expected4", "plot(0:10)");

            var code = @"
plot(0:10)
plot(5:15)
device_id <- rtvs:::graphics.ide.getactivedeviceid()
rtvs:::graphics.ide.resize(device_id, 600, 600, 96)
rtvs:::graphics.ide.previousplot(device_id)
";

            var inputs = Interactive(code);
            var actualPlotPaths = (await GraphicsTestAsync(inputs)).ToArray();
            var expectedPlotPaths = new string[] { expected1Path, expected2Path, expected3Path, expected4Path };
            CompareImages(actualPlotPaths, expectedPlotPaths);
        }

        [Test]
        [Category.Plots]
        public async Task Locator() {
            var outputFilePath = _files.LocatorResultPath;
            var code = string.Format(@"
plot(0:10)
res <- locator()
write.csv(res, {0})
",
                outputFilePath.ToRPath().ToRStringLiteral());

            var locatorProvider = new TestLocatorResultProvider(new Point[] {
                new Point(10, 10),
                new Point(100, 50),
                new Point(290, 90),
            });

            var inputs = Interactive(code);
            var actualPlotFilePaths = (await GraphicsTestAsync(inputs, locatorProvider.Next)).ToArray();

            // Locator results for the above clicked positions
            var x = new double[] { -2.48008095952895, 1.55378525638498, 10.0697250455366 };
            var y = new double[] { 14.4476461865435, 12.091623959219, 9.73560173189449 };
            CheckLocatorResult(outputFilePath, x, y);
        }

        private void CompareImages(string[] actualPlotPaths, string[] expectedPlotPaths) {
            actualPlotPaths.Select(f => File.ReadAllBytes(f)).ShouldBeEquivalentTo(expectedPlotPaths.Select(f => File.ReadAllBytes(f)));
        }

        private void CheckLocatorResult(string locatorFilePath, double[] x, double[] y) {
            // Example result:
            //"","x","y"
            //"1",-2.48008095952895,14.4476461865435
            //"2",1.55378525638498,12.091623959219
            //"3",10.0697250455366,9.73560173189449
            string all = File.ReadAllText(locatorFilePath);
            string[] lines = File.ReadAllLines(locatorFilePath);
            lines[0].Should().Be("\"\",\"x\",\"y\"");
            x.Should().HaveSameCount(y);
            for (int i = 0; i < x.Length; i++) {
                var expected = $"\"{i+1}\",{x[i]},{y[i]}";
                lines[i + 1].Should().Be(expected);
            }
        }

        internal string SavePlotFile(string plotFilePath, int i) {
            var newFileName = $"{_testMethod.MethodInfo.DeclaringType?.FullName}-{_testMethod.MethodInfo.Name}-{i}{Path.GetExtension(plotFilePath)}";
            var testOutputFilePath = Path.Combine(_files.ActualFolderPath, newFileName);
            File.Copy(plotFilePath, testOutputFilePath);
            return testOutputFilePath;
        }

        private async Task<string> WriteExpectedImageAsync(string imageType, int width, int height, int res, string name, string code) {
            string filePath = _files.GetDestinationPath(_testMethod.MethodInfo.Name + name + "." + imageType);
            var inputs = Batch(string.Format(@"
{0}({1}, width={2}, height={3}, res={4})
{5}
dev.off()
", imageType, filePath.ToRPath().ToRStringLiteral(), width, height, res, code));

            // Don't set PlotHandler, so if any code accidentally triggers a plot msg, it will fail
            await ExecuteInSession(inputs, new RHostClientTestApp());

            return filePath;
        }

        private async Task<IEnumerable<string>> GraphicsTestAsync(string[] inputs, Func<LocatorResult> locatorHandler = null) {
            await ExecuteInSession(inputs, new RHostClientTestApp { PlotHandler = OnPlot, LocatorHandler = locatorHandler, PlotDeviceCreateHandler = OnDeviceCreate, PlotDeviceDestroyHandler = OnDeviceDestroy });

            // Ensure that all plot files created by the graphics device have been deleted
            foreach (var plot in OriginalPlotMessages) {
                File.Exists(plot.FilePath).Should().BeFalse();
            }

            return PlotFilePaths.AsReadOnly();
        }

        private async Task ExecuteInSession(string[] inputs, IRSessionCallback app) {
            using (var sessionProvider = new RSessionProvider(_services)) {
                await sessionProvider.TrySwitchBrokerAsync(nameof(IdeGraphicsDeviceTest));
                var session = sessionProvider.GetOrCreate(_testMethod.FileSystemSafeName);
                await session.StartHostAsync(new RHostStartupInfo(), app, 50000);

                foreach (var input in inputs) {
                    using (var interaction = await session.BeginInteractionAsync()) {
                        await interaction.RespondAsync(input.EnsureLineBreak());
                    }
                }

                await session.StopHostAsync();
            }
        }

        private async Task ExportToImageAsync(IRSession session, string format, string filePath, int widthInPixels,int heightInPixels, int resolution) {
            string script = String.Format(@"
device_id <- rtvs:::graphics.ide.getactivedeviceid()
rtvs:::export_to_image(device_id, rtvs:::graphics.ide.getactiveplotid(device_id), {0}, {1}, {2}, {3})
", format, widthInPixels, heightInPixels, resolution);
            var blobid = await session.EvaluateAsync<ulong>(script, REvaluationKind.Normal);

            using(DataTransferSession dts = new DataTransferSession(session, new WindowsFileSystem())) {
                await dts.FetchFileAsync(new RBlobInfo(blobid), filePath, true, null, CancellationToken.None);
            }
        }

        private async Task<IEnumerable<string>> ExportToImageAsync(string[] inputs, string[] format, string[] paths, int widthInPixels, int heightInPixels, int resolution) {
            var app = new RHostClientTestApp { PlotHandler = OnPlot, PlotDeviceCreateHandler = OnDeviceCreate, PlotDeviceDestroyHandler = OnDeviceDestroy };
            using (var sessionProvider = new RSessionProvider(_services)) {
                await sessionProvider.TrySwitchBrokerAsync(nameof(IdeGraphicsDeviceTest));
                var session = sessionProvider.GetOrCreate(_testMethod.FileSystemSafeName);
                await session.StartHostAsync(new RHostStartupInfo(), app, 50000);

                foreach (var input in inputs) {
                    using (var interaction = await session.BeginInteractionAsync()) {
                        await interaction.RespondAsync(input.EnsureLineBreak());
                    }
                }

                for (int i = 0; i < format.Length; ++i) {
                    await ExportToImageAsync(session, format[i], paths[i], widthInPixels, heightInPixels, resolution);
                }

                await session.StopHostAsync();
            }
            // Ensure that all plot files created by the graphics device have been deleted
            foreach (var plot in OriginalPlotMessages) {
                File.Exists(plot.FilePath).Should().BeFalse();
            }

            return PlotFilePaths.AsReadOnly();
        }

        private async Task<IEnumerable<string>> ExportToPdfAsync(string[] inputs, string filePath, int width, int height) {
            var app = new RHostClientTestApp { PlotHandler = OnPlot, PlotDeviceCreateHandler = OnDeviceCreate, PlotDeviceDestroyHandler = OnDeviceDestroy };
            using (var sessionProvider = new RSessionProvider(_services)) {
                await sessionProvider.TrySwitchBrokerAsync(nameof(IdeGraphicsDeviceTest));
                var session = sessionProvider.GetOrCreate(_testMethod.FileSystemSafeName);
                await session.StartHostAsync(new RHostStartupInfo(), app, 50000);

                foreach (var input in inputs) {
                    using (var interaction = await session.BeginInteractionAsync()) {
                        await interaction.RespondAsync(input.EnsureLineBreak());
                    }
                }

                string script = String.Format(@"
device_id <- rtvs:::graphics.ide.getactivedeviceid()
rtvs:::export_to_pdf(device_id, rtvs:::graphics.ide.getactiveplotid(device_id), {0}, {1}, {2}, {3})
", "pdf", width, height, ("special").ToRStringLiteral());
                var blobid = await session.EvaluateAsync<ulong>(script, REvaluationKind.Normal);
                using (DataTransferSession dts = new DataTransferSession(session, new WindowsFileSystem())) {
                    await dts.FetchFileAsync(new RBlobInfo(blobid), filePath, true, null, CancellationToken.None);
                }

                await session.StopHostAsync();
            }
            // Ensure that all plot files created by the graphics device have been deleted
            foreach (var plot in OriginalPlotMessages) {
                File.Exists(plot.FilePath).Should().BeFalse();
            }

            return PlotFilePaths.AsReadOnly();
        }

        private static string[] Interactive(string code) {
            return code.Split(CharExtensions.LineBreakChars, StringSplitOptions.RemoveEmptyEntries);
        }

        private static string[] Batch(string code) {
            return new[] { code };
        }

        private PlotDeviceProperties OnDeviceCreate(Guid deviceId) {
            return DefaultDeviceProperties;
        }

        private void OnDeviceDestroy(Guid deviceId) {
        }

        private void OnPlot(PlotMessage plot) {
            // We also store the original plot messages, so we can
            // validate that the files have been deleted when the host goes away
            OriginalPlotMessages.Add(plot);

            if (plot.FilePath.Length <= 0) {
                return;
            }

            // Make a copy of the plot file, and store the path to the copy
            // When the R code finishes executing, the graphics device is destructed,
            // which destructs all the plots which deletes the original plot files
            int index = PlotFilePaths.Count;
            PlotFilePaths.Add(SavePlotFile(plot.FilePath, index));
        }

        class TestLocatorResultProvider {
            private Point[] _points;
            private int _index;

            public TestLocatorResultProvider(Point[] points) {
                _points = points;
            }

            public LocatorResult Next() {
                if (_index < _points.Length) {
                    var res = LocatorResult.CreateClicked(_points[_index].X, _points[_index].Y);
                    _index++;
                    return res;
                }
                return LocatorResult.CreateNotClicked();
            }
        }
    }
}


text:
package internal

import (
	"appengine_internal"
)

func Main() {
	appengine_internal.Main()
}

redpajama_set_name: RedPajamaGithub


text:
set -u # This prevents running the script if any of the variables have not been set
set -e # Exit if error is detected during pipeline execution

source ./setenv.sh

# Where do we want to copy all these images
DESTINATION_BUCKET="crowd-sourced-images-archive"

# How many GCS buckets were found
BUCKETS_TOTAL=0

# How many buckets were copied
BUCKETS_COPIED=0

# How many projects were found
PROJECTS_FOUND=0

# How many folders found
FOLDERS_FOUND=0

###############################################################################
# Scan all folders and projects under a designated folder ID
# Input
#   1 - folder ID under which all VMs to be stopped
###############################################################################
scan_folders() {
    local PARENT_FOLDER_ID=$1
    local FOLDER_ID
    FOLDERS_FOUND=$((FOLDERS_FOUND+1))

    echo_my "Scanning projects under folder id '$PARENT_FOLDER_ID'..."
    scan_projects "$PARENT_FOLDER_ID"

    local FOLDER_LIST=$(gcloud alpha resource-manager folders list --folder=$PARENT_FOLDER_ID --format="value(name)")

    while read -r FOLDER_ID; do
        if [[ ! -z "$FOLDER_ID" ]] ; then
            echo_my "Recursively processing folders under folder id '$FOLDER_ID'..."
            scan_folders "$FOLDER_ID"
        fi
    done <<< "$FOLDER_LIST"
}

###############################################################################
# Scan all projects under a given folder
# Inputs
#   1 - Folder ID
###############################################################################
scan_projects() {
    echo_my "Scanning projects under folder '$1'..."
    local PROJECT_LIST=$(gcloud projects list --filter="parent.id=$1" --format="value(projectId)")
    local PROJ_ID

    while read -r PROJ_ID; do
        if [[ ! -z "$PROJ_ID" ]] ; then
            PROJECTS_FOUND=$((PROJECTS_FOUND+1))
            echo_my "Processing project id '$PROJ_ID'..."
            scan_buckets $PROJ_ID
        fi
    done <<< "$PROJECT_LIST"
}

###############################################################################
# Scan and process all GCS buckets in a project
# Inputs
#   1 - project ID
###############################################################################
scan_buckets() {
    local BUCKET
    echo_my "Scanning buckets for project '$1'..."

    local BUCKET_LIST=$(gsutil ls -p $1 gs://)

    if [ -z ${BUCKET_LIST+x} ] ; then
        return  # No buckets found in this project
    fi

    while read -r BUCKET; do
        if [[ ! -z "$BUCKET" ]] ; then
            echo_my "Processing bucket '$BUCKET'"
            BUCKETS_TOTAL=$((BUCKETS_TOTAL+1))

            if echo "$BUCKET" | grep -q "annotated-images" ; then
                BUCKETS_COPIED=$((BUCKETS_COPIED+1))
                echo_my "Copy contents of the bucket '$BUCKET'..."
                gsutil -m cp $BUCKET*.zip gs://${DESTINATION_BUCKET}/annotated-images/$1/ | true # Ignore if error or empty
            fi

            if echo "$BUCKET" | grep -q "camera-" ; then
                BUCKETS_COPIED=$((BUCKETS_COPIED+1))
                echo_my "Copy contents of the bucket '$BUCKET'..."
                gsutil -m cp $BUCKET*.jpg gs://${DESTINATION_BUCKET}/camera-images/$1/ | true # ignore if error or empty
            fi
        fi
    done <<< "$BUCKET_LIST"
}

###############################################################################
# MAIN
###############################################################################

if [ -z ${1+x} ] ; then
    echo_my "NUMERIC_FOLDER_ID not found. \n Usage: collect-images.sh [NUMERIC_FOLDER_ID] \n Example: \n ./collect-images.sh 8763450985677 \n   \n" $ECHO_ERROR
    exit 1
fi

# Process all projects and folders under this starting folder
START_FOLDER=$1

print_header "Collect all raw and annotated images from folder ID '$1'"

scan_folders $START_FOLDER

print_footer "SUCCESS: Found $PROJECTS_FOUND projects, $FOLDERS_FOUND folders, $BUCKETS_TOTAL buckets, including $BUCKETS_COPIED buckets with image content."


text:
'use strict';

module.exports = function IndexModel() {
    return {
        name: 'sustaste'
    };
};


text:
package net.zeminvaders.lang.ast;

import net.zeminvaders.lang.Interpreter;
import net.zeminvaders.lang.SourcePosition;
import net.zeminvaders.lang.runtime.ZemBoolean;
import net.zeminvaders.lang.runtime.ZemObject;

/**
 * Boolean and (&&) operator.
 *
 * @author Cameron Zemek
 */
public class AndOpNode extends BinaryOpNode implements IBooleanOpNode {
    public AndOpNode(SourcePosition pos, Node left, Node right) {
        super(pos, "and", left, right);
    }

    @Override
    public ZemObject eval(Interpreter interpreter) {
        ZemBoolean left = getLeft().eval(interpreter).toBoolean(getLeft().getPosition());
        if (!left.booleanValue()) {
            // Short circuit the operator, since false && test == false
            return left;
        }
        ZemBoolean right = getRight().eval(interpreter).toBoolean(getRight().getPosition());
        return left.and(right);
    }
}


text:
FactoryGirl.define do
  factory :some_model do
    first_name 'Scott'
    last_name 'Adams'
    random_array [1,2,3,4]
    some_hash { {:cat => 'Catbert'} }
  end

  factory :my_namespaced_model, class: Namespace::MyNamespacedModel, parent: :some_model

  factory :my_single_namespaced_model, class: Namespace::MySingleNamespacedModel, parent: :some_model
end


text:
<?php
require_once '/var/www/html/OSSzikken/model/UrlCreator.php';
require_once '/var/www/html/OSSzikken/model/EventDAO.php';

$eventName = $_POST['event_name'];
$memo = $_POST['memo'];
$candidateSchedule = $_POST['candidate_schedule'];
$date = new DateTime();
$now = $date -> format("Y-m-d");

$hash = UrlCreator::createUrl($eventName);
session_start();
$_SESSION['url'] = $hash;
//$_POST['hash'] = $hash;
$eventDao = new EventDAO();
$eventDao -> setEvent($hash, $eventName, $memo, $candidateSchedule, $now);

header('Location: ../view/URLConfirm.php');
exit();


text:
cask "katalon-studio" do
  version "8.4.1"
  sha256 "d047ea526f6d4c5d4c531953e456a9b16b760acf50f008ceb293d01cf7f22e48"

  url "https://download.katalon.com/#{version}/Katalon%20Studio.dmg"
  name "Katalon Studio"
  desc "Test automation solution"
  homepage "https://www.katalon.com/download/"

  livecheck do
    url "https://github.com/katalon-studio/katalon-studio"
    strategy :github_latest
  end

  app "Katalon Studio.app"

  zap trash: [
    "~/.katalon",
    "~/Library/Preferences/com.kms.katalon.product.product.plist",
    "~/Library/Saved Application State/com.kms.katalon.product.product.savedState",
  ]
end


text:
This is a library of Bluetooth 4.0 which based on iOS. It makes you easy to implement Bluetooth technique on your project. First of all, you should initial object of BLEManager, it is a singleton object, then you can re-use in your program by the method of "sharedManager". When you need to communicate with device, you should use the method of "scanningForServicesWithPeripheral" to search all services and characters first. It is an important procedure before you want to send or receive data with device. If you do not use this method, it cannot correct to communicate with device. When the length of transmission data is too long, the write/read method may has long time to process.

## Installation

* BLEManager is available through [CocoaPods](http://cocoapods.org).
* You can also download the BLEManager.{m,h} files into your project directly.

## How to use

* Inital this object
```objc
+ (BLEManager *)sharedManagerWithDelegate:(id<BLEManagerDelegate>)delegate;
```

* Reuse object (singleton)
```objc
+ (BLEManager *)sharedManager;
```

* Kill object
```objc
- (void)disableBLEManager;
```

* Check bluetooth  device is connected
```objc
- (BOOL)isConnecting;
```

* Scan all devices
```objc
- (void)scanningForPeripherals;
```

* Scan all devices by restricted distance
```objc
- (void)scanningForPeripheralsWithDistance:(int)RSSI;
```

* Stop scan devices
```objc
- (void)stopScanningForPeripherals;
```

* Connect specified device
```objc
- (void)connectingPeripheral:(CBPeripheral *)peripheral;
```

* Disconnect specified device
```objc
- (void)disconnectPeripheral:(CBPeripheral *)peripheral;
```

* Get Received Signal Strength Indicator(RSSI) by device
```objc
- (int)readRSSI:(CBPeripheral *)peripheral;
```

* Scan all services in the device
```objc
- (void)scanningForServicesWithPeripheral:(CBPeripheral *)peripheral;
```

### Communicate with device after scanning all services
* Write data to device
```objc
- (NSError *)setValue:(NSData *) data forServiceUUID:(NSString *) serviceUUID andCharacteristicUUID:(NSString *) charUUID withPeripheral:(CBPeripheral *)peripheral;
```

* Read data from device
```objc
- (NSData *)readValueForServiceUUID:(NSString *) serviceUUID andCharacteristicUUID:(NSString *) charUUID withPeripheral:(CBPeripheral *)peripheral;
```


text:
'use strict';

var assert = require('assert');

var propAssign = require('./index.js');

describe('propAssign', function () {
  it('should assign a property and value to an object', function () {
    var obj = {};
    propAssign('prop', 'value')(obj);
    assert.equal(obj.prop, 'value');
  });
});


text:
/* $PostgreSQL: pgsql/contrib/tsearch2/wordparser/parser.h,v 1.11 2006/03/11 04:38:30 momjian Exp $ */

#ifndef __PARSER_H__
#define __PARSER_H__

#include <ctype.h>
#include <limits.h>
#include "ts_locale.h"

typedef enum
{
	TPS_Base = 0,
	TPS_InUWord,
	TPS_InLatWord,
	TPS_InCyrWord,
	TPS_InUnsignedInt,
	TPS_InSignedIntFirst,
	TPS_InSignedInt,
	TPS_InSpace,
	TPS_InUDecimalFirst,
	TPS_InUDecimal,
	TPS_InDecimalFirst,
	TPS_InDecimal,
	TPS_InVerVersion,
	TPS_InSVerVersion,
	TPS_InVersionFirst,
	TPS_InVersion,
	TPS_InMantissaFirst,
	TPS_InMantissaSign,
	TPS_InMantissa,
	TPS_InHTMLEntityFirst,
	TPS_InHTMLEntity,
	TPS_InHTMLEntityNumFirst,
	TPS_InHTMLEntityNum,
	TPS_InHTMLEntityEnd,
	TPS_InTagFirst,
	TPS_InXMLBegin,
	TPS_InTagCloseFirst,
	TPS_InTagName,
	TPS_InTagBeginEnd,
	TPS_InTag,
	TPS_InTagEscapeK,
	TPS_InTagEscapeKK,
	TPS_InTagBackSleshed,
	TPS_InTagEnd,
	TPS_InCommentFirst,
	TPS_InCommentLast,
	TPS_InComment,
	TPS_InCloseCommentFirst,
	TPS_InCloseCommentLast,
	TPS_InCommentEnd,
	TPS_InHostFirstDomain,
	TPS_InHostDomainSecond,
	TPS_InHostDomain,
	TPS_InPortFirst,
	TPS_InPort,
	TPS_InHostFirstAN,
	TPS_InHost,
	TPS_InEmail,
	TPS_InFileFirst,
	TPS_InFileTwiddle,
	TPS_InPathFirst,
	TPS_InPathFirstFirst,
	TPS_InPathSecond,
	TPS_InFile,
	TPS_InFileNext,
	TPS_InURIFirst,
	TPS_InURIStart,
	TPS_InURI,
	TPS_InFURL,
	TPS_InProtocolFirst,
	TPS_InProtocolSecond,
	TPS_InProtocolEnd,
	TPS_InHyphenLatWordFirst,
	TPS_InHyphenLatWord,
	TPS_InHyphenCyrWordFirst,
	TPS_InHyphenCyrWord,
	TPS_InHyphenUWordFirst,
	TPS_InHyphenUWord,
	TPS_InHyphenValueFirst,
	TPS_InHyphenValue,
	TPS_InHyphenValueExact,
	TPS_InParseHyphen,
	TPS_InParseHyphenHyphen,
	TPS_InHyphenCyrWordPart,
	TPS_InHyphenLatWordPart,
	TPS_InHyphenUWordPart,
	TPS_InHyphenUnsignedInt,
	TPS_InHDecimalPartFirst,
	TPS_InHDecimalPart,
	TPS_InHVersionPartFirst,
	TPS_InHVersionPart,
	TPS_Null					/* last state (fake value) */
}	TParserState;

/* forward declaration */
struct TParser;

typedef int (*TParserCharTest) (struct TParser *);		/* any p_is* functions
														 * except p_iseq */
typedef void (*TParserSpecial) (struct TParser *);		/* special handler for
														 * special cases... */

typedef struct
{
	TParserCharTest isclass;
	char		c;
	uint16		flags;
	TParserState tostate;
	int			type;
	TParserSpecial special;
}	TParserStateActionItem;

typedef struct
{
	TParserState state;
	TParserStateActionItem *action;
}	TParserStateAction;

typedef struct TParserPosition
{
	int			posbyte;		/* position of parser in bytes */
	int			poschar;		/* osition of parser in characters */
	int			charlen;		/* length of current char */
	int			lenbytelexeme;
	int			lencharlexeme;
	TParserState state;
	struct TParserPosition *prev;
	int			flags;
	TParserStateActionItem *pushedAtAction;
}	TParserPosition;

typedef struct TParser
{
	/* string and position information */
	char	   *str;			/* multibyte string */
	int			lenstr;			/* length of mbstring */
#ifdef TS_USE_WIDE
	wchar_t    *wstr;			/* wide character string */
	int			lenwstr;		/* length of wsting */
#endif

	/* State of parse */
	int			charmaxlen;
	bool		usewide;
	TParserPosition *state;
	bool		ignore;
	bool		wanthost;

	/* silly char */
	char		c;

	/* out */
	char	   *lexeme;
	int			lenbytelexeme;
	int			lencharlexeme;
	int			type;

}	TParser;

TParser    *TParserInit(char *, int);
bool		TParserGet(TParser *);
void		TParserClose(TParser *);

#endif


text:
using System;

namespace ZXing.Common
{
   ///
This provides an easy abstraction to read bits at a time from a sequence of bytes, where the
   /// number of bits read is not often a multiple of 8.

   ///
   ///
This class is thread-safe but not reentrant. Unless the caller modifies the bytes array
   /// it passed in, in which case all bets are off.

   ///
   ///
   /// <author>  Sean Owen
   /// </author>
   /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
   /// </author>
   public sealed class BitSource
   {
      private readonly byte[] bytes;
      private int byteOffset;
      private int bitOffset;

      /// <param name="bytes">bytes from which this will read bits. Bits will be read from the first byte first.
      /// Bits are read within a byte from most-significant to least-significant bit.
      /// </param>
      public BitSource([System.Runtime.InteropServices.WindowsRuntime.ReadOnlyArray] byte[] bytes)
      {
         this.bytes = bytes;
      }

      ///
      /// index of next bit in current byte which would be read by the next call to {@link #readBits(int)}.
      ///
      public int BitOffset
      {
         get { return bitOffset; }
      }

      ///
      /// index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.
      ///
      public int ByteOffset
      {
         get { return byteOffset; }
      }

      /// <param name="numBits">number of bits to read
      /// </param>
      /// <returns> int representing the bits read. The bits will appear as the least-significant
      /// bits of the int
      /// </returns>
      /// <exception cref="ArgumentException">if numBits isn't in [1,32] or more than is available</exception>
      public int readBits(int numBits)
      {
         if (numBits < 1 || numBits > 32 || numBits > available())
         {
            throw new ArgumentException(numBits.ToString(), "numBits");
         }

         int result = 0;

         // First, read remainder from current byte
         if (bitOffset > 0)
         {
            int bitsLeft = 8 - bitOffset;
            int toRead = numBits < bitsLeft ? numBits : bitsLeft;
            int bitsToNotRead = bitsLeft - toRead;
            int mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
            result = (bytes[byteOffset] & mask) >> bitsToNotRead;
            numBits -= toRead;
            bitOffset += toRead;
            if (bitOffset == 8)
            {
               bitOffset = 0;
               byteOffset++;
            }
         }

         // Next read whole bytes
         if (numBits > 0)
         {
            while (numBits >= 8)
            {
               result = (result << 8) | (bytes[byteOffset] & 0xFF);
               byteOffset++;
               numBits -= 8;
            }

            // Finally read a partial byte
            if (numBits > 0)
            {
               int bitsToNotRead = 8 - numBits;
               int mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
               result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead);
               bitOffset += numBits;
            }
         }

         return result;
      }

      /// <returns> number of bits that can be read successfully
      /// </returns>
      public int available()
      {
         return 8 * (bytes.Length - byteOffset) - bitOffset;
      }
   }
}


text:
package org.kurento.commons.testing;

/**
 * Category for integration tests belonging to kurento-repository-api-test
 *
 * @author Ivan Gracia (izanmail@gmail.com)
 * @since 4.3.0
 *
 */
public interface RepositoryApiTests extends IntegrationTests {

}


text:
<!doctype html>

    <meta charset="UTF-8">
    <title>查看课程表</title>
    <link rel="stylesheet" type="text/css" href="/static/bootstrap.min.css">

            <form action="{:url('update')}" method="post">
                id:
                <input type="hidden" name="id" value="{$kechengbiao->getData('id')}" />
                <input type="text" name="name" value="{$kechengbiao->getData('id')}" />

                kclass_id:
                <input type="text" name="kclass_id" value="{$kechengbiao->getData('kclass_id')}" />

                course_id:
                <input type="text" name="course_id" value="{$kechengbiao->getData('course_id')}" />

                student_id:
                <input type="text" name="student_id" value="{$kechengbiao->getData('student_id')}" />

                teacher_id:
                <input type="text" name="teacher_id" value="{$kechengbiao->getData('teacher_id')}" />

                class:
                <input type="text" name="class" value="{$kechengbiao->getData('class')}" />

                status:
                <select name="status">
                            <option value="1">正常</option>
                            <option value="2" {eq name="kechengbiao->getData('status')" value="2"}selected="selected"{/eq}>旷课</option>
                            <option value="3" {eq name="kechengbiao->getData('status')" value="3"}selected="selected"{/eq}>请假</option>
                            <option value="4" {eq name="kechengbiao->getData('status')" value="4"}selected="selected"{/eq}>迟到</option>
                            <option value="5" {eq name="kechengbiao->getData('status')" value="5"}selected="selected"{/eq}>早退</option>
                        </select>

                <button type="submit">保存</button>
            </form>


text:
using System;
using System.Collections.Generic;

namespace Headmaster
{
    public interface IControllerTypesResolver
    {
        IReadOnlyCollection<Type> GetControllerTypes();
    }
}


text:
General description, background on author, how you heard found it, why it interested you, etc.

## The Good
What you liked about it, what it taught you, how the food tasted

## The Bad
What sucked, terrible recipes, missing steps, typos, quality of the book, etc

## Favorite Recipes
List of recipes that you loved, sentence or two long. link to recipes if you find them online or reproduce them.

## Conclusion
Whether you recommend the book or not.


text:
module Reddit.Actions.FlairSpec where

import Reddit.Actions.Flair

import ConfigLoad
import Test.Hspec

isRight :: Either a b -> Bool
isRight = const False `either` const True

main :: IO ()
main = hspec spec

spec :: Spec
spec = describe "Reddit.Actions.Flair" $ do
  (reddit, _, subreddit) <- runIO loadConfig

  it "should be able to get the flair list" $ do
    res <- run reddit $ getFlairList subreddit
    res `shouldSatisfy` isRight


text:
// HTML5 boilerplate scripts parser (originally called ScriptsToConcat.java)
// Daniel Holth <dholth@fastmail.fm.com>, 2012
// Public Domain. http://creativecommons.org/publicdomain/zero/1.0/
// Modified by Naresh Bhatia to generalize filename extraction from different comment blocks

import java.io.FileReader;
import java.io.IOException;

import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Attribute;;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.swing.text.html.parser.ParserDelegator;

/**
 * Parse an HTML file, printing all occurrences of the specified attribute for
 * the specified tag when it occurs between the following comments:
 * <!-- //-beg- section_name -->
 * <!-- //-end- section_name -->
 *
 * Example:
 * <!-- //-beg- concatenate_scripts -->
 * <script src="js/libs/jquery-1.8.0.js"></script>
 * <script src="js/libs/jquery-ui-1.8.20.custom.min.js"></script>
 * <!-- //-end- concatenate_scripts -->
 *
 * To extract the "src" attribute for all "script" tags in the
 * "concatenate_scripts" section, call FindAttribute as follows:
 *
 * FindAttribute index.html concatenate_scripts script src
 */
public class FindAttribute extends ParserCallback {
    private String begComment;
    private String endComment;
    private Tag tag;
    private Attribute attribute;
    private boolean emitting = false;

    public FindAttribute(String sectionName, String tagName, String attributeName) {
        this.begComment = "//-beg- " + sectionName;
        this.endComment = "//-end- " + sectionName;
        this.tag = HTML.getTag(tagName);
        this.attribute = HTML.getAttributeKey(attributeName);
    }

    @Override
    public void handleComment(char[] data, int pos) {
        String text = new String(data);
        if (text.indexOf(this.begComment) >= 0) {
            emitting = true;
        }
        else if (text.indexOf(this.endComment) >= 0) {
            emitting = false;
        }
    }

    @Override
    public void handleSimpleTag(Tag t, MutableAttributeSet a, int pos) {
        this.handleTag(t, a, pos);
    }

    @Override
    public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
        this.handleTag(t, a, pos);
    }

    // Handles both simple and start tags
    private void handleTag(Tag t, MutableAttributeSet a, int pos) {
        if (emitting && t == this.tag) {
            String attributeValue =
                a.getAttribute(this.attribute).toString();
            if (attributeValue != null) {
                System.out.println(attributeValue);
            }
        }
    }

    public static void main(String args[]) throws IOException {
        if (args.length != 4) {
            System.err.println("usage: FindAttribute htmlFilename sectionName tagName attributeName");
            System.exit(1);
        }
        FileReader fr = new FileReader(args[0]);
        new ParserDelegator().parse(
                fr, new FindAttribute(args[1], args[2], args[3]), true);
    }
}


text:
New Game

Pick a name for the game, and choose a wordbank that will populate the bingo board.

<form #newGame="ngForm">
  Game Name: <input #newGameName placeholder="Game Name"/>
  <select name="wordbank" ngModel>
    <option value="" disabled>Choose a wordbank</option>
    <option *ngFor="let wb of wordbanks" [ngValue]="wb">
      {{ wb }}
    </option>
  </select>
  <button (click)="createGame(newGameName.value,newGame.value.wordbank);
    newGameName.value=''">Create Game</button>
</form>


text:
using FeedlySharp.Models;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace FeedlySharp
{
  public partial class FeedlyClient
  {
    /// <summary>
    /// Get the profile of the user.
    /// </summary>
    /// <remarks>profile-endpoint (https://developer.feedly.com/v3/profile/#get-the-profile-of-the-user)</remarks>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns></returns>
    public async Task<FeedlyUser> GetProfile(CancellationToken cancellationToken = default(CancellationToken))
    {
      return await Client.Request<FeedlyUser>(HttpMethod.Get, "v3/profile", null, false, true, cancellationToken);
    }

    /// <summary>
    /// Update the profile of the user.
    /// </summary>
    /// <remarks>profile-endpoint (https://developer.feedly.com/v3/profile/#update-the-profile-of-the-user)</remarks>
    /// <param name="parameters">The update profile parameters, see https://developer.feedly.com/v3/profile/#update-the-profile-of-the-user </param>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns></returns>
    public async Task<FeedlyUser> UpdateProfile(Dictionary<string, string> parameters, CancellationToken cancellationToken = default(CancellationToken))
    {
      return await Client.Request<FeedlyUser>(HttpMethod.Post, "v3/profile", parameters, true, true, cancellationToken);
    }
  }
}


text:
"use strict";

var React = require('react');

/*
    A delete button asking for confirmation

interface DeleteButtonProps{
    askForConfirmation: boolean // (defaults to true)
    onConfirm: () => void
}
interface DeleteButtonState{
    pendingConfirmation: boolean
}

*/

module.exports = React.createClass({
    getInitialState: function(){
        return {pendingConfirmation: false};
    },

    render: function(){
        var props = this.props;
        var state = this.state;
        var self = this;

        var askForConfirmation = 'askForConfirmation' in props ? props.askForConfirmation : true;

        var children = [
            React.DOM.div({
                key: 0,
                onClick: function(){
                    if(askForConfirmation){
                        self.setState({pendingConfirmation: true});
                    }
                    else{
                        props.onConfirm();
                    }
                }
            })
        ];

        if(state.pendingConfirmation){
            children.push(React.DOM.div({className: 'confirmation-box', key: 1},
                React.DOM.h1({}, 'Confirm ?'),
                React.DOM.div({className: "button-group"},
                    React.DOM.button({
                        className: 'cancel',
                        onClick: function(){
                            self.setState({pendingConfirmation: false});
                        }
                    }, 'cancel'),
                    React.DOM.button({
                            className: 'confirm',
                            onClick: function(){
                                props.onConfirm();
                                self.setState({pendingConfirmation: false});
                            }
                        },
                        'confirm'
                    )
            )));
        }

        return React.DOM.div({
            className: "delete",
            title: "delete"
        }, children);
    }
});


text:
package bookshop2.shipper.ui;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

@WebServlet(name="bookshop2.shipper", urlPatterns={"/shipper"})
public class ShipperServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

//	@EJB
//	MessageSession session;

	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
		super.service(request, response);
	}

}


text:
use protocol;

/// The state of some connection that hasn't been promoted to a node.
#[derive(Clone, Debug)]
pub enum PendingState
{
    /// We just connected and need to send a 'Ping'.
    PendingPing,

    /// We sent a `Ping` and are awaiting a `Pong`.
    PendingPong {
        /// The original ping that we sent.
        original_ping: protocol::Ping,
    },

    /// Pong matched original data, we now need to send a `JoinRequest`.
    PendingJoinRequest,
    /// We sent a `JoinRequest` and are awaiting a response.
    PendingJoinResponse,

    Complete {
        join_response: protocol::JoinResponse,
    },
}

impl PendingState
{
    pub fn is_complete(&self) -> bool {
        if let PendingState::Complete { .. } = *self { true } else { false }
    }
}


text:
using namespace Renga;

namespace
{
  const std::list<GUID> c_levelTreeTypes =
  {
    ObjectTypes::Wall,
    ObjectTypes::Column,
    ObjectTypes::Floor,
    ObjectTypes::Opening,
    ObjectTypes::Roof,
    ObjectTypes::Beam,
    ObjectTypes::Stair,
    ObjectTypes::Ramp,
    ObjectTypes::Window,
    ObjectTypes::Door,
    ObjectTypes::Railing,
    ObjectTypes::Room,
    ObjectTypes::IsolatedFoundation,
    ObjectTypes::WallFoundation,
    ObjectTypes::AssemblyInstance,
    ObjectTypes::Element,
    ObjectTypes::Plate,
    ObjectTypes::RoutePoint,
    ObjectTypes::Equipment,
    ObjectTypes::PlumbingFixture,
    ObjectTypes::MechanicalEquipment,
    ObjectTypes::Line3D,
    ObjectTypes::Hatch,
    ObjectTypes::TextShape,
    ObjectTypes::Rebar
  };

  const std::list<GUID> c_nonLevelTreeTypes
  {
    ObjectTypes::PipeAccessory,
    ObjectTypes::PipeFitting,
    ObjectTypes::Pipe,
    ObjectTypes::Duct,
    ObjectTypes::DuctAccessory,
    ObjectTypes::DuctFitting,
    ObjectTypes::LineElectricalCircuit,
    ObjectTypes::LightFixture,
    ObjectTypes::ElectricDistributionBoard,
    ObjectTypes::WiringAccessory,
    ObjectTypes::Route,
    ObjectTypes::Axis,
    ObjectTypes::Elevation,
    ObjectTypes::Section,
    ObjectTypes::Dimension,
  };

  const GuidMap <GUID> c_parameterToIdDict =
  {
    { ParameterIds::MaterialStyleId, StyleTypeIds::Material },
    { ParameterIds::LayeredMaterialStyleId, StyleTypeIds::LayeredMaterial },
    { ParameterIds::PlumbingFixtureStyleId, StyleTypeIds::PlumbingFixtureStyle },
    { ParameterIds::MepEquipmentStyleId, StyleTypeIds::EquipmentStyle },
    { ParameterIds::MepPipeStyleId, StyleTypeIds::PipeStyle },
    { ParameterIds::PipeComponentStyleId, StyleTypeIds::PipeFittingStyle },
    { ParameterIds::PipeAccessoryStyleId, StyleTypeIds::PipeAccessoryStyle },
    { ParameterIds::AirEquipmentStyleId, StyleTypeIds::MechanicalEquipmentStyle },
    { ParameterIds::AirDuctStyleId, StyleTypeIds::DuctStyle },
    { ParameterIds::AirComponentStyleId, StyleTypeIds::DuctFittingStyle },
    { ParameterIds::AirAccessoryStyleId, StyleTypeIds::DuctAccessoryStyle },
    { ParameterIds::WiringAccessoryStyleId, StyleTypeIds::WiringAccessoryStyle },
    { ParameterIds::LightFixtureStyleId, StyleTypeIds::LightFixtureStyle },
    { ParameterIds::DistributionBoardStyleId, StyleTypeIds::ElectricDistributionBoardStyle },
    { ParameterIds::ConductorStyleId, StyleTypeIds::ElectricalConductorStyle },
    { ParameterIds::LineElectricalCircuitStyleId, StyleTypeIds::ElectricCircuitLineStyle },
    { ParameterIds::MepSystemStyleId, StyleTypeIds::SystemStyle },
    { ParameterIds::AssemblyId, StyleTypeIds::Assembly },
  };
}

TreeViewModelBuilder::TreeViewModelBuilder(IApplicationPtr pApplication) :
  m_pApplication(pApplication)
{
}

static double getLevelElevation(IModelObjectPtr pModelObject)
{
  ILevelPtr pLevel;

  pModelObject->QueryInterface(&pLevel);
  assert(pLevel != nullptr);

  return pLevel->GetElevation();
}

static bool compareLevelElevations(IModelObjectPtr pLeftModelObject, IModelObjectPtr pRightModelObject)
{
  return getLevelElevation(pLeftModelObject) < getLevelElevation(pRightModelObject);
}

QStandardItemModel* TreeViewModelBuilder::build()
{
  QStandardItemModel* pItemModel = new QStandardItemModel();

  auto pProject = m_pApplication->GetProject();
  auto pModel = pProject->GetModel();
  auto pModelObjectCollection = pModel->GetObjects();

  processModelObjectCollection(pModelObjectCollection);

  m_levels.sort(compareLevelElevations);

  for (auto pLevelModelObject : m_levels)
    addLevelSubtree(pItemModel, pLevelModelObject, pModelObjectCollection);

  addNonLevelSubtree(pItemModel, pModelObjectCollection);

  return pItemModel;
}

void TreeViewModelBuilder::processModelObjectCollection(IModelObjectCollectionPtr pModelObjectCollection)
{
  m_levels.clear();
  m_levelObjects.clear();
  m_nonLevelObjects.clear();

  for (int i = 0; i < pModelObjectCollection->Count; i++)
  {
    auto pModelObject = pModelObjectCollection->GetByIndex(i);

    if (pModelObject->GetObjectType() == ObjectTypes::Level)
    {
      m_levels.push_back(pModelObject);
    }
    else
    {
      ILevelObjectPtr pLevelObject;
      pModelObject->QueryInterface(&pLevelObject);

      if (pLevelObject)
        processLevelObject(pModelObject);
      else
        processNonLevelObject(pModelObject);
    }
  }
}

void TreeViewModelBuilder::processLevelObject(IModelObjectPtr pModelObject)
{
  ILevelObjectPtr pLevelObject;
  pModelObject->QueryInterface(&pLevelObject);
  assert(pLevelObject != nullptr);

  LevelObjectGroup group(pLevelObject->GetLevelId(), pModelObject->GetObjectType());

  m_levelObjects[group].push_back(pModelObject);
}

void TreeViewModelBuilder::processNonLevelObject(IModelObjectPtr pNonLevelObject)
{
  m_nonLevelObjects[pNonLevelObject->GetObjectType()].push_back(pNonLevelObject);
}

void TreeViewModelBuilder::addNonLevelSubtree(QStandardItemModel * pItemModel, IModelObjectCollectionPtr pModelObjectCollection)
{
  auto pItem = createOtherGroupItem();

  for (const auto& objectType : c_nonLevelTreeTypes)
    addObjectGroupSubtree(pItem.at(0), m_nonLevelObjects[objectType], getRengaEntityUIData(objectType).pluralName);

  pItemModel->appendRow(pItem);
}

void TreeViewModelBuilder::addLevelSubtree(
  QStandardItemModel* pItemModel,
  IModelObjectPtr pLevelModelObject,
  IModelObjectCollectionPtr pModelObjectCollection)
{
  assert(pLevelModelObject->GetObjectType() == ObjectTypes::Level);

  auto pItem = createLevelItem(pLevelModelObject);

  for (const auto& objectType : c_levelTreeTypes)
  {
    LevelObjectGroup group(pLevelModelObject->GetId(), objectType);
    addObjectGroupSubtree(pItem.at(0), m_levelObjects[group], getRengaEntityUIData(objectType).pluralName);
  }

  pItemModel->appendRow(pItem);
}

void TreeViewModelBuilder::addAssemblySubtree(QStandardItem* pParentItem, IEntityPtr assembly)
{
  auto itemList = createItem(
    QString::fromWCharArray(assembly->Name), ":/icons/Assembly", eTreeViewItemType::Style, false, true);

  itemList.first()->setData(assembly->Id, eTreeViewItemRole::EntityId);

  for (const auto& objectType : c_levelTreeTypes)
  {
    LevelObjectGroup group(assembly->Id, objectType);
    addObjectGroupSubtree(itemList.at(0), m_levelObjects[group], getRengaEntityUIData(objectType).pluralName);
  }

  pParentItem->appendRow(itemList);
}

void TreeViewModelBuilder::addObjectGroupSubtree(
  QStandardItem* pParentItem,
  const std::list<IModelObjectPtr>& objectGroup,
  const QString groupName,
  bool createVisibilityItem,
  Renga::IEntityPtr pParentAssembly)
{
  QList<QStandardItem*> objectGroupItemList =
    createItem(groupName, ":/icons/Folder", eTreeViewItemType::ObjectGroup, createVisibilityItem, true);

  if (objectGroup.empty())
    return;

  for (auto pObject : objectGroup)
    addObjectSubtree(objectGroupItemList.at(0), pObject, createVisibilityItem, pParentAssembly);

  setItemVisibilityState(objectGroupItemList, objectGroupHasVisibleObject(objectGroup));
  pParentItem->appendRow(objectGroupItemList);
}

void TreeViewModelBuilder::addObjectSubtree(
    QStandardItem* pParentItem,
    IModelObjectPtr pObject,
    bool createVisibilityItem,
    Renga::IEntityPtr pParentAssembly)
{
  QList<QStandardItem*> itemList = createModelObjectItem(pObject, createVisibilityItem, pParentAssembly);

  auto pObjectParameters = pObject->GetParameters();
  auto pIds = pObjectParameters->GetIds();
  for (int i = 0; i < pIds->Count; ++i)
  {
    auto id = pIds->Get(i);
    auto pParameter = pObjectParameters->Get(id);
    if (pParameter->Definition->_ParameterType != ParameterType::ParameterType_IntID)
      continue;

    auto entityTypeIt = c_parameterToIdDict.find(id);
    if (entityTypeIt != c_parameterToIdDict.cend())
      addStyleSubtree(itemList.at(0), pObject, entityTypeIt->second, pParameter->GetIntValue());
  }

  pParentItem->appendRow(itemList);
}

void TreeViewModelBuilder::addStyleSubtree(
  QStandardItem* pParentItem,
  IModelObjectPtr pModelObject,
  GUID styleType,
  int id)
{
  if (styleType == StyleTypeIds::LayeredMaterial)
  {
    IObjectWithLayeredMaterialPtr pObjectWithLayeredMaterial;
    pModelObject->QueryInterface(&pObjectWithLayeredMaterial);

    if (pObjectWithLayeredMaterial != nullptr && pObjectWithLayeredMaterial->HasLayeredMaterial())
      addLayersSubtree(pParentItem, pModelObject, pObjectWithLayeredMaterial->LayeredMaterialId);
  }
  else if (styleType == StyleTypeIds::Material)
  {
    IObjectWithMaterialPtr pObjectWithMaterial;
    pModelObject->QueryInterface(&pObjectWithMaterial);

    if (pObjectWithMaterial != nullptr && pObjectWithMaterial->HasMaterial())
      addSingleMaterialMaterialSubtree(pParentItem, pModelObject);
  }
  else
  {
    auto pEntityCollection = getProjectEntityCollection(m_pApplication->Project, styleType);
    auto pEntity = pEntityCollection->GetById(id);
    if (pEntity)
      addEntitySubtree(pParentItem, pEntity);
  }
}

std::list<Renga::IModelObjectPtr> TreeViewModelBuilder::getAssemblyObjects(int assemblyId, GUID objectType) const
{
  auto result = std::list<Renga::IModelObjectPtr>();

  auto pAssembly = m_pApplication->Project->Assemblies->GetById(assemblyId);
  assert(pAssembly != nullptr);

  auto pModel = IModelPtr();
  pAssembly->QueryInterface(&pModel);
  assert(pModel != nullptr);

  auto pModelObjects = pModel->GetObjects();

  for (int i = 0; i < pModelObjects->Count; ++i)
  {
    auto pModelObject = pModelObjects->GetByIndex(i);
    if (pModelObject->ObjectType == objectType)
      result.push_back(pModelObject);
  }
  return result;
}

void TreeViewModelBuilder::addEntitySubtree(QStandardItem * pParentItem, Renga::IEntityPtr entity)
{
  auto name = QString::fromWCharArray(entity->Name);
  auto iconPath = getRengaEntityUIData(entity->TypeId).icon16Path;
  auto itemList = createItem(name, iconPath, eTreeViewItemType::Style);

  itemList.first()->setData(entity->Id, eTreeViewItemRole::EntityId);
  itemList.first()->setData(GuidToString(entity->TypeId).c_str(), eTreeViewItemRole::EntityType);

  pParentItem->appendRow(itemList);

  if (entity->TypeId == Renga::StyleTypeIds::Assembly)
  {
    // Here we assume only level based objects can be inserted in Assembly // Tyan
    for (const auto& objectType : c_levelTreeTypes)
      addObjectGroupSubtree(
          itemList.at(0),
          getAssemblyObjects(entity->GetId(), objectType),
          getRengaEntityUIData(objectType).pluralName,
          false,
          entity);
  }
}

void TreeViewModelBuilder::addSingleMaterialMaterialSubtree(
  QStandardItem* pParentItem,
  IModelObjectPtr pModelObject)
{
  QList<QStandardItem*> materialItemList = createSolidMaterialItem(pModelObject);
  addReinforcementSubtree(materialItemList.first(), pModelObject);
  pParentItem->appendRow(materialItemList);
}

void TreeViewModelBuilder::addLayersSubtree(
  QStandardItem* pParentItem,
  IModelObjectPtr pModelObject,
  int layeredMaterialId)
{
  ILayeredMaterialPtr pLayeredMaterial = getLayeredMaterial(layeredMaterialId);
  if (pLayeredMaterial == nullptr)
    return;

  auto pMaterialLayerCollection = pLayeredMaterial->Layers;
  if (pMaterialLayerCollection == nullptr)
    return;

  int baseLayerIndex = pLayeredMaterial->BaseLayerIndex;

  int layerCount = pMaterialLayerCollection->Count;

  for (int i = 0; i < layerCount; i++)
  {
    auto pMaterialLayer = pMaterialLayerCollection->Get(i);

    QList<QStandardItem*> layerItemList = createMaterialLayerItem(pModelObject, pMaterialLayer, i);

    if (i == baseLayerIndex)
      addReinforcementSubtree(layerItemList.at(0), pModelObject);

    pParentItem->appendRow(layerItemList);
  }
}

void TreeViewModelBuilder::addReinforcementSubtree(
  QStandardItem* pParentItem,
  IModelObjectPtr pModelObject)
{
  IObjectReinforcementModelPtr pObjectReinforcementModel;

  pModelObject->QueryInterface(&pObjectReinforcementModel);

  if (pObjectReinforcementModel == nullptr)
    return;

  auto pRebarUsageCollection = pObjectReinforcementModel->GetRebarUsages();

  for (int i = 0; i < pRebarUsageCollection->Count; i++)
  {
    auto pRebarUsage = pRebarUsageCollection->Get(i);
    addRebarUsageSubtree(pParentItem, pModelObject, pRebarUsage, i, 0);
  }

  auto pReinforcementUnitUsageCollection = pObjectReinforcementModel->GetReinforcementUnitUsages();

  for (int i = 0; i < pReinforcementUnitUsageCollection->Count; i++)
  {
    auto pReinforcementUnitUsage = pReinforcementUnitUsageCollection->Get(i);
    addReinforcementUnitUsageSubtree(pParentItem, pModelObject, pReinforcementUnitUsage, i);
  }
}

void TreeViewModelBuilder::addRebarUsageSubtree(
  QStandardItem* pParentItem,
  IModelObjectPtr pModelObject,
  IRebarUsagePtr pRebarUsage,
  int rebarUsageIndex,
  int reinforcementUnitStyleId)
{
  auto pRebarStyle = getRebarStyle(pRebarUsage->StyleId);
  if (pRebarStyle == nullptr)
    return;

  QList<QStandardItem*> rebarUsageItemList =
    createRebarUsageItem(pModelObject, pRebarUsage, rebarUsageIndex, reinforcementUnitStyleId);

  pParentItem->appendRow(rebarUsageItemList);
}

void TreeViewModelBuilder::addReinforcementUnitUsageSubtree(
  QStandardItem* pParentItem,
  IModelObjectPtr pModelObject,
  IReinforcementUnitUsagePtr pReinforcementUnitUsage,
  int reinforcementUnitUsageIndex)
{
  QList<QStandardItem*> reinforcementUnitUsageItemList =
    createReinforcementUnitUsageItem(pModelObject, pReinforcementUnitUsage, reinforcementUnitUsageIndex);

  auto pReinforcementUnitStyle = getReinforcementUnitStyle(pReinforcementUnitUsage->StyleId);

  auto pRebarUsageCollection = pReinforcementUnitStyle->GetRebarUsages();

  for (int i = 0; i < pRebarUsageCollection->Count; i++)
  {
    auto pRebarUsage = pRebarUsageCollection->Get(i);
    addRebarUsageSubtree(reinforcementUnitUsageItemList.first(), pModelObject, pRebarUsage, i, pReinforcementUnitUsage->StyleId);
  }

  pParentItem->appendRow(reinforcementUnitUsageItemList);
}

IMaterialPtr TreeViewModelBuilder::getMaterial(int materialId) const
{
  auto pProject = m_pApplication->Project;
  if (pProject == nullptr)
    return nullptr;

  auto pMaterialManager = pProject->MaterialManager;
  if (pMaterialManager == nullptr)
    return nullptr;

  return pMaterialManager->GetMaterial(materialId);
}

ILayeredMaterialPtr TreeViewModelBuilder::getLayeredMaterial(int layeredMaterialId) const
{
  auto pProject = m_pApplication->Project;
  if (pProject == nullptr)
    return nullptr;

  auto pLayeredMaterialManager = pProject->LayeredMaterialManager;
  if (pLayeredMaterialManager == nullptr)
    return nullptr;

  return pLayeredMaterialManager->GetLayeredMaterial(layeredMaterialId);
}

IRebarStylePtr TreeViewModelBuilder::getRebarStyle(int rebarStyleId) const
{
  auto pProject = m_pApplication->Project;
  if (pProject == nullptr)
    return nullptr;

  auto pReinforcementUnitStyleManager = pProject->ReinforcementUnitStyleManager;
  if (pReinforcementUnitStyleManager == nullptr)
    return nullptr;

  return pReinforcementUnitStyleManager->GetRebarStyle(rebarStyleId);
}

IReinforcementUnitStylePtr TreeViewModelBuilder::getReinforcementUnitStyle(int reinforcementStyleId) const
{
  auto pProject = m_pApplication->Project;
  if (pProject == nullptr)
    return nullptr;

  auto pReinforcementUnitStyleManager = pProject->ReinforcementUnitStyleManager;
  if (pReinforcementUnitStyleManager == nullptr)
    return nullptr;

  return pReinforcementUnitStyleManager->GetUnitStyle(reinforcementStyleId);
}

QList<QStandardItem*> TreeViewModelBuilder::createOtherGroupItem() const
{
  return createItem(QApplication::translate("me_modelObjects", "OtherObjectGroup"),
                    ":/icons/Folder",
                    eTreeViewItemType::ObjectGroup,
                    true,
                    true);
}

QList<QStandardItem*> TreeViewModelBuilder::createLevelItem(IModelObjectPtr pLevelModelObject) const
{
  bool isLevelVisible = getRengaObjectVisibility(m_pApplication, pLevelModelObject->Id);

  QList<QStandardItem*> itemList = createItem(
    QString::fromWCharArray(pLevelModelObject->Name), ":/icons/Level", eTreeViewItemType::Level, true, isLevelVisible);

  itemList.first()->setData(pLevelModelObject->Id, eTreeViewItemRole::EntityId);

  return itemList;
}

QList<QStandardItem*> TreeViewModelBuilder::createModelObjectItem(
    IModelObjectPtr pModelObject,
    bool createVisibilityItem,
    Renga::IEntityPtr pParentAssembly) const
{
  bool isModelObjectVisible = getRengaObjectVisibility(m_pApplication, pModelObject->Id);
  auto name = QString::fromWCharArray(pModelObject->Name);
  auto iconPath = getRengaEntityUIData(pModelObject->ObjectType).icon16Path;
  QList<QStandardItem*> itemList =
    createItem(name, iconPath, eTreeViewItemType::ModelObject, createVisibilityItem, isModelObjectVisible);

  itemList.first()->setData(pModelObject->Id, eTreeViewItemRole::EntityId);

  if (pParentAssembly)
    itemList.first()->setData(pParentAssembly->GetId(), eTreeViewItemRole::AssemblyId);

  return itemList;
}

QList<QStandardItem*> TreeViewModelBuilder::createMaterialLayerItem(
  IModelObjectPtr pModelObject,
  IMaterialLayerPtr pMaterialLayer,
  int layerIndex) const
{
  auto pMaterial = pMaterialLayer->GetMaterial();

  QString materialName = pMaterial != nullptr ?
    QString::fromWCharArray(pMaterial->Name) :
    QApplication::translate("me_materials", "No material");

  QList<QStandardItem*> itemList = createItem(materialName, ":/icons/Material", eTreeViewItemType::MaterialLayer);

  itemList.first()->setData(pModelObject->Id, eTreeViewItemRole::EntityId);
  itemList.first()->setData(layerIndex, eTreeViewItemRole::LayerIndex);

  return itemList;
}

QList<QStandardItem*> TreeViewModelBuilder::createSolidMaterialItem(IModelObjectPtr pModelObject) const
{
  IObjectWithMaterialPtr pObjectWithMaterial;
  pModelObject->QueryInterface(&pObjectWithMaterial);

  bool hasMaterial = pObjectWithMaterial != nullptr && pObjectWithMaterial->HasMaterial();

  IMaterialPtr pMaterial = hasMaterial ? getMaterial(pObjectWithMaterial->MaterialId) : nullptr;

  QString materialItemName = pMaterial != nullptr ?
    QString::fromWCharArray(pMaterial->Name) :
    QApplication::translate("me_materials", "No material");

  QList<QStandardItem*> itemList = createItem(materialItemName, ":/icons/Material", eTreeViewItemType::Undefined);

  itemList.first()->setData(pModelObject->Id, eTreeViewItemRole::EntityId);

  return itemList;
}

QList<QStandardItem*> TreeViewModelBuilder::createRebarUsageItem(
  IModelObjectPtr pModelObject,
  IRebarUsagePtr pRebarUsage,
  int rebarUsageIndex,
  int reinforcementUnitStyleId)
{
  IRebarStylePtr pRebarStyle = getRebarStyle(pRebarUsage->StyleId);
  assert(pRebarStyle != nullptr);

  QList<QStandardItem*> itemList = createItem(QString::fromWCharArray(pRebarStyle->Name), ":/icons/Rebar", eTreeViewItemType::RebarUsage);

  itemList.first()->setData(pModelObject->Id, eTreeViewItemRole::EntityId);

  itemList.first()->setData(rebarUsageIndex, eTreeViewItemRole::RebarUsageIndex);
  itemList.first()->setData(reinforcementUnitStyleId, eTreeViewItemRole::ReinforcementUnitStyleId);

  return itemList;
}

QList<QStandardItem*> TreeViewModelBuilder::createReinforcementUnitUsageItem(
  IModelObjectPtr pModelObject,
  IReinforcementUnitUsagePtr pReinforcementUnitUsage,
  int reinforcementUnitUsageIndex)
{
  auto pReinforcementUnitStyle = getReinforcementUnitStyle(pReinforcementUnitUsage->StyleId);
  assert(pReinforcementUnitStyle != nullptr);

  QList<QStandardItem*> itemList = createItem(
    QString::fromWCharArray(pReinforcementUnitStyle->Name),
    ":/icons/Reinforcement", eTreeViewItemType::ReinforcementUnitUsage);

  itemList.first()->setData(pModelObject->Id, eTreeViewItemRole::EntityId);
  itemList.first()->setData(reinforcementUnitUsageIndex, eTreeViewItemRole::ReinforcementUnitUsageIndex);

  return itemList;
}

QList<QStandardItem*> TreeViewModelBuilder::createItem(
  const QString& name,
  const QString& iconPath,
  int itemType,
  bool createVisibilityItem,
  bool isVisible) const
{
  QList<QStandardItem*> itemList;

  auto pItem = new QStandardItem(name);

  pItem->setIcon(QIcon(iconPath));
  pItem->setData(itemType, eTreeViewItemRole::ItemType);

  itemList.append(pItem);

  if (createVisibilityItem)
  {
    auto pVisibilityItem = new QStandardItem();
    itemList.append(pVisibilityItem);

    setItemVisibilityState(itemList, isVisible);
  }

  return itemList;
}

void TreeViewModelBuilder::setItemVisibilityState(QList<QStandardItem*>& itemList, bool isVisible) const
{
  if (itemList.count() <= 1)
    return;

  QStandardItem* pVisibilityItem = itemList.at(1);

  QString iconPath = isVisible ? ":/icons/Visible" : ":/icons/Hidden";

  pVisibilityItem->setIcon(QIcon(iconPath));
  pVisibilityItem->setData(isVisible, eTreeViewItemRole::IsVisible);
}

bool TreeViewModelBuilder::objectGroupHasVisibleObject(const std::list<IModelObjectPtr>& objectsGroup) const
{
  for (auto pObject : objectsGroup)
    if (getRengaObjectVisibility(m_pApplication, pObject->Id))
      return true;
  return false;
}


text:
'''
Module defining update state for the UrbanScape class
'''

import numpy as np

#=============================
#  					  	 	 |
#  UrbanScape Agent Methods  |
#  						  	 |
#=============================

# Base class for all Food Agents
# agent has a location and wealth

class Agent(object):
	def __init__(self, loc, wealth):
		self.loc = loc		# x,y coordinates of location in urbanscape
		self.wealth = wealth	# $ amount

	# Called every time-step
	def step(self, urbanscape):
		self.check_bankruptcy(urbanscape)

	# Remove the agent if broke
	def check_bankruptcy(self, urbanscape):
		if self.wealth < 0:
			self.wealth = 0
			urbanscape.remove_agent(self)

class FastFoodAgent(Agent):
	operations = 50000	# $ per year
	initial_wealth = 10000	# $ amount
	radius = 2	# number of block effected around location
	effect_coordinates = []

	def __init__(self, loc, urbanscape):
		super(FastFoodAgent, self).__init__(loc, self.initial_wealth)
		self.define_radius(urbanscape)
		self.operating_costs = (urbanscape.rent[loc]) + (FastFoodAgent.operations)
	def step(self, urbanscape):
		# 1. Gather revenues for the year
		self.capture_revenue(urbanscape)

		# 2. Perform parent class step function
		super(FastFoodAgent, self).step(urbanscape)

	#this function defines how much of fast food expenditures are
	#captured by the FoodAgent. If there are no competing FastFoodAgents,
	#assumes that FoodAgent captures all of block expenditures.

	def define_radius(self, urbanscape):
		self.effect_coordinates = urbanscape.effect_radius(self.loc, self.radius)

	def capture_revenue(self, urbanscape):
		x,y = self.loc
		self.wealth += (urbanscape.capture_expenditures(self.effect_coordinates)[0]) - self.operating_costs
		#capture_expenditures returns a list of two values, the 0th index being the ff_revenues

class GroceryStoreAgent(Agent):
	operations = 200000	# $ per year
	initial_wealth = 25000	# $ amount
	radius = 2	# number of block effected around location
	effect_coordinates = []

	def __init__(self, loc, urbanscape):
		super(GroceryStoreAgent, self).__init__(loc, self.initial_wealth)
		self.define_radius(urbanscape)
		self.operating_costs = (urbanscape.rent[loc]) + (GroceryStoreAgent.operations)
	def step(self, urbanscape):
		# 1. Gather revenues for the year
		self.capture_revenue(urbanscape)

		# 2. Perform parent class step function
		super(GroceryStoreAgent, self).step(urbanscape)

	#this function defines how much of grocery store expenditures are
	#captured by the FoodAgent. If there are no competing FoodAgents,
	#assumes that FoodAgent captures all of block expenditures.

	def define_radius(self, urbanscape):
		self.effect_coordinates = urbanscape.effect_radius(self.loc, self.radius)

	#assumes that the rest of income spent on food away from home is spent on groceries
	def capture_revenue(self, urbanscape):
		x,y = self.loc
		self.wealth += (urbanscape.capture_expenditures(self.effect_coordinates)[1]) - self.operating_costs
		#capture_expenditures returns a list of two values, the 1st index being the ff_revenues


text:
namespace tpie {

#if !defined(TPIE_NDEBUG) || defined(DOXYGEN)

#ifdef _WIN32
#pragma warning ( disable : 4127 )
#endif

///////////////////////////////////////////////////////////////////////////////
/// \def tp_assert
/// \param condition The condition to assert
/// \param message Message describing the erroneous condition
///////////////////////////////////////////////////////////////////////////////
#define tp_assert(condition,message) {									      \
	if (!((condition) && 1)) {												  \
	    TP_LOG_FATAL_ID("Assertion failed:");								  \
		TP_LOG_FATAL_ID(message);										      \
		std::cerr << "Assertion (" #condition ") failed " __FILE__ ":"		  \
				  << __LINE__ << ": " << message << "\n";					  \
		std::terminate();													  \
		assert(condition);												      \
	}																		  \
}

#else // TPIE_NDEBUG
#define tp_assert(condition,message)
#endif // TPIE_NDEBUG

}  // tpie namespace

#endif // _TPIE_ASSERT_H


text:
package openfoodfacts.github.scrachx.openfood.views.adapters;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import java.util.ArrayList;
import java.util.List;

import openfoodfacts.github.scrachx.openfood.fragments.BaseFragment;
import openfoodfacts.github.scrachx.openfood.models.ProductState;

public class ProductFragmentPagerAdapter extends FragmentStateAdapter {
    private final List<BaseFragment> fragments;
    private final List<String> tabsTitles;

    public ProductFragmentPagerAdapter(FragmentActivity fragmentActivity) {
        super(fragmentActivity);
        this.fragments = new ArrayList<>();
        this.tabsTitles = new ArrayList<>();
    }

    public void addFragment(BaseFragment fragment, String tabTitle) {
        this.fragments.add(fragment);
        this.tabsTitles.add(tabTitle);
    }

    @NonNull
    @Override
    public Fragment createFragment(int i) {
        return fragments.get(i);
    }

    @Override
    public int getItemCount() {
        return fragments.size();
    }

    public CharSequence getPageTitle(int position) {
        return tabsTitles.get(position);
    }

    public void refresh(ProductState productState) {
        for (BaseFragment f : fragments) {
            if (f.isAdded()) {
                f.refreshView(productState);
            }
        }
    }
}


text:
    <?php load_medias(1, $input_media_id = '#input-media', true); ?>

<input id="input-media" type="text" value="1" name="media_ids" />

<button type="button" class="btn btn-primary media-button" data-input-field="#input-media"  data-preview="#preview" >Media</button>

    <?php load_medias([2, 3], $input_media_id = '#input-media2'); ?>

<input id="input-media2" type="text" value="2,3" name="media_ids" />

<button type="button" class="btn btn-primary media-button" data-input-field="#input-media2" data-is-multi="true" data-preview="#preview2" >Media</button>

<?php media(2); ?>

                Collapsible panel

Panel Body

Panel Footer

Try it Yourself »
Collapsible List Group
Collapsible list group
The following shows a collapsible panel with a list group inside:

Example

                Collapsible list group

One

Two

Three

Footer

Try it Yourself »
Accordion
Collapsible Group 1
Collapsible Group 2
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Collapsible Group 3
The following example shows a simple accordion by extending the panel component.

Note: Use the data-parent attribute to make sure that all collapsible elements under the specified parent will be closed when one of the collapsible item is shown.

Example

                    Collapsible Group 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                commodo consequat.

                    Collapsible Group 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                commodo consequat.

                    Collapsible Group 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                commodo consequat.


text:
namespace GL {

class Shader {
 public:
  explicit Shader(boost::filesystem::path const &path);
  virtual ~Shader(void);

  virtual void Create(void) = 0;

  GLuint shader_id(void) {
    return shader_id_;
  }

 protected:
  void Create(const GLenum shader_type);

 private:
  std::string LoadSource(void);

  GLuint shader_id_;
  boost::filesystem::path path_;
};

}  // namespace GL

#endif  // JASS_GL_SHADER_H_


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

internal static partial class Interop
{
    internal static partial class Sys
    {
        internal const int NI_MAXHOST = 1025;
        internal const int NI_MAXSERV = 32;

        internal enum GetAddrInfoErrorFlags : int
        {
            EAI_AGAIN = 1,      // Temporary failure in name resolution.
            EAI_BADFLAGS = 2,   // Invalid value for `ai_flags' field.
            EAI_FAIL = 3,       // Non-recoverable failure in name resolution.
            EAI_FAMILY = 4,     // 'ai_family' not supported.
            EAI_NONAME = 5,     // NAME or SERVICE is unknown.
            EAI_BADARG = 6,     // One or more input arguments were invalid.
            EAI_NOMORE = 7,     // No more entries are present in the list.
            EAI_MEMORY = 8,     // Out of memory.
        }

        [StructLayout(LayoutKind.Sequential)]
        internal unsafe struct HostEntry
        {
            internal byte* CanonicalName;      // Canonical Name of the Host
            internal byte** Aliases;           // List of aliases for the host
            internal IPAddress* IPAddressList; // Handle for socket address list
            internal int IPAddressCount;       // Number of IP addresses in the list
        }

        [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetHostEntryForName")]
        internal static extern unsafe int GetHostEntryForName(string address, HostEntry* entry);

        [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FreeHostEntry")]
        internal static extern unsafe void FreeHostEntry(HostEntry* entry);
    }
}


text:
layout: next-post
title: vim
published: false
categories: learning
tags: vim
permalink: /:categories/:title.html
---

# Vim

## Initial Setup

I got into vim from a co-worker.
I thought it's that clunky text editor in your terminal you must use when you have ssh into the linux server.
However, I've grown to understand vim is much more than a text editor.
It can also be an IDE.

When I first used vim, it just looked plain an boring.
The black screen with hard to understand shortcuts.
There weren't any line numbers.
I didn't even know how to exit the damn program for a good 5 minutes.

Then I started figuring it out slowly.
Vim has different modes.
Vim can do macros.
Vim can find things with the same grep commands.
And it's quite expandable with the limitless plugins.
Vim is an endless rabbithole where you will get sucked in hours just setting it up.
But it's your customization.
And that's the beauty of vim.

Best advice - configure vim, and for that matter dotfiles, on your own.
Don't blindly copy and paste configurations, because you'll never understand them all.

### Modal Editing

Quoted from Nick Nisi

> Change the meaning of the keys in each mode of operation

> - Normal mode - navigate the structure of the file
> - Insert Mode - editing the file
> - Visual mode - highlighting portions of the file to manipulate at once
> - Ex mode - command mode

### Line Numbers

Where are my line numbers?
Simply type the following.

```
:set number
```

To remove the numbers, you can use this command.

```
:set nonumber
```

## Configuration

If you're sick and tired of setting everything up every time you boot up vim, simply place the configuration in your configuration file.
You can find the configuration file at this location.
`~/.vimrc`

Here's a truncated version of my general settings.

```vim
syntax enable     " Enable syntax highlighting
set tabstop=2     " set the tab stop at 2 spaces
set shiftwidth=2  " set the shift width by 2 spaces
set noexpandtab   " do not expand tab
set number        " show line numbers
```

For all of my settings, please view my [dotfiles](https://github.com/jermspeaks/dotfiles).

## Useful Shortcuts

All of the shortcuts can be found on the [Vim Wiki Website](http://vim.wikia.com/wiki/Vim_Tips_Wiki)

### Navigation

* `h` for left
* `l` for right
* `j` for down
* `k` for up
* `gg` top of the file
* `H` top of the window
* `ctrl + e` move window down one line
* `ctrl + y` move window up one line

### Word Manipulation

* `w` to go forward to the beginning of next word
* `b` to go backward to the beginning of previous word
* `e` to go forward to the end of the next word
* `dw` delete word up to the cursor including space between next word
* `diw` delete word on cursor

#### Yanking Words

* `yiw` yank in word

### Line Manipulation

* `0` or `^` for beginning of line
* `shift + i` go to the beginning of line and insert
* `$` go to end of line
* `shift + a` go to end of line and insert
* `dd` for delete line where cursor is on

#### Moving lines

* `:m <line number>` move to after the line number
* `[selected_line_num]m <line_number>` moves the line to after the line number
* `[from_line_num,to_line_num]m <line_number>` moves the selected lines to after the line number

### Vim as a Language

Operations and thing you want to do the operation to.
:

### Editing

* `u` for undo

Many times, you'll want to know how to copy and paste.

- TODO http://vim.wikia.com/wiki/Mac_OS_X_clipboard_sharing

### Colon Commands

* `:help <command>` for help on any command

## Plugins

Vim, like other text editors, has an ecosystem of plugins.

- [vundle](https://github.com/VundleVim/Vundle.vim) - plugin manager
- [nerdtree](https://github.com/scrooloose/nerdtree) - file tree
- [ctrlp](https://github.com/kien/ctrlp.vim) - Fuzzy file finder
- [fugitive](https://github.com/tpope/vim-fugitive) - git tool
- [syntastic](https://github.com/scrooloose/syntastic) - syntax checker/linter
- [vim-markdown](https://github.com/plasticboy/vim-markdown) - markdown syntax, matching rules and mappings, and extensions

### Packages

- [Sparkup](https://github.com/rstacruz/sparkup) - For html tag completion

### Colorize

I'm currently using Monokai, mainly because it was a default I had with Ruby on sublime.
I set it up using [vim-monokai](https://github.com/sickill/vim-monokai), which I actually want to go back and figure out how to hook it up with vundle and have it linked to the repo.

I want to figure out how to do this better, so I placed a todo with the wiki from the vim wikia.

- Todo: http://vim.wikia.com/wiki/Turn_on_syntax_coloring_in_Mac_OS_X
- Todo: talk about [colorschemes package](https://github.com/flazz/vim-colorschemes)

You can change the color scheme within normal mode. Heres how.

```vim
:colorscheme <name>
" short version
:colo <name>
" autocomplete
:colo <press tab>
```

## Macros

### Repeat last change

`.` command repeats the last change made in normal mode.
It's like oh my gosh amaze balls.

- TODO http://vim.wikia.com/wiki/Repeat_last_change
- TODO Show an example

### Recording

q{register}
(do the things)
q

### Registers

`WIP`

## More Research to go through

- http://yannesposito.com/Scratch/en/blog/Vim-as-IDE/
- coloring vim (as stated above)
- adding more language support
- adding line numbers
- go to top of file (shortcut)
- go to bottom of file (shortcut)
- how to find
- Macros: q command, recording so you don't repeat yourself
- Surround.vim
- mapping escape key to caps lock
- relative numbering
- commenting
- copying and pasting that doesn't get ruined with crazy indents
- Snippets

## Helpful Resources

- [vim + tmux](https://www.youtube.com/watch?v=5r6yzFEXajQ) - Talk at [OMG!Code](http://code.omahamakergroup.org/) given by [Nick Nisi](http://nicknisi.com/)
<iframe width="560" height="315" src="https://www.youtube.com/embed/5r6yzFEXajQ" frameborder="0" allowfullscreen></iframe>
- vimtutor - type `vimtutor` in your terminal. Quick lessons summaries can be found on [this post](./vimtutor.md).


text:
/* global describe, it */

'use strict';

var assert = require('chai').assert,
	Rx = require('rx'),
	watch = require('..'),
	fs = require('fs');

process.chdir(__dirname + '/fixtures');

it('init test', function (done) {
	watch('**/*.js', {init: true})
	.take(1)
	.concatAll()
	.do(function (file) {
		assert.equal(file.program.type, 'Program');
	})
	.pluck('loc').pluck('source')
	.toArray()
	.do(function (sources) {
		assert.deepEqual(sources.sort(), ['a.js', 'b.js']);
	})
	.subscribe(function () {}, done, done);
});

it('change test', function (done) {
	watch('**/*.js', {init: false})
	.take(1)
	.concatAll()
	.do(function (file) {
		assert.equal(file.program.type, 'Program');
	})
	.pluck('loc').pluck('source')
	.toArray()
	.do(function (sources) {
		assert.deepEqual(sources.sort(), ['a.js', 'b.js']);
	})
	.subscribe(function () {}, done, done);

	fs.writeFile('b.js', 'var b = 1;\r\n', function () {});
});


text:
{{title}}

Cover is a one-page template for building simple and beautiful home pages. Download, edit the text, and add your own
        fullscreen background photo to make it your own.

        Learn more


text:
require 'chefspec'

if defined?(Chef::Resource::CabPackage)
  describe 'cab_package::install' do
    platform 'windows'

    describe 'installs a cab_package with the default action' do
      it { is_expected.to install_cab_package('default_action') }
      it { is_expected.to_not install_cab_package('not_default_action') }
    end

    describe 'installs a cab_package with an explicit action' do
      it { is_expected.to install_cab_package('explicit_action') }
    end

    describe 'installs a cab_package with attributes' do
      it { is_expected.to install_cab_package('with_attributes').with(version: '1.2.3') }
      it { is_expected.to_not install_cab_package('with_attributes').with(version: '1.2.4') }
    end

    describe 'installs a cab_package when specifying the identity attribute' do
      it { is_expected.to install_cab_package('identity_attribute') }
    end
  end
end


text:
import datetime

now = datetime.date.today()
print now

print now.strftime("%m-%d-%y. %d %d %Y is a %A on the %d day of %B.")

birthday = datetime.date(1990, 5, 24)
age = now - birthday
print age.days


text:
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.0.0. The user interface will be using Angular framework with RxJS & PWA support.

## Module Details

Below are the modules identified for the application -

* Welcome
* Login
* Registration
* Guest
* Profile Management
* Product Catalog
* Ratings
* Reviews
* Discussion Forums
* Articles
* Featured Content
* Recommendation
* Coupons
* Purchase Cart
* Transaction History
* Location Detection
* Payment
* Iris/ Fingerprint Scanner
* Document Upload
* Single Sign-On
* Visual Graphs
* Administration Panel

## Deployment
The deployment is done using the firebase tools for the deployment
1. Refer Firebase deployment steps [here](https://firebase.google.com/docs/hosting/deploying)
2. Execute `firebase login` within the deploy folder
3. Execute `firebase deploy` within the deploy folder

## Upgrade commands
* Update NodeJS `sudo n lts`
* Upgrade package.json dependencies `ncu -a`
* Update Typescript `npm install -g typescript@2.9.2`
* Update Angular CLI `npm install -g @angular/cli`
* Update firebase tools `npm install -g firebase-tools`


text:
using System;
using System.Collections.Generic;
using System.Linq;
using AppIdent.Metrics;
using AppIdent.Misc;
using AppIdent.Models;
using Framework.Models;
using Netfox.Core.Enums;

namespace AppIdent.Features.Bases
{
    public class MaxInterArrivalTimeBase : FeatureBase
    {
        public MaxInterArrivalTimeBase() { }
        public MaxInterArrivalTimeBase(L7Conversation l7Conversation, DaRFlowDirection flowDirection) : base(l7Conversation, flowDirection) { }
        public MaxInterArrivalTimeBase(double featureValue) : base(featureValue) { }
        public override FeatureKind FeatureKind { get; } = FeatureKind.Continous;
        public override double WeightBias { get; } = 0.3;

        public override double ComputeDistanceToProtocolModel(FeatureBase sampleFeature)
        {
            return Math.Abs(this.Normalize(this.FeatureValue) - this.Normalize(sampleFeature.FeatureValue));
        }

        public override double ComputeFeature(L7Conversation l7Conversation, DaRFlowDirection flowDirection)
        {
            IEnumerable<L7PDU> pdus;
            switch(flowDirection)
            {
                case DaRFlowDirection.up:
                    pdus = l7Conversation.UpFlowPDUs;
                    break;
                case DaRFlowDirection.down:
                    pdus = l7Conversation.DownFlowPDUs;
                    break;
                case DaRFlowDirection.non:
                    pdus = l7Conversation.L7PDUs;
                    break;
                default: throw new ArgumentOutOfRangeException(nameof(flowDirection), flowDirection, null);
            }
            var l7Pdus = pdus as L7PDU[] ?? pdus.ToArray();
            if(pdus == null || !l7Pdus.Any()) { return -1; }

            var length = l7Pdus.Count();

            if(length <= 1) { return 0; }

            var maxTime = Math.Abs((l7Pdus[1].FirstSeen - l7Pdus[0].FirstSeen).TotalSeconds);

            for(var i = 1; i < length - 1; i++)
            {
                var tmpTime = Math.Abs((l7Pdus[i + 1].FirstSeen - l7Pdus[i].FirstSeen).TotalSeconds);

                if(maxTime.CompareTo(tmpTime) < 0) { maxTime = tmpTime; }
            }

            return maxTime;
        }

        public override void ComputeFeatureForProtocolModel(IFeatureCollectionWrapper<FeatureBase> featureValues)
        {
            this.FeatureValue = FeatureMetrics.FeatureMetricAverage(featureValues);
            this.Weight = WeightMetrics.WeightUsingStandarDeviation(featureValues);
        }
    }
}