using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.CSharp.Resolver;
using OmniSharp.Configuration;
using OmniSharp.FindUsages;
using OmniSharp.Parser;
using OmniSharp.Refactoring;
using OmniSharp.Solution;

namespace OmniSharp.Rename
{
    public class RenameHandler
    {
        private readonly ISolution _solution;
        private readonly BufferParser _bufferParser;
        private readonly FindUsagesHandler _findUsagesHandler;
		private readonly OmniSharpConfiguration _config;

        public RenameHandler(ISolution solution, BufferParser bufferParser, OmniSharpConfiguration config, FindUsagesHandler findUsagesHandler)
        {
            _solution = solution;
            _bufferParser = bufferParser;
            _findUsagesHandler = findUsagesHandler;
            _config = config;
        }

        public RenameResponse Rename(RenameRequest req)
        {
            var project = _solution.ProjectContainingFile(req.FileName);
            var syntaxTree = project.CreateParser().Parse(req.Buffer, req.FileName);
            var sourceNode = syntaxTree.GetNodeAt(req.Line, req.Column);
            if(sourceNode == null)
                return new RenameResponse();

            IEnumerable<AstNode> nodes = _findUsagesHandler.FindUsageNodes(req).ToArray();

            var response = new RenameResponse();

            var modfiedFiles = new List<ModifiedFileResponse>();
            response.Changes = modfiedFiles;

            foreach (IGrouping<string, AstNode> groupedNodes in nodes.GroupBy(n => n.GetRegion().FileName))
            {
                string fileName = groupedNodes.Key;
                OmniSharpRefactoringContext context;
                if (groupedNodes.Key != req.FileName)
                {
                    var file = _solution.GetFile(fileName);
                    var bufferParser = new BufferParser(_solution);
                    var content = bufferParser.ParsedContent(file.Document.Text, file.FileName);
                    var resolver = new CSharpAstResolver(content.Compilation, content.SyntaxTree, content.UnresolvedFile);
                    context = new OmniSharpRefactoringContext(file.Document, resolver);
                }
                else
                {
                    context = OmniSharpRefactoringContext.GetContext(_bufferParser, req);
                }
                string modifiedBuffer = null;

                var lastToFirstNodes = groupedNodes.OrderByDescending(n => n.EndLocation.Line)
                                                   .ThenByDescending(n => n.EndLocation.Column);

                foreach (var node in lastToFirstNodes)
                {
                    using (var script = new OmniSharpScript(context, _config))
                    {
                        script.Rename(node, req.RenameTo);
                        modifiedBuffer = script.CurrentDocument.Text;
                    }
                }

                if (modifiedBuffer != null)
                {
                    var modifiedFile = new ModifiedFileResponse
                    {
                        FileName
                        = fileName,
                        Buffer = modifiedBuffer
                    };
                    modfiedFiles.Add(modifiedFile);
                    response.Changes = modfiedFiles;

                    _bufferParser.ParsedContent(modifiedBuffer, fileName);
                    _solution.ProjectContainingFile(fileName).UpdateFile (fileName, modifiedBuffer);
                }
            }

            return response;
        }
    }
}


@model ShortcodeTemplateViewModel
@inject IDisplayManager<ShortcodeDescriptor> ShortcodeDescriptorDisplayManager
@inject IShortcodeDescriptorManager ShortcodeDescriptorManager
@{
    var shortcodeDescriptors = await ShortcodeDescriptorManager.GetShortcodeDescriptors();
    var categories = shortcodeDescriptors
        .SelectMany(s => s.Categories)
        .GroupBy(c => c, StringComparer.OrdinalIgnoreCase)
        .Select(g => g.Key);

    var jCategories = JsonConvert.SerializeObject(categories);
    var jSelectedCategories = JsonConvert.SerializeObject(Model.Categories);
}

@RenderTitleSegments(T["Create Shortcode"])

<form asp-action="Create" method="post">

                @T["Name"]
                <input asp-for="Name" class="form-control" autofocus />

                @T["The name of the shortcode."]

                @T["Hint"]
                <input asp-for="Hint" class="form-control" />
                @T["The hint for the shortcode."]

                @T["Usage"]
                <textarea asp-for="Usage" rows="10" class="form-control"></textarea>
                @T["Example usage of the shortcode."]

            @* Do not move app from here, it is specific to categories, and causes conflicts with codemirror due to dom rewrites. *@

                @T["Categories"]
                <input class="form-control" asp-for="SelectedCategories" type="hidden" v-bind:value="getSelectedCategories()"/>
                    <vue-multiselect v-model="value"
                                     placeholder="@T["Type to search"]"
                                     select-label="@T["Select"]"
                                     deselect-label="@T["Remove"]"
                                     :options="options"
                                     :multiple="true"
                                     :show-labels="false"
                                     :close-on-select="false"
                                     :clear-on-select="false"
                                     :taggable="true"
                                     tag-position="bottom"
                                     tag-placeholder="@T["Press enter to add a category"]"
                                     @@tag="addCategory">
                        <template slot="noResult">
                            @T["No categories found"]
                        </template>
                        <template slot="noOptions">
                            @T["No categories found"]
                        </template>
                    </vue-multiselect>
                @T["The categories for this shortcode."]

                @T["Default Shortcode Value"]
                <input asp-for="DefaultValue" class="form-control" />
                @T["The default value of the short code when selected. Defaults to [name]."]

            @{
                var descriptor = new ShortcodeDescriptor();
                dynamic shape = await ShortcodeDescriptorDisplayManager.BuildDisplayAsync(descriptor, null, "SummaryAdmin");
                shape.Actions = null;
                @await DisplayAsync(shape)
            }

                @T["Content"]
                <textarea asp-for="Content" rows="10" class="form-control"></textarea>
                @T["The Shortcode Liquid template."]

            <button type="submit" name="submit" class="btn btn-success">@T["Save"]</button>
            <button type="button" class="btn btn-success dropdown-toggle dropdown-toggle-split" data-reference="parent" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                @T["Toggle Dropdown"]
            </button>

                <button class="dropdown-item" name="submit" type="submit" value="SaveAndContinue">@T["and continue"]</button>

        @T["Cancel"]

</form>


class C { foo: string; }

module M {
    var C = 1;
    class D extends C { // error, C must evaluate to constructor function
        bar: string;
    }
}


/*
 * 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.
 */
package org.apache.ofbiz.base.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.Properties;

import org.junit.Test;

public class UtilPropertiesTests {

    private static final String COUNTRY = "AU";
    private static final String LANGUAGE = "en";
    private final Locale locale = new Locale(LANGUAGE, COUNTRY);

    /**
     * Old style xml:lang attribute value was of form en_AU. Test this
     * format still works.
     * @throws Exception
     */
    @Test
    public void testReadXmlLangOldStyle() throws Exception {
        Properties result = xmlToProperties("_");
        assertNotNull(result);
        assertTrue(!result.isEmpty());
        assertEquals(1, result.size());
        assertEquals("Key Value", result.getProperty("PropertyKey"));
    }

    /**
     * New (and correct) style xml:lang value is en-AU.
     * Test it works.
      * @throws Exception
     */
    @Test
    public void testReadXmlLangNewStyle() throws Exception {
        Properties result = xmlToProperties("-");
        assertNotNull(result);
        assertTrue(!result.isEmpty());
        assertEquals(1, result.size());
        assertEquals("Key Value", result.getProperty("PropertyKey"));
    }

    private Properties xmlToProperties(String separator) throws IOException {
        String xmlData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "<resource xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
                + "          xsi:noNamespaceSchemaLocation=\"http://ofbiz.apache.org/dtds/ofbiz-properties.xsd\">\n"
                + "    <property key=\"PropertyKey\">\n"
                + "        <value xml:lang=\"" + LANGUAGE + separator + COUNTRY + "\">Key Value</value>\n"
                + "    </property>\n"
                + "</resource>";
        try (InputStream in = new ByteArrayInputStream(
                new String(xmlData.getBytes(), Charset.forName("UTF-8")).getBytes())) {
            return UtilProperties.xmlToProperties(in, locale, null);
        }
    }
}


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

using System;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp
{
    public partial class CSharpSyntaxTree
    {
        internal sealed class DummySyntaxTree : CSharpSyntaxTree
        {
            private readonly CompilationUnitSyntax _node;

            public DummySyntaxTree()
            {
                _node = this.CloneNodeAsRoot(SyntaxFactory.ParseCompilationUnit(string.Empty));
            }

            public override string ToString()
            {
                return string.Empty;
            }

            public override SourceText GetText(CancellationToken cancellationToken)
            {
                return SourceText.From(string.Empty, Encoding.UTF8);
            }

            public override bool TryGetText(out SourceText text)
            {
                text = SourceText.From(string.Empty, Encoding.UTF8);
                return true;
            }

            public override int Length
            {
                get { return 0; }
            }

            public override CSharpParseOptions Options
            {
                get { return CSharpParseOptions.Default; }
            }

            public override string FilePath
            {
                get { return string.Empty; }
            }

            public override SyntaxReference GetReference(SyntaxNode node)
            {
                return new SimpleSyntaxReference(node);
            }

            public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken)
            {
                return _node;
            }

            public override bool TryGetRoot(out CSharpSyntaxNode root)
            {
                root = _node;
                return true;
            }

            public override bool HasCompilationUnitRoot
            {
                get { return true; }
            }

            public override FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default(CancellationToken))
            {
                return default(FileLinePositionSpan);
            }

            public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options)
            {
                return SyntaxFactory.SyntaxTree(root, options: options, path: FilePath, encoding: null);
            }

            public override SyntaxTree WithFilePath(string path)
            {
                return SyntaxFactory.SyntaxTree(_node, options: this.Options, path: path, encoding: null);
            }
        }
    }
}


// Time Complexity: O(n^2)
// Space Complexity: O(1)

class Solution {
    public:
        vector<vector<int> > threeSum(vector<int> &num) {
            vector<vector<int> > ans;
            const int target = 0;

            sort(num.begin(), num.end());
            auto last = num.rend();
            for(auto a = num.rbegin(); a < prev(last, 2); ++a) {
                if(a > num.rbegin() && *a == *(a - 1))
                    continue;
                auto b = next(a);
                auto c = prev(last);

                while(b < c) {
                    if(b > next(a) && *b == *(b - 1)) {
                        ++b;
                    }
                    else if(c < prev(last) && *c == *(c + 1)) {
                        --c;
                    }
                    else {
                        const int sum = *a + *b + *c;

                        if(sum < target)
                            --c;
                        else if(sum > target)
                            ++b;
                        else {
                            ans.push_back({ *c, *b, *a});
                            ++b;
                            --c;
                        }
                    }
                }
            }

            return ans;
        }
};


export * from './community-card.component';


package match

import (
	"fmt"
	"unicode/utf8"
)

type BTree struct {
	Value            Matcher
	Left             Matcher
	Right            Matcher
	ValueLengthRunes int
	LeftLengthRunes  int
	RightLengthRunes int
	LengthRunes      int
}

func NewBTree(Value, Left, Right Matcher) (tree BTree) {
	tree.Value = Value
	tree.Left = Left
	tree.Right = Right

	lenOk := true
	if tree.ValueLengthRunes = Value.Len(); tree.ValueLengthRunes == -1 {
		lenOk = false
	}

	if Left != nil {
		if tree.LeftLengthRunes = Left.Len(); tree.LeftLengthRunes == -1 {
			lenOk = false
		}
	}

	if Right != nil {
		if tree.RightLengthRunes = Right.Len(); tree.RightLengthRunes == -1 {
			lenOk = false
		}
	}

	if lenOk {
		tree.LengthRunes = tree.LeftLengthRunes + tree.ValueLengthRunes + tree.RightLengthRunes
	} else {
		tree.LengthRunes = -1
	}

	return tree
}

func (self BTree) Len() int {
	return self.LengthRunes
}

// todo?
func (self BTree) Index(s string) (int, []int) {
	return -1, nil
}

func (self BTree) Match(s string) bool {
	inputLen := len(s)

	// self.Length, self.RLen and self.LLen are values meaning the length of runes for each part
	// here we manipulating byte length for better optimizations
	// but these checks still works, cause minLen of 1-rune string is 1 byte.
	if self.LengthRunes != -1 && self.LengthRunes > inputLen {
		return false
	}

	// try to cut unnecessary parts
	// by knowledge of length of right and left part
	var offset, limit int
	if self.LeftLengthRunes >= 0 {
		offset = self.LeftLengthRunes
	}
	if self.RightLengthRunes >= 0 {
		limit = inputLen - self.RightLengthRunes
	} else {
		limit = inputLen
	}

	for offset < limit {
		// search for matching part in substring
		index, segments := self.Value.Index(s[offset:limit])
		if index == -1 {
			releaseSegments(segments)
			return false
		}

		l := s[:offset+index]
		var left bool
		if self.Left != nil {
			left = self.Left.Match(l)
		} else {
			left = l == ""
		}

		if left {
			for i := len(segments) - 1; i >= 0; i-- {
				length := segments[i]

				var right bool
				var r string
				// if there is no string for the right branch
				if inputLen <= offset+index+length {
					r = ""
				} else {
					r = s[offset+index+length:]
				}

				if self.Right != nil {
					right = self.Right.Match(r)
				} else {
					right = r == ""
				}

				if right {
					releaseSegments(segments)
					return true
				}
			}
		}

		_, step := utf8.DecodeRuneInString(s[offset+index:])
		offset += index + step

		releaseSegments(segments)
	}

	return false
}

func (self BTree) String() string {
	const n string = "<nil>"
	var l, r string
	if self.Left == nil {
		l = n
	} else {
		l = self.Left.String()
	}
	if self.Right == nil {
		r = n
	} else {
		r = self.Right.String()
	}

	return fmt.Sprintf("<btree:[%s<-%s->%s]>", l, self.Value, r)
}