text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Collections.Immutable
Imports System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.QuickInfo
Imports Microsoft.CodeAnalysis.Tags
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.Core.Imaging
Imports Microsoft.VisualStudio.Imaging
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Adornments
Imports Moq
Imports QuickInfoItem = Microsoft.CodeAnalysis.QuickInfo.QuickInfoItem

Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense

    <UseExportProvider>
    Public Class IntellisenseQuickInfoBuilderTests

        <WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
        <WorkItem(33001, "https://github.com/dotnet/roslyn/issues/33001")>
        Public Async Sub BuildQuickInfoItem()

            Dim codeAnalysisQuickInfoItem =
                QuickInfoItem.Create(
                    New TextSpan(0, 0),
                    ImmutableArray.Create(WellKnownTags.Method, WellKnownTags.Public),
                    ImmutableArray.Create(
                        QuickInfoSection.Create(
                            QuickInfoSectionKinds.Description,
                            ImmutableArray.Create(
                                New TaggedText(TextTags.Keyword, "void"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Class, "Console"),
                                New TaggedText(TextTags.Punctuation, "."),
                                New TaggedText(TextTags.Method, "WriteLine"),
                                New TaggedText(TextTags.Punctuation, "("),
                                New TaggedText(TextTags.Keyword, "string"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Parameter, "value"),
                                New TaggedText(TextTags.Punctuation, ")"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Punctuation, "("),
                                New TaggedText(TextTags.Punctuation, "+"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Text, "18"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Text, "overloads"),
                                New TaggedText(TextTags.Punctuation, ")"))),
                        QuickInfoSection.Create(
                            QuickInfoSectionKinds.DocumentationComments,
                            ImmutableArray.Create(New TaggedText(TextTags.Text, "Writes the specified string value, followed by the current line terminator, to the standard output stream."))),
                        QuickInfoSection.Create(
                            QuickInfoSectionKinds.Exception,
                            ImmutableArray.Create(
                                New TaggedText(TextTags.Text, "Exceptions"),
                                New TaggedText(TextTags.LineBreak, "\r\n"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Namespace, "System"),
                                New TaggedText(TextTags.Punctuation, "."),
                                New TaggedText(TextTags.Namespace, "IO"),
                                New TaggedText(TextTags.Punctuation, "."),
                                New TaggedText(TextTags.Class, "IOException")))))

            Dim trackingSpan = New Mock(Of ITrackingSpan) With {
                .DefaultValue = DefaultValue.Mock
            }

            Dim intellisenseQuickInfo = Await IntellisenseQuickInfoBuilder.BuildItemAsync(trackingSpan.Object, codeAnalysisQuickInfoItem, Nothing, Nothing, Threading.CancellationToken.None)
            Assert.NotNull(intellisenseQuickInfo)

            Dim container = Assert.IsType(Of ContainerElement)(intellisenseQuickInfo.Item)

            Dim expected = New ContainerElement(
                ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding,
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ContainerElement(
                        ContainerElementStyle.Wrapped,
                        New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPublic)),
                        New ClassifiedTextElement(
                            New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.ClassName, "Console"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                            New ClassifiedTextRun(ClassificationTypeNames.MethodName, "WriteLine"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("),
                            New ClassifiedTextRun(ClassificationTypeNames.Keyword, "string"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.ParameterName, "value"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "+"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.Text, "18"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.Text, "overloads"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))),
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "Writes the specified string value, followed by the current line terminator, to the standard output stream."))),
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "Exceptions")),
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                        New ClassifiedTextRun(ClassificationTypeNames.NamespaceName, "System"),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                        New ClassifiedTextRun(ClassificationTypeNames.NamespaceName, "IO"),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                        New ClassifiedTextRun(ClassificationTypeNames.ClassName, "IOException"))))

            AssertEqualAdornments(expected, container)
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
        <WorkItem(33001, "https://github.com/dotnet/roslyn/issues/33001")>
        Public Async Sub BuildQuickInfoItemWithoutDocumentation()

            Dim codeAnalysisQuickInfoItem =
                QuickInfoItem.Create(
                    New TextSpan(0, 0),
                    ImmutableArray.Create(WellKnownTags.Method, WellKnownTags.Public),
                    ImmutableArray.Create(
                        QuickInfoSection.Create(
                            QuickInfoSectionKinds.Description,
                            ImmutableArray.Create(
                                New TaggedText(TextTags.Keyword, "void"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Class, "Console"),
                                New TaggedText(TextTags.Punctuation, "."),
                                New TaggedText(TextTags.Method, "WriteLine"),
                                New TaggedText(TextTags.Punctuation, "("),
                                New TaggedText(TextTags.Keyword, "string"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Parameter, "value"),
                                New TaggedText(TextTags.Punctuation, ")"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Punctuation, "("),
                                New TaggedText(TextTags.Punctuation, "+"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Text, "18"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Text, "overloads"),
                                New TaggedText(TextTags.Punctuation, ")"))),
                        QuickInfoSection.Create(
                            QuickInfoSectionKinds.Exception,
                            ImmutableArray.Create(
                                New TaggedText(TextTags.Text, "Exceptions"),
                                New TaggedText(TextTags.LineBreak, "\r\n"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Namespace, "System"),
                                New TaggedText(TextTags.Punctuation, "."),
                                New TaggedText(TextTags.Namespace, "IO"),
                                New TaggedText(TextTags.Punctuation, "."),
                                New TaggedText(TextTags.Class, "IOException")))))

            Dim trackingSpan = New Mock(Of ITrackingSpan) With {
                .DefaultValue = DefaultValue.Mock
            }

            Dim intellisenseQuickInfo = Await IntellisenseQuickInfoBuilder.BuildItemAsync(trackingSpan.Object, codeAnalysisQuickInfoItem, Nothing, Nothing, Threading.CancellationToken.None)
            Assert.NotNull(intellisenseQuickInfo)

            Dim container = Assert.IsType(Of ContainerElement)(intellisenseQuickInfo.Item)

            Dim expected = New ContainerElement(
                ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding,
                New ContainerElement(
                    ContainerElementStyle.Wrapped,
                    New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPublic)),
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"),
                        New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                        New ClassifiedTextRun(ClassificationTypeNames.ClassName, "Console"),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                        New ClassifiedTextRun(ClassificationTypeNames.MethodName, "WriteLine"),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("),
                        New ClassifiedTextRun(ClassificationTypeNames.Keyword, "string"),
                        New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                        New ClassifiedTextRun(ClassificationTypeNames.ParameterName, "value"),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"),
                        New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "+"),
                        New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "18"),
                        New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "overloads"),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))),
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "Exceptions")),
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                        New ClassifiedTextRun(ClassificationTypeNames.NamespaceName, "System"),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                        New ClassifiedTextRun(ClassificationTypeNames.NamespaceName, "IO"),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                        New ClassifiedTextRun(ClassificationTypeNames.ClassName, "IOException"))))

            AssertEqualAdornments(expected, container)
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
        <WorkItem(33001, "https://github.com/dotnet/roslyn/issues/33001")>
        Public Async Sub BuildQuickInfoItemWithMultiLineDocumentation()

            Dim codeAnalysisQuickInfoItem =
                QuickInfoItem.Create(
                    New TextSpan(0, 0),
                    ImmutableArray.Create(WellKnownTags.Method, WellKnownTags.Public),
                    ImmutableArray.Create(
                        QuickInfoSection.Create(
                            QuickInfoSectionKinds.Description,
                            ImmutableArray.Create(
                                New TaggedText(TextTags.Keyword, "void"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Class, "Console"),
                                New TaggedText(TextTags.Punctuation, "."),
                                New TaggedText(TextTags.Method, "WriteLine"),
                                New TaggedText(TextTags.Punctuation, "("),
                                New TaggedText(TextTags.Keyword, "string"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Parameter, "value"),
                                New TaggedText(TextTags.Punctuation, ")"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Punctuation, "("),
                                New TaggedText(TextTags.Punctuation, "+"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Text, "18"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Text, "overloads"),
                                New TaggedText(TextTags.Punctuation, ")"))),
                        QuickInfoSection.Create(
                            QuickInfoSectionKinds.DocumentationComments,
                            ImmutableArray.Create(
                                New TaggedText(TextTags.Text, "Documentation line 1."),
                                New TaggedText(TextTags.LineBreak, "\r\n"),
                                New TaggedText(TextTags.Text, "Documentation line 2."),
                                New TaggedText(TextTags.LineBreak, "\r\n"),
                                New TaggedText(TextTags.LineBreak, "\r\n"),
                                New TaggedText(TextTags.Text, "Documentation paragraph 2."),
                                New TaggedText(TextTags.LineBreak, "\r\n"),
                                New TaggedText(TextTags.Text, "Documentation paragraph 2 line 2."),
                                New TaggedText(TextTags.LineBreak, "\r\n"),
                                New TaggedText(TextTags.LineBreak, "\r\n"),
                                New TaggedText(TextTags.Text, "Documentation paragraph 3."))),
                        QuickInfoSection.Create(
                            QuickInfoSectionKinds.Exception,
                            ImmutableArray.Create(
                                New TaggedText(TextTags.Text, "Exceptions"),
                                New TaggedText(TextTags.LineBreak, "\r\n"),
                                New TaggedText(TextTags.Space, " "),
                                New TaggedText(TextTags.Namespace, "System"),
                                New TaggedText(TextTags.Punctuation, "."),
                                New TaggedText(TextTags.Namespace, "IO"),
                                New TaggedText(TextTags.Punctuation, "."),
                                New TaggedText(TextTags.Class, "IOException")))))

            Dim trackingSpan = New Mock(Of ITrackingSpan) With {
                .DefaultValue = DefaultValue.Mock
            }

            Dim intellisenseQuickInfo = Await IntellisenseQuickInfoBuilder.BuildItemAsync(trackingSpan.Object, codeAnalysisQuickInfoItem, Nothing, Nothing, Threading.CancellationToken.None)
            Assert.NotNull(intellisenseQuickInfo)

            Dim container = Assert.IsType(Of ContainerElement)(intellisenseQuickInfo.Item)

            Dim expected = New ContainerElement(
                ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding,
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ContainerElement(
                        ContainerElementStyle.Wrapped,
                        New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPublic)),
                        New ClassifiedTextElement(
                            New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.ClassName, "Console"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                            New ClassifiedTextRun(ClassificationTypeNames.MethodName, "WriteLine"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("),
                            New ClassifiedTextRun(ClassificationTypeNames.Keyword, "string"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.ParameterName, "value"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "+"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.Text, "18"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.Text, "overloads"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))),
                    New ContainerElement(
                        ContainerElementStyle.Stacked,
                        New ClassifiedTextElement(
                            New ClassifiedTextRun(ClassificationTypeNames.Text, "Documentation line 1.")),
                        New ClassifiedTextElement(
                            New ClassifiedTextRun(ClassificationTypeNames.Text, "Documentation line 2.")))),
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "Documentation paragraph 2.")),
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "Documentation paragraph 2 line 2."))),
                New ClassifiedTextElement(
                    New ClassifiedTextRun(ClassificationTypeNames.Text, "Documentation paragraph 3.")),
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "Exceptions")),
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                        New ClassifiedTextRun(ClassificationTypeNames.NamespaceName, "System"),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                        New ClassifiedTextRun(ClassificationTypeNames.NamespaceName, "IO"),
                        New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                        New ClassifiedTextRun(ClassificationTypeNames.ClassName, "IOException"))))

            AssertEqualAdornments(expected, container)
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
        <WorkItem(33001, "https://github.com/dotnet/roslyn/issues/33001")>
        Public Async Sub BuildQuickInfoFromSymbol()
            Dim workspace =
                <Workspace>
                    <Project Language="C#" CommonReferences="true">
                        <Document>
                            using System.IO;
                            using System.Threading;
                            class MyClass {
                                /// <summary>
                                /// Documentation line 1.<br/>
                                /// Documentation line 2.
                                /// <para>Documentation paragraph 2.<br/>
                                /// Documentation paragraph 2
                                /// line 2.</para>
                                /// <para>Documentation paragraph 3.</para>
                                /// </summary>
                                /// <exception cref="IOException">If something fails</exception>
                                void MyMethod(CancellationToken cancellationToken = default(CancellationToken)) {
                                    MyM$$ethod();
                                }
                            }
                        </Document>
                    </Project>
                </Workspace>

            Dim codeAnalysisQuickInfoItem = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp)

            Dim trackingSpan = New Mock(Of ITrackingSpan) With {
                .DefaultValue = DefaultValue.Mock
            }

            Dim intellisenseQuickInfo = Await IntellisenseQuickInfoBuilder.BuildItemAsync(trackingSpan.Object, codeAnalysisQuickInfoItem, Nothing, Nothing, CancellationToken.None)
            Assert.NotNull(intellisenseQuickInfo)

            Dim container = Assert.IsType(Of ContainerElement)(intellisenseQuickInfo.Item)

            Dim expected = New ContainerElement(
                ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding,
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ContainerElement(
                        ContainerElementStyle.Wrapped,
                        New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)),
                        New ClassifiedTextElement(
                            New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                            New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "["),
                            New ClassifiedTextRun(ClassificationTypeNames.StructName, "CancellationToken"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.ParameterName, "cancellationToken"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "="),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.Keyword, "default"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "]"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))),
                    New ContainerElement(
                        ContainerElementStyle.Stacked,
                        New ClassifiedTextElement(
                            New ClassifiedTextRun(ClassificationTypeNames.Text, "Documentation line 1.")),
                        New ClassifiedTextElement(
                            New ClassifiedTextRun(ClassificationTypeNames.Text, "Documentation line 2.")))),
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "Documentation paragraph 2.")),
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "Documentation paragraph 2 line 2."))),
                New ClassifiedTextElement(
                    New ClassifiedTextRun(ClassificationTypeNames.Text, "Documentation paragraph 3.")),
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, FeaturesResources.Exceptions_colon)),
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, "  "),
                        New ClassifiedTextRun(ClassificationTypeNames.ClassName, "IOException"))))

            AssertEqualAdornments(expected, container)
        End Sub

        <WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)>
        <InlineData("<para>text1</para><para>text2</para>")>
        <InlineData("text1<br/><br/>text2")>
        <InlineData("text1<br/><br/><br/>text2")>
        <InlineData("<br/>text1<br/><br/>text2<br/>")>
        <InlineData("<br/><br/>text1<br/><br/>text2<br/><br/>")>
        <InlineData("<para>text1<br/><br/>text2</para>")>
        <InlineData("<para/>text1<br/><br/>text2<para/>")>
        <InlineData("<para/><para/>text1<br/><br/>text2<para/><para/>")>
        <InlineData("<para>text1</para><br/><para>text2</para>")>
        <WorkItem(33001, "https://github.com/dotnet/roslyn/issues/33001")>
        Public Async Sub EquivalentParagraphForms(summary As String)
            Dim workspace =
                <Workspace>
                    <Project Language="C#" CommonReferences="true">
                        <Document>
                            using System.IO;
                            using System.Threading;
                            class MyClass {
                                /// <summary>
                                /// <%= summary %>
                                /// </summary>
                                void MyMethod() {
                                    MyM$$ethod();
                                }
                            }
                        </Document>
                    </Project>
                </Workspace>

            Dim codeAnalysisQuickInfoItem = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp)

            Dim trackingSpan = New Mock(Of ITrackingSpan) With {
                .DefaultValue = DefaultValue.Mock
            }

            Dim intellisenseQuickInfo = Await IntellisenseQuickInfoBuilder.BuildItemAsync(trackingSpan.Object, codeAnalysisQuickInfoItem, Nothing, Nothing, CancellationToken.None)
            Assert.NotNull(intellisenseQuickInfo)

            Dim container = Assert.IsType(Of ContainerElement)(intellisenseQuickInfo.Item)

            Dim expected = New ContainerElement(
                ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding,
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ContainerElement(
                        ContainerElementStyle.Wrapped,
                        New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)),
                        New ClassifiedTextElement(
                            New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                            New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))),
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "text1"))),
                New ClassifiedTextElement(
                    New ClassifiedTextRun(ClassificationTypeNames.Text, "text2")))

            AssertEqualAdornments(expected, container)
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
        <WorkItem(33546, "https://github.com/dotnet/roslyn/issues/33546")>
        Public Async Sub QuickInfoForParameterReference()
            Dim workspace =
                <Workspace>
                    <Project Language="C#" CommonReferences="true">
                        <Document>
                            using System.Threading;
                            class MyClass {
                                /// <summary>
                                /// The parameter is <paramref name="p"/>.
                                /// </summary>
                                void MyMethod(CancellationToken p) {
                                    MyM$$ethod(CancellationToken.None);
                                }
                            }
                        </Document>
                    </Project>
                </Workspace>

            Dim codeAnalysisQuickInfoItem = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp)

            Dim trackingSpan = New Mock(Of ITrackingSpan) With {
                .DefaultValue = DefaultValue.Mock
            }

            Dim intellisenseQuickInfo = Await IntellisenseQuickInfoBuilder.BuildItemAsync(trackingSpan.Object, codeAnalysisQuickInfoItem, Nothing, Nothing, CancellationToken.None)
            Assert.NotNull(intellisenseQuickInfo)

            Dim container = Assert.IsType(Of ContainerElement)(intellisenseQuickInfo.Item)

            Dim expected = New ContainerElement(
                ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding,
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ContainerElement(
                        ContainerElementStyle.Wrapped,
                        New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)),
                        New ClassifiedTextElement(
                            New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                            New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("),
                            New ClassifiedTextRun(ClassificationTypeNames.StructName, "CancellationToken"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.ParameterName, "p"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))),
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "The parameter is"),
                        New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                        New ClassifiedTextRun(ClassificationTypeNames.ParameterName, "p"),
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "."))))

            AssertEqualAdornments(expected, container)
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)>
        <WorkItem(33546, "https://github.com/dotnet/roslyn/issues/33546")>
        Public Async Sub QuickInfoForTypeParameterReference()
            Dim workspace =
                <Workspace>
                    <Project Language="C#" CommonReferences="true">
                        <Document>
                            using System.Threading;
                            class MyClass {
                                /// <summary>
                                /// The type parameter is <typeparamref name="T"/>.
                                /// </summary>
                                void MyMethod<T>() {
                                    MyM$$ethod<int>();
                                }
                            }
                        </Document>
                    </Project>
                </Workspace>

            Dim codeAnalysisQuickInfoItem = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp)

            Dim trackingSpan = New Mock(Of ITrackingSpan) With {
                .DefaultValue = DefaultValue.Mock
            }

            Dim intellisenseQuickInfo = Await IntellisenseQuickInfoBuilder.BuildItemAsync(trackingSpan.Object, codeAnalysisQuickInfoItem, Nothing, Nothing, CancellationToken.None)
            Assert.NotNull(intellisenseQuickInfo)

            Dim container = Assert.IsType(Of ContainerElement)(intellisenseQuickInfo.Item)

            Dim expected = New ContainerElement(
                ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding,
                New ContainerElement(
                    ContainerElementStyle.Stacked,
                    New ContainerElement(
                        ContainerElementStyle.Wrapped,
                        New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)),
                        New ClassifiedTextElement(
                            New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"),
                            New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                            New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."),
                            New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "<"),
                            New ClassifiedTextRun(ClassificationTypeNames.Keyword, "int"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ">"),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("),
                            New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))),
                    New ClassifiedTextElement(
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "The type parameter is"),
                        New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                        New ClassifiedTextRun(ClassificationTypeNames.TypeParameterName, "T"),
                        New ClassifiedTextRun(ClassificationTypeNames.Text, "."))))

            AssertEqualAdornments(expected, container)
        End Sub

        Private Async Function GetQuickInfoItemAsync(workspaceDefinition As XElement, language As String) As Task(Of QuickInfoItem)
            Using workspace = TestWorkspace.Create(workspaceDefinition)
                Dim solution = workspace.CurrentSolution
                Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
                Dim cursorPosition = cursorDocument.CursorPosition.Value
                Dim cursorBuffer = cursorDocument.TextBuffer

                Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id)

                Dim languageServiceProvider = workspace.Services.GetLanguageServices(language)
                Dim quickInfoService = languageServiceProvider.GetRequiredService(Of QuickInfoService)

                Return Await quickInfoService.GetQuickInfoAsync(document, cursorPosition, CancellationToken.None).ConfigureAwait(False)
            End Using
        End Function

        Private Shared Sub AssertEqualAdornments(expected As Object, actual As Object)
            Try
                Assert.IsType(expected.GetType, actual)

                Dim containerElement = TryCast(expected, ContainerElement)
                If containerElement IsNot Nothing Then
                    AssertEqualContainerElement(containerElement, DirectCast(actual, ContainerElement))
                    Return
                End If

                Dim imageElement = TryCast(expected, ImageElement)
                If imageElement IsNot Nothing Then
                    AssertEqualImageElement(imageElement, DirectCast(actual, ImageElement))
                    Return
                End If

                Dim classifiedTextElement = TryCast(expected, ClassifiedTextElement)
                If classifiedTextElement IsNot Nothing Then
                    AssertEqualClassifiedTextElement(classifiedTextElement, DirectCast(actual, ClassifiedTextElement))
                    Return
                End If

                Dim classifiedTextRun = TryCast(expected, ClassifiedTextRun)
                If classifiedTextRun IsNot Nothing Then
                    AssertEqualClassifiedTextRun(classifiedTextRun, DirectCast(actual, ClassifiedTextRun))
                    Return
                End If

                Throw Roslyn.Utilities.ExceptionUtilities.Unreachable
            Catch ex As Exception
                Dim renderedExpected = ContainerToString(expected)
                Dim renderedActual = ContainerToString(actual)
                AssertEx.EqualOrDiff(renderedExpected, renderedActual)

                ' This is not expected to be hit, but it will be hit if the difference cannot be detected within the diff
                Throw
            End Try
        End Sub

        Private Shared Sub AssertEqualContainerElement(expected As ContainerElement, actual As ContainerElement)
            Assert.Equal(expected.Style, actual.Style)
            Assert.Equal(expected.Elements.Count, actual.Elements.Count)
            For Each pair In expected.Elements.Zip(actual.Elements, Function(expectedElement, actualElement) (expectedElement, actualElement))
                AssertEqualAdornments(pair.expectedElement, pair.actualElement)
            Next
        End Sub

        Private Shared Sub AssertEqualImageElement(expected As ImageElement, actual As ImageElement)
            Assert.Equal(expected.ImageId.Guid, actual.ImageId.Guid)
            Assert.Equal(expected.ImageId.Id, actual.ImageId.Id)
            Assert.Equal(expected.AutomationName, actual.AutomationName)
        End Sub

        Private Shared Sub AssertEqualClassifiedTextElement(expected As ClassifiedTextElement, actual As ClassifiedTextElement)
            Assert.Equal(expected.Runs.Count, actual.Runs.Count)
            For Each pair In expected.Runs.Zip(actual.Runs, Function(expectedRun, actualRun) (expectedRun, actualRun))
                AssertEqualClassifiedTextRun(pair.expectedRun, pair.actualRun)
            Next
        End Sub

        Private Shared Sub AssertEqualClassifiedTextRun(expected As ClassifiedTextRun, actual As ClassifiedTextRun)
            Assert.Equal(expected.ClassificationTypeName, actual.ClassificationTypeName)
            Assert.Equal(expected.Text, actual.Text)
        End Sub

        Private Shared Function ContainerToString(element As Object) As String
            Dim result = New StringBuilder
            ContainerToString(element, "", result)
            Return result.ToString()
        End Function

        Private Shared Sub ContainerToString(element As Object, indent As String, result As StringBuilder)
            result.Append($"{indent}New {element.GetType().Name}(")

            Dim container = TryCast(element, ContainerElement)
            If container IsNot Nothing Then
                result.AppendLine()
                indent += "    "
                result.AppendLine($"{indent}{ContainerStyleToString(container.Style)},")
                Dim elements = container.Elements.ToArray()
                For i = 0 To elements.Length - 1
                    ContainerToString(elements(i), indent, result)

                    If i < elements.Length - 1 Then
                        result.AppendLine(",")
                    Else
                        result.Append(")")
                    End If
                Next

                Return
            End If

            Dim image = TryCast(element, ImageElement)
            If image IsNot Nothing Then
                Dim guid = GetKnownImageGuid(image.ImageId.Guid)
                Dim id = GetKnownImageId(image.ImageId.Id)
                result.Append($"New {NameOf(ImageId)}({guid}, {id}))")
                Return
            End If

            Dim classifiedTextElement = TryCast(element, ClassifiedTextElement)
            If classifiedTextElement IsNot Nothing Then
                result.AppendLine()
                indent += "    "
                Dim runs = classifiedTextElement.Runs.ToArray()
                For i = 0 To runs.Length - 1
                    ContainerToString(runs(i), indent, result)

                    If i < runs.Length - 1 Then
                        result.AppendLine(",")
                    Else
                        result.Append(")")
                    End If
                Next

                Return
            End If

            Dim classifiedTextRun = TryCast(element, ClassifiedTextRun)
            If classifiedTextRun IsNot Nothing Then
                Dim classification = GetKnownClassification(classifiedTextRun.ClassificationTypeName)
                result.Append($"{classification}, ""{classifiedTextRun.Text.Replace("""", """""")}"")")
                Return
            End If

            Throw Roslyn.Utilities.ExceptionUtilities.Unreachable
        End Sub

        Private Shared Function ContainerStyleToString(style As ContainerElementStyle) As String
            Dim stringValue = style.ToString()
            Return String.Join(" Or ", stringValue.Split({","c, " "c}, StringSplitOptions.RemoveEmptyEntries).Select(Function(value) $"{NameOf(ContainerElementStyle)}.{value}"))
        End Function

        Private Shared Function GetKnownClassification(classification As String) As String
            For Each field In GetType(ClassificationTypeNames).GetFields()
                If Not field.IsStatic Then
                    Continue For
                End If

                Dim rawValue = field.GetValue(Nothing)
                Dim value = TryCast(rawValue, String)
                If value = classification Then
                    Return $"{NameOf(ClassificationTypeNames)}.{field.Name}"
                End If
            Next

            Return $"""{classification}"""
        End Function

        Private Shared Function GetKnownImageGuid(guid As Guid) As String
            For Each field In GetType(KnownImageIds).GetFields()
                If Not field.IsStatic Then
                    Continue For
                End If

                Dim rawValue = field.GetValue(Nothing)
                Dim value As Guid? = If(TypeOf rawValue Is Guid, DirectCast(rawValue, Guid), Nothing)
                If value = guid Then
                    Return $"{NameOf(KnownImageIds)}.{field.Name}"
                End If
            Next

            Return guid.ToString()
        End Function

        Private Shared Function GetKnownImageId(id As Integer) As String
            For Each field In GetType(KnownImageIds).GetFields()
                If Not field.IsStatic Then
                    Continue For
                End If

                Dim rawValue = field.GetValue(Nothing)
                Dim value As Integer? = If(TypeOf rawValue Is Integer, CInt(rawValue), Nothing)
                If value = id Then
                    Return $"{NameOf(KnownImageIds)}.{field.Name}"
                End If
            Next

            Return id.ToString()
        End Function
    End Class
End Namespace


text:
/**
 * @module ol/style/Image
 */
import {abstract} from '../util.js';
import {toSize} from '../size.js';

/**
 * @typedef {Object} Options
 * @property {number} opacity
 * @property {boolean} rotateWithView
 * @property {number} rotation
 * @property {number|import("../size.js").Size} scale
 * @property {Array<number>} displacement
 */

/**
 * @classdesc
 * A base class used for creating subclasses and not instantiated in
 * apps. Base class for {@link module:ol/style/Icon~Icon}, {@link module:ol/style/Circle~CircleStyle} and
 * {@link module:ol/style/RegularShape~RegularShape}.
 * @abstract
 * @api
 */
class ImageStyle {
  /**
   * @param {Options} options Options.
   */
  constructor(options) {
    /**
     * @private
     * @type {number}
     */
    this.opacity_ = options.opacity;

    /**
     * @private
     * @type {boolean}
     */
    this.rotateWithView_ = options.rotateWithView;

    /**
     * @private
     * @type {number}
     */
    this.rotation_ = options.rotation;

    /**
     * @private
     * @type {number|import("../size.js").Size}
     */
    this.scale_ = options.scale;

    /**
     * @private
     * @type {import("../size.js").Size}
     */
    this.scaleArray_ = toSize(options.scale);

    /**
     * @private
     * @type {Array<number>}
     */
    this.displacement_ = options.displacement;
  }

  /**
   * Clones the style.
   * @return {ImageStyle} The cloned style.
   * @api
   */
  clone() {
    const scale = this.getScale();
    return new ImageStyle({
      opacity: this.getOpacity(),
      scale: Array.isArray(scale) ? scale.slice() : scale,
      rotation: this.getRotation(),
      rotateWithView: this.getRotateWithView(),
      displacement: this.getDisplacement().slice(),
    });
  }

  /**
   * Get the symbolizer opacity.
   * @return {number} Opacity.
   * @api
   */
  getOpacity() {
    return this.opacity_;
  }

  /**
   * Determine whether the symbolizer rotates with the map.
   * @return {boolean} Rotate with map.
   * @api
   */
  getRotateWithView() {
    return this.rotateWithView_;
  }

  /**
   * Get the symoblizer rotation.
   * @return {number} Rotation.
   * @api
   */
  getRotation() {
    return this.rotation_;
  }

  /**
   * Get the symbolizer scale.
   * @return {number|import("../size.js").Size} Scale.
   * @api
   */
  getScale() {
    return this.scale_;
  }

  /**
   * Get the symbolizer scale array.
   * @return {import("../size.js").Size} Scale array.
   */
  getScaleArray() {
    return this.scaleArray_;
  }

  /**
   * Get the displacement of the shape
   * @return {Array<number>} Shape's center displacement
   * @api
   */
  getDisplacement() {
    return this.displacement_;
  }

  /**
   * Get the anchor point in pixels. The anchor determines the center point for the
   * symbolizer.
   * @abstract
   * @return {Array<number>} Anchor.
   */
  getAnchor() {
    return abstract();
  }

  /**
   * Get the image element for the symbolizer.
   * @abstract
   * @param {number} pixelRatio Pixel ratio.
   * @return {HTMLCanvasElement|HTMLVideoElement|HTMLImageElement} Image element.
   */
  getImage(pixelRatio) {
    return abstract();
  }

  /**
   * @abstract
   * @return {HTMLCanvasElement|HTMLVideoElement|HTMLImageElement} Image element.
   */
  getHitDetectionImage() {
    return abstract();
  }

  /*
   * Get the image pixel ratio.
   * @param {number} pixelRatio Pixel ratio.
   * */
  getPixelRatio(pixelRatio) {
    return 1;
  }

  /**
   * @abstract
   * @return {import("../ImageState.js").default} Image state.
   */
  getImageState() {
    return abstract();
  }

  /**
   * @abstract
   * @return {import("../size.js").Size} Image size.
   */
  getImageSize() {
    return abstract();
  }

  /**
   * @abstract
   * @return {import("../size.js").Size} Size of the hit-detection image.
   */
  getHitDetectionImageSize() {
    return abstract();
  }

  /**
   * Get the origin of the symbolizer.
   * @abstract
   * @return {Array<number>} Origin.
   */
  getOrigin() {
    return abstract();
  }

  /**
   * Get the size of the symbolizer (in pixels).
   * @abstract
   * @return {import("../size.js").Size} Size.
   */
  getSize() {
    return abstract();
  }

  /**
   * Set the opacity.
   *
   * @param {number} opacity Opacity.
   * @api
   */
  setOpacity(opacity) {
    this.opacity_ = opacity;
  }

  /**
   * Set whether to rotate the style with the view.
   *
   * @param {boolean} rotateWithView Rotate with map.
   * @api
   */
  setRotateWithView(rotateWithView) {
    this.rotateWithView_ = rotateWithView;
  }

  /**
   * Set the rotation.
   *
   * @param {number} rotation Rotation.
   * @api
   */
  setRotation(rotation) {
    this.rotation_ = rotation;
  }
  /**
   * Set the scale.
   *
   * @param {number|import("../size.js").Size} scale Scale.
   * @api
   */
  setScale(scale) {
    this.scale_ = scale;
    this.scaleArray_ = toSize(scale);
  }

  /**
   * @abstract
   * @param {function(import("../events/Event.js").default): void} listener Listener function.
   */
  listenImageChange(listener) {
    abstract();
  }

  /**
   * Load not yet loaded URI.
   * @abstract
   */
  load() {
    abstract();
  }

  /**
   * @abstract
   * @param {function(import("../events/Event.js").default): void} listener Listener function.
   */
  unlistenImageChange(listener) {
    abstract();
  }
}

export default ImageStyle;

redpajama_set_name: RedPajamaGithub


text:
package pages

import org.scalatest.selenium.WebBrowser.{click, currentUrl, pageSource}
import pages.vrm_assign.VehicleLookupPage.currentKeeperNo
import pages.vrm_assign.VehicleLookupPage.currentKeeperYes
import pages.vrm_assign.VehicleLookupPage.findVehicleDetails
import pages.vrm_assign.VehicleLookupPage.replacementVRNTag
import pages.vrm_assign.VehicleLookupPage.url
import pages.vrm_assign.VehicleLookupPage.documentReferenceNumber
import pages.vrm_assign.VehicleLookupPage.keeperPostcode
import pages.vrm_assign.VehicleLookupPage.vehicleRegistrationNumber
import uk.gov.dvla.vehicles.presentation.common.helpers.webbrowser.WebBrowserDriver
import uk.gov.dvla.vehicles.presentation.common.testhelpers.RandomVrmGenerator

final class VehicleLookupPageSteps(implicit webDriver: WebBrowserDriver)
  extends helpers.AcceptanceTestHelper {

  def `happy path for business`(regNo: String = "A2") = {
    `is displayed`.
      enter(replacementVRN = "ABC123", registrationNumber = regNo, docRefNumber = "11111111111", postcode = "SA11AA").
      `keeper is not acting`.
      `find vehicle`
    this
  }

  def `is displayed` = {
    eventually {
      currentUrl should equal(url)
    }
    this
  }

  def `keeper is not acting` = {
    click on currentKeeperNo
    this
  }

  def enter(replacementVRN: String, registrationNumber: String, docRefNumber: String, postcode: String) = {
    replacementVRNTag.value = replacementVRN
    vehicleRegistrationNumber.value = registrationNumber
    documentReferenceNumber.value = docRefNumber
    keeperPostcode.value = postcode
    this
  }

  def `find vehicle` = {
    click on findVehicleDetails
    this
  }

  def `happy path for keeper`(regNo: String = "A2") = {
    enter(replacementVRN = "ABC123", registrationNumber = regNo, docRefNumber = "11111111111", postcode = "SA11AA").
      `keeper is acting`.
      `find vehicle`
    this
  }

  def `keeper is acting` = {
    click on currentKeeperYes
    this
  }

  def `form is filled with the values I previously entered`(regNo: String = "A2") = {
    vehicleRegistrationNumber.value should equal(regNo)
    documentReferenceNumber.value should equal("11111111111")
    keeperPostcode.value should equal("SA11AA")
    this
  }

  def `form is not filled`() = {
    vehicleRegistrationNumber.value should equal("")
    documentReferenceNumber.value should equal("")
    keeperPostcode.value should equal("")
    this
  }

  def `has error messages` = {
    pageSource should include("Vehicle registration number - Vehicle registration number must be valid format")
    pageSource should include("Document reference number - Document reference number must be an 11-digit number")
    this
  }
}


text:
.table i {
  padding-top: 6px;
}

img.loading {
    width: 25px;
}

.welcome table {
    display: none;
    width: 100%;
}

input {
    margin-left: 5px;
    margin-top: 8px;
}

.panel-body {
    overflow: auto;
}

.cal-heatmap-panel {
  padding: 20px;
  background-color: #fff;
}
.search input {
  width: 400px;
}
.search-container .fa-search {
  float: left;
  margin-left: -25px;
  margin-top: 12px;
  font-size: 18px;
}
div.dataTables_length label {
    font-weight: normal;
    text-align: left;
    white-space: nowrap;
}

div.dataTables_length select {
    width: 75px;
    display: inline-block;
}

div.dataTables_filter {
    text-align: right;
}

div.dataTables_filter label {
    font-weight: normal;
    white-space: nowrap;
    text-align: left;
}

div.dataTables_filter input {
    margin-left: 0.5em;
    display: inline-block;
}

div.dataTables_info {
    padding-top: 8px;
    white-space: nowrap;
}

div.dataTables_paginate {
    margin: 0;
    white-space: nowrap;
    text-align: right;
}

div.dataTables_paginate ul.pagination {
    margin: 2px 0;
    white-space: nowrap;
}

div.dataTables_paginate li.first > a,
div.dataTables_paginate li.previous > a {
    position: relative;
    padding-left: 24px;
}

div.dataTables_paginate li.next > a,
div.dataTables_paginate li.last > a {
    position: relative;
    padding-right: 24px;
}

div.dataTables_paginate li.first a:before,
div.dataTables_paginate li.previous a:before {
    position: absolute;
    top: 6px;
    left: 10px;
    display: block;
    font-family: FontAwesome;
}

div.dataTables_paginate li.next a:after,
div.dataTables_paginate li.last a:after {
    position: absolute;
    top: 6px;
    right: 10px;
    display: block;
    font-family: FontAwesome;
}

div.dataTables_paginate li.first a:before {
    content: "\F100";
}

div.dataTables_paginate li.previous a:before {
    content: "\F104";
}

div.dataTables_paginate li.next a:after {
    content: "\F105";
}

div.dataTables_paginate li.last a:after {
    content: "\F101";
}

@media screen and (max-width: 767px) {
    div.dataTables_length,
    div.dataTables_filter,
    div.dataTables_info,
    div.dataTables_paginate {
        text-align: center;
    }
}

table.dataTable td,
table.dataTable th {
    -webkit-box-sizing: content-box;
    -moz-box-sizing: content-box;
    box-sizing: content-box;
}

table.dataTable thead th {
    position: relative;
    background-image: none !important;
}

table.dataTable {
    clear: both;
    margin-top: 6px !important;
    margin-bottom: 6px !important;
    max-width: none !important;
}

table.dataTable thead .sorting,
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting_asc_disabled,
table.dataTable thead .sorting_desc_disabled {
    cursor: pointer;
}

table.dataTable thead th.sorting:after,
table.dataTable thead th.sorting_asc:after,
table.dataTable thead th.sorting_desc:after {
    position: absolute;
    top: 12px;
    right: 8px;
    display: block;
    font-family: FontAwesome;
}

table.dataTable thead th.sorting:after {
    content: "\F0DC";
    color: #ddd;
    font-size: 0.8em;
    padding-top: 0.12em;
}
table.dataTable thead th.sorting_asc:after {
    content: "\F0DE";
}
table.dataTable thead th.sorting_desc:after {
    content: "\F0DD";
}

div.dataTables_scrollBody table.dataTable thead th.sorting:after,
div.dataTables_scrollBody table.dataTable thead th.sorting_asc:after,
div.dataTables_scrollBody table.dataTable thead th.sorting_desc:after {
    content: "";
}

/* In Bootstrap and Foundation the padding top is a little different from the DataTables stylesheet */
table.table thead th.sorting:after,
table.table thead th.sorting_asc:after,
table.table thead th.sorting_desc:after {
    top: 8px;
}

table.dataTable thead > tr > th {
    padding-left: 18px;
    padding-right: 18px;
}

table.dataTable th:active {
    outline: none;
}

/* Scrolling */
div.dataTables_scrollHead table {
    margin-bottom: 0 !important;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
}

div.dataTables_scrollHead table thead tr:last-child th:first-child,
div.dataTables_scrollHead table thead tr:last-child td:first-child {
    border-bottom-left-radius: 0 !important;
    border-bottom-right-radius: 0 !important;
}

div.dataTables_scrollBody table {
    border-top: none;
    margin-top: 0 !important;
    margin-bottom: 0 !important;
}

div.dataTables_scrollBody tbody tr:first-child th,
div.dataTables_scrollBody tbody tr:first-child td {
    border-top: none;
}

div.dataTables_scrollFoot table {
    margin-top: 0 !important;
    border-top: none;
}

/* Frustratingly the border-collapse:collapse used by Bootstrap makes the column
   width calculations when using scrolling impossible to align columns. We have
   to use separate
 */
table.table-bordered.dataTable {
    border-collapse: separate !important;
}
table.table-bordered thead th,
table.table-bordered thead td {
    border-left-width: 0;
    border-top-width: 0;
}
table.table-bordered tbody th,
table.table-bordered tbody td {
    border-left-width: 0;
    border-bottom-width: 0;
}
table.table-bordered th:last-child,
table.table-bordered td:last-child {
    border-right-width: 0;
}
div.dataTables_scrollHead table.table-bordered {
    border-bottom-width: 0;
}

/*
 * TableTools styles
 */
.table.dataTable tbody tr.active td,
.table.dataTable tbody tr.active th {
    background-color: #08C;
    color: white;
}

.table.dataTable tbody tr.active:hover td,
.table.dataTable tbody tr.active:hover th {
    background-color: #0075b0 !important;
}

.table.dataTable tbody tr.active th > a,
.table.dataTable tbody tr.active td > a {
    color: white;
}

.table-striped.dataTable tbody tr.active:nth-child(odd) td,
.table-striped.dataTable tbody tr.active:nth-child(odd) th {
    background-color: #017ebc;
}

table.DTTT_selectable tbody tr {
    cursor: pointer;
}

div.DTTT .btn:hover {
    text-decoration: none !important;
}

ul.DTTT_dropdown.dropdown-menu {
    z-index: 2003;
}

ul.DTTT_dropdown.dropdown-menu a {
    color: #333 !important; /* needed only when demo_page.css is included */
}

ul.DTTT_dropdown.dropdown-menu li {
    position: relative;
}

ul.DTTT_dropdown.dropdown-menu li:hover a {
    background-color: #0088cc;
    color: white !important;
}

div.DTTT_collection_background {
    z-index: 2002;
}

/* TableTools information display */
div.DTTT_print_info {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 400px;
    height: 150px;
    margin-left: -200px;
    margin-top: -75px;
    text-align: center;
    color: #333;
    padding: 10px 30px;
    opacity: 0.95;

    background-color: white;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 6px;

    -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
    box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
}

div.DTTT_print_info h6 {
    font-weight: normal;
    font-size: 28px;
    line-height: 28px;
    margin: 1em;
}

div.DTTT_print_info p {
    font-size: 14px;
    line-height: 20px;
}

div.dataTables_processing {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100%;
    height: 60px;
    margin-left: -50%;
    margin-top: -25px;
    padding-top: 20px;
    padding-bottom: 20px;
    text-align: center;
    font-size: 1.2em;
    background-color: white;
    background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255,255,255,0)), color-stop(25%, rgba(255,255,255,0.9)), color-stop(75%, rgba(255,255,255,0.9)), color-stop(100%, rgba(255,255,255,0)));
    background: -webkit-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);
    background: -moz-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);
    background: -ms-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);
    background: -o-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);
    background: linear-gradient(to right, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);
}

/*
 * FixedColumns styles
 */
div.DTFC_LeftHeadWrapper table,
div.DTFC_LeftFootWrapper table,
div.DTFC_RightHeadWrapper table,
div.DTFC_RightFootWrapper table,
table.DTFC_Cloned tr.even {
    background-color: white;
    margin-bottom: 0;
}

div.DTFC_RightHeadWrapper table ,
div.DTFC_LeftHeadWrapper table {
    border-bottom: none !important;
    margin-bottom: 0 !important;
    border-top-right-radius: 0 !important;
    border-bottom-left-radius: 0 !important;
    border-bottom-right-radius: 0 !important;
}

div.DTFC_RightHeadWrapper table thead tr:last-child th:first-child,
div.DTFC_RightHeadWrapper table thead tr:last-child td:first-child,
div.DTFC_LeftHeadWrapper table thead tr:last-child th:first-child,
div.DTFC_LeftHeadWrapper table thead tr:last-child td:first-child {
    border-bottom-left-radius: 0 !important;
    border-bottom-right-radius: 0 !important;
}

div.DTFC_RightBodyWrapper table,
div.DTFC_LeftBodyWrapper table {
    border-top: none;
    margin: 0 !important;
}

div.DTFC_RightBodyWrapper tbody tr:first-child th,
div.DTFC_RightBodyWrapper tbody tr:first-child td,
div.DTFC_LeftBodyWrapper tbody tr:first-child th,
div.DTFC_LeftBodyWrapper tbody tr:first-child td {
    border-top: none;
}

div.DTFC_RightFootWrapper table,
div.DTFC_LeftFootWrapper table {
    border-top: none;
    margin-top: 0 !important;
}

/*
 * FixedHeader styles
 */
div.FixedHeader_Cloned table {
    margin: 0 !important
}


text:
layout: post
title: How to Re-touch an image with the Clone Stamp.
---

Clone Stamp Tool in Photoshop.

Adobe Photoshop is software used as a pixel-base image editor. It composes raster images in multiple layers,
providing special effects services, such as backgrounds, masks and transparency. You may as well make some
adjustments with the brightness/contrast, color balance or the exposure of the image. These adjustments will
change the style and aspect of the original image. On this how to I will be teaching the basics of "Clone Stamp"
a Photoshop Tool. With the clone stamp tool you can make some adjustments to the image like fix or eliminate things
out of the picture. These adjustments will change the style and the aspect of the original image. This tutorial will
be focus on re-touching a self-image.

We will be using Adobe Photoshop and a image of a Model. Follow us step-by-step and in no time you will be a master!

Step I.

Open Photoshop and take one of your personal photos or go to google and type "unedited photography", we can find unlimited
close up photos or how we call it today selfies. ! Drag it or click Command + O and open the image on Photoshop.
(I have select one of my photographies, is an image for a fashion photo shoot).

![Image](https://farm9.staticflickr.com/8708/16697940658_2fa7d18ff1_c.jpg)

______________________________________________________________________________________________________________________________
Step II.

On this tutorial will be making some adjustments;

- Remove the eye bags
- Clean the skin bubbles on her face

Is important to keep in mind that, when working with close up pictures you should not distort much the original image,
unless that is the purpose. But is always fun to play a little bit with the adjustments, to provide a cinematic style
to the photo.

![Image](https://farm8.staticflickr.com/7623/16884568661_a7e256528a_c.jpg)

_____________________________________________________________________________________________________________________________
Step III.

Make a duplicate the photo, that way you will be able to see the changes apply to the edited photo. Make sure the
copy layer is selected. Double-clink on the layer and name it "Cloning Img".

Now let's start working on the forehead with the "Clone Stamp Tool", which is located on the Photoshop Toolbar.
This tool allows you to clone a part of the picture you select and copy it onto another area. Afterwards choose a
Brush (shape & size ) and change the opacity to a minimum of 15%. Once select the default settings, let's go ahead
and used the Clone stamp tool to cover the skin bubbles and remove the eye bags.I am going to select a "Soft Round" brush
style, because the borders are blurry and it will apply the copy area that I have selected in a smoother way.

![Image] (https://farm9.staticflickr.com/8685/16884375282_e98deb9e78_c.jpg)

_______________________________________________________________________________________________________________________________
Step IV.

Select the area you want to copy from and place the brush on the area you wish to duplicate. Alt-click(Windows) or Option-click(Mac), the cursor automatically will change to a target. Click the exact spot you want to start
copying from and release them on the spot you are trying to cover/fix. And "X" will be presented next to
the brush, indicating the are from which the tool is cloning from. In my case I will select a clean spot on
the forehead and apply it onto the areas that have skin bubbles.

Is important to pay attention to the direction and color of the light that is reflected on (in my case, the face).
To maintain the same lighting effect is necessary to graduated the opacity and flow of the brush when cloning a stamp
area. Also if necessary change the size of the brush, this will allow you flexibility on some particular areas.

Gently I will start to move the brush through the forehead like if I am applying foundation makeup. I will not
like to leave some parts uneven, and my goal is to have a clean and spotless skin.

![Image](https://farm9.staticflickr.com/8684/16678224577_21cb5f75d6_c.jpg)

__________________________________________________________________________________________________________________________
 Step V.

The same process will be apply to the eye bags. In this area is better to used less opacity since they are dark circles.
Starting from the left to the right, continue to can change the size and flow while cloning. Once apply a select area
onto another one, I recommended to clone the same duplicated area and again paste it into a new area. That way you will
maintain the direction of the color and light effect. The X target will be closer or further from the brush depending
on the proximity of both the area you want to copy and the area you want to duplicate. Depending of the light, for some
areas is better to have the X further from the brush.

![Image](https://farm9.staticflickr.com/8684/16678224577_21cb5f75d6_c.jpg)

_________________________________________________________________________________________________________________________
Step VI.

It is optional to continue to used the clone stamp tool until you feel that all spots are even and cover. Remember every
photo is different and is up to you to apply the whatever style interests you. Don't forget to click on the original photo
and preview the differences and what a little cloning can to do cover the imperfections.

![Image](https://farm9.staticflickr.com/8697/16885563725_84c99f39aa_c.jpg)

Thanks for your attention, hope the tutorial was  helpful. Start practicing some more and you'll become a PRO.
Until next time!!


text:
if [[ "$#" -ne 2 ]]
then
    echo "Usage: dconf-term COMMAND FILE"
    echo "A single dash ( - ) can be used to refer \
to stdin or stdout, where appropriate"
    echo "COMMAND is either \`import' or \`export'"
    echo "\`import' loads from a file, \`export' saves to a file"
fi

if [[ "$1" = "import" ]]
then
    echo "importing from $2..."
    if [[ "$2" = "-" ]]
    then
        $2="/dev/stdin"
    fi
    cat "$2" | dconf load /org/gnome/terminal/legacy/profiles:/
elif [[ "$1" = "export" ]]
then
    echo "exporting to $2..."
    if [[ "$2" = "-" ]]
    then
        $2="/dev/stdout"
    fi
    dconf dump /org/gnome/terminal/legacy/profiles:/ >"$2"
fi

# import from $2
# dconf reset -f /org/gnome/terminal/legacy/profiles:/
# cat "$2" | dconf load /org/gnome/terminal/legacy/profiles:/

# export
# dconf dump /org/gnome/terminal/legacy/profiles:/ >"$2"


text:
namespace Shader {
	class ShaderProgram {
	public:
		ShaderProgram(const std::string& vertexShaderFile, const std::string& fragmentShaderFile);
		~ShaderProgram();

		void bind();
		void unbind();

	protected:
		virtual void getUniformLocations() = 0;

		GLuint getId() const;

		void loadFloat(GLuint location, float value);

	private:
		GLuint m_programId;
	};
}


text:
function changerPrestation()
{
var divSortie ="fdr_adminbundle_feuillederoute_secteurs";
var idChampsCntrl ="fdr_adminbundle_feuillederoute_typePrestation";
var method = "GET";
var fichierParh = "../../php/test.php";
var paramUrl = "typeprestation_id";
var nomMethode = "secteursDePrestation";
var ajaxRequest=maVarAjax(divSortie,idChampsCntrl,method,fichierParh,paramUrl,nomMethode);
}
function changerClient()
{
var divSortie ="fdr_adminbundle_feuillederoute_clientRamassage";
var idChampsCntrl ="fdr_adminbundle_feuillederoute_secteurs";
var method = "GET";
var fichierParh = "../../php/test.php";
var paramUrl = "secteur_id";
var nomMethode = "clientsDeSecteur";
var ajaxRequest=maVarAjax(divSortie,idChampsCntrl,method,fichierParh,paramUrl,nomMethode);
//alert($('#fdr_adminbundle_feuillederoute_secteurs option:selected').attr('value'));
var secteurs= document.getElementById("fdr_adminbundle_feuillederoute_secteurs");
var total="";
for(i=0;i<secteurs.options.length;i++)
	{
		if (secteurs.options[i].selected)
		{
			total = secteurs.options[i].value+"|"+total;

		}
	}
   var ajaxRequest=maVarAjaxClient(divSortie,total,method,fichierParh,paramUrl,nomMethode);

}
function hideClient()
{
    $res= $('#fdr_adminbundle_feuillederoute_typePrestation option:selected').text();
    if($res.toLowerCase()==="ramassage")
    {
        $('#fdr_adminbundle_feuillederoute_clientRamassage').show();
    }
    else
    {
        $('#fdr_adminbundle_feuillederoute_clientRamassage').hide();
    }

}

//function checkForm()
//{
//    $manGlobal=("#nombreManutention");
//    $man1=("#nombreManutentionChauf1");
//    $man2=("#nombreManutentionChauf2");
//    if($man1+$man2>$manGlobal)
//    {
//        return false;
//        alert("false");
//        //("#diffMan").innerHtml("blabla");
//        ("#diffMan").hide();
//    }
//}
function checkMan()
{
    $manGlobal=("#nombreManutention");
    $man1=("#nombreManutentionChauf1");
    $man2=("#nombreManutentionChauf2");
    if($man1+$man2>$manGlobal)
    {
        ("#diffMan").hide();
    }
}

///
function maVarAjax(divSortie,idChampsCntrl,method,fichierParh,paramUrl,nomMethode){
   var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
var ajaxDisplay = document.getElementById(divSortie);
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var idchamps = document.getElementById(idChampsCntrl);
ajaxRequest.open(method, fichierParh+"?"+paramUrl+"="+idchamps.value+"&nomMethode="+nomMethode, true);

ajaxRequest.send();
return ajaxRequest;
}
function maVarAjaxClient(divSortie,total,method,fichierParh,paramUrl,nomMethode){
   var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
var ajaxDisplay = document.getElementById(divSortie);
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
//var idchamps = document.getElementById(idChampsCntrl);
ajaxRequest.open(method, fichierParh+"?"+paramUrl+"="+total+"&nomMethode="+nomMethode, true);

ajaxRequest.send();
return ajaxRequest;
}


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

package org.apache.tapestry5.integration.app1;

import org.testng.annotations.Test;

/**
 * Tests for various kinds of failure conditions. Generally, what's being tested is that the exception
 * is being reported correctly.
 */
public class FailureTests extends App1TestCase
{
    /**
     * With lt;span t:id="foo"/> in the template, there should be an @Component
     * in the Java class. When there's not, it's an error.
     */
    @Test
    public void component_id_in_template_with_no_type()
    {
        openLinks("No Component Type Provided");

        assertTextPresent("org.apache.tapestry5.integration.app1.pages.NoTypeProvidedDemo",
                "You must specify the type via t:type, the element, or @Component annotation.");
    }

}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

/**
 * Conversion handler for the accumulative grading strategy data
 */
class moodle1_workshopform_accumulative_handler extends moodle1_workshopform_handler {

    /** @var used by {@link self::migrate_legacy_scales()} */
    private $newscaleids = array();

    /**
     * Converts <ELEMENT> into <workshopform_accumulative_dimension>
     */
    public function process_legacy_element(array $data, array $raw) {
        // prepare a fake record and re-use the upgrade logic
        $fakerecord = (object)$data;
        $newscaleid = $this->get_new_scaleid($data['scale']);
        $converted = (array)workshopform_accumulative_upgrade_element($fakerecord, $newscaleid, 12345678);
        unset($converted['workshopid']);

        $converted['id'] = $data['id'];
        $this->write_xml('workshopform_accumulative_dimension', $converted, array('/workshopform_accumulative_dimension/id'));

        return $converted;
    }

    /**
     * If needed, creates new standard (global) scale to replace the legacy workshop one and returns the mapping
     *
     * If the given $oldscaleid represents a scale, returns array $oldscaleid => $newscaleid that
     * can be used as a parameter for {@link workshopform_accumulative_upgrade_element()}. Otherwise
     * this method returns empty array.
     *
     * In workshop 1.x, scale field in workshop_elements had the following meaning:
     *   0 | 2 point Yes/No scale
     *   1 | 2 point Present/Absent scale
     *   2 | 2 point Correct/Incorrect scale
     *   3 | 3 point Good/Poor scale
     *   4 | 4 point Excellent/Very Poor scale
     *   5 | 5 point Excellent/Very Poor scale
     *   6 | 7 point Excellent/Very Poor scale
     *   7 | Score out of 10
     *   8 | Score out of 20
     *   9 | Score out of 100
     *
     * @see workshopform_accumulative_upgrade_scales()
     * @param int $oldscaleid the value of the 'scale' field in the moodle.xml backup file
     * @return array (int)oldscaleid => (int)newscaleid
     */
    protected function get_new_scaleid($oldscaleid) {

        if ($oldscaleid >= 0 and $oldscaleid <= 6) {
            // we need a new scale id
            if (!isset($this->newscaleids[$oldscaleid])) {
                // this is the first time the legacy scale is used in moodle.xml
                // let us migrate it
                $scale = $this->get_new_scale_definition($oldscaleid);
                // other scales are already stashed - let us append a new artificial record
                $currentscaleids = $this->converter->get_stash_itemids('scales');
                if (empty($currentscaleids)) {
                    $scale['id'] = 1;
                } else {
                    $scale['id'] = max($currentscaleids) + 1;
                }
                $this->converter->set_stash('scales', $scale, $scale['id']);
                $this->newscaleids[$oldscaleid] = $scale['id'];
                // inform the workshop instance that it should annotate the new scale
                $inforefman = $this->parenthandler->get_inforef_manager();
                $inforefman->add_ref('scale', $scale['id']);
            }
            return array($oldscaleid => $this->newscaleids[$oldscaleid]);

        } else {
            // not a scale
            return array();
        }
    }

    /**
     * Returns a definition of a legacy workshop scale
     *
     * @see workshopform_accumulative_upgrade_scales
     * @param object $oldscaleid
     * @return array
     */
    private function get_new_scale_definition($oldscaleid) {

        $data = array(
            'userid'            => 0,   // restore will remap to the current user
            'courseid'          => 0,   // global scale
            'description'       => '',
            'descriptionformat' => FORMAT_HTML,
        );

        switch ($oldscaleid) {
        case 0:
            $data['name']  = get_string('scalename0', 'workshopform_accumulative');
            $data['scale'] = implode(',', array(get_string('no'), get_string('yes')));
            break;
        case 1:
            $data['name']  = get_string('scalename1', 'workshopform_accumulative');
            $data['scale'] = implode(',', array(get_string('absent', 'workshopform_accumulative'),
                                                get_string('present', 'workshopform_accumulative')));
            break;
        case 2:
            $data['name']  = get_string('scalename2', 'workshopform_accumulative');
            $data['scale'] = implode(',', array(get_string('incorrect', 'workshopform_accumulative'),
                                                get_string('correct', 'workshopform_accumulative')));
            break;
        case 3:
            $data['name']  = get_string('scalename3', 'workshopform_accumulative');
            $data['scale'] = implode(',', array('* ' . get_string('poor', 'workshopform_accumulative'),
                                                '**',
                                                '*** ' . get_string('good', 'workshopform_accumulative')));
            break;
        case 4:
            $data['name']  = get_string('scalename4', 'workshopform_accumulative');
            $data['scale'] = implode(',', array('* ' . get_string('verypoor', 'workshopform_accumulative'),
                                                '**',
                                                '***',
                                                '**** ' . get_string('excellent', 'workshopform_accumulative')));
            break;
        case 5:
            $data['name']  = get_string('scalename5', 'workshopform_accumulative');
            $data['scale'] = implode(',', array('* ' . get_string('verypoor', 'workshopform_accumulative'),
                                                '**',
                                                '***',
                                                '****',
                                                '***** ' . get_string('excellent', 'workshopform_accumulative')));
            break;
        case 6:
            $data['name']  = get_string('scalename6', 'workshopform_accumulative');
            $data['scale'] = implode(',', array('* ' . get_string('verypoor', 'workshopform_accumulative'),
                                                '**',
                                                '***',
                                                '****',
                                                '*****',
                                                '******',
                                                '******* ' . get_string('excellent', 'workshopform_accumulative')));
            break;
        }

        return $data;
    }
}

/**
 * Transforms a given record from workshop_elements_old into an object to be saved into workshopform_accumulative
 *
 * @param stdClass $old legacy record from workshop_elements_old
 * @param array $newscaleids mapping from old scale types into new standard ones
 * @param int $newworkshopid id of the new workshop instance that replaced the previous one
 * @return stdclass to be saved in workshopform_accumulative
 */
function workshopform_accumulative_upgrade_element(stdclass $old, array $newscaleids, $newworkshopid) {
    $new = new stdclass();
    $new->workshopid = $newworkshopid;
    $new->sort = $old->elementno;
    $new->description = $old->description;
    $new->descriptionformat = FORMAT_HTML;
    // calculate new grade/scale of the element
    if ($old->scale >= 0 and $old->scale <= 6 and isset($newscaleids[$old->scale])) {
        $new->grade = -$newscaleids[$old->scale];
    } elseif ($old->scale == 7) {
        $new->grade = 10;
    } elseif ($old->scale == 8) {
        $new->grade = 20;
    } elseif ($old->scale == 9) {
        $new->grade = 100;
    } else {
        $new->grade = 0;    // something is wrong
    }
    // calculate new weight of the element. Negative weights are not supported any more and
    // are replaced with weight = 0. Legacy workshop did not store the raw weight but the index
    // in the array of weights (see $WORKSHOP_EWEIGHTS in workshop 1.x)
    // workshop 2.0 uses integer weights only (0-16) so all previous weights are multiplied by 4.
    switch ($old->weight) {
        case 8: $new->weight = 1; break;
        case 9: $new->weight = 2; break;
        case 10: $new->weight = 3; break;
        case 11: $new->weight = 4; break;
        case 12: $new->weight = 6; break;
        case 13: $new->weight = 8; break;
        case 14: $new->weight = 16; break;
        default: $new->weight = 0;
    }
    return $new;
}


text:
SingleDatabaseQueryTest::SingleDatabaseQueryTest(QObject *parent) : Controller(parent)
{

}

void SingleDatabaseQueryTest::dbp(Context *c)
{
    const int id = (qrand() % 10000) + 1;

    ASync async(c);
    static thread_local auto db = APool::database();
    db.execPrepared(APreparedQueryLiteral("SELECT id, randomNumber FROM world WHERE id=$1"),
                           {id}, [c, async] (AResult &result) {
        if (Q_LIKELY(!result.error() && result.size())) {
            auto it = result.begin();
            c->response()->setJsonObjectBody({
                                                 {QStringLiteral("id"), it[0].toInt()},
                                                 {QStringLiteral("randomNumber"), it[1].toInt()}
                                             });
            return;
        }

        c->res()->setStatus(Response::InternalServerError);
    }, c);
}

void SingleDatabaseQueryTest::db_postgres(Context *c)
{
    QSqlQuery query = CPreparedSqlQueryThreadForDB(
                QLatin1String("SELECT id, randomNumber FROM world WHERE id = :id"),
                QStringLiteral("postgres"));
    processQuery(c, query);
}

void SingleDatabaseQueryTest::db_mysql(Context *c)
{
    QSqlQuery query = CPreparedSqlQueryThreadForDB(
                QLatin1String("SELECT id, randomNumber FROM world WHERE id = :id"),
                QStringLiteral("mysql"));
    processQuery(c, query);
}

void SingleDatabaseQueryTest::processQuery(Context *c, QSqlQuery &query)
{
    int id = (qrand() % 10000) + 1;

    query.bindValue(QStringLiteral(":id"), id);
    if (Q_UNLIKELY(!query.exec() || !query.next())) {
        c->res()->setStatus(Response::InternalServerError);
        return;
    }

    c->response()->setJsonObjectBody({
                                         {QStringLiteral("id"), query.value(0).toInt()},
                                         {QStringLiteral("randomNumber"), query.value(1).toInt()}
                                     });
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="Shindig"
         version="2.5">
  <display-name>Shindig</display-name>
  <!-- configuration -->
  <!-- If you have your own Guice module(s), put them here as a colon-separated list. -->
  <context-param>
    <param-name>guice-modules</param-name>
    <param-value>
      org.apache.shindig.common.PropertiesModule:
      org.apache.shindig.gadgets.DefaultGuiceModule:
      org.apache.shindig.social.sample.SampleModule:
      org.apache.shindig.gadgets.oauth.OAuthModule:
      org.apache.shindig.common.cache.ehcache.EhCacheModule
    </param-value>
  </context-param>

    <filter>
        <filter-name>JSecurityFilter</filter-name>
        <filter-class>org.jsecurity.web.servlet.JSecurityFilter</filter-class>
        <init-param>
            <param-name>config</param-name>
            <param-value>

                # The JSecurityFilter configuration is very powerful and flexible, while still remaining succinct.
                # Please read the comprehensive example, with full comments and explanations, in the JavaDoc:
                #
                # http://www.jsecurity.org/api/org/jsecurity/web/servlet/JSecurityFilter.html
                [main]
                shindigSampleRealm = org.apache.shindig.social.sample.oauth.SampleRealm
                securityManager.realm = $shindigSampleRealm

                [filters]
                jsecurity.loginUrl = /login.jsp

                [urls]
                # The /login.jsp is not restricted to authenticated users (otherwise no one could log in!), but
                # the 'authc' filter must still be specified for it so it can process that url's
                # login submissions. It is 'smart' enough to allow those requests through as specified by the
                # jsecurity.loginUrl above.
                /login.jsp = authc

                /oauth/authorize/** = authc
                /remoting/** = authc, roles[b2bClient], perms[remote:invoke:"lan,wan"]

            </param-value>
        </init-param>
    </filter>

  <filter>
    <filter-name>authFilter</filter-name>
    <filter-class>org.apache.shindig.auth.AuthenticationServletFilter</filter-class>
  </filter>

  <filter-mapping>
      <filter-name>JSecurityFilter</filter-name>
      <url-pattern>/oauth/authorize</url-pattern>
  </filter-mapping>

  <filter-mapping>
      <filter-name>JSecurityFilter</filter-name>
      <url-pattern>*.jsp</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>authFilter</filter-name>
    <url-pattern>/social/*</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>authFilter</filter-name>
    <url-pattern>/gadgets/ifr</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>authFilter</filter-name>
    <url-pattern>/gadgets/makeRequest</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>authFilter</filter-name>
    <url-pattern>/gadgets/api/rpc/*</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>authFilter</filter-name>
    <url-pattern>/gadgets/api/rest/*</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>org.apache.shindig.common.servlet.GuiceServletContextListener</listener-class>
  </listener>

  <!-- Render a Gadget -->
  <servlet>
    <servlet-name>xml-to-html</servlet-name>
    <servlet-class>
      org.apache.shindig.gadgets.servlet.GadgetRenderingServlet
    </servlet-class>
  </servlet>

  <!-- Proxy -->
  <servlet>
    <servlet-name>proxy</servlet-name>
    <servlet-class>
      org.apache.shindig.gadgets.servlet.ProxyServlet
    </servlet-class>
  </servlet>

  <!-- makeRequest -->
  <servlet>
    <servlet-name>makeRequest</servlet-name>
    <servlet-class>
      org.apache.shindig.gadgets.servlet.MakeRequestServlet
    </servlet-class>
  </servlet>

  <!-- Concat -->
  <servlet>
    <servlet-name>concat</servlet-name>
    <servlet-class>
      org.apache.shindig.gadgets.servlet.ConcatProxyServlet
    </servlet-class>
  </servlet>

  <!-- OAuth callback -->
  <servlet>
    <servlet-name>oauthCallback</servlet-name>
    <servlet-class>
      org.apache.shindig.gadgets.servlet.OAuthCallbackServlet
    </servlet-class>
  </servlet>

  <!-- Metadata RPC -->
  <servlet>
    <servlet-name>metadata</servlet-name>
    <servlet-class>
      org.apache.shindig.gadgets.servlet.RpcServlet
    </servlet-class>
  </servlet>

  <!-- javascript serving -->
  <servlet>
    <servlet-name>js</servlet-name>
    <servlet-class>org.apache.shindig.gadgets.servlet.JsServlet</servlet-class>
  </servlet>

  <!-- Serve social REST api -->
  <servlet>
    <servlet-name>socialRestapiServlet</servlet-name>
    <servlet-class>
      org.apache.shindig.protocol.DataServiceServlet
    </servlet-class>
    <init-param>
      <param-name>handlers</param-name>
      <param-value>org.apache.shindig.social.handlers</param-value>
    </init-param>
  </servlet>

  <!-- Serve social RPC api -->
  <servlet>
    <servlet-name>socialJsonRpcServlet</servlet-name>
    <servlet-class>
      org.apache.shindig.protocol.JsonRpcServlet
    </servlet-class>
    <init-param>
      <param-name>handlers</param-name>
      <param-value>org.apache.shindig.social.handlers</param-value>
    </init-param>
  </servlet>

  <!-- Serve gadgets RPC api -->
  <servlet>
    <servlet-name>gadgetsJsonRpcServlet</servlet-name>
    <servlet-class>
      org.apache.shindig.protocol.JsonRpcServlet
    </servlet-class>
    <init-param>
      <param-name>handlers</param-name>
      <param-value>org.apache.shindig.gadgets.handlers</param-value>
    </init-param>
  </servlet>

  <servlet>
    <servlet-name>gadgetsRestapiServlet</servlet-name>
    <servlet-class>
      org.apache.shindig.protocol.DataServiceServlet
    </servlet-class>
    <init-param>
      <param-name>handlers</param-name>
      <param-value>org.apache.shindig.gadgets.handlers</param-value>
    </init-param>
  </servlet>

  <!-- Serve sample OAuth apis -->
  <servlet>
    <servlet-name>sampleOAuth</servlet-name>
    <servlet-class>
      org.apache.shindig.social.sample.oauth.SampleOAuthServlet
    </servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>js</servlet-name>
    <url-pattern>/gadgets/js/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>proxy</servlet-name>
    <url-pattern>/gadgets/proxy/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>makeRequest</servlet-name>
    <url-pattern>/gadgets/makeRequest</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>gadgetsJsonRpcServlet</servlet-name>
    <url-pattern>/gadgets/api/rpc/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>gadgetsRestapiServlet</servlet-name>
    <url-pattern>/gadgets/api/rest/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>concat</servlet-name>
    <url-pattern>/gadgets/concat</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>oauthCallback</servlet-name>
    <url-pattern>/gadgets/oauthcallback</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>xml-to-html</servlet-name>
    <url-pattern>/gadgets/ifr</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>metadata</servlet-name>
    <url-pattern>/gadgets/metadata</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>socialRestapiServlet</servlet-name>
    <url-pattern>/social/rest/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>socialJsonRpcServlet</servlet-name>
    <url-pattern>/social/rpc/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>sampleOAuth</servlet-name>
    <url-pattern>/oauth/*</url-pattern>
  </servlet-mapping>
</web-app>


text:
/*
 * This file is part of Evo2DSim.
 *
 * Evo2DSim is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Evo2DSim is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Evo2DSim.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.vastness.evo2dsim.core.utils

import org.vastness.evo2dsim.core.evolution.Evolution.Generation
import spray.json._
import org.vastness.evo2dsim.core.utils.MyJsonProtocol._
import scalax.file._
import OutputHandler._
import org.vastness.evo2dsim.core.evolution.EvolutionConfig
import de.schlichtherle.truezip.file.{TFileWriter, TFile}

/**
 * Allows for either compressed or uncompressed output of generations
 * @param dir base dir
 * @param compress flag
 */
class OutputHandler(dir: Path, val compress: Boolean) extends Writer {
  /**
   * Given a generation write it
   * @param id generation number
   * @param gen generation
   */
  def writeGeneration(id: Int, gen: Generation) = {
    write(dir, gDirName, gFileTemplate(id), gen2JSONString(gen))
  }

  def writeEvolutionConfig(config: EvolutionConfig) = {
    val s = config.toJson.prettyPrint
    val file = dir / configFileName
    file.write(s)
  }

  private def gen2JSONString(gen: Generation) = gen.toJson.prettyPrint
}

object OutputHandler {
  val gDirName = "generations"
  def gFileTemplate(id: Int) = s"Gen_$id.json"
  val configFileName = "Config.json"
}


text:
export class Penalty {
  constructor(readonly max: number, readonly current = 0, readonly difference = 0) {}

  accrue(amount: number) {
    let newAmount = Math.min(this.current + amount, this.max);
    return new Penalty(this.max, newAmount, newAmount - this.current);
  }
}