text:
package org.bpmscript.mozilla.javascript.xmlimpl;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.EcmaError;
import org.mozilla.javascript.Kit;
import org.mozilla.javascript.Ref;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Undefined;

class XMLName extends Ref {
    static final long serialVersionUID = 3832176310755686977L;

    private static boolean isNCNameStartChar(int c) {
        if ((c & ~0x7F) == 0) {
            // Optimize for ASCII and use A..Z < _ < a..z
            if (c >= 'a') {
                return c <= 'z';
            } else if (c >= 'A') {
                if (c <= 'Z') {
                    return true;
                }
                return c == '_';
            }
        } else if ((c & ~0x1FFF) == 0) {
            return (0xC0 <= c && c <= 0xD6)
            || (0xD8 <= c && c <= 0xF6)
            || (0xF8 <= c && c <= 0x2FF)
            || (0x370 <= c && c <= 0x37D)
            || 0x37F <= c;
        }
        return (0x200C <= c && c <= 0x200D)
        || (0x2070 <= c && c <= 0x218F)
        || (0x2C00 <= c && c <= 0x2FEF)
        || (0x3001 <= c && c <= 0xD7FF)
        || (0xF900 <= c && c <= 0xFDCF)
        || (0xFDF0 <= c && c <= 0xFFFD)
        || (0x10000 <= c && c <= 0xEFFFF);
    }

    private static boolean isNCNameChar(int c) {
        if ((c & ~0x7F) == 0) {
            // Optimize for ASCII and use - < . < 0..9 < A..Z < _ < a..z
            if (c >= 'a') {
                return c <= 'z';
            } else if (c >= 'A') {
                if (c <= 'Z') {
                    return true;
                }
                return c == '_';
            } else if (c >= '0') {
                return c <= '9';
            } else {
                return c == '-' || c == '.';
            }
        } else if ((c & ~0x1FFF) == 0) {
            return isNCNameStartChar(c) || c == 0xB7
                || (0x300 <= c && c <= 0x36F);
        }
        return isNCNameStartChar(c) || (0x203F <= c && c <= 0x2040);
    }

    //    This means "accept" in the parsing sense
    //    See ECMA357 13.1.2.1
    static boolean accept(Object nameObj) {
        String name;
        try {
            name = ScriptRuntime.toString(nameObj);
        } catch (EcmaError ee) {
            if ("TypeError".equals(ee.getName())) {
                return false;
            }
            throw ee;
        }

        // See http://w3.org/TR/xml-names11/#NT-NCName
        int length = name.length();
        if (length != 0) {
            if (isNCNameStartChar(name.charAt(0))) {
                for (int i = 1; i != length; ++i) {
                    if (!isNCNameChar(name.charAt(i))) {
                        return false;
                    }
                }
                return true;
            }
        }

        return false;
    }

    private XmlNode.QName qname;
    private boolean isAttributeName;
    private boolean isDescendants;
    private XMLObjectImpl xmlObject;

    private XMLName() {
    }

    static XMLName formStar() {
        XMLName rv = new XMLName();
        rv.qname = XmlNode.QName.create(null, null);
        return rv;
    }

    /** @deprecated */
    static XMLName formProperty(XmlNode.Namespace namespace, String localName) {
        if (localName != null && localName.equals("*")) localName = null;
        XMLName rv = new XMLName();
        rv.qname = XmlNode.QName.create(namespace, localName);
        return rv;
    }

    /** TODO: marked deprecated by original author */
    static XMLName formProperty(String uri, String localName) {
        return formProperty(XmlNode.Namespace.create(uri), localName);
    }

    /** TODO: marked deprecated by original implementor */
    static XMLName create(String defaultNamespaceUri, String name) {
        if (name == null)
            throw new IllegalArgumentException();

        int l = name.length();
        if (l != 0) {
            char firstChar = name.charAt(0);
            if (firstChar == '*') {
                if (l == 1) {
                    return XMLName.formStar();
                }
            } else if (firstChar == '@') {
                XMLName xmlName = XMLName.formProperty("", name.substring(1));
                xmlName.setAttributeName();
                return xmlName;
            }
        }

        return XMLName.formProperty(defaultNamespaceUri, name);
    }

    static XMLName create(XmlNode.QName qname, boolean attribute, boolean descendants) {
        XMLName rv = new XMLName();
        rv.qname = qname;
        rv.isAttributeName = attribute;
        rv.isDescendants = descendants;
        return rv;
    }

    /** @deprecated */
    static XMLName create(XmlNode.QName qname) {
        return create(qname, false, false);
    }

    void initXMLObject(XMLObjectImpl xmlObject) {
        if (xmlObject == null) throw new IllegalArgumentException();
        if (this.xmlObject != null) throw new IllegalStateException();
        this.xmlObject = xmlObject;
    }

    String uri() {
        if (qname.getNamespace() == null) return null;
        return qname.getNamespace().getUri();
    }

    String localName() {
        if (qname.getLocalName() == null) return "*";
        return qname.getLocalName();
    }

    private void addDescendantChildren(XMLList list, XML target) {
        XMLName xmlName = this;
        if (target.isElement()) {
            XML[] children = target.getChildren();
            for (int i=0; i<children.length; i++) {
                if (xmlName.matches( children[i] )) {
                    list.addToList( children[i] );
                }
                addDescendantChildren(list, children[i]);
            }
        }
    }

    void addMatchingAttributes(XMLList list, XML target) {
        XMLName name = this;
        if (target.isElement()) {
            XML[] attributes = target.getAttributes();
            for (int i=0; i<attributes.length; i++) {
                if (name.matches( attributes[i]) ) {
                    list.addToList( attributes[i] );
                }
            }
        }
    }

    private void addDescendantAttributes(XMLList list, XML target) {
        if (target.isElement()) {
            addMatchingAttributes(list, target);
            XML[] children = target.getChildren();
            for (int i=0; i<children.length; i++) {
                addDescendantAttributes(list, children[i]);
            }
        }
    }

    XMLList matchDescendantAttributes(XMLList rv, XML target) {
        rv.setTargets(target, null);
        addDescendantAttributes(rv, target);
        return rv;
    }

    XMLList matchDescendantChildren(XMLList rv, XML target) {
        rv.setTargets(target, null);
        addDescendantChildren(rv, target);
        return rv;
    }

    void addDescendants(XMLList rv, XML target) {
        XMLName xmlName = this;
        if (xmlName.isAttributeName()) {
            matchDescendantAttributes(rv, target);
        } else {
            matchDescendantChildren(rv, target);
        }
    }

    private void addAttributes(XMLList rv, XML target) {
        addMatchingAttributes(rv, target);
    }

    void addMatches(XMLList rv, XML target) {
        if (isDescendants()) {
            addDescendants(rv, target);
        } else if (isAttributeName()) {
            addAttributes(rv, target);
        } else {
            XML[] children = target.getChildren();
            if (children != null) {
                for (int i=0; i<children.length; i++) {
                    if (this.matches(children[i])) {
                        rv.addToList( children[i] );
                    }
                }
            }
            rv.setTargets(target, this.toQname());
        }
    }

    XMLList getMyValueOn(XML target) {
        XMLList rv = target.newXMLList();
        addMatches(rv, target);
        return rv;
    }

    void setMyValueOn(XML target, Object value) {
        // Special-case checks for undefined and null
        if (value == null) {
            value = "null";
        } else if (value instanceof Undefined) {
            value = "undefined";
        }

        XMLName xmlName = this;
        // Get the named property
        if (xmlName.isAttributeName()) {
            target.setAttribute(xmlName, value);
        } else if (xmlName.uri() == null && xmlName.localName().equals("*")) {
            target.setChildren(value);
        } else {
            // Convert text into XML if needed.
            XMLObjectImpl xmlValue = null;

            if (value instanceof XMLObjectImpl) {
                xmlValue = (XMLObjectImpl)value;

                // Check for attribute type and convert to textNode
                if (xmlValue instanceof XML) {
                    if (((XML)xmlValue).isAttribute()) {
                        xmlValue = target.makeXmlFromString(xmlName,
                                xmlValue.toString());
                    }
                }

                if (xmlValue instanceof XMLList) {
                    for (int i = 0; i < xmlValue.length(); i++) {
                        XML xml = ((XMLList) xmlValue).item(i);

                        if (xml.isAttribute()) {
                            ((XMLList)xmlValue).replace(i, target.makeXmlFromString(xmlName, xml.toString()));
                        }
                    }
                }
            } else {
                xmlValue = target.makeXmlFromString(xmlName, ScriptRuntime.toString(value));
            }

            XMLList matches = target.getPropertyList(xmlName);

            if (matches.length() == 0) {
                target.appendChild(xmlValue);
            } else {
                // Remove all other matches
                for (int i = 1; i < matches.length(); i++) {
                    target.removeChild(matches.item(i).childIndex());
                }

                // Replace first match with new value.
                XML firstMatch = matches.item(0);
                target.replace(firstMatch.childIndex(), xmlValue);
            }
        }
    }

    @Override
    public boolean has(Context cx) {
        if (xmlObject == null) {
            return false;
        }
        return xmlObject.hasXMLProperty(this);
    }

    @Override
    public Object get(Context cx) {
        if (xmlObject == null) {
            throw ScriptRuntime.undefReadError(Undefined.instance,
                toString());
        }
        return xmlObject.getXMLProperty(this);
    }

    @Override
    public Object set(Context cx, Object value) {
        if (xmlObject == null) {
            throw ScriptRuntime.undefWriteError(Undefined.instance,
                toString(),
                value);
        }
        // Assignment to descendants causes parse error on bad reference
        // and this should not be called
        if (isDescendants) throw Kit.codeBug();
        xmlObject.putXMLProperty(this, value);
        return value;
    }

    @Override
    public boolean delete(Context cx) {
        if (xmlObject == null) {
            return true;
        }
        xmlObject.deleteXMLProperty(this);
        return !xmlObject.hasXMLProperty(this);
    }

    @Override
    public String toString() {
        //return qname.localName();
        StringBuffer buff = new StringBuffer();
        if (isDescendants) buff.append("..");
        if (isAttributeName) buff.append('@');
        if (uri() == null) {
            buff.append('*');
            if(localName().equals("*")) {
                return buff.toString();
            }
        } else {
            buff.append('"').append(uri()).append('"');
        }
        buff.append(':').append(localName());
        return buff.toString();
    }

    final XmlNode.QName toQname() {
        return this.qname;
    }

    final boolean matchesLocalName(String localName) {
        return localName().equals("*") || localName().equals(localName);
    }

    final boolean matchesElement(XmlNode.QName qname) {
        if (this.uri() == null || this.uri().equals(qname.getNamespace().getUri())) {
            if (this.localName().equals("*") || this.localName().equals(qname.getLocalName())) {
                return true;
            }
        }
        return false;
    }

    final boolean matches(XML node) {
        XmlNode.QName qname = node.getNodeQname();
        String nodeUri = null;
        if (qname.getNamespace() != null) {
            nodeUri = qname.getNamespace().getUri();
        }
        if (isAttributeName) {
            if (node.isAttribute()) {
                if (this.uri() == null || this.uri().equals(nodeUri)) {
                    if (this.localName().equals("*") || this.localName().equals(qname.getLocalName())) {
                        return true;
                    }
                }
                return false;
            } else {
                //    TODO    Could throw exception maybe, should not call this method on attribute name with arbitrary node type
                //            unless we traverse all attributes and children habitually
                return false;
            }
        } else {
            if ( this.uri() == null || ((node.isElement()) && this.uri().equals(nodeUri)) ) {
                if (localName().equals("*")) return true;
                if (node.isElement()) {
                    if (localName().equals(qname.getLocalName())) return true;
                }
            }
            return false;
        }
    }

    /* TODO: marked deprecated by original author */
    boolean isAttributeName() {
        return isAttributeName;
    }

    // TODO Fix whether this is an attribute XMLName at construction?
    // Marked deprecated by original author
    void setAttributeName() {
//        if (isAttributeName) throw new IllegalStateException();
        isAttributeName = true;
    }

    /* TODO: was marked deprecated by original author */
    boolean isDescendants() {
        return isDescendants;
    }

    //    TODO    Fix whether this is an descendant XMLName at construction?
    /** @deprecated */
    void setIsDescendants() {
//        if (isDescendants) throw new IllegalStateException();
        isDescendants = true;
    }
}


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.

/*****************************************************************************/
// <OWNER>clrjit</OWNER>
//
// This class abstracts the telemetry information collected for the JIT.
//
// Goals:
//    1. Telemetry information should be a NO-op when JIT level telemetry is disabled.
//    2. Data collection should be actionable.
//    3. Data collection should comply to privacy rules.
//    4. Data collection cannot impact JIT/OS performance.
//    5. Data collection volume should be manageable by our remote services.
//
// DESIGN CONCERNS:
//
// > To collect data, we use the TraceLogging API provided by Windows.
//
//   The brief workflow suggested is:
//     #include <TraceLoggingProvider.h>
//     TRACELOGGING_DEFINE_PROVIDER( // defines g_hProvider
//         g_hProvider,  // Name of the provider variable
//         "MyProvider", // Human-readable name of the provider
//         (0xb3864c38, 0x4273, 0x58c5, 0x54, 0x5b, 0x8b, 0x36, 0x08, 0x34, 0x34, 0x71)); // Provider GUID
//     int main(int argc, char* argv[]) // or DriverEntry for kernel-mode.
//     {
//         TraceLoggingRegister(g_hProvider, NULL, NULL, NULL); // NULLs only needed for C. Please do not include the NULLs in C++ code.
//         TraceLoggingWrite(g_hProvider,
//            "MyEvent1",
//            TraceLoggingString(argv[0], "arg0"),
//            TraceLoggingInt32(argc));
//         TraceLoggingUnregister(g_hProvider);
//         return 0;
//     }
//
//     In summary, this involves:
//     1. Creating a binary/DLL local provider using:
//        TRACELOGGING_DEFINE_PROVIDER(g_hProvider, "ProviderName", providerId, [option])
//     2. Registering the provider instance
//        TraceLoggingRegister(g_hProvider)
//     3. Perform TraceLoggingWrite operations to write out data.
//     4. Unregister the provider instance.
//        TraceLoggingUnregister(g_hProvider)
//
//     A. Determining where to create the provider instance?
//        1) We use the same provider name/GUID as the CLR and the CLR creates its own DLL local provider handle.
//           For CLRJIT.dll, the question is, can the same provider name/GUIDs be shared across binaries?
//
//           Answer:
//           "For TraceLogging providers, it is okay to use the same provider GUID / name
//           in different binaries. Do not share the same provider handle across DLLs.
//           As long as you do not pass an hProvider from one DLL to another, TraceLogging
//           will properly keep track of the events."
//
//        2) CoreCLR is linked into the CLR. CLR already creates an instance, so where do we create the JIT's instance?
//            Answer:
//            "Ideally you would have one provider per DLL, but if you're folding distinct sets
//            of functionality into one DLL (like shell32.dll or similar sort of catch-all things)
//            you can have perhaps a few more providers per binary."
//
//    B. Determining where to register and unregister the provider instance?
//         1) For CLRJIT.dll we can register the provider instance during jitDllOnProcessAttach.
//            Since one of our goals is to turn telemetry off, we need to be careful about
//            referencing environment variables during the DLL load and unload path.
//            Referencing environment variables through ConfigDWORD uses UtilCode.
//            This roughly translates to InitUtilcode() being called before jitDllOnProcessAttach.
//
//            For CLRJIT.dll, compStartup is called on jitOnDllProcessAttach().
//            This can be called twice through sxsJitStartup -- so prevent double initialization.
//            UtilCode is init-ed by this time. The same is true for CoreCLR.
//
//         2) For CLRJIT.dll and CoreCLR, compShutdown will be called during jitOnDllProcessDetach().
//
//    C. Determining the data to collect:
//
//         IMPORTANT: Since telemetry data can be collected at any time after DLL load,
//         make sure you initialize the compiler state variables you access in telemetry
//         data collection. For example, if you are transmitting method names, then
//         make sure info.compMethodHnd is initialized at that point.
//
//         1) Tracking noway assert count:
//            After a noway assert is hit, in both min-opts and non-min-opts, we collect
//            info such as the JIT version, method hash being compiled, filename and
//            line number etc.
//
//         2) Tracking baseline for the noway asserts:
//            During DLL unload, we report the number of methods that were compiled by
//            the JIT per process both under normal mode and during min-opts. NOTE that
//            this is ON for all processes.
//
//         3) For the future, be aware of privacy, performance and actionability of the data.
//

#include "jitpch.h"
#include "compiler.h"

#ifdef FEATURE_TRACELOGGING
#include "TraceLoggingProvider.h"
#include "MicrosoftTelemetry.h"
#include "clrtraceloggingcommon.h"
#include "fxver.h"

// Since telemetry code could be called under a noway_assert, make sure,
// we don't call noway_assert again.
#undef noway_assert

#define BUILD_STR1(x) #x
#define BUILD_STR2(x) BUILD_STR1(x)
#define BUILD_MACHINE BUILD_STR2(__BUILDMACHINE__)

// A DLL local instance of the DotNet provider
TRACELOGGING_DEFINE_PROVIDER(g_hClrJitProvider, CLRJIT_PROVIDER_NAME, CLRJIT_PROVIDER_ID, TraceLoggingOptionMicrosoftTelemetry());

// Threshold to detect if we are hitting too many bad (noway) methods
// over good methods per process to prevent logging too much data.
static const double NOWAY_NOISE_RATIO                       = 0.6; // Threshold of (bad / total) beyond which we'd stop logging. We'd restart if the pass rate improves.
static const unsigned NOWAY_SUFFICIENCY_THRESHOLD           = 25;  // Count of methods beyond which we'd apply percent threshold

// Initialize Telemetry State
volatile bool     JitTelemetry::s_fProviderRegistered     = false;
volatile UINT32 JitTelemetry::s_uMethodsCompiled          = 0;
volatile UINT32 JitTelemetry::s_uMethodsHitNowayAssert    = 0;

// Constructor for telemetry state per compiler instance
JitTelemetry::JitTelemetry()
{
    Initialize(nullptr);
}

//------------------------------------------------------------------------
// Initialize: Initialize the object with the compiler instance
//
//  Description:
//     Compiler instance may not be fully initialized. If you are
//     tracking object data for telemetry, make sure they are initialized
//     in the compiler is ready.
//
void JitTelemetry::Initialize(Compiler* c)
{
    comp = c;
    m_pszAssemblyName = "";
    m_pszScopeName = "";
    m_pszMethodName = "";
    m_uMethodHash = 0;
    m_fMethodInfoCached = false;
}

//------------------------------------------------------------------------
// IsTelemetryEnabled: Can we perform JIT telemetry
//
//  Return Value:
//      Returns "true" if COMPlus_JitTelemetry environment flag is
//      non-zero. Else returns "false".
//
//
/* static */
bool JitTelemetry::IsTelemetryEnabled()
{
    return JitConfig.JitTelemetry() != 0;
}

//------------------------------------------------------------------------
// NotifyDllProcessAttach: Notification for DLL load and static initializations
//
//  Description:
//     Register telemetry provider with the OS.
//
//  Note:
//     This method can be called twice in NGEN scenario.
//
void JitTelemetry::NotifyDllProcessAttach()
{
    if (!IsTelemetryEnabled())
    {
        return;
    }

    if (!s_fProviderRegistered)
    {
        // Register the provider.
        TraceLoggingRegister(g_hClrJitProvider);
        s_fProviderRegistered = true;
    }
}

//------------------------------------------------------------------------
// NotifyDllProcessDetach: Notification for DLL unload and teardown
//
//  Description:
//     Log the methods compiled data if telemetry is enabled and
//     Unregister telemetry provider with the OS.
//
void JitTelemetry::NotifyDllProcessDetach()
{
    if (!IsTelemetryEnabled())
    {
        return;
    }

    assert(s_fProviderRegistered); // volatile read

    // Unregister the provider.
    TraceLoggingUnregister(g_hClrJitProvider);
}

//------------------------------------------------------------------------
// NotifyEndOfCompilation: Notification for end of current method
//     compilation.
//
//  Description:
//      Increment static volatile counters for the current compiled method.
//      This is slightly inaccurate due to lack of synchronization around
//      the counters. Inaccuracy is the tradeoff for JITting cost.
//
//  Note:
//      1. Must be called post fully successful compilation of the method.
//      2. This serves as an effective baseline as how many methods compiled
//         successfully.
void JitTelemetry::NotifyEndOfCompilation()
{
    if (!IsTelemetryEnabled())
    {
        return;
    }

    s_uMethodsCompiled++; // volatile increment
}

//------------------------------------------------------------------------
// NotifyNowayAssert: Notification that a noway handling is under-way.
//
//  Arguments:
//      filename - The JIT source file name's absolute path at the time of
//                 building the JIT.
//      line     - The line number where the noway assert was hit.
//
//  Description:
//      If telemetry is enabled, then obtain data to collect from the
//      compiler or the VM and use the tracelogging APIs to write out.
//
void JitTelemetry::NotifyNowayAssert(const char* filename, unsigned line)
{
    if (!IsTelemetryEnabled())
    {
        return;
    }

    s_uMethodsHitNowayAssert++;

    // Check if our assumption that noways are rare is invalid for this
    // process. If so, return early than logging too much data.
    unsigned noways = s_uMethodsHitNowayAssert;
    unsigned attempts = max(1, s_uMethodsCompiled + noways);
    double ratio = (noways / ((double) attempts));
    if (noways > NOWAY_SUFFICIENCY_THRESHOLD && ratio > NOWAY_NOISE_RATIO)
    {
        return;
    }

    assert(comp);

    UINT32 nowayIndex = s_uMethodsHitNowayAssert;
    UINT32 codeSize = 0;
    INT32 minOpts = -1;
    const char* lastPhase = "";
    if (comp != nullptr)
    {
        codeSize = comp->info.compILCodeSize;
        minOpts = comp->opts.IsMinOptsSet() ? comp->opts.MinOpts() : -1;
        lastPhase = PhaseNames[comp->previousCompletedPhase];
    }

    CacheCurrentMethodInfo();

    TraceLoggingWrite(g_hClrJitProvider,
        "CLRJIT.NowayAssert",

        TraceLoggingUInt32(codeSize, "IL_CODE_SIZE"),
        TraceLoggingInt32(minOpts, "MINOPTS_MODE"),
        TraceLoggingString(lastPhase, "PREVIOUS_COMPLETED_PHASE"),

        TraceLoggingString(m_pszAssemblyName, "ASSEMBLY_NAME"),
        TraceLoggingString(m_pszMethodName, "METHOD_NAME"),
        TraceLoggingString(m_pszScopeName, "METHOD_SCOPE"),
        TraceLoggingUInt32(m_uMethodHash, "METHOD_HASH"),

        TraceLoggingString(filename, "FILENAME"),
        TraceLoggingUInt32(line, "LINE"),
        TraceLoggingUInt32(nowayIndex, "NOWAY_INDEX"),

        TraceLoggingString(TARGET_READABLE_NAME, "ARCH"),
        TraceLoggingString(VER_FILEVERSION_STR, "VERSION"),
        TraceLoggingString(BUILD_MACHINE, "BUILD"),
        TraceLoggingString(VER_COMMENTS_STR, "FLAVOR"),

        TraceLoggingKeyword(MICROSOFT_KEYWORD_TELEMETRY));
}

//------------------------------------------------------------------------
// CacheCurrentMethodInfo: Cache the method/assembly/scope name info.
//
//  Description:
//      Obtain the method information if not already cached, for the
//      method under compilation from the compiler. This includes:
//
//          Method name, assembly name, scope name, method hash.
//
void JitTelemetry::CacheCurrentMethodInfo()
{
    if (m_fMethodInfoCached)
    {
        return;
    }

    assert(comp);
    if (comp != nullptr)
    {
        comp->compGetTelemetryDefaults(&m_pszAssemblyName, &m_pszScopeName, &m_pszMethodName, &m_uMethodHash);
        assert(m_pszAssemblyName);
        assert(m_pszScopeName);
        assert(m_pszMethodName);
    }

    // Set cached to prevent getting this twice.
    m_fMethodInfoCached = true;
}

//------------------------------------------------------------------------
// compGetTelemetryDefaults: Obtain information specific to telemetry
//      from the JIT-interface.
//
//  Arguments:
//      assemblyName - Pointer to hold assembly name upon return
//      scopeName    - Pointer to hold scope name upon return
//      methodName   - Pointer to hold method name upon return
//      methodHash   - Pointer to hold method hash upon return
//
//  Description:
//      Obtains from the JIT EE interface the information for the
//      current method under compilation.
//
//  Warning:
//      The eeGetMethodName call could be expensive for generic
//      methods, so call this method only when there is less impact
//      to throughput.
//
void Compiler::compGetTelemetryDefaults(const char** assemblyName, const char** scopeName, const char** methodName, unsigned* methodHash)
{
    if (info.compMethodHnd != nullptr)
    {
        __try
        {

            // Expensive calls, call infrequently or in exceptional scenarios.
            *methodHash = info.compCompHnd->getMethodHash(info.compMethodHnd);
            *methodName = eeGetMethodName(info.compMethodHnd, scopeName);

            // SuperPMI needs to implement record/replay of these method calls.
            *assemblyName = info.compCompHnd->getAssemblyName(
                    info.compCompHnd->getModuleAssembly(
                        info.compCompHnd->getClassModule(info.compClassHnd)));
        }
        __except (EXCEPTION_EXECUTE_HANDLER)
        {
        }
    }

    // If the JIT interface methods init-ed these values to nullptr,
    // make sure they are set to empty string.
    if (*methodName == nullptr)
    {
        *methodName = "";
    }
    if (*scopeName == nullptr)
    {
        *scopeName = "";
    }
    if (*assemblyName == nullptr)
    {
        *assemblyName = "";
    }
}

#endif // FEATURE_TRACELOGGING

redpajama_set_name: RedPajamaGithub


text:
package io.leopard.web.freemarker;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import io.leopard.web.freemarker.htdocs.ClassPathHtdocs;

/**
 * 资源文件访问.
 *
 * @author 阿海
 */
public abstract class AbstractFileServlet extends ClassPathHtdocs {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String filename = request.getParameter("f");
		if (StringUtils.isEmpty(filename)) {
			throw new IllegalArgumentException("文件名不能为空.");
		}
		this.doFile(request, response, filename);
	}

	// @Override
	// public String getHtdocsPath() {
	// throw new NotImplementedException();
	// }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.storage.file.datalake;

import com.azure.core.http.rest.Response;
import com.azure.storage.file.datalake.models.DataLakeAccessPolicy;
import com.azure.storage.file.datalake.models.DataLakeRequestConditions;
import com.azure.storage.file.datalake.models.DataLakeSignedIdentifier;
import com.azure.storage.file.datalake.models.ListPathsOptions;
import com.azure.storage.file.datalake.models.PathHttpHeaders;
import com.azure.storage.file.datalake.models.PublicAccessType;
import com.azure.storage.file.datalake.models.UserDelegationKey;
import com.azure.storage.file.datalake.sas.DataLakeServiceSasSignatureValues;
import com.azure.storage.file.datalake.sas.FileSystemSasPermission;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Code snippets for {@link DataLakeFileSystemAsyncClient}
 */
@SuppressWarnings({"unused"})
public class FileSystemAsyncClientJavaDocCodeSamples {

    private DataLakeFileSystemAsyncClient client = JavaDocCodeSnippetsHelpers.getFileSystemAsyncClient();
    private String fileName = "fileName";
    private String directoryName = "directoryName";
    private String leaseId = "leaseId";
    private String proposedId = "proposedId";
    private int leaseDuration = (int) Duration.ofSeconds(30).getSeconds();
    private UserDelegationKey userDelegationKey = JavaDocCodeSnippetsHelpers.getUserDelegationKey();

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#getFileAsyncClient(String)}
     */
    public void getFileAsyncClient() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getFileAsyncClient#String
        DataLakeFileAsyncClient dataLakeFileAsyncClient = client.getFileAsyncClient(fileName);
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getFileAsyncClient#String
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#getDirectoryAsyncClient(String)}
     */
    public void getDirectoryAsyncClient() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getDirectoryAsyncClient#String
        DataLakeDirectoryAsyncClient dataLakeDirectoryAsyncClient = client.getDirectoryAsyncClient(directoryName);
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getDirectoryAsyncClient#String
    }

    /**
     * Generates a code sample for using {@link DataLakeFileSystemAsyncClient#getFileSystemName()}
     */
    public void getFileSystemName() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getFileSystemName
        String fileSystemName = client.getFileSystemName();
        System.out.println("The name of the file system is " + fileSystemName);
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getFileSystemName
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#create()}
     */
    public void create() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.create
        client.create().subscribe(
            response -> System.out.printf("Create completed%n"),
            error -> System.out.printf("Error while creating file system %s%n", error));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.create
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#createWithResponse(Map, PublicAccessType)}
     */
    public void create2() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.createWithResponse#Map-PublicAccessType
        Map<String, String> metadata = Collections.singletonMap("metadata", "value");
        client.createWithResponse(metadata, PublicAccessType.CONTAINER).subscribe(response ->
            System.out.printf("Create completed with status %d%n", response.getStatusCode()));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.createWithResponse#Map-PublicAccessType
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#delete()}
     */
    public void delete() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.delete
        client.delete().subscribe(
            response -> System.out.printf("Delete completed%n"),
            error -> System.out.printf("Delete failed: %s%n", error));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.delete
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#deleteWithResponse(DataLakeRequestConditions)}
     */
    public void delete2() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.deleteWithResponse#DataLakeRequestConditions
        DataLakeRequestConditions requestConditions = new DataLakeRequestConditions()
            .setLeaseId(leaseId)
            .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3));

        client.deleteWithResponse(requestConditions).subscribe(response ->
            System.out.printf("Delete completed with status %d%n", response.getStatusCode()));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.deleteWithResponse#DataLakeRequestConditions
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#getProperties()}
     */
    public void getProperties() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getProperties
        client.getProperties().subscribe(response ->
            System.out.printf("Public Access Type: %s, Legal Hold? %b, Immutable? %b%n",
                response.getDataLakePublicAccess(),
                response.hasLegalHold(),
                response.hasImmutabilityPolicy()));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getProperties
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#getPropertiesWithResponse(String)}
     */
    public void getProperties2() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getPropertiesWithResponse#String

        client.getPropertiesWithResponse(leaseId).subscribe(response ->
            System.out.printf("Public Access Type: %s, Legal Hold? %b, Immutable? %b%n",
                response.getValue().getDataLakePublicAccess(),
                response.getValue().hasLegalHold(),
                response.getValue().hasImmutabilityPolicy()));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getPropertiesWithResponse#String
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#setMetadata(Map)}
     */
    public void setMetadata() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.setMetadata#Map
        Map<String, String> metadata = Collections.singletonMap("metadata", "value");
        client.setMetadata(metadata).subscribe(
            response -> System.out.printf("Set metadata completed%n"),
            error -> System.out.printf("Set metadata failed: %s%n", error));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.setMetadata#Map
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#setMetadataWithResponse(Map, DataLakeRequestConditions)}
     */
    public void setMetadata2() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.setMetadataWithResponse#Map-DataLakeRequestConditions
        Map<String, String> metadata = Collections.singletonMap("metadata", "value");
        DataLakeRequestConditions requestConditions = new DataLakeRequestConditions()
            .setLeaseId(leaseId)
            .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3));

        client.setMetadataWithResponse(metadata, requestConditions).subscribe(response ->
            System.out.printf("Set metadata completed with status %d%n", response.getStatusCode()));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.setMetadataWithResponse#Map-DataLakeRequestConditions
    }

    /**
     * Code snippets for {@link DataLakeFileSystemAsyncClient#createFile(String)} and
     * {@link DataLakeFileSystemAsyncClient#createFileWithResponse(String, String, String, PathHttpHeaders, Map, DataLakeRequestConditions)}
     */
    public void createFileCodeSnippets() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.createFile#String
        Mono<DataLakeFileAsyncClient> fileClient = client.createFile(fileName);
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.createFile#String

        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.createFileWithResponse#String-String-String-PathHttpHeaders-Map-DataLakeRequestConditions
        PathHttpHeaders httpHeaders = new PathHttpHeaders()
            .setContentLanguage("en-US")
            .setContentType("binary");
        DataLakeRequestConditions requestConditions = new DataLakeRequestConditions()
            .setLeaseId(leaseId);
        String permissions = "permissions";
        String umask = "umask";
        Mono<Response<DataLakeFileAsyncClient>> newFileClient = client.createFileWithResponse(fileName, permissions,
            umask, httpHeaders, Collections.singletonMap("metadata", "value"), requestConditions);
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.createFileWithResponse#String-String-String-PathHttpHeaders-Map-DataLakeRequestConditions
    }

    /**
     * Code snippets for {@link DataLakeFileSystemAsyncClient#deleteFile(String)} and
     * {@link DataLakeFileSystemAsyncClient#deleteFileWithResponse(String, DataLakeRequestConditions)}
     */
    public void deleteFileCodeSnippets() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.deleteFile#String
        client.deleteFile(fileName).subscribe(response ->
            System.out.println("Delete request completed"));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.deleteFile#String

        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.deleteFileWithResponse#String-DataLakeRequestConditions
        DataLakeRequestConditions requestConditions = new DataLakeRequestConditions()
            .setLeaseId(leaseId);

        client.deleteFileWithResponse(fileName, requestConditions)
            .subscribe(response -> System.out.println("Delete request completed"));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.deleteFileWithResponse#String-DataLakeRequestConditions
    }

    /**
     * Code snippets for {@link DataLakeFileSystemAsyncClient#createDirectory(String)} and
     * {@link DataLakeFileSystemAsyncClient#createDirectoryWithResponse(String, String, String, PathHttpHeaders, Map, DataLakeRequestConditions)}
     */
    public void createDirectoryCodeSnippets() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.createDirectory#String
        Mono<DataLakeDirectoryAsyncClient> directoryClient = client.createDirectory(fileName);
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.createDirectory#String

        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.createDirectoryWithResponse#String-String-String-PathHttpHeaders-Map-DataLakeRequestConditions
        PathHttpHeaders httpHeaders = new PathHttpHeaders()
            .setContentLanguage("en-US")
            .setContentType("binary");
        DataLakeRequestConditions requestConditions = new DataLakeRequestConditions()
            .setLeaseId(leaseId);
        String permissions = "permissions";
        String umask = "umask";
        Mono<Response<DataLakeDirectoryAsyncClient>> newDirectoryClient = client.createDirectoryWithResponse(fileName,
            permissions, umask, httpHeaders, Collections.singletonMap("metadata", "value"), requestConditions);
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.createDirectoryWithResponse#String-String-String-PathHttpHeaders-Map-DataLakeRequestConditions
    }

    /**
     * Code snippets for {@link DataLakeFileSystemAsyncClient#deleteDirectory(String)} and
     * {@link DataLakeFileSystemAsyncClient#deleteDirectoryWithResponse(String, boolean, DataLakeRequestConditions)}
     */
    public void deleteDirectoryCodeSnippets() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.deleteDirectory#String
        client.deleteDirectory(directoryName).subscribe(response ->
            System.out.println("Delete request completed"));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.deleteDirectory#String

        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.deleteDirectoryWithResponse#String-boolean-DataLakeRequestConditions
        DataLakeRequestConditions requestConditions = new DataLakeRequestConditions()
            .setLeaseId(leaseId);
        boolean recursive = false; // Default value

        client.deleteDirectoryWithResponse(directoryName, recursive, requestConditions)
            .subscribe(response -> System.out.println("Delete request completed"));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.deleteDirectoryWithResponse#String-boolean-DataLakeRequestConditions
    }

    /**
     * Code snippets for {@link DataLakeFileSystemAsyncClient#listPaths()} and
     * {@link DataLakeFileSystemAsyncClient#listPaths(ListPathsOptions)}
     */
    public void listPaths() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.listPaths
        client.listPaths().subscribe(path -> System.out.printf("Name: %s%n", path.getName()));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.listPaths

        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.listPaths#ListPathsOptions
        ListPathsOptions options = new ListPathsOptions()
            .setPath("PathNamePrefixToMatch")
            .setMaxResults(10);

        client.listPaths(options).subscribe(path -> System.out.printf("Name: %s%n", path.getName()));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.listPaths#ListPathsOptions
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#getAccessPolicy()}
     */
    public void getAccessPolicy() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getAccessPolicy
        client.getAccessPolicy().subscribe(response -> {
            System.out.printf("Data Lake Access Type: %s%n", response.getDataLakeAccessType());

            for (DataLakeSignedIdentifier identifier : response.getIdentifiers()) {
                System.out.printf("Identifier Name: %s, Permissions %s%n",
                    identifier.getId(),
                    identifier.getAccessPolicy().getPermissions());
            }
        });
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getAccessPolicy
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#getAccessPolicyWithResponse(String)}
     */
    public void getAccessPolicy2() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getAccessPolicyWithResponse#String
        client.getAccessPolicyWithResponse(leaseId).subscribe(response -> {
            System.out.printf("Data Lake Access Type: %s%n", response.getValue().getDataLakeAccessType());

            for (DataLakeSignedIdentifier identifier : response.getValue().getIdentifiers()) {
                System.out.printf("Identifier Name: %s, Permissions %s%n",
                    identifier.getId(),
                    identifier.getAccessPolicy().getPermissions());
            }
        });
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.getAccessPolicyWithResponse#String
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#setAccessPolicy(PublicAccessType, List)}
     */
    public void setAccessPolicy() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.setAccessPolicy#PublicAccessType-List
        DataLakeSignedIdentifier identifier = new DataLakeSignedIdentifier()
            .setId("name")
            .setAccessPolicy(new DataLakeAccessPolicy()
                .setStartsOn(OffsetDateTime.now())
                .setExpiresOn(OffsetDateTime.now().plusDays(7))
                .setPermissions("permissionString"));

        client.setAccessPolicy(PublicAccessType.CONTAINER, Collections.singletonList(identifier)).subscribe(
            response -> System.out.printf("Set access policy completed%n"),
            error -> System.out.printf("Set access policy failed: %s%n", error));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.setAccessPolicy#PublicAccessType-List
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#setAccessPolicyWithResponse(PublicAccessType, List, DataLakeRequestConditions)}
     */
    public void setAccessPolicy2() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.setAccessPolicyWithResponse#PublicAccessType-List-DataLakeRequestConditions
        DataLakeSignedIdentifier identifier = new DataLakeSignedIdentifier()
            .setId("name")
            .setAccessPolicy(new DataLakeAccessPolicy()
                .setStartsOn(OffsetDateTime.now())
                .setExpiresOn(OffsetDateTime.now().plusDays(7))
                .setPermissions("permissionString"));

        DataLakeRequestConditions requestConditions = new DataLakeRequestConditions()
            .setLeaseId(leaseId)
            .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3));

        client.setAccessPolicyWithResponse(PublicAccessType.CONTAINER, Collections.singletonList(identifier), requestConditions)
            .subscribe(response ->
                System.out.printf("Set access policy completed with status %d%n", response.getStatusCode()));
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.setAccessPolicyWithResponse#PublicAccessType-List-DataLakeRequestConditions
    }

    /**
     * Code snippet for {@link DataLakeFileSystemAsyncClient#generateUserDelegationSas(DataLakeServiceSasSignatureValues, UserDelegationKey)}
     * and {@link DataLakeFileSystemAsyncClient#generateSas(DataLakeServiceSasSignatureValues)}
     */
    public void generateSas() {
        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.generateSas#DataLakeServiceSasSignatureValues
        OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1);
        FileSystemSasPermission permission = new FileSystemSasPermission().setReadPermission(true);

        DataLakeServiceSasSignatureValues values = new DataLakeServiceSasSignatureValues(expiryTime, permission)
            .setStartTime(OffsetDateTime.now());

        client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.generateSas#DataLakeServiceSasSignatureValues

        // BEGIN: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.generateUserDelegationSas#DataLakeServiceSasSignatureValues-UserDelegationKey
        OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1);
        FileSystemSasPermission myPermission = new FileSystemSasPermission().setReadPermission(true);

        DataLakeServiceSasSignatureValues myValues = new DataLakeServiceSasSignatureValues(expiryTime, permission)
            .setStartTime(OffsetDateTime.now());

        client.generateUserDelegationSas(values, userDelegationKey);
        // END: com.azure.storage.file.datalake.DataLakeFileSystemAsyncClient.generateUserDelegationSas#DataLakeServiceSasSignatureValues-UserDelegationKey
    }

}


text:
package com.huskygames.rekhid.slugger.resource.sprite;

import com.huskygames.rekhid.slugger.actor.Fighter;

public class SpriteState {

    public SpriteSequence getSequence() {
        return sequence;
    }

    private final SpriteSequence sequence;

    private int cur = 0;
    private int temp = 0;
    private boolean loop;
    private Fighter parent;

    public SpriteState(SpriteSequence sequence, boolean loop, int start, Fighter parent) {
        this.sequence = sequence;
        this.loop = loop;
        this.cur = start;
        this.parent = parent;
    }

    public int getX() {
        return sequence.row[cur];
    }

    public int getY() {
        return sequence.col[cur];
    }

    public int getFrames() {
        return sequence.frames[cur];
    }

    public void next() {
        if (sequence.frames[cur] - temp > 0) {
            temp++;
        } else {
            temp = 0;
            if (cur+1 == sequence.row.length && !loop) {
                parent.endAnimation();
            }
            else {
                cur = (cur + 1) % sequence.row.length;
            }
        }
    }
}


text:
/**
 * Created by Luis Montero on 7/18/2016.
 */
function parseFromDateTimeToDate(date) {
  var day = date.getDate();
  var month = date.getMonth() + 1;
  var year = date.getFullYear();

  var newDay = day < 10 ? ('0' + day) : ('' + day);
  var newMonth = month < 10 ? ('0' + month) : ('' + month);
  var newYear = '' + year;

  return newDay + '/' + newMonth + '/' + newYear;
}

module.exports = {
  parseFromDateTimeToDate: parseFromDateTimeToDate
};


text:
class ExtensionPrefValueMap;
class PrefService;

namespace content {
class BrowserContext;
}

namespace user_prefs {
class PrefRegistrySyncable;
}

namespace extensions {

class AppSorting;
class ExtensionPrefsObserver;
class URLPatternSet;

// Class for managing global and per-extension preferences.
//
// This class distinguishes the following kinds of preferences:
// - global preferences:
//       internal state for the extension system in general, not associated
//       with an individual extension, such as lastUpdateTime.
// - per-extension preferences:
//       meta-preferences describing properties of the extension like
//       installation time, whether the extension is enabled, etc.
// - extension controlled preferences:
//       browser preferences that an extension controls. For example, an
//       extension could use the proxy API to specify the browser's proxy
//       preference. Extension-controlled preferences are stored in
//       PrefValueStore::extension_prefs(), which this class populates and
//       maintains as the underlying extensions change.
class ExtensionPrefs : public ExtensionScopedPrefs, public KeyedService {
 public:
  typedef std::vector<linked_ptr<ExtensionInfo> > ExtensionsInfo;

  // Vector containing identifiers for preferences.
  typedef std::set<std::string> PrefKeySet;

  // This enum is used to store the reason an extension's install has been
  // delayed.  Do not remove items or re-order this enum as it is used in
  // preferences.
  enum DelayReason {
    DELAY_REASON_NONE = 0,
    DELAY_REASON_GC = 1,
    DELAY_REASON_WAIT_FOR_IDLE = 2,
    DELAY_REASON_WAIT_FOR_IMPORTS = 3,
  };

  // Creates base::Time classes. The default implementation is just to return
  // the current time, but tests can inject alternative implementations.
  class TimeProvider {
   public:
    TimeProvider();

    virtual ~TimeProvider();

    // By default, returns the current time (base::Time::Now()).
    virtual base::Time GetCurrentTime() const;

   private:
    DISALLOW_COPY_AND_ASSIGN(TimeProvider);
  };

  // A wrapper around a ScopedUserPrefUpdate, which allows us to access the
  // entry of a particular key for an extension. Use this if you need a mutable
  // record of a dictionary or list in the current settings. Otherwise, prefer
  // ReadPrefAsT() and UpdateExtensionPref() methods.
  template <typename T, base::Value::Type type_enum_value>
  class ScopedUpdate {
   public:
    ScopedUpdate(ExtensionPrefs* prefs,
                 const std::string& extension_id,
                 const std::string& key);
    virtual ~ScopedUpdate();

    // Returns a mutable value for the key (ownership remains with the prefs),
    // if one exists. Otherwise, returns NULL.
    virtual T* Get();

    // Creates and returns a mutable value for the key (the prefs own the new
    // value), if one does not already exist. Otherwise, returns the current
    // value.
    virtual T* Create();

   private:
    DictionaryPrefUpdate update_;
    const std::string extension_id_;
    const std::string key_;

    DISALLOW_COPY_AND_ASSIGN(ScopedUpdate);
  };
  typedef ScopedUpdate<base::DictionaryValue, base::Value::TYPE_DICTIONARY>
      ScopedDictionaryUpdate;
  typedef ScopedUpdate<base::ListValue, base::Value::TYPE_LIST>
      ScopedListUpdate;

  // Creates an ExtensionPrefs object.
  // Does not take ownership of |prefs| or |extension_pref_value_map|.
  // If |extensions_disabled| is true, extension controlled preferences and
  // content settings do not become effective. ExtensionPrefsObservers should be
  // included in |early_observers| if they need to observe events which occur
  // during initialization of the ExtensionPrefs object.
  static ExtensionPrefs* Create(
      content::BrowserContext* browser_context,
      PrefService* prefs,
      const base::FilePath& root_dir,
      ExtensionPrefValueMap* extension_pref_value_map,
      bool extensions_disabled,
      const std::vector<ExtensionPrefsObserver*>& early_observers);

  // A version of Create which allows injection of a custom base::Time provider.
  // Use this as needed for testing.
  static ExtensionPrefs* Create(
      content::BrowserContext* browser_context,
      PrefService* prefs,
      const base::FilePath& root_dir,
      ExtensionPrefValueMap* extension_pref_value_map,
      bool extensions_disabled,
      const std::vector<ExtensionPrefsObserver*>& early_observers,
      scoped_ptr<TimeProvider> time_provider);

  ~ExtensionPrefs() override;

  // Convenience function to get the ExtensionPrefs for a BrowserContext.
  static ExtensionPrefs* Get(content::BrowserContext* context);

  // Returns all installed extensions from extension preferences provided by
  // |pref_service|. This is exposed for ProtectedPrefsWatcher because it needs
  // access to the extension ID list before the ExtensionService is initialized.
  static ExtensionIdList GetExtensionsFrom(const PrefService* pref_service);

  // Add or remove an observer from the ExtensionPrefs.
  void AddObserver(ExtensionPrefsObserver* observer);
  void RemoveObserver(ExtensionPrefsObserver* observer);

  // Returns true if the specified external extension was uninstalled by the
  // user.
  bool IsExternalExtensionUninstalled(const std::string& id) const;

  // Checks whether |extension_id| is disabled. If there's no state pref for
  // the extension, this will return false. Generally you should use
  // ExtensionService::IsExtensionEnabled instead.
  // Note that blacklisted extensions are NOT marked as disabled!
  bool IsExtensionDisabled(const std::string& id) const;

  // Get/Set the order that the browser actions appear in the toolbar.
  ExtensionIdList GetToolbarOrder() const;
  void SetToolbarOrder(const ExtensionIdList& extension_ids);

  // Called when an extension is installed, so that prefs get created.
  // If |page_ordinal| is invalid then a page will be found for the App.
  // |install_flags| are a bitmask of extension::InstallFlags.
  void OnExtensionInstalled(const Extension* extension,
                            Extension::State initial_state,
                            const syncer::StringOrdinal& page_ordinal,
                            int install_flags,
                            const std::string& install_parameter);
  // OnExtensionInstalled with no install flags.
  void OnExtensionInstalled(const Extension* extension,
                            Extension::State initial_state,
                            const syncer::StringOrdinal& page_ordinal,
                            const std::string& install_parameter) {
    OnExtensionInstalled(extension,
                         initial_state,
                         page_ordinal,
                         kInstallFlagNone,
                         install_parameter);
  }

  // Called when an extension is uninstalled, so that prefs get cleaned up.
  void OnExtensionUninstalled(const std::string& extension_id,
                              const Manifest::Location& location,
                              bool external_uninstall);

  // Sets the extension's state to enabled and clears disable reasons.
  void SetExtensionEnabled(const std::string& extension_id);

  // Sets the extension's state to disabled and sets the disable reasons.
  // However, if the current state is EXTERNAL_EXTENSION_UNINSTALLED then that
  // is preserved (but the disable reasons are still set).
  void SetExtensionDisabled(const std::string& extension_id,
                            int disable_reasons);

  // Called to change the extension's BlacklistState. Currently only used for
  // non-malicious extensions.
  // TODO(oleg): replace SetExtensionBlacklisted by this function.
  void SetExtensionBlacklistState(const std::string& extension_id,
                                  BlacklistState state);

  // Checks whether |extension_id| is marked as greylisted.
  // TODO(oleg): Replace IsExtensionBlacklisted by this method.
  BlacklistState GetExtensionBlacklistState(
      const std::string& extension_id) const;

  // Populates |out| with the ids of all installed extensions.
  void GetExtensions(ExtensionIdList* out) const;

  // ExtensionScopedPrefs methods:
  void UpdateExtensionPref(const std::string& id,
                           const std::string& key,
                           base::Value* value) override;

  void DeleteExtensionPrefs(const std::string& id) override;

  bool ReadPrefAsBoolean(const std::string& extension_id,
                         const std::string& pref_key,
                         bool* out_value) const override;

  bool ReadPrefAsInteger(const std::string& extension_id,
                         const std::string& pref_key,
                         int* out_value) const override;

  bool ReadPrefAsString(const std::string& extension_id,
                        const std::string& pref_key,
                        std::string* out_value) const override;

  bool ReadPrefAsList(const std::string& extension_id,
                      const std::string& pref_key,
                      const base::ListValue** out_value) const override;

  bool ReadPrefAsDictionary(
      const std::string& extension_id,
      const std::string& pref_key,
      const base::DictionaryValue** out_value) const override;

  bool HasPrefForExtension(const std::string& extension_id) const override;

  // Did the extension ask to escalate its permission during an upgrade?
  bool DidExtensionEscalatePermissions(const std::string& id) const;

  // Getters and setters for disabled reason.
  // Note that you should rarely need to modify disable reasons directly -
  // pass the proper value to SetExtensionState instead when you enable/disable
  // an extension. In particular, AddDisableReason(s) is only legal when the
  // extension is not enabled.
  int GetDisableReasons(const std::string& extension_id) const;
  bool HasDisableReason(const std::string& extension_id,
                        Extension::DisableReason disable_reason) const;
  void AddDisableReason(const std::string& extension_id,
                        Extension::DisableReason disable_reason);
  void AddDisableReasons(const std::string& extension_id, int disable_reasons);
  void RemoveDisableReason(const std::string& extension_id,
                           Extension::DisableReason disable_reason);
  void ReplaceDisableReasons(const std::string& extension_id,
                             int disable_reasons);
  void ClearDisableReasons(const std::string& extension_id);

  // Gets the set of extensions that have been blacklisted in prefs. This will
  // return only the blocked extensions, not the "greylist" extensions.
  // TODO(oleg): Make method names consistent here, in extension service and in
  // blacklist.
  std::set<std::string> GetBlacklistedExtensions() const;

  // Sets whether the extension with |id| is blacklisted.
  void SetExtensionBlacklisted(const std::string& extension_id,
                               bool is_blacklisted);

  // Returns the version string for the currently installed extension, or
  // the empty string if not found.
  std::string GetVersionString(const std::string& extension_id) const;

  // Re-writes the extension manifest into the prefs.
  // Called to change the extension's manifest when it's re-localized.
  void UpdateManifest(const Extension* extension);

  // Returns base extensions install directory.
  const base::FilePath& install_directory() const { return install_directory_; }

  // Returns whether the extension with |id| has its blacklist bit set.
  //
  // WARNING: this only checks the extension's entry in prefs, so by definition
  // can only check extensions that prefs knows about. There may be other
  // sources of blacklist information, such as safebrowsing. You probably want
  // to use Blacklist::GetBlacklistedIDs rather than this method.
  bool IsExtensionBlacklisted(const std::string& id) const;

  // Increment the count of how many times we prompted the user to acknowledge
  // the given extension, and return the new count.
  int IncrementAcknowledgePromptCount(const std::string& extension_id);

  // Whether the user has acknowledged an external extension.
  bool IsExternalExtensionAcknowledged(const std::string& extension_id) const;
  void AcknowledgeExternalExtension(const std::string& extension_id);

  // Whether the user has acknowledged a blacklisted extension.
  bool IsBlacklistedExtensionAcknowledged(
      const std::string& extension_id) const;
  void AcknowledgeBlacklistedExtension(const std::string& extension_id);

  // Whether the external extension was installed during the first run
  // of this profile.
  bool IsExternalInstallFirstRun(const std::string& extension_id) const;
  void SetExternalInstallFirstRun(const std::string& extension_id);

  // Returns true if the extension notification code has already run for the
  // first time for this profile. Currently we use this flag to mean that any
  // extensions that would trigger notifications should get silently
  // acknowledged. This is a fuse. Calling it the first time returns false.
  // Subsequent calls return true. It's not possible through an API to ever
  // reset it. Don't call it unless you mean it!
  bool SetAlertSystemFirstRun();

  // Returns the last value set via SetLastPingDay. If there isn't such a
  // pref, the returned Time will return true for is_null().
  base::Time LastPingDay(const std::string& extension_id) const;

  // The time stored is based on the server's perspective of day start time, not
  // the client's.
  void SetLastPingDay(const std::string& extension_id, const base::Time& time);

  // Similar to the 2 above, but for the extensions blacklist.
  base::Time BlacklistLastPingDay() const;
  void SetBlacklistLastPingDay(const base::Time& time);

  // Similar to LastPingDay/SetLastPingDay, but for sending "days since active"
  // ping.
  base::Time LastActivePingDay(const std::string& extension_id) const;
  void SetLastActivePingDay(const std::string& extension_id,
                            const base::Time& time);

  // A bit we use for determining if we should send the "days since active"
  // ping. A value of true means the item has been active (launched) since the
  // last update check.
  bool GetActiveBit(const std::string& extension_id) const;
  void SetActiveBit(const std::string& extension_id, bool active);

  // Returns the granted permission set for the extension with |extension_id|,
  // and NULL if no preferences were found for |extension_id|.
  // This passes ownership of the returned set to the caller.
  scoped_ptr<const PermissionSet> GetGrantedPermissions(
      const std::string& extension_id) const;

  // Adds |permissions| to the granted permissions set for the extension with
  // |extension_id|. The new granted permissions set will be the union of
  // |permissions| and the already granted permissions.
  void AddGrantedPermissions(const std::string& extension_id,
                             const PermissionSet& permissions);

  // As above, but subtracts the given |permissions| from the granted set.
  void RemoveGrantedPermissions(const std::string& extension_id,
                                const PermissionSet& permissions);

  // Gets the active permission set for the specified extension. This may
  // differ from the permissions in the manifest due to the optional
  // permissions API. This passes ownership of the set to the caller.
  scoped_ptr<const PermissionSet> GetActivePermissions(
      const std::string& extension_id) const;

  // Sets the active |permissions| for the extension with |extension_id|.
  void SetActivePermissions(const std::string& extension_id,
                            const PermissionSet& permissions);

  // Records whether or not this extension is currently running.
  void SetExtensionRunning(const std::string& extension_id, bool is_running);

  // Returns whether or not this extension is marked as running. This is used to
  // restart apps across browser restarts.
  bool IsExtensionRunning(const std::string& extension_id) const;

  // Set/Get whether or not the app is active. Used to force a launch of apps
  // that don't handle onRestarted() on a restart. We can only safely do that if
  // the app was active when it was last running.
  void SetIsActive(const std::string& extension_id, bool is_active);
  bool IsActive(const std::string& extension_id) const;

  // Returns true if the user enabled this extension to be loaded in incognito
  // mode.
  //
  // IMPORTANT: you probably want to use extensions::util::IsIncognitoEnabled
  // instead of this method.
  bool IsIncognitoEnabled(const std::string& extension_id) const;
  void SetIsIncognitoEnabled(const std::string& extension_id, bool enabled);

  // Returns true if the user has chosen to allow this extension to inject
  // scripts into pages with file URLs.
  //
  // IMPORTANT: you probably want to use extensions::util::AllowFileAccess
  // instead of this method.
  bool AllowFileAccess(const std::string& extension_id) const;
  void SetAllowFileAccess(const std::string& extension_id, bool allow);
  bool HasAllowFileAccessSetting(const std::string& extension_id) const;

  // Saves ExtensionInfo for each installed extension with the path to the
  // version directory and the location. Blacklisted extensions won't be saved
  // and neither will external extensions the user has explicitly uninstalled.
  // Caller takes ownership of returned structure.
  scoped_ptr<ExtensionsInfo> GetInstalledExtensionsInfo() const;

  // Same as above, but only includes external extensions the user has
  // explicitly uninstalled.
  scoped_ptr<ExtensionsInfo> GetUninstalledExtensionsInfo() const;

  // Returns the ExtensionInfo from the prefs for the given extension. If the
  // extension is not present, NULL is returned.
  scoped_ptr<ExtensionInfo> GetInstalledExtensionInfo(
      const std::string& extension_id) const;

  // We've downloaded an updated .crx file for the extension, but are waiting
  // to install it.
  //
  // |install_flags| are a bitmask of extension::InstallFlags.
  void SetDelayedInstallInfo(const Extension* extension,
                             Extension::State initial_state,
                             int install_flags,
                             DelayReason delay_reason,
                             const syncer::StringOrdinal& page_ordinal,
                             const std::string& install_parameter);

  // Removes any delayed install information we have for the given
  // |extension_id|. Returns true if there was info to remove; false otherwise.
  bool RemoveDelayedInstallInfo(const std::string& extension_id);

  // Update the prefs to finish the update for an extension.
  bool FinishDelayedInstallInfo(const std::string& extension_id);

  // Returns the ExtensionInfo from the prefs for delayed install information
  // for |extension_id|, if we have any. Otherwise returns NULL.
  scoped_ptr<ExtensionInfo> GetDelayedInstallInfo(
      const std::string& extension_id) const;

  DelayReason GetDelayedInstallReason(const std::string& extension_id) const;

  // Returns information about all the extensions that have delayed install
  // information.
  scoped_ptr<ExtensionsInfo> GetAllDelayedInstallInfo() const;

  // Returns true if the user repositioned the app on the app launcher via drag
  // and drop.
  bool WasAppDraggedByUser(const std::string& extension_id) const;

  // Sets a flag indicating that the user repositioned the app on the app
  // launcher by drag and dropping it.
  void SetAppDraggedByUser(const std::string& extension_id);

  // Returns true if there is an extension which controls the preference value
  //  for |pref_key| *and* it is specific to incognito mode.
  bool HasIncognitoPrefValue(const std::string& pref_key) const;

  // Returns the creation flags mask for the extension.
  int GetCreationFlags(const std::string& extension_id) const;

  // Returns the creation flags mask for a delayed install extension.
  int GetDelayedInstallCreationFlags(const std::string& extension_id) const;

  // Returns true if the extension was installed from the Chrome Web Store.
  bool IsFromWebStore(const std::string& extension_id) const;

  // Returns true if the extension was installed from an App generated from a
  // bookmark.
  bool IsFromBookmark(const std::string& extension_id) const;

  // Returns true if the extension was installed as a default app.
  bool WasInstalledByDefault(const std::string& extension_id) const;

  // Returns true if the extension was installed as an oem app.
  bool WasInstalledByOem(const std::string& extension_id) const;

  // Helper method to acquire the installation time of an extension.
  // Returns base::Time() if the installation time could not be parsed or
  // found.
  base::Time GetInstallTime(const std::string& extension_id) const;

  // Returns true if the extension should not be synced.
  bool DoNotSync(const std::string& extension_id) const;

  // Gets/sets the last launch time of an extension.
  base::Time GetLastLaunchTime(const std::string& extension_id) const;
  void SetLastLaunchTime(const std::string& extension_id,
                         const base::Time& time);

  // Clear any launch times. This is called by the browsing data remover when
  // history is cleared.
  void ClearLastLaunchTimes();

  static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);

  bool extensions_disabled() const { return extensions_disabled_; }

  // The underlying PrefService.
  PrefService* pref_service() const { return prefs_; }

  // The underlying AppSorting.
  AppSorting* app_sorting() const;

  // Schedules garbage collection of an extension's on-disk data on the next
  // start of this ExtensionService. Applies only to extensions with isolated
  // storage.
  void SetNeedsStorageGarbageCollection(bool value);
  bool NeedsStorageGarbageCollection() const;

  // Used by AppWindowGeometryCache to persist its cache. These methods
  // should not be called directly.
  const base::DictionaryValue* GetGeometryCache(
        const std::string& extension_id) const;
  void SetGeometryCache(const std::string& extension_id,
                        scoped_ptr<base::DictionaryValue> cache);

  // Used for verification of installed extension ids. For the Set method, pass
  // null to remove the preference.
  const base::DictionaryValue* GetInstallSignature() const;
  void SetInstallSignature(const base::DictionaryValue* signature);

  // The installation parameter associated with the extension.
  std::string GetInstallParam(const std::string& extension_id) const;
  void SetInstallParam(const std::string& extension_id,
                       const std::string& install_parameter);

  // The total number of times we've disabled an extension due to corrupted
  // contents.
  int GetCorruptedDisableCount() const;
  void IncrementCorruptedDisableCount();

  // Whether the extension with the given |id| needs to be synced. This is set
  // when the state (such as enabled/disabled or allowed in incognito) is
  // changed before Sync is ready.
  bool NeedsSync(const std::string& extension_id) const;
  void SetNeedsSync(const std::string& extension_id, bool needs_sync);

 private:
  friend class ExtensionPrefsBlacklistedExtensions;  // Unit test.
  friend class ExtensionPrefsComponentExtension;     // Unit test.
  friend class ExtensionPrefsUninstallExtension;     // Unit test.

  enum DisableReasonChange {
    DISABLE_REASON_ADD,
    DISABLE_REASON_REMOVE,
    DISABLE_REASON_REPLACE,
    DISABLE_REASON_CLEAR
  };

  // See the Create methods.
  ExtensionPrefs(content::BrowserContext* browser_context,
                 PrefService* prefs,
                 const base::FilePath& root_dir,
                 ExtensionPrefValueMap* extension_pref_value_map,
                 scoped_ptr<TimeProvider> time_provider,
                 bool extensions_disabled,
                 const std::vector<ExtensionPrefsObserver*>& early_observers);

  // Converts absolute paths in the pref to paths relative to the
  // install_directory_.
  void MakePathsRelative();

  // Converts internal relative paths to be absolute. Used for export to
  // consumers who expect full paths.
  void MakePathsAbsolute(base::DictionaryValue* dict);

  // Helper function used by GetInstalledExtensionInfo() and
  // GetDelayedInstallInfo() to construct an ExtensionInfo from the provided
  // |extension| dictionary.
  scoped_ptr<ExtensionInfo> GetInstalledInfoHelper(
      const std::string& extension_id,
      const base::DictionaryValue* extension) const;

  // Interprets the list pref, |pref_key| in |extension_id|'s preferences, as a
  // URLPatternSet. The |valid_schemes| specify how to parse the URLPatterns.
  bool ReadPrefAsURLPatternSet(const std::string& extension_id,
                               const std::string& pref_key,
                               URLPatternSet* result,
                               int valid_schemes) const;

  // Converts |new_value| to a list of strings and sets the |pref_key| pref
  // belonging to |extension_id|.
  void SetExtensionPrefURLPatternSet(const std::string& extension_id,
                                     const std::string& pref_key,
                                     const URLPatternSet& new_value);

  // Read the boolean preference entry and return true if the preference exists
  // and the preference's value is true; false otherwise.
  bool ReadPrefAsBooleanAndReturn(const std::string& extension_id,
                                  const std::string& key) const;

  // Interprets |pref_key| in |extension_id|'s preferences as an
  // PermissionSet, and passes ownership of the set to the caller.
  scoped_ptr<const PermissionSet> ReadPrefAsPermissionSet(
      const std::string& extension_id,
      const std::string& pref_key) const;

  // Converts the |new_value| to its value and sets the |pref_key| pref
  // belonging to |extension_id|.
  void SetExtensionPrefPermissionSet(const std::string& extension_id,
                                     const std::string& pref_key,
                                     const PermissionSet& new_value);

  // Returns an immutable dictionary for extension |id|'s prefs, or NULL if it
  // doesn't exist.
  const base::DictionaryValue* GetExtensionPref(const std::string& id) const;

  // Modifies the extensions disable reasons to add a new reason, remove an
  // existing reason, or clear all reasons. Notifies observers if the set of
  // DisableReasons has changed.
  // If |change| is DISABLE_REASON_CLEAR, then |reason| is ignored.
  void ModifyDisableReasons(const std::string& extension_id,
                            int reasons,
                            DisableReasonChange change);

  // Installs the persistent extension preferences into |prefs_|'s extension
  // pref store. Does nothing if extensions_disabled_ is true.
  void InitPrefStore();

  // Checks whether there is a state pref for the extension and if so, whether
  // it matches |check_state|.
  bool DoesExtensionHaveState(const std::string& id,
                              Extension::State check_state) const;

  // Reads the list of strings for |pref| from user prefs into
  // |id_container_out|. Returns false if the pref wasn't found in the user
  // pref store.
  template <class ExtensionIdContainer>
  bool GetUserExtensionPrefIntoContainer(
      const char* pref,
      ExtensionIdContainer* id_container_out) const;

  // Writes the list of strings contained in |strings| to |pref| in prefs.
  template <class ExtensionIdContainer>
  void SetExtensionPrefFromContainer(const char* pref,
                                     const ExtensionIdContainer& strings);

  // Helper function to populate |extension_dict| with the values needed
  // by a newly installed extension. Work is broken up between this
  // function and FinishExtensionInfoPrefs() to accommodate delayed
  // installations.
  //
  // |install_flags| are a bitmask of extension::InstallFlags.
  void PopulateExtensionInfoPrefs(const Extension* extension,
                                  const base::Time install_time,
                                  Extension::State initial_state,
                                  int install_flags,
                                  const std::string& install_parameter,
                                  base::DictionaryValue* extension_dict) const;

  void InitExtensionControlledPrefs(ExtensionPrefValueMap* value_map);

  // Helper function to complete initialization of the values in
  // |extension_dict| for an extension install. Also see
  // PopulateExtensionInfoPrefs().
  void FinishExtensionInfoPrefs(
      const std::string& extension_id,
      const base::Time install_time,
      bool needs_sort_ordinal,
      const syncer::StringOrdinal& suggested_page_ordinal,
      base::DictionaryValue* extension_dict);

  content::BrowserContext* browser_context_;

  // The pref service specific to this set of extension prefs. Owned by the
  // BrowserContext.
  PrefService* prefs_;

  // Base extensions install directory.
  base::FilePath install_directory_;

  // Weak pointer, owned by BrowserContext.
  ExtensionPrefValueMap* extension_pref_value_map_;

  scoped_ptr<TimeProvider> time_provider_;

  bool extensions_disabled_;

  base::ObserverList<ExtensionPrefsObserver> observer_list_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionPrefs);
};

}  // namespace extensions

#endif  // EXTENSIONS_BROWSER_EXTENSION_PREFS_H_


text:
'use strict';

const chalk = require('chalk');
const runScript = require('./utils').runScript;

module.exports = postuninstall;

// @see https://docs.npmjs.com/misc/scripts
function* postuninstall(pkg, root, options) {
  const scripts = pkg.scripts || {};
  if (scripts.postuninstall) {
    options.console.warn(chalk.yellow('[%s@%s]%s scripts.postuninstall: %j'),
      pkg.name, pkg.version, options.ignoreScripts ? ' ignore' : '', scripts.postuninstall);
    if (!options.ignoreScripts) {
      // root is removed
      yield runScript(options.root, scripts.postuninstall, options);
    }
  }
}


text:
package com.intellij.util.fmap;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

final class TwoKeysFMap<@NotNull K, @NotNull V> implements FMap<K, V> {

  private final K myKey1;
  private final K myKey2;
  private final V myValue1;
  private final V myValue2;

  TwoKeysFMap(K key1, V value1, K key2, V value2) {
    myKey1 = key1;
    myKey2 = key2;
    myValue1 = value1;
    myValue2 = value2;
  }

  @Override
  public @NotNull FMap<K, V> plus(K key, V value) {
    if (myKey1.equals(key)) {
      if (myValue1.equals(value)) {
        return this;
      }
      else {
        return new TwoKeysFMap<>(key, value, myKey2, myValue2);
      }
    }
    else if (myKey2.equals(key)) {
      if (myValue2.equals(value)) {
        return this;
      }
      else {
        return new TwoKeysFMap<>(myKey1, myValue1, key, value);
      }
    }
    else {
      return new ArrayBackedFMap<>(myKey1, myValue1, myKey2, myValue2, key, value);
    }
  }

  @Override
  public @NotNull FMap<K, V> minus(K key) {
    return myKey1.equals(key)
           ? new OneKeyFMap<>(myKey2, myValue2)
           : myKey2.equals(key)
             ? new OneKeyFMap<>(myKey1, myValue1)
             : this;
  }

  @Override
  public @Nullable V get(K key) {
    return myKey1.equals(key)
           ? myValue1
           : myKey2.equals(key)
             ? myValue2
             : null;
  }

  @Override
  public boolean isEmpty() {
    return false;
  }

  @Override
  public int size() {
    return 2;
  }

  @Override
  public @NotNull Collection<K> keys() {
    return Arrays.asList(myKey1, myKey2);
  }

  @Override
  public @NotNull Map<K, V> toMap() {
    Map<K, V> map = new HashMap<>(2);
    map.put(myKey1, myValue1);
    map.put(myKey2, myValue2);
    return Collections.unmodifiableMap(map);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    TwoKeysFMap<?, ?> map = (TwoKeysFMap<?, ?>)o;
    return myKey1.equals(map.myKey1) && myKey2.equals(map.myKey2) &&
           myValue1.equals(map.myValue1) && myValue2.equals(map.myValue2) ||
           myKey1.equals(map.myKey2) && myKey2.equals(map.myKey1) &&
           myValue1.equals(map.myValue2) && myValue2.equals(map.myValue1);
  }

  @Override
  public int hashCode() {
    return (myKey1.hashCode() ^ myKey2.hashCode())
           + 31 * (myValue1.hashCode() ^ myValue2.hashCode());
  }

  @Override
  public String toString() {
    return String.format("[\n  %s: %s,\n  %s: %s,\n]", myKey1, myValue1, myKey2, myValue2);
  }
}


text:
XMIO = {};

var WEB_SERVICE_URL;
var INITIATOR;
var PASSWORD;

(function(){
	var javaPkgs = new JavaImporter(
			com.alarmpoint.integrationagent.script.api,
			com.alarmpoint.integrationagent.security,
			com.alarmpoint.integrationagent.exceptions.retriable
	);

	with (javaPkgs) {
		var httpClient = new IntegrationServiceHttpClient();
		XMIO.http = httpClient;

		XMIO.decryptFile = function(path) {
			return EncryptionUtils.decrypt(new java.io.File(path));
		}

		XMIO.post = function(jsonStr, url, username, password) {
			return execute('POST', jsonStr, url, username, password);
		}

		XMIO.put = function(jsonStr, url, username, password) {
			return execute('PUT', jsonStr, url, username, password);
		}

		XMIO.get = function(url, username, password) {
			return execute('GET', null, url, username, password);
		}

		function execute(method, jsonStr, url, username, password) {
			var urL = url === undefined ? WEB_SERVICE_URL : url,
				    user = username === undefined ? INITIATOR : username,
				    pwd = password === undefined ? XMIO.decryptFile(PASSWORD) : password;

			XMIO.http.setUrl(urL);
			XMIO.http.setCredentials(user, pwd);

			if (method !== 'GET') {
				XMIO.http.addHeader('Content-Type', 'application/json');
			}

			var resp;
			if (method === 'POST') {
				//ServiceAPI.getLogger().debug("POST to: {0} with payload: {1}", urL, jsonStr);
				resp = XMIO.http.post(jsonStr);
			}
			else if (method === 'PUT') {
				//ServiceAPI.getLogger().debug("PUT to: {0} with payload: {1}", urL, jsonStr);
				resp = XMIO.http.put(jsonStr);
			}
			else if (method === 'GET') {
				//ServiceAPI.getLogger().debug("GET from: {0}", urL);
				resp = XMIO.http.get();
			}

			var response = {};
			response.status = resp.getStatusLine().getStatusCode();
			response.body = XMIO.http.getResponseAsString(resp);

	        XMIO.http.releaseConnection(resp);
			//ServiceAPI.getLogger().info("xMatters response code: {0} and payload: {1}", response.status, response.body);
			return response;
		}
	}
})();


text:
/*	$NetBSD: pwcache.h,v 1.5 2003/11/10 08:51:51 wiz Exp $	*/

/*-
 * Copyright (c) 1992 Keith Muller.
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Keith Muller of the University of California, San Diego.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *      @(#)cache.h	8.1 (Berkeley) 5/31/93
 */

/*
 * Constants and data structures used to implement group and password file
 * caches. Traditional passwd/group cache routines perform quite poorly with
 * archives. The chances of hitting a valid lookup with an archive is quite a
 * bit worse than with files already resident on the file system. These misses
 * create a MAJOR performance cost. To address this problem, these routines
 * cache both hits and misses.
 *
 * NOTE:  name lengths must be as large as those stored in ANY PROTOCOL and
 * as stored in the passwd and group files. CACHE SIZES MUST BE PRIME
 */
#define UNMLEN		32	/* >= user name found in any protocol */
#define GNMLEN		32	/* >= group name found in any protocol */
#define UID_SZ		317	/* size of uid to user_name cache */
#define UNM_SZ		317	/* size of user_name to uid cache */
#define GID_SZ		251	/* size of gid to group_name cache */
#define GNM_SZ		251	/* size of group_name to gid cache */
#define VALID		1	/* entry and name are valid */
#define INVALID		2	/* entry valid, name NOT valid */

/*
 * Node structures used in the user, group, uid, and gid caches.
 */

typedef struct uidc {
	int valid;		/* is this a valid or a miss entry */
	char name[UNMLEN];	/* uid name */
	uid_t uid;		/* cached uid */
} UIDC;

typedef struct gidc {
	int valid;		/* is this a valid or a miss entry */
	char name[GNMLEN];	/* gid name */
	gid_t gid;		/* cached gid */
} GIDC;


text:
@interface Rain : MTLModel<MTLJSONSerializing>

@property(nonatomic, copy) NSNumber *volume3h;

@end


text:
<?php

/**
 * Class provides a simple keyword element, only contains the keyword as
 * key of a keyword insertion request.
 * You can extend this Element with your own data and fields.
 */
class KeywordInsertionItem extends DataObject {

    /**
     * @var array
     */
    private static $db = array(
        'Keyword' => 'Varchar(200)',
        'Value' => 'Varchar(200)',
    );

    /**
     * @var array
     */
    private static $has_one = array(
        'KeywordInsertionPage' => 'KeywordInsertionPage',
    );

    /**
     * @var string
     */
    static $singular_name = 'Wildcard Element';

    /**
     * @var string
     */
    static $plural_name = 'Wildcard Element';

    /**
     * Returns the fieldset for cms backend
     *
     * @return \FieldList
     */
    public function getCMSFields() {
        $fields = new FieldList(
            $rootTab = new TabSet('Root',
                $tabMain = new Tab('Main')
            )
        );

        $fields->addFieldsToTab(
            'Root.Main',
            array(
                new TextField(
                    'Keyword',
                    _t('KeywordInsertionPage.KEYWORD_LABEL', 'Keyword')
                ),
                new TextField(
                    'Value',
                    _t('KeywordInsertionPage.VALUE_LABEL', 'Value')
                )
            )
        );

        return $fields;
    }

    /**
     * Method returns all values based on a specific keyword
     *
     * @return array
     */
    public function allKeywordValues() {
        $aAllKeywordValues = array();
        $aAllKeywords = self::allKeywords();

        foreach($aAllKeywords as $sKeyword) {
            $aAllKeywordValues[$sKeyword] = $this->{$sKeyword};
        }

        return $aAllKeywordValues;
    }

    /**
     * Return keywords for wildcard insertion.
     *
     * @return array
     */
    public static function allKeywords() {
        return array(
            'Value',
        );
    }
}


text:
package model

import (
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils"

	"strings"
)

// This is a auto create Body Object
type CreatePostPaidServersRequestBody struct {
	// 是否只预检此次请求。  true:发送检查请求,不会创建实例。检查项包括是否填写了必需参数、请求格式等。 如果检查不通过,则返回对应错误。 如果检查通过,则返回202状态码。 false:发送正常请求,通过检查后并且执行创建云服务器请求。

	DryRun *bool `json:"dry_run,omitempty"`

	Server *PostPaidServer `json:"server"`
}

func (o CreatePostPaidServersRequestBody) String() string {
	data, err := utils.Marshal(o)
	if err != nil {
		return "CreatePostPaidServersRequestBody struct{}"
	}

	return strings.Join([]string{"CreatePostPaidServersRequestBody", string(data)}, " ")
}