text:
#include "Events.hpp"

#include <vector>
#include <unordered_map>
#include <queue>

#include "Logger.hpp"
#include "Platform.hpp"
#include "Profiler.hpp"

namespace Engine {
    static std::function<bool(Json::Value)> emptyFilter = [](Json::Value e) { return true; };

    class CPPEventTarget : public EventTarget {
    public:
        CPPEventTarget(EventTargetFunc func, void* userPointer)
            : _func(func), _userPointer(userPointer) { }

        EventMagic Run(Json::Value& e) override {
            if (e.isNull()) {
                return this->_func(Json::nullValue, this->_userPointer);
            } else {
                return this->_func(e, this->_userPointer);
            }
        }

        bool IsScript() override { return false; }
        Type GetType() override { return Type::CPlusPlus; }

    private:
        EventTargetFunc _func;
        void* _userPointer;
    };

    inline EventMagic GetScriptingReturnType(v8::Local<v8::Value> ret) {
        if (!ret->IsExternal()) {
            return EM_OK;
        } else {
            v8::Local<v8::External> exVal = ret.As<v8::External>();
            void* value = exVal->Value();
            EventMagic* magic = (EventMagic*) value;
            return *magic;
        }
    }

    class JSEventTarget : public EventTarget {
    public:
        JSEventTarget(v8::Handle<v8::Function> func) {
            _func.Reset(v8::Isolate::GetCurrent(), func);
        }

        inline EventMagic Run(Json::Value& e, int jsArgC, v8::Handle<v8::Value> jsArgV[]) {
            static EventMagic ret_magic = EM_BADTARGET; // Warning this could cause issues with threads.

            v8::Isolate* currentIsolate = v8::Isolate::GetCurrent();
            v8::HandleScope scope(currentIsolate);
            v8::Local<v8::Context> ctx = currentIsolate->GetCurrentContext();
            if (ctx.IsEmpty() || ctx->Global().IsEmpty()) return EM_BADTARGET;

            v8::TryCatch tryCatch;

            v8::Local<v8::Value>* args = new v8::Local<v8::Value>[1 + jsArgC];

            if ((e.isObject() || e.isArray()) &&
                e.getMemberNames().size() == 0) {
                args[0] = v8::Object::New(currentIsolate);
            } else if (e.isNull()) {
                args[0] = v8::Null(currentIsolate);
            } else {
                args[0] = ScriptingManager::GetObjectFromJson(e);
            }

            if (jsArgC > 0) {
                for (int i = 0; i < jsArgC; i++) {
                    args[i + 1] = jsArgV[i];
                }
            }

            v8::Local<v8::Function> func = v8::Local<v8::Function>::New(currentIsolate, _func);

            v8::Local<v8::Value> ret = func->Call(ctx->Global(), 1 + jsArgC, args);

            if (!tryCatch.StackTrace().IsEmpty()) {
                ScriptingManager::ReportException(currentIsolate, &tryCatch);
                ret.Clear();
                func.Clear();
                return EM_BADTARGET;
            }

            ret_magic = GetScriptingReturnType(ret);

            ret.Clear();
            func.Clear();

            delete [] args;

            return ret_magic;
        }

        EventMagic Run(Json::Value& e) override {
            return this->Run(e, 0, {});
        }

        Type GetType() override { return Type::Javascript; }

    private:
        v8::Persistent<v8::Function> _func;
    };

    size_t EventClass::GetDeferedMessageCount() {
        return this->_deferedMessages.size();
    }

    void EventClass::LogEvents(std::string logName) {
        for (auto iter2 = this->_events.begin();
             iter2 != this->_events.end();
             iter2++) {
            Logger::begin(logName, Logger::LogLevel_Log)
                << "        | " << iter2->first << " | " << (iter2->second.Target->IsScript() ? "Script" : "C++   ") << " | " << iter2->second.Label
                << Logger::end();
        }
    }

    EventMagic EventClass::Emit(Json::Value args, int jsArgC, v8::Handle<v8::Value> jsArgV[]) {
        ENGINE_PROFILER_SCOPE_EX(this->TargetName.c_str());
        static std::vector<int> deleteTargets;
        if (this->_alwaysDefered) {
            this->_deferedMessages.push(args);
            return EM_DEFERED;
        } else {
            int index = 0;
            bool canceled = false;
            for (auto iter = this->_events.begin(); iter != this->_events.end(); iter++) {
                if (iter->second.Target != NULL && iter->second.Active) {
                    if (!(this->Security.NoScript && iter->second.Target->IsScript())) {
                        ENGINE_PROFILER_SCOPE_EX(iter->second.Label.c_str());
                        EventMagic ret = EM_BADTARGET;
                        if (jsArgC > 0 && iter->second.Target->GetType() == EventTarget::Type::Javascript) {
                            JSEventTarget* target = (JSEventTarget*) iter->second.Target;
                            ret = target->Run(args, jsArgC, jsArgV);
                        } else {
                            ret = iter->second.Target->Run(args);
                        }
                        if (ret == EM_CANCEL) {
                            canceled = true;
                            break;
                        }
                    }
                } else {
                    deleteTargets.push_back(index);
                }
                index++;
            }
            if (deleteTargets.size() > 0) {
                for (auto iter = deleteTargets.begin(); iter != deleteTargets.end(); iter++) {
                    this->_events.erase(*iter);
                }
                deleteTargets.empty();
            }
            return canceled ? EM_CANCEL : EM_OK;
        }
    }

    EventMagic EventClass::Emit(Json::Value args) {
        return this->Emit(args, 0, {});
    }

    EventMagic EventClass::Emit() {
        return this->Emit(Json::nullValue);
    }

    EventClassPtr EventClass::AddListener(size_t priority, std::string name, EventTargetPtr target) {
        for (auto iter = this->_events.begin(); iter != this->_events.end(); iter++) {
            if (iter->second.Label == name) {
                delete iter->second.Target;
                iter->second.Target = target;
                return this;
            }
        }
        this->_events.insert(std::pair<size_t, Event>(priority, Event(name, target)));
        return this;
    }

    EventClassPtr EventClass::AddListener(std::string name, EventTargetPtr target) {
        return this->AddListener(500, name, target);
    }

    void EventClass::Clear(std::string eventID) {
        for (auto iter = this->_events.begin(); iter != this->_events.end(); iter++) {
            if (iter->second.Label == eventID) {
                iter->second.Active = false;
                return;
            }
        }
    }

    EventClass* EventClass::SetDefered(bool defered) {
        this->_alwaysDefered = defered;
        return this;
    }

    EventClass* EventClass::SetNoScript(bool noScript) {
        this->Security.NoScript = noScript;
        return this;
    }

    void EventClass::PollDeferedMessages() {
        ENGINE_PROFILER_SCOPE;
        while (this->_deferedMessages.size() > 0) {
            for (auto iter2 = this->_events.begin(); iter2 != this->_events.end(); iter2++) {
                if (iter2->second.Target == NULL) { throw "Invalid Target"; }
                if (iter2->second.Active) {
                    if (!(this->Security.NoScript && iter2->second.Target->IsScript())) {
                        iter2->second.Target->Run(this->_deferedMessages.front());
                    }
                }
            }
            this->_deferedMessages.pop();
        }
    }

    void EventClass::AddDeferedMessage(Json::Value e) {
        this->_deferedMessages.push(e);
    }

    int EventClass::ListenerCount() {
        return this->_events.size();
    }

    EventMagic EventEmitter::_debug(Json::Value args, void* userPointer) {
        Logger::begin("Events", Logger::LogLevel_Log) << " == EVENT DEBUG ==" << Logger::end();

        EventEmitterPtr events = static_cast<EventEmitterPtr>(userPointer);

        for (auto iter = events->_events.begin();
             iter != events->_events.end();
             iter++) {
            EventClassPtr cls = iter->second;
            Logger::begin("Events", Logger::LogLevel_Log)
                << "    ==========================="
                << Logger::end();
            Logger::begin("Events", Logger::LogLevel_Log)
                << "    Event Class: " << iter->first
            << Logger::end();
            if (cls != NULL) {
                Logger::begin("Events", Logger::LogLevel_Log)
                    << "    Event Security: " << iter->second->Security.ToString()
                    << Logger::end();
                Logger::begin("Events", Logger::LogLevel_Log) << "    Event Defered Messages: " << cls->GetDeferedMessageCount() << Logger::end();
                Logger::begin("Events", Logger::LogLevel_Log)
                    << "    Event Members: "
                    << Logger::end();

                cls->LogEvents("Events");
            }
        }
        return EM_OK;
    }

    EventEmitter::EventEmitter() {
        this->_eventMutex = Platform::CreateMutex();
        this->GetEvent("eventDebug")->AddListener("Events::_debug", MakeTarget(_debug, this));
    }

    EventClassPtrRef EventEmitter::GetEvent(std::string eventName) {
        std::string evnt_copy = std::string(eventName.c_str());
        EventClassPtrRef cls = this->_events[evnt_copy];
        if (cls == NULL) {
            cls = new EventClass();
            cls->TargetName = evnt_copy;
        }
        return cls;
    }

    EventTarget* EventEmitter::MakeTarget(EventTargetFunc target) {
        return new CPPEventTarget(target, NULL);
    }

    EventTargetPtr EventEmitter::MakeTarget(EventTargetFunc target, void* userPointer) {
        return new CPPEventTarget(target, userPointer);
    }

    EventTargetPtr EventEmitter::MakeTarget(v8::Handle<v8::Function> target) {
        return new JSEventTarget(target);
    }

    void EventEmitter::Clear(std::string eventID) {
        for (auto iter = this->_events.begin();
             iter != this->_events.end(); iter++) {
            if (iter->second == NULL) return;
            iter->second->Clear(eventID);
        }
    }

    // Only called from the main thread
    void EventEmitter::PollDeferedMessages() {
        this->_eventMutex->Enter();

        for (auto iter = this->_events.begin();
             iter != this->_events.end(); iter++) {
            if (iter->second == NULL) continue;
            iter->second->PollDeferedMessages();
        }

        this->_eventMutex->Exit();
    }

    // Only called from main thread, does not interact with other threads right now
    void EventEmitter::PollDeferedMessages(std::string eventName) {
        EventClassPtrRef cls = this->_events[eventName];
        if (cls == NULL) { return; }

        cls->PollDeferedMessages();
    }

    // Called from any worker thread
    void EventEmitter::EmitThread(std::string threadID, std::string evnt, Json::Value e) {
        this->_eventMutex->Enter();

        if (this->_events.count(evnt) > 0) {
            this->_events[evnt]->AddDeferedMessage(e);
        }

        this->_eventMutex->Exit();
    }

    EventEmitterPtr GetEventsSingilton() {
        static EventEmitterPtr events = NULL;
        if (events == NULL) {
            events = new EventEmitter();
        }
        return events;
    }
}


text:
/**
 * <!-- Package description. -->
 * Contains APIs for IGFS secondary file system base on local file system.
 */
package org.apache.ignite.igfs.secondary;

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.opsworks.model.transform;

import java.util.Map;
import java.util.Map.Entry;
import java.math.*;
import java.nio.ByteBuffer;

import com.amazonaws.services.opsworks.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * DescribeRaidArraysResult JSON Unmarshaller
 */
public class DescribeRaidArraysResultJsonUnmarshaller implements
        Unmarshaller<DescribeRaidArraysResult, JsonUnmarshallerContext> {

    public DescribeRaidArraysResult unmarshall(JsonUnmarshallerContext context)
            throws Exception {
        DescribeRaidArraysResult describeRaidArraysResult = new DescribeRaidArraysResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL)
            return null;

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("RaidArrays", targetDepth)) {
                    context.nextToken();
                    describeRaidArraysResult
                            .setRaidArrays(new ListUnmarshaller<RaidArray>(
                                    RaidArrayJsonUnmarshaller.getInstance())
                                    .unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null
                        || context.getLastParsedParentElement().equals(
                                currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return describeRaidArraysResult;
    }

    private static DescribeRaidArraysResultJsonUnmarshaller instance;

    public static DescribeRaidArraysResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new DescribeRaidArraysResultJsonUnmarshaller();
        return instance;
    }
}


text:
package org.apache.kafka.streams;

import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.streams.kstream.GlobalKTable;
import org.apache.kafka.streams.processor.StateStore;

import java.util.Map;

/**
 * {@code KafkaClientSupplier} can be used to provide custom Kafka clients to a {@link KafkaStreams} instance.
 *
 * @see KafkaStreams#KafkaStreams(Topology, java.util.Properties, KafkaClientSupplier)
 */
public interface KafkaClientSupplier {
    /**
     * Create an {@link Admin} which is used for internal topic management.
     *
     * @param config Supplied by the {@link java.util.Properties} given to the {@link KafkaStreams}
     * @return an instance of {@link Admin}
     */
    default Admin getAdmin(final Map<String, Object> config) {
        throw new UnsupportedOperationException("Implementations of KafkaClientSupplier should implement the getAdmin() method.");
    }

    /**
     * Create a {@link Producer} which is used to write records to sink topics.
     *
     * @param config {@link StreamsConfig#getProducerConfigs(String) producer config} which is supplied by the
     *               {@link java.util.Properties} given to the {@link KafkaStreams} instance
     * @return an instance of Kafka producer
     */
    Producer<byte[], byte[]> getProducer(final Map<String, Object> config);

    /**
     * Create a {@link Consumer} which is used to read records of source topics.
     *
     * @param config {@link StreamsConfig#getMainConsumerConfigs(String, String, int) consumer config} which is
     *               supplied by the {@link java.util.Properties} given to the {@link KafkaStreams} instance
     * @return an instance of Kafka consumer
     */
    Consumer<byte[], byte[]> getConsumer(final Map<String, Object> config);

    /**
     * Create a {@link Consumer} which is used to read records to restore {@link StateStore}s.
     *
     * @param config {@link StreamsConfig#getRestoreConsumerConfigs(String) restore consumer config} which is supplied
     *               by the {@link java.util.Properties} given to the {@link KafkaStreams}
     * @return an instance of Kafka consumer
     */
    Consumer<byte[], byte[]> getRestoreConsumer(final Map<String, Object> config);

    /**
     * Create a {@link Consumer} which is used to consume records for {@link GlobalKTable}.
     *
     * @param config {@link StreamsConfig#getGlobalConsumerConfigs(String) global consumer config} which is supplied
     *               by the {@link java.util.Properties} given to the {@link KafkaStreams}
     * @return an instance of Kafka consumer
     */
    Consumer<byte[], byte[]> getGlobalConsumer(final Map<String, Object> config);
}


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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.simplemented.okdelay.MainActivity"
        >

        <TextView
            android:id="@+id/activity_main_seek_bar_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:text="@string/activity_main_seek_bar_value_fmt"
            />

        <android.support.v7.widget.AppCompatSeekBar
            android:id="@+id/activity_main_seek_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:max="10"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            />

        <Button
            android:id="@+id/activity_main_call_request"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/activity_main_button_label"
            />

        <ProgressBar
            android:id="@+id/activity_main_progress_bar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="invisible"
            />

        <TextView
            android:id="@+id/activity_main_response"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:text="Lorem ipsum"
            />

    </LinearLayout>

</ScrollView>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Net;

namespace ServicePublisher.MXD
{
    public class PublishMXD
    {
        private string _sMXDTemplate;
        private string _ArcGISServer;
        private string _sMapServiceName;
        private string _sOutputDirectory;
        private bool _bSDE;
        private string _sDBConn;
        private string _sDataset;

        public PublishMXD(string sMXDTemplate, string ArcGISServer, string sServiceName, string sDBConn, string sDataset, string sOutputDirectory, bool bSDE)
        {
            _sMXDTemplate = sMXDTemplate;
            _ArcGISServer = ArcGISServer;
            _sMapServiceName = CleanMXDName(sServiceName);
            _sOutputDirectory = sOutputDirectory;
            _sDBConn = sDBConn;
            _sDataset = sDataset;
            _bSDE = bSDE;
        }

        /// <summary>
        /// Publishes a Map Service using ArcGIS 10
        /// </summary>
        /// <returns>Published URL or Error as a string</returns>
        public string Publish()
        {
            int minInstances = 0;
            int maxInstances = 2;
            int waitTimeout = 60;
            int usageTimeout = 60;
            int idleTimeout = 60;

            return Publish(minInstances, maxInstances, waitTimeout, usageTimeout, idleTimeout, "", "");
        }

        /// <summary>
        /// Passes Ags Connection file and Python Script to publish using ArcGIS 10.1
        /// </summary>
        /// <param name="sAgsConnFile"></param>
        /// <param name="sPythonScriptFile"></param>
        /// <returns>Published URL or Error as a string</returns>
        public string Publish(string sAgsConnFile, string sPythonScriptFile)
        {
           return Publish(0, 0, 0, 0, 0, sAgsConnFile, sPythonScriptFile);
        }

        /// <summary>
        /// Publishes a Map Service
        /// </summary>
        /// <param name="minInstances"></param>
        /// <param name="maxInstances"></param>
        /// <param name="waitTimeout"></param>
        /// <param name="usageTimeout"></param>
        /// <param name="idleTimeout"></param>
        /// <param name="sAgsConnFile"></param>
        /// <param name="sPythonScriptFile"></param>
        /// <returns>Published URL or Error as a string</returns>
        public string Publish(int minInstances, int maxInstances, int waitTimeout, int usageTimeout, int idleTimeout, string sAgsConnFile, string sPythonScriptFile)
        {
            string sURLs = string.Empty;
            string sMapServiceName = string.Empty;
            string sMxdFile = string.Empty;
            string sMxdTemplateName = string.Empty;
            MxdManager pManager = null;

            try
            {
                if (String.IsNullOrEmpty(_sMXDTemplate)) return "Error: No MXD passed.";

                pManager = new MxdManager(_sMXDTemplate);

                if (pManager.IsInitialized)
                {
                    // Set sMapServiceName
                    sMapServiceName = _sMapServiceName;

                    // Set sMxdTemplateName
                    _sMXDTemplate = _sMXDTemplate.Replace("C:\\\\", "C:\\");
                    sMxdTemplateName = _sMXDTemplate.Substring(_sMXDTemplate.LastIndexOf("\\") + 1);
                    sMxdTemplateName = sMxdTemplateName.Remove(sMxdTemplateName.IndexOf(".mxd"));

                    // Set sMxdFile
                    sMxdFile = Path.Combine(_sOutputDirectory, sMapServiceName + "_" + sMxdTemplateName + ".mxd");

                    if (!(pManager.CreateMxd(_sMXDTemplate, _sOutputDirectory, _ArcGISServer, sMxdFile, _sDBConn, _sDataset, _bSDE)))
                    {
                        sURLs = sURLs + "MxdManager.CreateMxd failed for " + _sMXDTemplate + ". Please see logfile for details.,";
                    }

                    // If sAgsConnFile is empty then publish using ArcGIS Server 10
                    if (string.IsNullOrEmpty(sAgsConnFile))
                    {
                        sURLs = sURLs + pManager.PublishMap(sMapServiceName + "_" + sMxdTemplateName, _ArcGISServer, sMxdFile, _bSDE, minInstances, maxInstances, waitTimeout, usageTimeout, idleTimeout);
                    }
                    else // publish using ArcGIS Server 10.1
                    {
#if _WIN64
                        sURLs = sURLs + pManager.PublishMap10_1(sMapServiceName + "_" + sMxdTemplateName, _ArcGISServer, sMxdFile, _sOutputDirectory, sAgsConnFile, sPythonScriptFile);
#endif
                    }
                }

                return sURLs.TrimEnd(',');
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Error in PublishMXD.Publish: " + ex.Message + " Stack trace: " + ex.StackTrace);
            }
            finally
            {

                pManager = null;
            }
        }

        // TODO: Add 10.1 method
        public string UnPublish()
        {
            string sDeleteFgdbResult = "";
            string sURLs = "";
            string sMapServiceName = "";
            string sMxdName;
            FileInfo fiMxd;
            MxdManager manager = null;
            bool errorOccured = false;

            try
            {
                if (String.IsNullOrEmpty(_sMXDTemplate))
                    return "Error: No MXD passed.";

                    sMxdName = "";
                    manager = new MxdManager("");

                    sMapServiceName = _sMXDTemplate;
                    if (!(manager.UnPublishMap(sMapServiceName, _ArcGISServer, _sOutputDirectory, _sDataset, _sDBConn)))
                    {
                        sURLs = sURLs + "Error: MxdManager.UnPublishMap failed for " + sMapServiceName + ". Please see logfile for details.,";
                        errorOccured = true;
                    }
                    else
                    {
                        sURLs = sURLs + "Removal of " + sMapServiceName + " was successful.,";
                    }

                // Remove trailing ','
                sURLs = sURLs.Remove(sURLs.Length - 1);

                if (!(errorOccured))
                {
                    //if locks exist only path is passed in
                    if (_sDBConn.Contains(".gdb"))
                    {
                        sDeleteFgdbResult = manager.DeleteGdb(_sDBConn);
                        if (sDeleteFgdbResult.Length > 0) sURLs = sURLs + "," + sDeleteFgdbResult;
                    }
                }
                return sURLs;
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Error in PublishMXD.UnPublish: " + ex.Message + " Stack trace: " + ex.StackTrace);
            }
            finally
            {
                fiMxd = null;
                manager = null;
            }
        }

        #region Privates
        private string CleanMXDName(string sMXDName)
        {
            sMXDName = sMXDName.Replace(" ", "_");
            sMXDName = sMXDName.Replace(".", "");
            sMXDName = sMXDName.Replace(",", "");
            sMXDName = sMXDName.Replace("&", "");
            sMXDName = sMXDName.Replace("'", "");
            sMXDName = sMXDName.Replace("\\", "");
            sMXDName = sMXDName.Replace(";", "");
            sMXDName = sMXDName.Replace(":", "");
            sMXDName = sMXDName.Replace("\"", "");
            sMXDName = sMXDName.Replace("|", "");
            sMXDName = sMXDName.Replace("=", "");
            sMXDName = sMXDName.Replace(">", "");
            sMXDName = sMXDName.Replace("<", "");
            sMXDName = sMXDName.Replace("?", "");
            sMXDName = sMXDName.Replace("!", "");
            sMXDName = sMXDName.Replace("@", "");
            sMXDName = sMXDName.Replace("#", "");
            sMXDName = sMXDName.Replace("$", "");
            sMXDName = sMXDName.Replace("%", "");
            sMXDName = sMXDName.Replace("^", "");
            sMXDName = sMXDName.Replace("*", "");
            sMXDName = sMXDName.Replace("(", "");
            sMXDName = sMXDName.Replace(")", "");
            sMXDName = sMXDName.Replace("'", "");

            return sMXDName;
        }
        #endregion

    }
}


text:
const $ = id => document.getElementById(id);
const bgExclusions = chrome.extension.getBackgroundPage().Exclusions;

// We have to use Settings from the background page here (not Settings, directly) to avoid a race condition for
// the page popup.  Specifically, we must ensure that the settings have been updated on the background page
// *before* the popup closes.  This ensures that any exclusion-rule changes are in place before the page
// regains the focus.
const bgSettings = chrome.extension.getBackgroundPage().Settings;

//
// Class hierarchy for various types of option.
// Call "fetch" after constructing an Option object, to fetch it from localStorage.
class Option {
  // Base class for all option classes.
  // Abstract. Option does not define @populateElement or @readValueFromElement.
  constructor(field, onUpdated) {
    this.field = field;
    this.onUpdated = onUpdated;
    this.element = $(this.field);
    this.element.addEventListener("change", this.onUpdated);
    Option.all.push(this);
  }

  // Fetch a setting from localStorage, remember the @previous value and populate the DOM element.
  // Return the fetched value.
  fetch() {
    this.populateElement(this.previous = bgSettings.get(this.field));
    return this.previous;
  }

  // Write this option's new value back to localStorage, if necessary.
  save() {
    const value = this.readValueFromElement();
    if (JSON.stringify(value) !== JSON.stringify(this.previous))
      bgSettings.set(this.field, (this.previous = value));
  }

  restoreToDefault() {
    bgSettings.clear(this.field);
    return this.fetch();
  }

  static onSave(callback) {
    this.onSaveCallbacks.push(callback);
  }

  // Static method.
  static saveOptions() {
    Option.all.map(option => option.save());
    this.onSaveCallbacks.map((callback) => callback());
  }
}

  // Abstract method; only implemented in sub-classes.
  // Populate the option's DOM element (@element) with the setting's current value.
  // populateElement: (value) -> DO_SOMETHING

  // Abstract method; only implemented in sub-classes.
  // Extract the setting's new value from the option's DOM element (@element).
  // readValueFromElement: -> RETURN_SOMETHING

Option.all = []; // Static. Array of all options.
Option.onSaveCallbacks = [];

class NumberOption extends Option {
  populateElement(value) { this.element.value = value; }
  readValueFromElement() { return parseFloat(this.element.value); }
}

class TextOption extends Option {
  constructor(...args) {
    super(...Array.from(args || []));
    this.element.addEventListener("input", this.onUpdated);
  }
  populateElement(value) { this.element.value = value; }
  readValueFromElement() { return this.element.value.trim(); }
}

class NonEmptyTextOption extends Option {
  constructor(...args) {
    super(...Array.from(args || []));
    this.element.addEventListener("input", this.onUpdated);
  }

  populateElement(value) { this.element.value = value; }
  // If the new value is not empty, then return it. Otherwise, restore the default value.
  readValueFromElement() {
    const value = this.element.value.trim();
    if (value)
      return value;
    else
      return this.restoreToDefault();
  }
}

class CheckBoxOption extends Option {
  populateElement(value) { this.element.checked = value; }
  readValueFromElement() { return this.element.checked; }
}

class ExclusionRulesOption extends Option {
  constructor(...args) {
    super(...Array.from(args || []));
    $("exclusionAddButton").addEventListener("click", event => {
      this.addRule();
    });
  }

  // Add a new rule, focus its pattern, scroll it into view, and return the newly-added element.  On the
  // options page, there is no current URL, so there is no initial pattern.  This is the default.  On the popup
  // page (see ExclusionRulesOnPopupOption), the pattern is pre-populated based on the current tab's URL.
  addRule(pattern) {
    if (pattern == null)
      pattern = "";
    const element = this.appendRule({ pattern, passKeys: "" });
    this.getPattern(element).focus();
    const exclusionScrollBox = $("exclusionScrollBox");
    exclusionScrollBox.scrollTop = exclusionScrollBox.scrollHeight;
    this.onUpdated();
    return element;
  }

  populateElement(rules) {
    // For the case of restoring a backup, we first have to remove existing rules.
    const exclusionRules = $("exclusionRules");
    while (exclusionRules.rows[1]) { exclusionRules.deleteRow(1); }
    for (let rule of rules)
      this.appendRule(rule);
  }

  // Append a row for a new rule.  Return the newly-added element.
  appendRule(rule) {
    let element;
    const content = document.querySelector('#exclusionRuleTemplate').content;
    const row = document.importNode(content, true);

    for (let field of ["pattern", "passKeys"]) {
      element = row.querySelector(`.${field}`);
      element.value = rule[field];
      for (let event of [ "input", "change" ])
        element.addEventListener(event, this.onUpdated);
    }

    this.getRemoveButton(row).addEventListener("click", event => {
      rule = event.target.parentNode.parentNode;
      rule.parentNode.removeChild(rule);
      this.onUpdated();
    });

    this.element.appendChild(row);
    return this.element.children[this.element.children.length-1];
  }

  readValueFromElement() {
    const rules =
      Array.from(this.element.getElementsByClassName("exclusionRuleTemplateInstance")).map((element) => ({
        pattern: this.getPattern(element).value.trim(),
        passKeys: this.getPassKeys(element).value.trim()
      }));
    return rules.filter(rule => rule.pattern);
  }

  // Accessors for the three main sub-elements of an "exclusionRuleTemplateInstance".
  getPattern(element) { return element.querySelector(".pattern"); }
  getPassKeys(element) { return element.querySelector(".passKeys"); }
  getRemoveButton(element) { return element.querySelector(".exclusionRemoveButton"); }
}

// ExclusionRulesOnPopupOption is ExclusionRulesOption, extended with some UI tweeks suitable for use in the
// page popup.  This also differs from ExclusionRulesOption in that, on the page popup, there is always a URL
// (@url) associated with the current tab.
class ExclusionRulesOnPopupOption extends ExclusionRulesOption {
  constructor(url, ...args) {
    super(...Array.from(args || []));
    this.url = url;
  }

  addRule() {
    const element = super.addRule(this.generateDefaultPattern());
    this.activatePatternWatcher(element);
    // ExclusionRulesOption.addRule()/super() has focused the pattern.  Here, focus the passKeys instead;
    // because, in the popup, we already have a pattern, so the user is more likely to edit the passKeys.
    this.getPassKeys(element).focus();
    // Return element (for consistency with ExclusionRulesOption.addRule()).
    return element;
  }

  populateElement(rules) {
    let element;
    super.populateElement(rules);
    const elements = this.element.getElementsByClassName("exclusionRuleTemplateInstance");
    for (element of Array.from(elements))
      this.activatePatternWatcher(element);

    let haveMatch = false;
    for (element of Array.from(elements)) {
      const pattern = this.getPattern(element).value.trim();
      if (0 <= this.url.search(bgExclusions.RegexpCache.get(pattern))) {
        haveMatch = true;
        this.getPassKeys(element).focus();
      } else {
        element.style.display = 'none';
      }
    }
    if (!haveMatch)
      return this.addRule();
  }

  // Provide visual feedback (make it red) when a pattern does not match the current tab's URL.
  activatePatternWatcher(element) {
    const patternElement = element.children[0].firstChild;
    patternElement.addEventListener("keyup", () => {
      if (this.url.match(bgExclusions.RegexpCache.get(patternElement.value))) {
        patternElement.title = (patternElement.style.color = "");
      } else {
        patternElement.style.color = "red";
        patternElement.title = "Red text means that the pattern does not\nmatch the current URL.";
      }
    });
  }

  // Generate a default exclusion-rule pattern from a URL.  This is then used to pre-populate the pattern on
  // the page popup.
  generateDefaultPattern() {
    if (/^https?:\/\/./.test(this.url)) {
      // The common use case is to disable Vimium at the domain level.
      // Generate "https?://www.example.com/*" from "http://www.example.com/path/to/page.html".
      // Note: IPV6 host addresses will contain "[" and "]" (which must be escaped).
      const hostname = this.url.split("/",3).slice(1).join("/").replace("[", "\\[").replace("]", "\\]");
      return "https?:/" + hostname + "/*";
    } else if (/^[a-z]{3,}:\/\/./.test(this.url)) {
      // Anything else which seems to be a URL.
      return this.url.split("/",3).join("/") + "/*";
    } else {
      return this.url + "*";
    }
  }
}

const Options = {
  exclusionRules: ExclusionRulesOption,
  filterLinkHints: CheckBoxOption,
  waitForEnterForFilteredHints: CheckBoxOption,
  hideHud: CheckBoxOption,
  keyMappings: TextOption,
  linkHintCharacters: NonEmptyTextOption,
  linkHintNumbers: NonEmptyTextOption,
  newTabUrl: NonEmptyTextOption,
  nextPatterns: NonEmptyTextOption,
  previousPatterns: NonEmptyTextOption,
  regexFindMode: CheckBoxOption,
  ignoreKeyboardLayout: CheckBoxOption,
  scrollStepSize: NumberOption,
  smoothScroll: CheckBoxOption,
  grabBackFocus: CheckBoxOption,
  searchEngines: TextOption,
  searchUrl: NonEmptyTextOption,
  userDefinedLinkHintCss: NonEmptyTextOption
};

const initOptionsPage = function() {
  const onUpdated = function() {
    $("saveOptions").removeAttribute("disabled");
    $("saveOptions").textContent = "Save Changes";
  };

  // Display either "linkHintNumbers" or "linkHintCharacters", depending upon "filterLinkHints".
  const maintainLinkHintsView = function() {
    const hide = el => el.style.display = "none";
    const show = el => el.style.display = "table-row";
    if ($("filterLinkHints").checked) {
      hide($("linkHintCharactersContainer"));
      show($("linkHintNumbersContainer"));
      show($("waitForEnterForFilteredHintsContainer"));
    } else {
      show($("linkHintCharactersContainer"));
      hide($("linkHintNumbersContainer"));
      hide($("waitForEnterForFilteredHintsContainer"));
    }
  };

  const maintainAdvancedOptions = function() {
    if (bgSettings.get("optionsPage_showAdvancedOptions")) {
      $("advancedOptions").style.display = "table-row-group";
      return $("advancedOptionsButton").textContent = "Hide Advanced Options";
    } else {
      $("advancedOptions").style.display = "none";
      return $("advancedOptionsButton").textContent = "Show Advanced Options";
    }
  };
  maintainAdvancedOptions();

  const toggleAdvancedOptions = function(event) {
    bgSettings.set("optionsPage_showAdvancedOptions", !bgSettings.get("optionsPage_showAdvancedOptions"));
    maintainAdvancedOptions();
    $("advancedOptionsButton").blur();
    event.preventDefault();
  };

  const activateHelpDialog = function() {
    HelpDialog.toggle({showAllCommandDetails: true});
  };

  const saveOptions = function() {
    $("linkHintCharacters").value = $("linkHintCharacters").value.toLowerCase();
    Option.saveOptions();
    $("saveOptions").disabled = true;
    $("saveOptions").textContent = "Saved";
  };

  $("saveOptions").addEventListener("click", saveOptions);
  $("advancedOptionsButton").addEventListener("click", toggleAdvancedOptions);
  $("showCommands").addEventListener("click", activateHelpDialog);
  $("filterLinkHints").addEventListener("click", maintainLinkHintsView);

  for (let element of Array.from(document.getElementsByClassName("nonEmptyTextOption"))) {
    element.className = element.className + " example info";
    element.textContent = "Leave empty to reset this option.";
  }

  window.onbeforeunload = function() {
    if (!$("saveOptions").disabled)
      return "You have unsaved changes to options.";
  };

  document.addEventListener("keyup", function(event) {
    if (event.ctrlKey && (event.keyCode === 13)) {
      if (document && document.activeElement && document.activeElement.blur) {
        document.activeElement.blur();
        return saveOptions();
      }
    }
  });

  // Populate options. The constructor adds each new object to "Option.all".
  for (let name of Object.keys(Options)) {
    const type = Options[name];
    const option = new type(name, onUpdated);
    option.fetch();
  }

  maintainLinkHintsView();
};

const initPopupPage = function() {
  chrome.tabs.query({ active: true, currentWindow: true }, function(...args) {
    const [tab] = Array.from(args[0]);
    let exclusions = null;
    document.getElementById("optionsLink").setAttribute("href", chrome.runtime.getURL("pages/options.html"));

    const tabPorts = chrome.extension.getBackgroundPage().portsForTab[tab.id];
    if (!tabPorts || !(Object.keys(tabPorts).length > 0)) {
      // The browser has disabled Vimium on this page. Place a message explaining this into the popup.
      document.body.innerHTML = `\

    Vimium is not running on this page.

    Your browser does not run web extensions like Vimium on certain pages,
    usually for security reasons.

    Unless your browser's developers change their policy, then unfortunately it is not possible to make Vimium (or any other
    web extension, for that matter) work on this page.

\
`;
      return;
    }

    // As the active URL, we choose the most recently registered URL from a frame in the tab, or the tab's own
    // URL.
    const url = chrome.extension.getBackgroundPage().urlForTab[tab.id] || tab.url;

    const updateState = function() {
      const rule = bgExclusions.getRule(url, exclusions.readValueFromElement());
      $("state").innerHTML = "Vimium will " +
        (rule && rule.passKeys ?
         `exclude <span class='code'>${rule.passKeys}</span>`
         : (rule ? "be disabled" : "be enabled"));
    };

    const onUpdated = function() {
      $("helpText").innerHTML = "Type Ctrl-Enter to save and close.";
      $("saveOptions").removeAttribute("disabled");
      $("saveOptions").textContent = "Save Changes";
      if (exclusions)
        return updateState();
    };

    const saveOptions = function() {
      Option.saveOptions();
      $("saveOptions").textContent = "Saved";
      $("saveOptions").disabled = true;
    };

    $("saveOptions").addEventListener("click", saveOptions);

    document.addEventListener("keyup", function(event) {
      if (event.ctrlKey && (event.keyCode === 13)) {
        saveOptions();
        window.close();
      }
    });

    // Populate options. Just one, here.
    exclusions = new ExclusionRulesOnPopupOption(url, "exclusionRules", onUpdated);
    exclusions.fetch();

    updateState();
    document.addEventListener("keyup", updateState);
  });

  // Install version number.
  const manifest = chrome.runtime.getManifest();
  $("versionNumber").textContent = manifest.version;
};

//
// Initialization.
document.addEventListener("DOMContentLoaded", function() {
  DomUtils.injectUserCss(); // Manually inject custom user styles.
  const xhr = new XMLHttpRequest();
  xhr.open('GET', chrome.extension.getURL('pages/exclusions.html'), true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      $("exclusionScrollBox").innerHTML = xhr.responseText;
      switch (location.pathname) {
        case "/pages/options.html": initOptionsPage(); break;
        case "/pages/popup.html": initPopupPage(); break;
      }
    }
  };

  xhr.send();
});

//
// Backup and restore.
if (window.DomUtils) { // window.DomUtils is not defined when running our tests.
  DomUtils.documentReady(function() {
    // Only initialize backup/restore on the options page (not the popup).
    if (location.pathname !== "/pages/options.html")
      return;

    let restoreSettingsVersion = null;

  const populateBackupLinkUrl = function() {
    const backup = {settingsVersion: bgSettings.get("settingsVersion")};
    for (let option of Array.from(Option.all))
      backup[option.field] = option.readValueFromElement();

    // Create the blob in the background page so it isn't garbage collected when the page closes in FF.
    const bgWin = chrome.extension.getBackgroundPage();
    const blob = new bgWin.Blob([ JSON.stringify(backup, null, 2) + "\n" ]);
    $("backupLink").href = bgWin.URL.createObjectURL(blob);
  };

  $("backupLink").addEventListener("mousedown", populateBackupLinkUrl, true);

  $("chooseFile").addEventListener("change", function(event) {
    if (document.activeElement)
      document.activeElement.blur();

    const files = event.target.files;
    if (files.length === 1) {
      const file = files[0];
      const reader = new FileReader;
      reader.readAsText(file);
      reader.onload = function(event) {
        let backup;
        try {
          backup = JSON.parse(reader.result);
        } catch (error) {
          alert("Failed to parse Vimium backup.");
          return;
        }

        if ("settingsVersion" in backup)
          restoreSettingsVersion = backup["settingsVersion"];
        for (let option of Array.from(Option.all)) {
          if (option.field in backup) {
            option.populateElement(backup[option.field]);
            option.onUpdated();
          }
        }
      };
    }
  });

  Option.onSave(function() {
    // If we're restoring a backup, then restore the backed up settingsVersion.
    if (restoreSettingsVersion != null) {
      bgSettings.set("settingsVersion", restoreSettingsVersion);
      restoreSettingsVersion = null;
    }
    // Reset the restore-backup input.
    $("chooseFile").value = "";
    // We need to apply migrations in case we are restoring an old backup.
    bgSettings.applyMigrations();
  });
});
}

// Exported for use by our tests.
window.Options = Options
window.isVimiumOptionsPage = true


text:
package com.drmilk.nbawrapper.domain;

import com.drmilk.nbawrapper.exception.TeamNotFoundException;

import junit.framework.Assert;
import junit.framework.TestCase;

public class TeamTest extends TestCase {

	public void testGetHawksShortProfileFromTeamId() throws TeamNotFoundException {
		TeamMin teamMin = Team.getShortProfileByTeamId("1610612737");
		Assert.assertNotNull(teamMin);
		Assert.assertEquals(Team.LOGO_BASE_URL + "ATL" + Team.LOGO_END_URL, teamMin.getLogoUrl());
		Assert.assertEquals("Atlanta Hawks", teamMin.getFullName());
		Assert.assertEquals("ATL", teamMin.getTriCode());
	}

	public void testGetHawksFromPersonId() throws TeamNotFoundException {
		Team team = Team.getTeamById("1610612737");
		Assert.assertNotNull(team);
		Assert.assertEquals("Atlanta", team.getCity());
		Assert.assertEquals("Atlanta Hawks", team.getFullName());
		Assert.assertTrue(team.getGames().size() > 0);
		Assert.assertTrue(team.getRoster().size() > 0);
		Assert.assertNotNull(team.getTeamLeaders());
		Assert.assertEquals(Team.LOGO_BASE_URL + "ATL" + Team.LOGO_END_URL, team.getLogoUrl());
	}

	public void testSearchForHawksByTeamName() throws TeamNotFoundException {
		Team team = Team.getTeamByNameKeywords("Hawks");
		Assert.assertNotNull(team);
		Assert.assertEquals("Atlanta", team.getCity());
		Assert.assertEquals("Atlanta Hawks", team.getFullName());
		Assert.assertTrue(team.getGames().size() > 0);
		Assert.assertTrue(team.getRoster().size() > 0);
		Assert.assertNotNull(team.getTeamLeaders());
		Assert.assertEquals(Team.LOGO_BASE_URL + "ATL" + Team.LOGO_END_URL, team.getLogoUrl());
	}

	public void testSearchForRaptorsByCity() throws TeamNotFoundException {
		Team team = Team.getTeamByNameKeywords("Toronto");
		Assert.assertNotNull(team);
		Assert.assertEquals("Toronto", team.getCity());
		Assert.assertEquals("Toronto Raptors", team.getFullName());
		Assert.assertTrue(team.getGames().size() > 0);
		Assert.assertTrue(team.getRoster().size() > 0);
		Assert.assertNotNull(team.getTeamLeaders());
	}

	public void testGetTeamFromInvalidTeamId() {
		try {
			Team.getTeamById("invalidID");
			Assert.assertTrue(false);
		} catch (TeamNotFoundException e) {
			Assert.assertTrue(true);
		}
	}

}


text: Countdown.Helper.Pluralize = {};


text:
A set of classes for generatively creating visually pleasing color schemes.

## Requirements
None!  This addon will work right out of the box.

## Usage
All palettes inherit from the class `Palette.h`, and therefore have the same interface.  For any palette included here, you can use it by:

* Creating a color palette:

  ```
  ofxColorPalette::ColorPalette palette = new RandomPalette();
  ```

* Calling `nextColor()` to get a `std::shared_ptr` to a color:

  ```
  std::shared_ptr<ofColor> color_to_be_used = palette->nextColor();
  ```

* Using the color as you normally would!  You'll need to use the dereference operator (`*`) to get the `ofColor` object.

  ```
  ofFill();
  ofSetColor(*color_to_be_used);
  ofCircle(0, 0, 100);
  ```

The included examples show this particular behavior.

We've included several color palette options in this addon:

### RandomPalette

The `RandomPalette` palette creates color with a random HSB triplet -- use this to create truly random colors.

### RandomSaturatedPalette

The `RandomSaturatedPalette` palette creates color with a random hue and random brightness, but always with a full saturation value.  This will produce random saturated colors, with zero probability of black or white.  This palette will also not create any pastels -- just fully saturated colors.

### ColorPalette

This palette is by far the most complex with the greatest number of options.  The constructor takes a root hue as the 'base' of the pallete, and a `PALETTE_TYPE` argument, which provides 9 options for a color palette:

* `MONOCHROME` -- A single hue, the root hue.
* `COMPLEMENTARY` -- Two hues: the root hue, and it's complementary color 180 degrees on the color wheel.
* `SPLIT_COMPLEMENTARY` -- Three hues: the root hue, and two hues evenly offset from the complement.
* `TRIADIC` -- Three hues evenly spaced on the color wheel.
* `TETRADIC` -- Four hues evenly spaced on the color wheel.
* `FOUR_TONE` -- The root, a color closely offset from the hue by 60 degrees, and then the two complements.
* `FIVE_TONE` -- The root and four split complementary colors.
* `SIX_TONE` -- Like `TRIADIC`, but with a neighboring tone for each of the three.
* `NEUTRAL` -- Six evenly spaced colors on the color wheel.

#### Basic Usage
Once you've created a `ColorPalette` object, it has random probabilities for generating black, white, and saturated (both partially and fully) colors.  If you'd like to set the probabilities to a specific ratio, you can do so using the function

     setProbabilities(float black, float white, float saturated)

All three probabilities should add up to one.  The colors that are generated will have randomly assigned values for brightness and saturation; if you wish to have a minimum or maximum for the randomly generated values, you can do so with

    setMinimumSaturation(float minimum_saturation);
    setMaximumSaturation(float maximum_saturation);
    setMinimumBrightness(float minimum_brightness);
    setMaximumBrightness(float maximum_brightness);

#### Saturation Options
In addition to the above options, there are three types of saturation options, described in the enum `SATURATION_TYPE`:

* `STATIC` -- The saturation will always be staticly set to the maximum value (default is 255.0).
* `LEVELS` -- The saturation will be quantized to a finite number of saturation values, up to the maximum value.  These levels do not include white (saturation = 0).  The default number of levels is 8, and this is the default behavior for the class.
* `RANDOM` -- This will make the saturation a random number chosen between the minimum and maximum saturation bounds.

The number of saturation levels is adjustable via the corresponding setter.

#### Hue Options
There are two options for hue, defined in the enum `HUE_TYPE`:

* `UNIFORM` -- all hues, as set by the `PALETTE_TYPE` variable, are equally probable.
* `SKEWED_ROOT` -- the root hue has a skewed probablity set by `mRootProbability`.

If you choose `SKEWED_ROOT`, the root probability can be set via:

    setProbabilities(float black, float white, float saturated, float root)

Not that this probability is seperate from the black/white/saturated probabilities, and does not have to add up to one.  This is because the hue is chosen after the type of color.

## Examples

* `example-paletteSelector` draws randomly placed circles on the screen using the color palette's `nextColor()` function.
* `example-colorVisualization` shows an alternative way to use the `ColorPalette` class, using it as a container to generate hues and saturations, but not using the color non-randomly to visualize a color wheel.


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis
{
    internal partial class DocumentState : TextDocumentState
    {
        private static readonly Func<string?, PreservationMode, string> s_fullParseLog = (path, mode) => $"{path} : {mode}";

        private static readonly ConditionalWeakTable<SyntaxTree, DocumentId> s_syntaxTreeToIdMap =
            new();

        private readonly HostLanguageServices _languageServices;
        private readonly ParseOptions? _options;

        // null if the document doesn't support syntax trees:
        private readonly ValueSource<TreeAndVersion>? _treeSource;

        protected DocumentState(
            HostLanguageServices languageServices,
            SolutionServices solutionServices,
            IDocumentServiceProvider? documentServiceProvider,
            DocumentInfo.DocumentAttributes attributes,
            ParseOptions? options,
            SourceText? sourceText,
            ValueSource<TextAndVersion> textSource,
            ValueSource<TreeAndVersion>? treeSource)
            : base(solutionServices, documentServiceProvider, attributes, sourceText, textSource)
        {
            _languageServices = languageServices;
            _options = options;
            _treeSource = treeSource;
        }

        public DocumentState(
            DocumentInfo info,
            ParseOptions? options,
            HostLanguageServices languageServices,
            SolutionServices services)
            : base(info, services)
        {
            _languageServices = languageServices;
            _options = options;

            // If this is document that doesn't support syntax, then don't even bother holding
            // onto any tree source.  It will never be used to get a tree, and can only hurt us
            // by possibly holding onto data that might cause a slow memory leak.
            if (languageServices.SyntaxTreeFactory == null)
            {
                _treeSource = null;
            }
            else
            {
                Contract.ThrowIfNull(options);
                _treeSource = CreateLazyFullyParsedTree(
                    base.TextAndVersionSource,
                    info.Id.ProjectId,
                    GetSyntaxTreeFilePath(info.Attributes),
                    options,
                    languageServices);
            }
        }

        internal bool SupportsSyntaxTree
            => _treeSource != null;

        public HostLanguageServices LanguageServices
            => _languageServices;

        public ParseOptions? ParseOptions
            => _options;

        public SourceCodeKind SourceCodeKind
            => ParseOptions == null ? Attributes.SourceCodeKind : ParseOptions.Kind;

        public bool IsGenerated
            => Attributes.IsGenerated;

        // This is the string used to represent the FilePath property on a SyntaxTree object.
        // if the document does not yet have a file path, use the document's name instead in regular code
        // or an empty string in script code.
        private static string GetSyntaxTreeFilePath(DocumentInfo.DocumentAttributes info)
        {
            if (info.FilePath != null)
            {
                return info.FilePath;
            }
            return info.SourceCodeKind == SourceCodeKind.Regular
                ? info.Name
                : "";
        }

        private static ValueSource<TreeAndVersion> CreateLazyFullyParsedTree(
            ValueSource<TextAndVersion> newTextSource,
            ProjectId cacheKey,
            string? filePath,
            ParseOptions options,
            HostLanguageServices languageServices,
            PreservationMode mode = PreservationMode.PreserveValue)
        {
            return new AsyncLazy<TreeAndVersion>(
                c => FullyParseTreeAsync(newTextSource, cacheKey, filePath, options, languageServices, mode, c),
                c => FullyParseTree(newTextSource, cacheKey, filePath, options, languageServices, mode, c),
                cacheResult: true);
        }

        private static async Task<TreeAndVersion> FullyParseTreeAsync(
            ValueSource<TextAndVersion> newTextSource,
            ProjectId cacheKey,
            string? filePath,
            ParseOptions options,
            HostLanguageServices languageServices,
            PreservationMode mode,
            CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.Workspace_Document_State_FullyParseSyntaxTree, s_fullParseLog, filePath, mode, cancellationToken))
            {
                var textAndVersion = await newTextSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
                return CreateTreeAndVersion(newTextSource, cacheKey, filePath, options, languageServices, mode, textAndVersion, cancellationToken);
            }
        }

        private static TreeAndVersion FullyParseTree(
            ValueSource<TextAndVersion> newTextSource,
            ProjectId cacheKey,
            string? filePath,
            ParseOptions options,
            HostLanguageServices languageServices,
            PreservationMode mode,
            CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.Workspace_Document_State_FullyParseSyntaxTree, s_fullParseLog, filePath, mode, cancellationToken))
            {
                var textAndVersion = newTextSource.GetValue(cancellationToken);
                return CreateTreeAndVersion(newTextSource, cacheKey, filePath, options, languageServices, mode, textAndVersion, cancellationToken);
            }
        }

        private static TreeAndVersion CreateTreeAndVersion(
            ValueSource<TextAndVersion> newTextSource,
            ProjectId cacheKey,
            string? filePath,
            ParseOptions options,
            HostLanguageServices languageServices,
            PreservationMode mode,
            TextAndVersion textAndVersion,
            CancellationToken cancellationToken)
        {
            var text = textAndVersion.Text;

            var treeFactory = languageServices.GetRequiredService<ISyntaxTreeFactoryService>();

            var tree = treeFactory.ParseSyntaxTree(filePath, options, text, cancellationToken);

            var root = tree.GetRoot(cancellationToken);
            if (mode == PreservationMode.PreserveValue && treeFactory.CanCreateRecoverableTree(root))
            {
                tree = treeFactory.CreateRecoverableTree(cacheKey, tree.FilePath, tree.Options, newTextSource, text.Encoding, root);
            }

            Contract.ThrowIfNull(tree);
            CheckTree(tree, text);

            // text version for this document should be unique. use it as a starting point.
            return TreeAndVersion.Create(tree, textAndVersion.Version);
        }

        private static ValueSource<TreeAndVersion> CreateLazyIncrementallyParsedTree(
            ValueSource<TreeAndVersion> oldTreeSource,
            ValueSource<TextAndVersion> newTextSource)
        {
            return new AsyncLazy<TreeAndVersion>(
                c => IncrementallyParseTreeAsync(oldTreeSource, newTextSource, c),
                c => IncrementallyParseTree(oldTreeSource, newTextSource, c),
                cacheResult: true);
        }

        private static async Task<TreeAndVersion> IncrementallyParseTreeAsync(
            ValueSource<TreeAndVersion> oldTreeSource,
            ValueSource<TextAndVersion> newTextSource,
            CancellationToken cancellationToken)
        {
            try
            {
                using (Logger.LogBlock(FunctionId.Workspace_Document_State_IncrementallyParseSyntaxTree, cancellationToken))
                {
                    var newTextAndVersion = await newTextSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
                    var oldTreeAndVersion = await oldTreeSource.GetValueAsync(cancellationToken).ConfigureAwait(false);

                    return IncrementallyParse(newTextAndVersion, oldTreeAndVersion, cancellationToken);
                }
            }
            catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

        private static TreeAndVersion IncrementallyParseTree(
            ValueSource<TreeAndVersion> oldTreeSource,
            ValueSource<TextAndVersion> newTextSource,
            CancellationToken cancellationToken)
        {
            try
            {
                using (Logger.LogBlock(FunctionId.Workspace_Document_State_IncrementallyParseSyntaxTree, cancellationToken))
                {
                    var newTextAndVersion = newTextSource.GetValue(cancellationToken);
                    var oldTreeAndVersion = oldTreeSource.GetValue(cancellationToken);

                    return IncrementallyParse(newTextAndVersion, oldTreeAndVersion, cancellationToken);
                }
            }
            catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

        private static TreeAndVersion IncrementallyParse(
            TextAndVersion newTextAndVersion,
            TreeAndVersion oldTreeAndVersion,
            CancellationToken cancellationToken)
        {
            var newText = newTextAndVersion.Text;
            var oldTree = oldTreeAndVersion.Tree;

            var oldText = oldTree.GetText(cancellationToken);
            var newTree = oldTree.WithChangedText(newText);
            Contract.ThrowIfNull(newTree);
            CheckTree(newTree, newText, oldTree, oldText);

            return MakeNewTreeAndVersion(oldTree, oldText, oldTreeAndVersion.Version, newTree, newText, newTextAndVersion.Version);
        }

        private static TreeAndVersion MakeNewTreeAndVersion(SyntaxTree oldTree, SourceText oldText, VersionStamp oldVersion, SyntaxTree newTree, SourceText newText, VersionStamp newVersion)
        {
            var topLevelChanged = TopLevelChanged(oldTree, oldText, newTree, newText);
            var version = topLevelChanged ? newVersion : oldVersion;
            return TreeAndVersion.Create(newTree, version);
        }

        private const int MaxTextChangeRangeLength = 1024 * 4;

        private static bool TopLevelChanged(SyntaxTree oldTree, SourceText oldText, SyntaxTree newTree, SourceText newText)
        {
            // ** currently, it doesn't do any text based quick check. we can add them later if current logic is not performant enough for typing case.
            var change = newText.GetEncompassingTextChangeRange(oldText);
            if (change == default)
            {
                // nothing has changed
                return false;
            }

            // if texts are small enough, just use the equivalent to find out whether there was top level edits
            if (oldText.Length < MaxTextChangeRangeLength && newText.Length < MaxTextChangeRangeLength)
            {
                var topLevel = !newTree.IsEquivalentTo(oldTree, topLevel: true);
                return topLevel;
            }

            // okay, text is not small and whole text is changed, then we always treat it as top level edit
            if (change.NewLength == newText.Length)
            {
                return true;
            }

            // if changes are small enough, we use IsEquivalentTo to find out whether there was a top level edit
            if (change.Span.Length < MaxTextChangeRangeLength && change.NewLength < MaxTextChangeRangeLength)
            {
                var topLevel = !newTree.IsEquivalentTo(oldTree, topLevel: true);
                return topLevel;
            }

            // otherwise, we always consider top level change
            return true;
        }

        public bool HasContentChanged(DocumentState oldState)
        {
            return oldState._treeSource != _treeSource
                || HasTextChanged(oldState, ignoreUnchangeableDocument: false);
        }

        [Obsolete("Use TextDocumentState.HasTextChanged")]
        public bool HasTextChanged(DocumentState oldState)
            => HasTextChanged(oldState, ignoreUnchangeableDocument: false);

        public DocumentState UpdateParseOptions(ParseOptions options)
        {
            var originalSourceKind = this.SourceCodeKind;

            var newState = this.SetParseOptions(options);
            if (newState.SourceCodeKind != originalSourceKind)
            {
                newState = newState.UpdateSourceCodeKind(originalSourceKind);
            }

            return newState;
        }

        private DocumentState SetParseOptions(ParseOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (!SupportsSyntaxTree)
            {
                throw new InvalidOperationException();
            }

            var newTreeSource = CreateLazyFullyParsedTree(
                TextAndVersionSource,
                Id.ProjectId,
                GetSyntaxTreeFilePath(Attributes),
                options,
                _languageServices);

            return new DocumentState(
                LanguageServices,
                solutionServices,
                Services,
                Attributes.With(sourceCodeKind: options.Kind),
                options,
                sourceText,
                TextAndVersionSource,
                newTreeSource);
        }

        public DocumentState UpdateSourceCodeKind(SourceCodeKind kind)
        {
            if (this.ParseOptions == null || kind == this.SourceCodeKind)
            {
                return this;
            }

            return this.SetParseOptions(this.ParseOptions.WithKind(kind));
        }

        // TODO: https://github.com/dotnet/roslyn/issues/37125
        // if FilePath is null, then this will change the name of the underlying tree, but we aren't producing a new tree in that case.
        public DocumentState UpdateName(string name)
            => UpdateAttributes(Attributes.With(name: name));

        public DocumentState UpdateFolders(IReadOnlyList<string> folders)
            => UpdateAttributes(Attributes.With(folders: folders));

        private DocumentState UpdateAttributes(DocumentInfo.DocumentAttributes attributes)
        {
            Debug.Assert(attributes != Attributes);

            return new DocumentState(
                _languageServices,
                solutionServices,
                Services,
                attributes,
                _options,
                sourceText,
                TextAndVersionSource,
                _treeSource);
        }

        public DocumentState UpdateFilePath(string? filePath)
        {
            var newAttributes = Attributes.With(filePath: filePath);
            Debug.Assert(newAttributes != Attributes);

            // TODO: it's overkill to fully reparse the tree if we had the tree already; all we have to do is update the
            // file path and diagnostic options for that tree.
            var newTreeSource = SupportsSyntaxTree ?
                CreateLazyFullyParsedTree(
                    TextAndVersionSource,
                    Id.ProjectId,
                    GetSyntaxTreeFilePath(newAttributes),
                    _options!,
                    _languageServices) : null;

            return new DocumentState(
                _languageServices,
                solutionServices,
                Services,
                newAttributes,
                _options,
                sourceText,
                TextAndVersionSource,
                newTreeSource);
        }

        public new DocumentState UpdateText(SourceText newText, PreservationMode mode)
            => (DocumentState)base.UpdateText(newText, mode);

        public new DocumentState UpdateText(TextAndVersion newTextAndVersion, PreservationMode mode)
            => (DocumentState)base.UpdateText(newTextAndVersion, mode);

        protected override TextDocumentState UpdateText(ValueSource<TextAndVersion> newTextSource, PreservationMode mode, bool incremental)
        {
            ValueSource<TreeAndVersion>? newTreeSource;

            if (_treeSource == null)
            {
                newTreeSource = null;
            }
            else if (incremental)
            {
                newTreeSource = CreateLazyIncrementallyParsedTree(_treeSource, newTextSource);
            }
            else
            {
                newTreeSource = CreateLazyFullyParsedTree(
                    newTextSource,
                    Id.ProjectId,
                    GetSyntaxTreeFilePath(Attributes),
                    _options!,
                    _languageServices,
                    mode); // TODO: understand why the mode is given here. If we're preserving text by identity, why also preserve the tree?
            }

            return new DocumentState(
                LanguageServices,
                solutionServices,
                Services,
                Attributes,
                _options,
                sourceText: null,
                textSource: newTextSource,
                treeSource: newTreeSource);
        }

        internal DocumentState UpdateText(TextLoader loader, SourceText? text, PreservationMode mode)
        {
            var documentState = (DocumentState)UpdateText(loader, mode);

            // If we are given a SourceText directly, fork it since we didn't pass that into the base.
            // TODO: understand why this is being called this way at all. It seems we only have a text in a specific case
            // when we are opening a file, when it seems this could have just called the other overload that took a
            // TextAndVersion that could have just pinned the object directly.
            if (text == null)
            {
                return documentState;
            }

            return new DocumentState(
                LanguageServices,
                solutionServices,
                Services,
                Attributes,
                _options,
                sourceText: text,
                textSource: documentState.TextAndVersionSource,
                treeSource: documentState._treeSource);
        }

        internal DocumentState UpdateTree(SyntaxNode newRoot, PreservationMode mode)
        {
            if (!SupportsSyntaxTree)
            {
                throw new InvalidOperationException();
            }

            var newTextVersion = GetNewerVersion();
            var newTreeVersion = GetNewTreeVersionForUpdatedTree(newRoot, newTextVersion, mode);

            // determine encoding
            Encoding? encoding;

            if (TryGetSyntaxTree(out var priorTree))
            {
                // this is most likely available since UpdateTree is normally called after modifying the existing tree.
                encoding = priorTree.Encoding;
            }
            else if (TryGetText(out var priorText))
            {
                encoding = priorText.Encoding;
            }
            else
            {
                // the existing encoding was never observed so is unknown.
                encoding = null;
            }

            var syntaxTreeFactory = _languageServices.GetRequiredService<ISyntaxTreeFactoryService>();

            var filePath = GetSyntaxTreeFilePath(Attributes);

            Contract.ThrowIfNull(_options);
            var (text, tree) = CreateRecoverableTextAndTree(newRoot, filePath, newTextVersion, newTreeVersion, encoding, Attributes, _options, syntaxTreeFactory, mode);

            return new DocumentState(
                LanguageServices,
                solutionServices,
                Services,
                Attributes,
                _options,
                sourceText: null,
                textSource: text,
                treeSource: new ConstantValueSource<TreeAndVersion>(tree));
        }

        private VersionStamp GetNewTreeVersionForUpdatedTree(SyntaxNode newRoot, VersionStamp newTextVersion, PreservationMode mode)
        {
            RoslynDebug.Assert(_treeSource != null);

            if (mode != PreservationMode.PreserveIdentity)
            {
                return newTextVersion;
            }

            if (!_treeSource.TryGetValue(out var oldTreeAndVersion) || !oldTreeAndVersion!.Tree.TryGetRoot(out var oldRoot))
            {
                return newTextVersion;
            }

            return oldRoot.IsEquivalentTo(newRoot, topLevel: true) ? oldTreeAndVersion.Version : newTextVersion;
        }

        // use static method so we don't capture references to this
        private static (ValueSource<TextAndVersion>, TreeAndVersion) CreateRecoverableTextAndTree(
            SyntaxNode newRoot,
            string filePath,
            VersionStamp textVersion,
            VersionStamp treeVersion,
            Encoding? encoding,
            DocumentInfo.DocumentAttributes attributes,
            ParseOptions options,
            ISyntaxTreeFactoryService factory,
            PreservationMode mode)
        {
            SyntaxTree tree;
            ValueSource<TextAndVersion> lazyTextAndVersion;

            if (mode == PreservationMode.PreserveIdentity || !factory.CanCreateRecoverableTree(newRoot))
            {
                tree = factory.CreateSyntaxTree(filePath, options, encoding, newRoot);

                // its okay to use a strong cached AsyncLazy here because the compiler layer SyntaxTree will also keep the text alive once its built.
                lazyTextAndVersion = new TreeTextSource(
                    new AsyncLazy<SourceText>(
                        c => tree.GetTextAsync(c),
                        c => tree.GetText(c),
                        cacheResult: true),
                    textVersion,
                    filePath);
            }
            else
            {
                // There is a strange circularity here: the creation of lazyTextAndVersion reads this local, but will see it as non-null since it
                // only uses it through a lambda that won't have ran. The assignment exists to placate the definite-assignment analysis (which is
                // right to be suspicious of this).
                tree = null!;

                // Uses CachedWeakValueSource so the document and tree will return the same SourceText instance across multiple accesses as long
                // as the text is referenced elsewhere.
                lazyTextAndVersion = new TreeTextSource(
                    new WeaklyCachedValueSource<SourceText>(
                        new AsyncLazy<SourceText>(
                            // Build text from root, so recoverable tree won't cycle.
                            async cancellationToken => (await tree.GetRootAsync(cancellationToken).ConfigureAwait(false)).GetText(encoding),
                            cancellationToken => tree.GetRoot(cancellationToken).GetText(encoding),
                            cacheResult: false)),
                    textVersion,
                    filePath);

                tree = factory.CreateRecoverableTree(attributes.Id.ProjectId, filePath, options, lazyTextAndVersion, encoding, newRoot);
            }

            return (lazyTextAndVersion, TreeAndVersion.Create(tree, treeVersion));
        }

        internal override Task<Diagnostic?> GetLoadDiagnosticAsync(CancellationToken cancellationToken)
        {
            if (TextAndVersionSource is TreeTextSource)
            {
                return SpecializedTasks.Null<Diagnostic>();
            }

            return base.GetLoadDiagnosticAsync(cancellationToken);
        }

        private VersionStamp GetNewerVersion()
        {
            if (TextAndVersionSource.TryGetValue(out var textAndVersion))
            {
                return textAndVersion!.Version.GetNewerVersion();
            }

            if (_treeSource != null && _treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
            {
                return treeAndVersion.Version.GetNewerVersion();
            }

            return VersionStamp.Create();
        }

        public bool TryGetSyntaxTree([NotNullWhen(returnValue: true)] out SyntaxTree? syntaxTree)
        {
            syntaxTree = null;
            if (_treeSource != null && _treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
            {
                syntaxTree = treeAndVersion.Tree;
                BindSyntaxTreeToId(syntaxTree, Id);
                return true;
            }

            return false;
        }

        [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
        public async ValueTask<SyntaxTree> GetSyntaxTreeAsync(CancellationToken cancellationToken)
        {
            // operation should only be performed on documents that support syntax trees
            RoslynDebug.Assert(_treeSource != null);

            var treeAndVersion = await _treeSource.GetValueAsync(cancellationToken).ConfigureAwait(false);

            // make sure there is an association between this tree and this doc id before handing it out
            BindSyntaxTreeToId(treeAndVersion.Tree, this.Id);
            return treeAndVersion.Tree;
        }

        internal SyntaxTree GetSyntaxTree(CancellationToken cancellationToken)
        {
            // operation should only be performed on documents that support syntax trees
            RoslynDebug.Assert(_treeSource != null);

            var treeAndVersion = _treeSource.GetValue(cancellationToken);

            // make sure there is an association between this tree and this doc id before handing it out
            BindSyntaxTreeToId(treeAndVersion.Tree, this.Id);
            return treeAndVersion.Tree;
        }

        public bool TryGetTopLevelChangeTextVersion(out VersionStamp version)
        {
            if (_treeSource != null && _treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
            {
                version = treeAndVersion.Version;
                return true;
            }
            else
            {
                version = default;
                return false;
            }
        }

        public override async Task<VersionStamp> GetTopLevelChangeTextVersionAsync(CancellationToken cancellationToken)
        {
            if (_treeSource == null)
            {
                return await GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
            }

            if (_treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
            {
                return treeAndVersion.Version;
            }

            treeAndVersion = await _treeSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
            return treeAndVersion.Version;
        }

        private static void BindSyntaxTreeToId(SyntaxTree tree, DocumentId id)
        {
            if (!s_syntaxTreeToIdMap.TryGetValue(tree, out var existingId))
            {
                // Avoid closing over parameter 'id' on the method's fast path
                var localId = id;
                existingId = s_syntaxTreeToIdMap.GetValue(tree, t => localId);
            }

            Contract.ThrowIfFalse(existingId == id);
        }

        public static DocumentId? GetDocumentIdForTree(SyntaxTree tree)
        {
            s_syntaxTreeToIdMap.TryGetValue(tree, out var id);
            return id;
        }

        private static void CheckTree(
            SyntaxTree newTree,
            SourceText newText,
            SyntaxTree? oldTree = null,
            SourceText? oldText = null)
        {
            // this should be always true
            if (newTree.Length == newText.Length)
            {
                return;
            }

            var newTreeContent = newTree.GetRoot().ToFullString();
            var newTextContent = newText.ToString();

            var oldTreeContent = oldTree?.GetRoot().ToFullString();
            var oldTextContent = oldText?.ToString();

            // we time to time see (incremental) parsing bug where text <-> tree round tripping is broken.
            // send NFW for those cases
            FatalError.ReportAndCatch(new Exception($"tree and text has different length {newTree.Length} vs {newText.Length}"));

            // this will make sure that these variables are not thrown away in the dump
            GC.KeepAlive(newTreeContent);
            GC.KeepAlive(newTextContent);
            GC.KeepAlive(oldTreeContent);
            GC.KeepAlive(oldTextContent);

            GC.KeepAlive(newTree);
            GC.KeepAlive(newText);
            GC.KeepAlive(oldTree);
            GC.KeepAlive(oldText);
        }
    }
}


text:
/**
* Instantiates a new TemplateServiceClient, given its endpoint URL.
*/
function TemplateServiceClient(endpointUrl) {
	// care for trailing slash in endpoint URL
	if(endpointUrl.endsWith("/")) {
		this._serviceEndpoint = endpointUrl.substr(0,endpointUrl.length-1);
	} else {
		this._serviceEndpoint = endpointUrl;
	}
}

/**
* An example function demonstrating a GET request on resource <endpointUrl>/example/validate
*/
TemplateServiceClient.prototype.getMethod = function(successCallback, errorCallback) {
	this.get("QVS/validate", {}, successCallback, errorCallback);
};

/**
* An example function demonstrating a POST request on resource <endpointUrl>/example/myMethodPath/<input>
*/
TemplateServiceClient.prototype.postMethod = function(input, successCallback, errorCallback) {
	this.post("QVS/myMethodPath/" + input, {}, successCallback, errorCallback);
};

/**
* Convenience functions for sending a GET, POST, PUT and DELETE request.
* Parameters:
*   - relativePath: the path relative to the client's endpoint URL
*   - content: the content to be sent in the HTTP request's body
*   - successCallback: a callback function invoked in case the request succeeded. Expects three parameters "data", "type" and "status", where "data" represents the content of the response, "type" describes the MIME-type of the response and "status" contains the HTTP return code.
*   - errorCallback: a callback function invoked in case the request failed. Expects two parameters "error" and "status" representing the error occurred and "status" containing the HTTP error return code.
*/
TemplateServiceClient.prototype.get = function(path, content, queryParams, successCallback, errorCallback) {
	this.sendRequest("GET", path, content, queryParams, "application/json", null, successCallback, errorCallback);
};

TemplateServiceClient.prototype.post = function(path, content, queryParams, successCallback, errorCallback) {
	this.sendRequest("POST", path, content, queryParams, "application/json", null, successCallback, errorCallback);
};

TemplateServiceClient.prototype.put = function(path, content, queryParams, successCallback, errorCallback) {
	this.sendRequest("PUT", path, content, queryParams, "application/json", null, successCallback, errorCallback);
};

TemplateServiceClient.prototype.delete = function(path, content, queryParams, successCallback, errorCallback) {
	this.sendRequest("DELETE", path, content, queryParams, "application/json", null, successCallback, errorCallback);
};

/**
* sends an AJAX request to a resource.
* Parameters:
*   - method: the HTTP method used
*	- relativePath: the path relative to the client's endpoint URL
*   - content: the content to be sent in the HTTP request's body
*   - queryParams: Parameters that are added to the URL.
*   - mime: the MIME-type of the content
*   - customHeaders: a JSON string with additional header parameters to be sent
*   - successCallback: a callback function invoked in case the request succeeded. Expects three parameters "data", "type" and "status", where "data" represents the content of the response, "type" describes the MIME-type of the response and "status" contains the HTTP return code.
*   - errorCallback: a callback function invoked in case the request failed. Expects two parameters "error" and "status" representing the error occurred and "status" containing the HTTP error return code.
*
*/
TemplateServiceClient.prototype.sendRequest = function(method, relativePath, content, queryParams, mime, customHeaders, successCallback, errorCallback) {
	var mtype = "text/plain; charset=UTF-8";
	if(typeof mime !== "undefined") {
		mtype = mime;
	}

	var rurl = this._serviceEndpoint + "/" + relativePath;

	if(this.loggedIn()){
		console.log("Authenticated request");
		if(rurl.indexOf("?") > 0){
			rurl += "&access_token=" + window.localStorage.access_token;
		} else {
			rurl += "?access_token=" + window.localStorage.access_token;
		}
	} else {
		console.log("Anonymous request... ");
	}

    if (typeof queryParams == "object") {
        for (var param in queryParams) {
            if(rurl.indexOf("?") > 0){
                rurl += "&" + param + "=" + queryParams[param];
            } else {
                rurl += "?" + param + "=" + queryParams[param];
            }
        }
    }

	var ajaxObj = {
		url: rurl,
		type: method.toUpperCase(),
		contentType: mtype,
		crossDomain: true,

		error: function (xhr, errorType, error) {
			console.log(error);
			var errorText = error;
			if (xhr.responseText !== null && xhr.responseText.trim().length > 0) {
				errorText = xhr.responseText;
			}
			errorCallback(errorText, xhr.status);
		},
		success: function (data, status, xhr) {
			var type = xhr.getResponseHeader("Content-Type");
			successCallback(data, type, xhr.status);
		},
	};

    if (content) {
        ajaxObj.data = JSON.stringify(content);
    }

	if (typeof customHeaders !== "undefined" && customHeaders !== null) {
		$.extend(ajaxObj.headers, customHeaders);
	}

	$.ajax(ajaxObj);
};

/**
* determines if user is authenticated via OpenID Connect or not.
*/
TemplateServiceClient.prototype.isAnonymous = function(){
    return !this.loggedIn();
};

/**
* determines if user is authenticated via OpenID Connect or not in a more obvious way.
*/
TemplateServiceClient.prototype.loggedIn = function(){
	if (typeof oidc_userinfo !== "undefined"){
		return true;
	} else {
		return false;
	}
};

/**
* Convenience function to check if a String ends with a given suffix.
*/
String.prototype.endsWith = function(suffix) {
	return this.indexOf(suffix, this.length - suffix.length) !== -1;
};


text:
package sri.universal.router

import sri.core.{ReactComponentJS, ReactJSProps, ReactComponent}

import scala.scalajs.js
import scala.scalajs.js.annotation.ScalaJSDefined

@ScalaJSDefined
abstract class UniversalRouterComponent[P, S] extends ReactComponent[P, S] {

  private var ctrl: UniversalRouterCtrl = _

  /**
   * reference to ctrl , you can use this to pass router control outside of component scope (example BackAndroid)
   * @return
   */
  def getRouterCtrl() = ctrl

  //TODO move this logic to secondary constructor ? when they are supported
  override def componentWillMount(): Unit = {
    ctrl = context.routerctrl.asInstanceOf[UniversalRouterCtrl]
  }

  /**
   * use this method to navigate to static pages ,it pushes new scene to the stack
   * @param page
   */
  def navigateTo(page: StaticPage) = ctrl.navigateTo(page)

  def navigateTo[T](page: DynamicPage[T], props: T, title: String) = ctrl.navigateTo(page, props, title)

  /**
   * it will take you to initial route/home route
   */
  def navigateToHome() = ctrl.navigateToHome()

  /**
   * navigates to previous route by unmounting current scene ,
   * if you call this on route stack on < 2 it will throw error so please us showbackButton() boolean as guard
   */
  def navigateBack() = ctrl.navigateBack()

  /**
   * it reloads the previous scene and pop current scene
   */
  def navigateBackAndReloadPrevious() = ctrl.navigateBackAndReloadPrevious()

  /**
   * use this method to replace previous route with static route and go back
   */
  def navigateBackAndReplacePrevious(page: StaticPage) = ctrl.navigateBackAndReplacePrevious(page)

  /**
   * use this method to replace previous route with dynamic route and go back
   */
  def navigateBackAndReplacePrevious[T](page: DynamicPage[T], props: T, title: String) = ctrl.navigateBackAndReplacePrevious(page,props,title)

  /**
   * use this method to replace the current scene with new scene
   * @param page
   */
  def replace(page: StaticPage) = ctrl.replace(page)
  /**
   * This is kinda hacky , use this method when you want to replace entire routestack with a new route
   * @param page
   */
  def resetStackWithNewRoute(page: StaticPage) = ctrl.resetStackWithNewRoute(page)

  def getCurrentRoutes() = ctrl.getCurrentRoutes()

  @inline def currentRoute = ctrl.currentRoute

  @inline def previousRoute: js.UndefOr[NavigatorRoute] = ctrl.previousRoute

}

/**
 * router component for JS props type
 * //TODO why no trait support for @ScalaJSDefined too much copy paste :(
 * @tparam P
 * @tparam S
 */
@ScalaJSDefined
abstract class UniversalRouterComponentJS[P <: ReactJSProps, S] extends ReactComponentJS[P, S] {

  private var ctrl: UniversalRouterCtrl = _

  /**
   * reference to ctrl , you can use this to pass router control outside of component scope (example BackAndroid)
   * @return
   */
  def getRouterCtrl() = ctrl

  //TODO move this logic to secondary constructor ? when they are supported
  override def componentWillMount(): Unit = {
    ctrl = context.routerctrl.asInstanceOf[UniversalRouterCtrl]
  }

  /**
   * use this method to navigate to static pages ,it pushes new scene to the stack
   * @param page
   */
  def navigateTo(page: StaticPage) = ctrl.navigateTo(page)

  def navigateTo[T](page: DynamicPage[T], props: T, title: String) = ctrl.navigateTo(page, props, title)

  /**
   * it will take you to initial route/home route
   */
  def navigateToHome() = ctrl.navigateToHome()

  /**
   * navigates to previous route by unmounting current scene ,
   * if you call this on route stack on < 2 it will throw error so please us showbackButton() boolean as guard
   */
  def navigateBack() = ctrl.navigateBack()

  /**
   * it reloads the previous scene and pop current scene
   */
  def navigateBackAndReloadPrevious() = ctrl.navigateBackAndReloadPrevious()

  /**
   * use this method to replace previous route with static route and go back
   */
  def navigateBackAndReplacePrevious(page: StaticPage) = ctrl.navigateBackAndReplacePrevious(page)

  /**
   * use this method to replace previous route with dynamic route and go back
   */
  def navigateBackAndReplacePrevious[T](page: DynamicPage[T], props: T, title: String) = ctrl.navigateBackAndReplacePrevious(page,props,title)

  /**
   * use this method to replace the current scene with new scene
   * @param page
   */
  def replace(page: StaticPage) = ctrl.replace(page)
  /**
   * This is kinda hacky , use this method when you want to replace entire routestack with a new route
   * @param page
   */
  def resetStackWithNewRoute(page: StaticPage) = ctrl.resetStackWithNewRoute(page)

  def getCurrentRoutes() = ctrl.getCurrentRoutes()

  @inline def currentRoute = ctrl.currentRoute

  @inline def previousRoute: js.UndefOr[NavigatorRoute] = ctrl.previousRoute

}


text:
package org.hibernate.validator.referenceguide.chapter02.typeargument;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;

public class Car {

	public static enum FuelConsumption {
		CITY,
		HIGHWAY
	}

	@Valid
	private List<@ValidPart String> parts = new ArrayList<>();

	@Valid
	private EnumMap<FuelConsumption, @MaxAllowedFuelConsumption Integer> fuelConsumption = new EnumMap<>(FuelConsumption.class);

	private Optional<@MinTowingCapacity(1000) Integer> towingCapacity = Optional.empty();

	private GearBox<@MinTorque(100) Gear> gearBox;

	public void addPart(String part) {
		parts.add( part );
	}

	public void setTowingCapacity(Integer alias) {
		towingCapacity = Optional.of( alias );
	}

	public void setFuelConsumption(FuelConsumption consumption, int value) {
		fuelConsumption.put( consumption, value );
	}

	public void setGearBox(GearBox<Gear> gearBox) {
		this.gearBox = gearBox;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BasketballRoster.Model;

namespace BasketballRoster.ViewModel
{
    using Model;
    using System.Collections.ObjectModel;

    class LeagueViewModel
    {
        public RosterViewModel BriansTeam { get; set; }
        public RosterViewModel JimmysTeam { get; set; }

        public LeagueViewModel()
        {
            Roster briansRoster = new Roster("The Bombers", GetBomberPlayers());
            BriansTeam = new RosterViewModel(briansRoster);

            Roster jimmysRoster = new Roster("The Amazins", GetAmazinPlayers());
            JimmysTeam = new RosterViewModel(jimmysRoster);
        }

        private IEnumerable<Player> GetBomberPlayers()
        {
            List<Player> bomberPlayers = new List<Player>() {
                new Player("Brian", 31, true),
                new Player("Lloyd", 23, true),
                new Player("Kathleen",6, true),
                new Player("Mike", 0, true),
                new Player("Joe", 42, true),
                new Player("Herb",32, false),
                new Player("Fingers",8, false),
            };
            return bomberPlayers;
        }

        private IEnumerable<Player> GetAmazinPlayers()
        {
            List<Player> amazinPlayers = new List<Player>() {
                new Player("Jimmy",42, true),
                new Player("Henry",11, true),
                new Player("Bob",4, true),
                new Player("Lucinda", 18, true),
                new Player("Kim", 16, true),
                new Player("Bertha", 23, false),
                new Player("Ed",21,  false),
            };
            return amazinPlayers;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using XenAspects;

namespace Xen2D
{
    /// <summary>
    /// Base class for 2D polygons
    /// </summary>
    public abstract class ShapePolygon2DBase<DerivedType> : ComposableObject<DerivedType>, IPolygon2D
        where DerivedType : ComposableObject, new()
    {
        public static int MaxSides = 64;

        protected Vector2[] _pointList = new Vector2[ MaxSides ];
        protected Vector2 _center;
        protected Vector2 _innerRadius;
        protected Vector2 _outerRadius;
        protected IEvent _onReset = new Event();

        public int NumSides { get; set; }

        public IEvent OnReset { get { return _onReset; } }

        /// <summary>
        /// Gets the set of vertices describing this polygon.  This is a fixed size collection, so use NumSides when enumerating instead of foreach.
        /// </summary>
        public Vector2[] Vertices
        {
            get { return _pointList; }
        }

        public Vector2 Center
        {
            get{ return _center; }
        }

        /// <summary>
        /// Gets the vector from the center to the closest point on an edge or vertex
        /// </summary>
        public Vector2 InnerRadiusVector
        {
            get { return _innerRadius; }
        }

        /// <summary>
        /// Gets the distance from the center to the closest point on an edge or vertex
        /// </summary>
        public float InnerRadius
        {
            get { return _innerRadius.Length(); }
        }

        /// <summary>
        /// Gets the vector from the center to the furthest vertex
        /// </summary>
        public Vector2 OuterRadiusVector
        {
            get { return _outerRadius; }
        }

        /// <summary>
        /// Gets the distance from the center to the furthest vertex
        /// </summary>
        public float OuterRadius
        {
            get { return _outerRadius.Length(); }
        }

        public void Reset( List<Vector2> clockwisePointList )
        {
            if( clockwisePointList.Count > MaxSides )
                throw new ArgumentException( "Too many sides" );

            if( clockwisePointList.Count < 3 )
                throw new ArgumentException( "You must have at least 3 points" );

            NumSides = clockwisePointList.Count;

            for( int i = 0; i < NumSides; i++ )
            {
                _pointList[ i ] = clockwisePointList[ i ];
            }

            ResetInternal();
        }

        public void Reset( Vector2[] clockwisePointList, int numPoints )
        {
            if( numPoints > MaxSides )
                throw new ArgumentException( "Too many sides" );

            if( numPoints < 3 )
                throw new ArgumentException( "You must have at least 3 points" );

            NumSides = numPoints;

            for( int i = 0; i < NumSides; i++ )
            {
                _pointList[ i ] = clockwisePointList[ i ];
            }

            ResetInternal();
        }

        private void ResetInternal()
        {
            _center = ShapeUtility.CalculateCenterPoint( this );
            _innerRadius = ShapeUtility.CalculateInnerRadius( this );
            _outerRadius = ShapeUtility.CalculateOuterRadius( this );

            _onReset.Notify();
        }

        public abstract bool Contains( Vector2 point );

        public Vector2 FindClosestPoint( Vector2 point )
        {
            return ShapeUtility.FindClosestPointOnPolygon( point, this );
        }

        public bool Intersects( IPolygon2D other )
        {
            return ShapeUtility.Intersects( this, other );
        }

        public bool Intersects( ICircle2D other )
        {
            return ShapeUtility.Intersects( this, other );
        }
    }
}


text:
package org.teavm.javascript.spi;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *
 * @author Alexey Andreev
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface InjectedBy {
    Class<? extends Injector> value();
}