using System;
using System.Collections.Generic;

namespace LibgenDesktop.Models.Localization.Localizators.Windows
{
    internal class ImportWindowLocalizator : Localizator<Translation.ImportTranslation>
    {
        public ImportWindowLocalizator(List<Translation> prioritizedTranslationList, LanguageFormatter formatter)
            : base(prioritizedTranslationList, formatter, translation => translation?.Import)
        {
            WindowTitle = Format(section => section?.WindowTitle);
            BrowseImportFileDialogTitle = Format(section => section?.BrowseImportFileDialogTitle);
            AllSupportedFiles = Format(section => section?.AllSupportedFiles);
            SqlDumps = Format(section => section?.SqlDumps);
            Archives = Format(section => section?.Archives);
            AllFiles = Format(section => section?.AllFiles);
            Unknown = Format(section => section?.Unknown);
            Interrupt = Format(section => section?.Interrupt);
            Interrupting = Format(section => section?.Interrupting);
            Close = Format(section => section?.Close);
            StatusDataLookup = FormatStatus(section => section?.DataLookup);
            StatusCreatingIndexes = FormatStatus(section => section?.CreatingIndexes);
            StatusLoadingIds = FormatStatus(section => section?.LoadingIds);
            StatusImportingData = FormatStatus(section => section?.ImportingData);
            StatusImportComplete = FormatStatus(section => section?.ImportComplete);
            StatusImportCancelled = FormatStatus(section => section?.ImportCancelled);
            StatusDataNotFound = FormatStatus(section => section?.DataNotFound);
            StatusImportError = FormatStatus(section => section?.ImportError);
            LogLineDataLookup = FormatLogLine(section => section?.DataLookup);
            LogLineScanning = FormatLogLine(section => section?.Scanning);
            LogLineNonFictionTableFound = FormatLogLine(section => section?.NonFictionTableFound);
            LogLineFictionTableFound = FormatLogLine(section => section?.FictionTableFound);
            LogLineSciMagTableFound = FormatLogLine(section => section?.SciMagTableFound);
            LogLineCreatingIndexes = FormatLogLine(section => section?.CreatingIndexes);
            LogLineLoadingIds = FormatLogLine(section => section?.LoadingIds);
            LogLineImportingData = FormatLogLine(section => section?.ImportingData);
            LogLineImportSuccessful = FormatLogLine(section => section?.ImportSuccessful);
            LogLineImportCancelled = FormatLogLine(section => section?.ImportCancelled);
            LogLineDataNotFound = FormatLogLine(section => section?.DataNotFound);
            LogLineInsufficientDiskSpace = FormatLogLine(section => section?.InsufficientDiskSpace);
            LogLineExpectedNonFictionTable = FormatLogLine(section => section?.ExpectedNonFictionTable);
            LogLineExpectedFictionTable = FormatLogLine(section => section?.ExpectedFictionTable);
            LogLineExpectedSciMagTable = FormatLogLine(section => section?.ExpectedSciMagTable);
            LogLineFoundNonFictionTable = FormatLogLine(section => section?.FoundNonFictionTable);
            LogLineFoundFictionTable = FormatLogLine(section => section?.FoundFictionTable);
            LogLineFoundSciMagTable = FormatLogLine(section => section?.FoundSciMagTable);
            LogLineImportError = FormatLogLine(section => section?.ImportError);
        }

        public string WindowTitle { get; }
        public string BrowseImportFileDialogTitle { get; }
        public string AllSupportedFiles { get; }
        public string SqlDumps { get; }
        public string Archives { get; }
        public string AllFiles { get; }
        public string Unknown { get; set; }
        public string Interrupt { get; }
        public string Interrupting { get; }
        public string Close { get; }
        public string StatusDataLookup { get; }
        public string StatusCreatingIndexes { get; }
        public string StatusLoadingIds { get; }
        public string StatusImportingData { get; }
        public string StatusImportComplete { get; }
        public string StatusImportCancelled { get; }
        public string StatusDataNotFound { get; }
        public string StatusImportError { get; }
        public string LogLineDataLookup { get; }
        public string LogLineScanning { get; }
        public string LogLineNonFictionTableFound { get; }
        public string LogLineFictionTableFound { get; }
        public string LogLineSciMagTableFound { get; }
        public string LogLineCreatingIndexes { get; }
        public string LogLineLoadingIds { get; }
        public string LogLineImportingData { get; }
        public string LogLineImportSuccessful { get; }
        public string LogLineImportCancelled { get; }
        public string LogLineDataNotFound { get; }
        public string LogLineInsufficientDiskSpace { get; }
        public string LogLineExpectedNonFictionTable { get; }
        public string LogLineExpectedFictionTable { get; }
        public string LogLineExpectedSciMagTable { get; }
        public string LogLineFoundNonFictionTable { get; }
        public string LogLineFoundFictionTable { get; }
        public string LogLineFoundSciMagTable { get; }
        public string LogLineImportError { get; }

        public string GetElapsedString(string elapsed) => Format(section => section?.Elapsed, new { elapsed });

        public string GetFreeSpaceString(string freeSpace) => Format(section => section?.FreeSpace, new { freeSpace });

        public string GetStatusStep(int current, int total) =>
            FormatStatus(section => section?.Step, new { current = Formatter.ToFormattedString(current), total = Formatter.ToFormattedString(total) });

        public string GetLogLineStep(int step) => FormatLogLine(section => section?.Step, new { step = Formatter.ToDecimalFormattedString(step) });

        public string GetLogLineScannedProgress(decimal percent) =>
            FormatLogLine(section => section?.ScannedProgress, new { percent = Formatter.ToFormattedString(percent) });

        public string GetLogLineCreatingIndexForColumn(string column) => FormatLogLine(section => section?.CreatingIndexForColumn, new { column });

        public string GetLogLineLoadingColumnValues(string column) => FormatLogLine(section => section?.LoadingColumnValues, new { column });

        public string GetLogLineImportBooksProgressNoUpdate(int added) =>
            FormatLogLine(section => section?.ImportBooksProgressNoUpdate, new { added = Formatter.ToFormattedString(added) });

        public string GetLogLineImportBooksProgressWithUpdate(int added, int updated) =>
            FormatLogLine(section => section?.ImportBooksProgressWithUpdate,
                new { added = Formatter.ToFormattedString(added), updated = Formatter.ToFormattedString(updated) });

        public string GetLogLineImportArticlesProgressNoUpdate(int added) =>
            FormatLogLine(section => section?.ImportArticlesProgressNoUpdate, new { added = Formatter.ToFormattedString(added) });

        public string GetLogLineImportArticlesProgressWithUpdate(int added, int updated) =>
            FormatLogLine(section => section?.ImportArticlesProgressWithUpdate,
                new { added = Formatter.ToFormattedString(added), updated = Formatter.ToFormattedString(updated) });

        public string GetLogLineWrongTableFound(string expected, string found) => FormatLogLine(section => section?.WrongTableFound, new { expected, found });

        private string FormatStatus(Func<Translation.ImportStatusMessagesTranslation, string> statusFieldSelector, object templateArguments = null) =>
            Format(translation => statusFieldSelector(translation?.Import?.StatusMessages), templateArguments);

        private string FormatLogLine(Func<Translation.ImportLogMessagesTranslation, string> logLineFieldSelector, object templateArguments = null) =>
            Format(translation => logLineFieldSelector(translation?.Import?.LogMessages), templateArguments);
    }
}

{'repo_name': 'libgenapps/LibgenDesktop', 'stars': '636', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': -859262895558436392, 'source_dataset': 'data'}


// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.project;

import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.util.Ref;
import com.intellij.testFramework.fixtures.BasePlatformTestCase;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;

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

public class DumbServiceSyncTaskQueueTest extends BasePlatformTestCase {
  private final DumbServiceMergingTaskQueue myQueue = new DumbServiceMergingTaskQueue();
  private final DumbServiceSyncTaskQueue myService = new DumbServiceSyncTaskQueue(myQueue);

  @NotNull
  private DumbServiceSyncTaskQueue service() {
    return myService;
  }

  public void testRecursionIsBlocked() {
    final Ref<Boolean> myInnerRunning = new Ref<>(null);
    service().runTaskSynchronously(new DumbModeTask("parent") {
      boolean myIsRunning = false;

      @Override
      public void performInDumbMode(@NotNull ProgressIndicator indicator) {
        myIsRunning = true;
        try {
          service().runTaskSynchronously(new DumbModeTask("child") {
            @Override
            public void performInDumbMode(@NotNull ProgressIndicator indicator) {
              //the task execution must be postponed, so the captured closure will evaluate to `false`
              myInnerRunning.set(myIsRunning);
            }
          });
        }
        finally {
          myIsRunning = false;
        }
      }
    });
    Assert.assertFalse("One task should complete before the nested one is running", myInnerRunning.get());
  }

  public void testEquivalentTasksAreMerged() {
    List<Integer> disposeLog = new ArrayList<>();
    List<Integer> childLog = new ArrayList<>();
    service().runTaskSynchronously(new DumbModeTask("parent") {
      @Override
      public void performInDumbMode(@NotNull ProgressIndicator indicator) {
        for (int i = 0; i < 100; i++) {
          int taskId = i;
          service().runTaskSynchronously(new DumbModeTask("child") {
            @Override
            public void performInDumbMode(@NotNull ProgressIndicator indicator) {
              childLog.add(taskId);
            }

            @Override
            public void dispose() {
              disposeLog.add(taskId);
            }
          });
        }
      }
    });

    Assert.assertEquals("Only one child task should run, but were: " + childLog, 1, childLog.size());
    Assert.assertEquals("All tasks must be disposed, but were: " + disposeLog, 100, disposeLog.size());
  }

  public void testDifferentClassesWithSameEquivalentAreNotMerged() {
    List<Integer> childLog = new ArrayList<>();
    service().runTaskSynchronously(new DumbModeTask("parent") {
      @Override
      public void performInDumbMode(@NotNull ProgressIndicator indicator) {
        final String commonEquivalence = "child";
        DumbModeTask taskA = new DumbModeTask(commonEquivalence) {
          @Override
          public void performInDumbMode(@NotNull ProgressIndicator indicator) {
            childLog.add(1);
          }
        };

        DumbModeTask taskB = new DumbModeTask(commonEquivalence) {
          @Override
          public void performInDumbMode(@NotNull ProgressIndicator indicator) {
            childLog.add(-1);
          }
        };

        //both taskA and taskB submits the same equality object, it must run both
        service().runTaskSynchronously(taskA);
        service().runTaskSynchronously(taskB);
      }
    });

    Assert.assertEquals("All tasks should run, but were: " + childLog, 2, childLog.size());
  }

  public void testNonEquivalentTasksAreNotMerged() {
    List<Integer> childLog = new ArrayList<>();
    service().runTaskSynchronously(new DumbModeTask("parent") {
      @Override
      public void performInDumbMode(@NotNull ProgressIndicator indicator) {
        for (int i = 0; i < 100; i++) {
          int taskId = i;
          service().runTaskSynchronously(new DumbModeTask("child" + i) {
            @Override
            public void performInDumbMode(@NotNull ProgressIndicator indicator) {
              childLog.add(taskId);
            }
          });
        }
      }
    });

    Assert.assertEquals("Every child task are not unique, all must be executed: " + childLog, 100, childLog.size());
  }
}

{'repo_name': 'JetBrains/intellij-community', 'stars': '10177', 'repo_language': 'None', 'file_name': 'ProjectSetRequestHandler.coffee', 'mime_type': 'text/plain', 'hash': 1627351601744703260, 'source_dataset': 'data'}


using System;

namespace Dev2.Common.Interfaces.DB
{
    public interface ISourceBase<T>
    {
        T Item { get; set; }
        bool HasChanged { get; }
        T ToModel();
        string Name { get; set; }
        void Save();
        Guid SelectedGuid { get; set; }
        void AfterSave(Guid environmentId, Guid resourceId);
    }
}

{'repo_name': 'Warewolf-ESB/Warewolf', 'stars': '227', 'repo_language': 'C#', 'file_name': 'testElasticsearchSource.xml', 'mime_type': 'text/plain', 'hash': 325142112330086847, 'source_dataset': 'data'}


// RUN: %clang_cc1  -fsyntax-only -verify %s
// RUN: %clang_cc1 -x objective-c++ -fsyntax-only -verify %s
// rdar://12456743

typedef signed char BOOL;

EXPORT BOOL FUNC(BOOL enabled); // expected-error {{unknown type name 'EXPORT'}} // expected-error {{expected ';' after top level declarator}}

static inline BOOL MFIsPrivateVersion(void) {
 return __objc_yes;
}

{'repo_name': 'microsoft/clang', 'stars': '166', 'repo_language': 'C++', 'file_name': '__init__.py', 'mime_type': 'text/plain', 'hash': 8789864806672478564, 'source_dataset': 'data'}


import Template from './template';
import { decorateSelector } from '../utils/decorate-selector';

export default new Template(
  'node',
  'Node',
  'https://codesandbox.io/docs/environment#container-environment',
  'node',
  decorateSelector(() => '#66cc33'),
  {
    showOnHomePage: true,
    main: true,
    netlify: false,
    popular: true,
    mainFile: ['/pages/index.vue', '/pages/index.js', '/src/pages/index.js'],
  }
);

{'repo_name': 'codesandbox/codesandbox-client', 'stars': '9600', 'repo_language': 'JavaScript', 'file_name': 'tsc', 'mime_type': 'text/plain', 'hash': 2605604726551911263, 'source_dataset': 'data'}


/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.elasticsearch.test.loggerusage;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.analysis.Analyzer;
import org.objectweb.asm.tree.analysis.AnalyzerException;
import org.objectweb.asm.tree.analysis.BasicInterpreter;
import org.objectweb.asm.tree.analysis.BasicValue;
import org.objectweb.asm.tree.analysis.Frame;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class ESLoggerUsageChecker {
    public static final Type LOGGER_CLASS = Type.getType(Logger.class);
    public static final Type THROWABLE_CLASS = Type.getType(Throwable.class);
    public static final Type STRING_CLASS = Type.getType(String.class);
    public static final Type STRING_ARRAY_CLASS = Type.getType(String[].class);

    public static final Type OBJECT_CLASS = Type.getType(Object.class);
    public static final Type OBJECT_ARRAY_CLASS = Type.getType(Object[].class);
    public static final Type SUPPLIER_ARRAY_CLASS = Type.getType(Supplier[].class);
    public static final Type MARKER_CLASS = Type.getType(Marker.class);
    public static final List<String> LOGGER_METHODS = Arrays.asList("trace", "debug", "info", "warn", "error", "fatal");
    public static final String IGNORE_CHECKS_ANNOTATION = "org.elasticsearch.common.SuppressLoggerChecks";
    // types which are subject to checking when used in logger. <code>TestMessage<code> is also declared here to
    // make sure this functionality works
    public static final Set<Type> CUSTOM_MESSAGE_TYPE = Set.of(
        Type.getObjectType("org/elasticsearch/common/logging/ESLogMessage"));

    public static final Type PARAMETERIZED_MESSAGE_CLASS = Type.getType(ParameterizedMessage.class);

    @SuppressForbidden(reason = "command line tool")
    public static void main(String... args) throws Exception {
        System.out.println("checking for wrong usages of ESLogger...");
        boolean[] wrongUsageFound = new boolean[1];
        checkLoggerUsage(wrongLoggerUsage -> {
            System.err.println(wrongLoggerUsage.getErrorLines());
            wrongUsageFound[0] = true;
        }, args);
        if (wrongUsageFound[0]) {
            throw new Exception("Wrong logger usages found");
        } else {
            System.out.println("No wrong usages found");
        }
    }

    private static void checkLoggerUsage(Consumer<WrongLoggerUsage> wrongUsageCallback, String... classDirectories)
        throws IOException {
        for (String classDirectory : classDirectories) {
            Path root = Paths.get(classDirectory);
            if (Files.isDirectory(root) == false) {
                throw new IllegalArgumentException(root + " should be an existing directory");
            }
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (Files.isRegularFile(file) && file.getFileName().toString().endsWith(".class")) {
                        try (InputStream in = Files.newInputStream(file)) {
                            ESLoggerUsageChecker.check(wrongUsageCallback, in);
                        }
                    }
                    return super.visitFile(file, attrs);
                }
            });
        }
    }

    public static void check(Consumer<WrongLoggerUsage> wrongUsageCallback, InputStream inputStream) throws IOException {
        check(wrongUsageCallback, inputStream, s -> true);
    }

    // used by tests
    static void check(Consumer<WrongLoggerUsage> wrongUsageCallback, InputStream inputStream, Predicate<String> methodsToCheck)
        throws IOException {
        ClassReader cr = new ClassReader(inputStream);
        cr.accept(new ClassChecker(wrongUsageCallback, methodsToCheck), 0);
    }

    public static class WrongLoggerUsage {
        private final String className;
        private final String methodName;
        private final String logMethodName;
        private final int line;
        private final String errorMessage;

        public WrongLoggerUsage(String className, String methodName, String logMethodName, int line, String errorMessage) {
            this.className = className;
            this.methodName = methodName;
            this.logMethodName = logMethodName;
            this.line = line;
            this.errorMessage = errorMessage;
        }

        @Override
        public String toString() {
            return "WrongLoggerUsage{" +
                "className='" + className + '\'' +
                ", methodName='" + methodName + '\'' +
                ", logMethodName='" + logMethodName + '\'' +
                ", line=" + line +
                ", errorMessage='" + errorMessage + '\'' +
                '}';
        }

        /**
         * Returns an error message that has the form of stack traces emitted by {@link Throwable#printStackTrace}
         */
        public String getErrorLines() {
            String fullClassName = Type.getObjectType(className).getClassName();
            String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf(".") + 1, fullClassName.length());
            int innerClassIndex = simpleClassName.indexOf("$");
            if (innerClassIndex > 0) {
                simpleClassName = simpleClassName.substring(0, innerClassIndex);
            }
            simpleClassName = simpleClassName + ".java";
            StringBuilder sb = new StringBuilder();
            sb.append("Bad usage of ");
            sb.append(LOGGER_CLASS.getClassName()).append("#").append(logMethodName);
            sb.append(": ");
            sb.append(errorMessage);
            sb.append("\n\tat ");
            sb.append(fullClassName);
            sb.append(".");
            sb.append(methodName);
            sb.append("(");
            sb.append(simpleClassName);
            sb.append(":");
            sb.append(line);
            sb.append(")");
            return sb.toString();
        }
    }

    private static class ClassChecker extends ClassVisitor {
        private String className;
        private boolean ignoreChecks;
        private final Consumer<WrongLoggerUsage> wrongUsageCallback;
        private final Predicate<String> methodsToCheck;

        ClassChecker(Consumer<WrongLoggerUsage> wrongUsageCallback, Predicate<String> methodsToCheck) {
            super(Opcodes.ASM7);
            this.wrongUsageCallback = wrongUsageCallback;
            this.methodsToCheck = methodsToCheck;
        }

        @Override
        public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
            this.className = name;
        }

        @Override
        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
            if (IGNORE_CHECKS_ANNOTATION.equals(Type.getType(desc).getClassName())) {
                ignoreChecks = true;
            }
            return super.visitAnnotation(desc, visible);
        }

        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
            if (ignoreChecks == false && methodsToCheck.test(name)) {
                return new MethodChecker(this.className, access, name, desc, wrongUsageCallback);
            } else {
                return super.visitMethod(access, name, desc, signature, exceptions);
            }
        }
    }

    private static class MethodChecker extends MethodVisitor {
        private final String className;
        private final Consumer<WrongLoggerUsage> wrongUsageCallback;
        private boolean ignoreChecks;

        MethodChecker(String className, int access, String name, String desc, Consumer<WrongLoggerUsage> wrongUsageCallback) {
            super(Opcodes.ASM5, new MethodNode(access, name, desc, null, null));
            this.className = className;
            this.wrongUsageCallback = wrongUsageCallback;
        }

        @Override
        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
            if (IGNORE_CHECKS_ANNOTATION.equals(Type.getType(desc).getClassName())) {
                ignoreChecks = true;
            }
            return super.visitAnnotation(desc, visible);
        }

        @Override
        public void visitEnd() {
            if (ignoreChecks == false) {
                findBadLoggerUsages((MethodNode) mv);
            }
            super.visitEnd();
        }

        public void findBadLoggerUsages(MethodNode methodNode) {
            Analyzer<BasicValue> stringPlaceHolderAnalyzer = new Analyzer<>(new PlaceHolderStringInterpreter());
            Analyzer<BasicValue> arraySizeAnalyzer = new Analyzer<>(new ArraySizeInterpreter());
            try {
                stringPlaceHolderAnalyzer.analyze(className, methodNode);
                arraySizeAnalyzer.analyze(className, methodNode);
            } catch (AnalyzerException e) {
                throw new RuntimeException("Internal error: failed in analysis step", e);
            }
            Frame<BasicValue>[] logMessageFrames = stringPlaceHolderAnalyzer.getFrames();
            Frame<BasicValue>[] arraySizeFrames = arraySizeAnalyzer.getFrames();
            AbstractInsnNode[] insns = methodNode.instructions.toArray();
            int lineNumber = -1;
            for (int i = 0; i < insns.length; i++) {
                AbstractInsnNode insn = insns[i];
                if (insn instanceof LineNumberNode) {
                    LineNumberNode lineNumberNode = (LineNumberNode) insn;
                    lineNumber = lineNumberNode.line;
                }
                if (insn.getOpcode() == Opcodes.INVOKEINTERFACE) {
                    MethodInsnNode methodInsn = (MethodInsnNode) insn;
                    if (Type.getObjectType(methodInsn.owner).equals(LOGGER_CLASS)) {
                        if (LOGGER_METHODS.contains(methodInsn.name) == false) {
                            continue;
                        }

                        Type[] argumentTypes = Type.getArgumentTypes(methodInsn.desc);
                        int markerOffset = 0;
                        if (argumentTypes[0].equals(MARKER_CLASS)) {
                            markerOffset = 1;
                        }

                        int lengthWithoutMarker = argumentTypes.length - markerOffset;

                        verifyLoggerUsage(methodNode, logMessageFrames, arraySizeFrames, lineNumber, i,
                            methodInsn, argumentTypes, markerOffset, lengthWithoutMarker);
                    }
                } else if (insn.getOpcode() == Opcodes.INVOKESPECIAL) { // constructor invocation
                    MethodInsnNode methodInsn = (MethodInsnNode) insn;
                    Type objectType = Type.getObjectType(methodInsn.owner);

                    if (CUSTOM_MESSAGE_TYPE.contains(objectType)) {
                        Type[] argumentTypes = Type.getArgumentTypes(methodInsn.desc);
                        if (argumentTypes.length == 2 &&
                            argumentTypes[0].equals(STRING_CLASS) &&
                            argumentTypes[1].equals(OBJECT_ARRAY_CLASS)) {
                            checkArrayArgs(methodNode, logMessageFrames[i], arraySizeFrames[i], lineNumber, methodInsn, 0, 1);
                        }
                    }else if (objectType.equals(PARAMETERIZED_MESSAGE_CLASS)) {
                        Type[] argumentTypes = Type.getArgumentTypes(methodInsn.desc);
                        if (argumentTypes.length == 2 &&
                            argumentTypes[0].equals(STRING_CLASS) &&
                            argumentTypes[1].equals(OBJECT_ARRAY_CLASS)) {
                            checkArrayArgs(methodNode, logMessageFrames[i], arraySizeFrames[i], lineNumber, methodInsn, 0, 1);
                        } else if (argumentTypes.length == 2 &&
                            argumentTypes[0].equals(STRING_CLASS) &&
                            argumentTypes[1].equals(OBJECT_CLASS)) {
                            checkFixedArityArgs(methodNode, logMessageFrames[i], lineNumber, methodInsn, 0, 1);
                        } else if (argumentTypes.length == 3 &&
                            argumentTypes[0].equals(STRING_CLASS) &&
                            argumentTypes[1].equals(OBJECT_CLASS) &&
                            argumentTypes[2].equals(OBJECT_CLASS)) {
                            checkFixedArityArgs(methodNode, logMessageFrames[i], lineNumber, methodInsn, 0, 2);
                        } else if (argumentTypes.length == 3 &&
                            argumentTypes[0].equals(STRING_CLASS) &&
                            argumentTypes[1].equals(OBJECT_ARRAY_CLASS) &&
                            argumentTypes[2].equals(THROWABLE_CLASS)) {
                            checkArrayArgs(methodNode, logMessageFrames[i], arraySizeFrames[i], lineNumber, methodInsn, 0, 1);
                        } else if (argumentTypes.length == 3 &&
                            argumentTypes[0].equals(STRING_CLASS) &&
                            argumentTypes[1].equals(STRING_ARRAY_CLASS) &&
                            argumentTypes[2].equals(THROWABLE_CLASS)) {
                            checkArrayArgs(methodNode, logMessageFrames[i], arraySizeFrames[i], lineNumber, methodInsn, 0, 1);
                        } else {
                            throw new IllegalStateException("Constructor invoked on " + objectType +
                                " that is not supported by logger usage checker"+
                                new WrongLoggerUsage(className, methodNode.name, methodInsn.name, lineNumber,
                                "Constructor: "+ Arrays.toString(argumentTypes)));
                        }
                    }
                } else if (insn.getOpcode() == Opcodes.INVOKEVIRTUAL) {
                    //using strings because this test do not depend on server

                    MethodInsnNode methodInsn = (MethodInsnNode) insn;
                    if (methodInsn.owner.equals("org/elasticsearch/common/logging/DeprecationLogger")) {
                        if (methodInsn.name.equals("deprecate")) {
                            Type[] argumentTypes = Type.getArgumentTypes(methodInsn.desc);
                            int markerOffset = 1; // skip key

                            int lengthWithoutMarker = argumentTypes.length - markerOffset;

                            verifyLoggerUsage(methodNode, logMessageFrames, arraySizeFrames, lineNumber, i,
                                methodInsn, argumentTypes, markerOffset, lengthWithoutMarker);
                        }
                    }
                }
            }
        }

        private void verifyLoggerUsage(MethodNode methodNode, Frame<BasicValue>[] logMessageFrames, Frame<BasicValue>[] arraySizeFrames,
                                       int lineNumber, int i, MethodInsnNode methodInsn, Type[] argumentTypes,
                                       int markerOffset, int lengthWithoutMarker) {
            if (lengthWithoutMarker == 2 &&
                argumentTypes[markerOffset + 0].equals(STRING_CLASS) &&
                (argumentTypes[markerOffset + 1].equals(OBJECT_ARRAY_CLASS) ||
                    argumentTypes[markerOffset + 1].equals(SUPPLIER_ARRAY_CLASS))) {
                // VARARGS METHOD: debug(Marker?, String, (Object...|Supplier...))
                checkArrayArgs(methodNode, logMessageFrames[i], arraySizeFrames[i], lineNumber, methodInsn, markerOffset + 0,
                    markerOffset + 1);
            } else if (lengthWithoutMarker >= 2 &&
                argumentTypes[markerOffset + 0].equals(STRING_CLASS) &&
                argumentTypes[markerOffset + 1].equals(OBJECT_CLASS)) {
                // MULTI-PARAM METHOD: debug(Marker?, String, Object p0, ...)
                checkFixedArityArgs(methodNode, logMessageFrames[i], lineNumber, methodInsn, markerOffset + 0,
                    lengthWithoutMarker - 1);
            } else if ((lengthWithoutMarker == 1 || lengthWithoutMarker == 2) &&
                lengthWithoutMarker == 2 ? argumentTypes[markerOffset + 1].equals(THROWABLE_CLASS) : true) {
                // all the rest: debug(Marker?, (Message|MessageSupplier|CharSequence|Object|String|Supplier), Throwable?)
                checkFixedArityArgs(methodNode, logMessageFrames[i], lineNumber, methodInsn, markerOffset + 0, 0);
            } else {
                throw new IllegalStateException("Method invoked on " + LOGGER_CLASS.getClassName() +
                    " that is not supported by logger usage checker");
            }
        }

        private void checkFixedArityArgs(MethodNode methodNode, Frame<BasicValue> logMessageFrame, int lineNumber,
                                         MethodInsnNode methodInsn, int messageIndex, int positionalArgsLength) {
            PlaceHolderStringBasicValue logMessageLength = checkLogMessageConsistency(methodNode, logMessageFrame, lineNumber, methodInsn,
                messageIndex, positionalArgsLength);
            if (logMessageLength == null) {
                return;
            }
            if (logMessageLength.minValue != positionalArgsLength) {
                wrongUsageCallback.accept(new WrongLoggerUsage(className, methodNode.name, methodInsn.name, lineNumber,
                    "Expected " + logMessageLength.minValue + " arguments but got " + positionalArgsLength));
                return;
            }
        }

        private void checkArrayArgs(MethodNode methodNode, Frame<BasicValue> logMessageFrame, Frame<BasicValue> arraySizeFrame,
                                    int lineNumber, MethodInsnNode methodInsn, int messageIndex, int arrayIndex) {
            BasicValue arraySizeObject = getStackValue(arraySizeFrame, methodInsn, arrayIndex);
            if (arraySizeObject instanceof ArraySizeBasicValue == false) {
                wrongUsageCallback.accept(new WrongLoggerUsage(className, methodNode.name, methodInsn.name, lineNumber,
                    "Could not determine size of array"));
                return;
            }
            ArraySizeBasicValue arraySize = (ArraySizeBasicValue) arraySizeObject;
            PlaceHolderStringBasicValue logMessageLength = checkLogMessageConsistency(methodNode, logMessageFrame, lineNumber, methodInsn,
                messageIndex, arraySize.minValue);
            if (logMessageLength == null) {
                return;
            }
            if (arraySize.minValue != arraySize.maxValue) {
                wrongUsageCallback.accept(new WrongLoggerUsage(className, methodNode.name, methodInsn.name, lineNumber,
                    "Multiple parameter arrays with conflicting sizes"));
                return;
            }
            assert logMessageLength.minValue == logMessageLength.maxValue && arraySize.minValue == arraySize.maxValue;
            int chainedParams = getChainedParams(methodInsn);
            int args = arraySize.minValue + chainedParams;
            if (logMessageLength.minValue != args) {
                wrongUsageCallback.accept(new WrongLoggerUsage(className, methodNode.name, methodInsn.name, lineNumber,
                    "Expected " + logMessageLength.minValue + " arguments but got " + arraySize.minValue));
                return;
            }
        }

        //counts how many times argAndField  was called on the method chain
        private int getChainedParams(AbstractInsnNode startNode) {
            int c = 0;
            AbstractInsnNode current = startNode;
            while(current.getNext() != null){
                current = current.getNext();
                if(current instanceof MethodInsnNode){
                    MethodInsnNode method = (MethodInsnNode)current;
                    if(method.name.equals("argAndField")){
                        c++;
                    }
                }
            }
            return c;
        }

        private PlaceHolderStringBasicValue checkLogMessageConsistency(MethodNode methodNode, Frame<BasicValue> logMessageFrame,
                                                                       int lineNumber, MethodInsnNode methodInsn, int messageIndex,
                                                                       int argsSize) {
            BasicValue logMessageLengthObject = getStackValue(logMessageFrame, methodInsn, messageIndex);
            if (logMessageLengthObject instanceof PlaceHolderStringBasicValue == false) {
                if (argsSize > 0) {
                    wrongUsageCallback.accept(new WrongLoggerUsage(className, methodNode.name, methodInsn.name, lineNumber,
                        "First argument must be a string constant so that we can statically ensure proper place holder usage"));
                } else {
                    // don't check logger usage for logger.warn(someObject)
                }
                return null;
            }
            PlaceHolderStringBasicValue logMessageLength = (PlaceHolderStringBasicValue) logMessageLengthObject;
            if (logMessageLength.minValue != logMessageLength.maxValue) {
                wrongUsageCallback.accept(new WrongLoggerUsage(className, methodNode.name, methodInsn.name, lineNumber,
                    "Multiple log messages with conflicting number of place holders"));
                return null;
            }
            return logMessageLength;
        }
    }

    private static int calculateNumberOfPlaceHolders(String message) {
        int count = 0;
        for (int i = 1; i < message.length(); i++) {
            if (message.charAt(i - 1) == '{' && message.charAt(i) == '}') {
                count++;
                i += 1;
            }
        }
        return count;
    }

    private static BasicValue getStackValue(Frame<BasicValue> f, MethodInsnNode methodInsn, int index) {
        int relIndex = Type.getArgumentTypes(methodInsn.desc).length - 1 - index;
        int top = f.getStackSize() - 1;
        return relIndex <= top ? f.getStack(top - relIndex) : null;
    }

    private static class IntMinMaxTrackingBasicValue extends BasicValue {
        protected final int minValue;
        protected final int maxValue;

        IntMinMaxTrackingBasicValue(Type type, int value) {
            super(type);
            this.minValue = value;
            this.maxValue = value;
        }

        IntMinMaxTrackingBasicValue(Type type, int minValue, int maxValue) {
            super(type);
            this.minValue = minValue;
            this.maxValue = maxValue;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            if (!super.equals(o)) return false;

            IntMinMaxTrackingBasicValue that = (IntMinMaxTrackingBasicValue) o;

            if (minValue != that.minValue) return false;
            return maxValue == that.maxValue;

        }

        @Override
        public int hashCode() {
            int result = super.hashCode();
            result = 31 * result + minValue;
            result = 31 * result + maxValue;
            return result;
        }

        @Override
        public String toString() {
            return "IntMinMaxTrackingBasicValue{" +
                "minValue=" + minValue +
                ", maxValue=" + maxValue +
                '}';
        }
    }

    private static final class PlaceHolderStringBasicValue extends IntMinMaxTrackingBasicValue {
        public static final Type STRING_OBJECT_TYPE = Type.getObjectType("java/lang/String");

        PlaceHolderStringBasicValue(int placeHolders) {
            super(STRING_OBJECT_TYPE, placeHolders);
        }

        PlaceHolderStringBasicValue(int minPlaceHolders, int maxPlaceHolders) {
            super(STRING_OBJECT_TYPE, minPlaceHolders, maxPlaceHolders);
        }
    }

    private static final class ArraySizeBasicValue extends IntMinMaxTrackingBasicValue {
        ArraySizeBasicValue(Type type, int minArraySize, int maxArraySize) {
            super(type, minArraySize, maxArraySize);
        }
    }

    private static final class IntegerConstantBasicValue extends IntMinMaxTrackingBasicValue {
        IntegerConstantBasicValue(Type type, int constant) {
            super(type, constant);
        }

        IntegerConstantBasicValue(Type type, int minConstant, int maxConstant) {
            super(type, minConstant, maxConstant);
        }
    }

    private static final class PlaceHolderStringInterpreter extends BasicInterpreter {

        PlaceHolderStringInterpreter() {
            super(Opcodes.ASM7);
        }

        @Override
        public BasicValue newOperation(AbstractInsnNode insnNode) throws AnalyzerException {
            if (insnNode.getOpcode() == Opcodes.LDC) {
                Object constant = ((LdcInsnNode) insnNode).cst;
                if (constant instanceof String) {
                    return new PlaceHolderStringBasicValue(calculateNumberOfPlaceHolders((String) constant));
                }
            }
            return super.newOperation(insnNode);
        }

        @Override
        public BasicValue merge(BasicValue value1, BasicValue value2) {
            if (value1 instanceof PlaceHolderStringBasicValue && value2 instanceof PlaceHolderStringBasicValue
                && value1.equals(value2) == false) {
                PlaceHolderStringBasicValue c1 = (PlaceHolderStringBasicValue) value1;
                PlaceHolderStringBasicValue c2 = (PlaceHolderStringBasicValue) value2;
                return new PlaceHolderStringBasicValue(Math.min(c1.minValue, c2.minValue), Math.max(c1.maxValue, c2.maxValue));
            }
            return super.merge(value1, value2);
        }
    }

    private static final class ArraySizeInterpreter extends BasicInterpreter {

        ArraySizeInterpreter() {
            super(Opcodes.ASM7);
        }

        @Override
        public BasicValue newOperation(AbstractInsnNode insnNode) throws AnalyzerException {
            switch (insnNode.getOpcode()) {
                case ICONST_0: return new IntegerConstantBasicValue(Type.INT_TYPE, 0);
                case ICONST_1: return new IntegerConstantBasicValue(Type.INT_TYPE, 1);
                case ICONST_2: return new IntegerConstantBasicValue(Type.INT_TYPE, 2);
                case ICONST_3: return new IntegerConstantBasicValue(Type.INT_TYPE, 3);
                case ICONST_4: return new IntegerConstantBasicValue(Type.INT_TYPE, 4);
                case ICONST_5: return new IntegerConstantBasicValue(Type.INT_TYPE, 5);
                case BIPUSH:
                case SIPUSH: return new IntegerConstantBasicValue(Type.INT_TYPE, ((IntInsnNode)insnNode).operand);
                case Opcodes.LDC: {
                    Object constant = ((LdcInsnNode)insnNode).cst;
                    if (constant instanceof Integer) {
                        return new IntegerConstantBasicValue(Type.INT_TYPE, (Integer)constant);
                    } else {
                        return super.newOperation(insnNode);
                    }
                }
                default: return super.newOperation(insnNode);
            }
        }

        @Override
        public BasicValue merge(BasicValue value1, BasicValue value2) {
            if (value1 instanceof IntegerConstantBasicValue && value2 instanceof IntegerConstantBasicValue) {
                IntegerConstantBasicValue c1 = (IntegerConstantBasicValue) value1;
                IntegerConstantBasicValue c2 = (IntegerConstantBasicValue) value2;
                return new IntegerConstantBasicValue(Type.INT_TYPE, Math.min(c1.minValue, c2.minValue), Math.max(c1.maxValue, c2.maxValue));
            } else if (value1 instanceof ArraySizeBasicValue && value2 instanceof ArraySizeBasicValue) {
                ArraySizeBasicValue c1 = (ArraySizeBasicValue) value1;
                ArraySizeBasicValue c2 = (ArraySizeBasicValue) value2;
                return new ArraySizeBasicValue(Type.INT_TYPE, Math.min(c1.minValue, c2.minValue), Math.max(c1.maxValue, c2.maxValue));
            }
            return super.merge(value1, value2);
        }

        @Override
        public BasicValue unaryOperation(AbstractInsnNode insnNode, BasicValue value) throws AnalyzerException {
            if (insnNode.getOpcode() == Opcodes.ANEWARRAY && value instanceof IntegerConstantBasicValue) {
                IntegerConstantBasicValue constantBasicValue = (IntegerConstantBasicValue) value;
                String desc = ((TypeInsnNode) insnNode).desc;
                return new ArraySizeBasicValue(Type.getType("[" + Type.getObjectType(desc)), constantBasicValue.minValue,
                    constantBasicValue.maxValue);
            }
            return super.unaryOperation(insnNode, value);
        }

        @Override
        public BasicValue ternaryOperation(AbstractInsnNode insnNode, BasicValue value1, BasicValue value2, BasicValue value3)
            throws AnalyzerException {
            if (insnNode.getOpcode() == Opcodes.AASTORE && value1 instanceof ArraySizeBasicValue) {
                return value1;
            }
            return super.ternaryOperation(insnNode, value1, value2, value3);
        }
    }
}

{'repo_name': 'elastic/elasticsearch', 'stars': '49964', 'repo_language': 'Java', 'file_name': 'UnassignedInfo.java', 'mime_type': 'text/x-java', 'hash': 5609314282355198635, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <!-- This file was generated by Fody. Manual changes to this file will be lost when your project is rebuilt. -->
  <xs:element name="Weavers">
    <xs:complexType>
      <xs:all>
        <xs:element name="ModuleInit" minOccurs="0" maxOccurs="1" type="xs:anyType" />
      </xs:all>
      <xs:attribute name="VerifyAssembly" type="xs:boolean">
        <xs:annotation>
          <xs:documentation>'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.</xs:documentation>
        </xs:annotation>
      </xs:attribute>
      <xs:attribute name="VerifyIgnoreCodes" type="xs:string">
        <xs:annotation>
          <xs:documentation>A comma-separated list of error codes that can be safely ignored in assembly verification.</xs:documentation>
        </xs:annotation>
      </xs:attribute>
      <xs:attribute name="GenerateXsd" type="xs:boolean">
        <xs:annotation>
          <xs:documentation>'false' to turn off automatic generation of the XML Schema file.</xs:documentation>
        </xs:annotation>
      </xs:attribute>
    </xs:complexType>
  </xs:element>
</xs:schema>

{'repo_name': 'approvals/ApprovalTests.Net', 'stars': '364', 'repo_language': 'C#', 'file_name': 'CustomizingDiffToolSelectionOrder.source.md', 'mime_type': 'text/plain', 'hash': 325888140194849595, 'source_dataset': 'data'}


// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Kolja Brix <brix@igpm.rwth-aachen.de>
// Copyright (C) 2011 Andreas Platen <andiplaten@gmx.de>
// Copyright (C) 2012 Chen-Pang He <jdh8@ms63.hinet.net>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef KRONECKER_TENSOR_PRODUCT_H
#define KRONECKER_TENSOR_PRODUCT_H

namespace Eigen {

/*!
 * \ingroup KroneckerProduct_Module
 *
 * \brief The base class of dense and sparse Kronecker product.
 *
 * \tparam Derived is the derived type.
 */
template<typename Derived>
class KroneckerProductBase : public ReturnByValue<Derived>
{
  private:
    typedef typename internal::traits<Derived> Traits;
    typedef typename Traits::Scalar Scalar;

  protected:
    typedef typename Traits::Lhs Lhs;
    typedef typename Traits::Rhs Rhs;

  public:
    /*! \brief Constructor. */
    KroneckerProductBase(const Lhs& A, const Rhs& B)
      : m_A(A), m_B(B)
    {}

    inline Index rows() const { return m_A.rows() * m_B.rows(); }
    inline Index cols() const { return m_A.cols() * m_B.cols(); }

    /*!
     * This overrides ReturnByValue::coeff because this function is
     * efficient enough.
     */
    Scalar coeff(Index row, Index col) const
    {
      return m_A.coeff(row / m_B.rows(), col / m_B.cols()) *
             m_B.coeff(row % m_B.rows(), col % m_B.cols());
    }

    /*!
     * This overrides ReturnByValue::coeff because this function is
     * efficient enough.
     */
    Scalar coeff(Index i) const
    {
      EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived);
      return m_A.coeff(i / m_A.size()) * m_B.coeff(i % m_A.size());
    }

  protected:
    typename Lhs::Nested m_A;
    typename Rhs::Nested m_B;
};

/*!
 * \ingroup KroneckerProduct_Module
 *
 * \brief Kronecker tensor product helper class for dense matrices
 *
 * This class is the return value of kroneckerProduct(MatrixBase,
 * MatrixBase). Use the function rather than construct this class
 * directly to avoid specifying template prarameters.
 *
 * \tparam Lhs  Type of the left-hand side, a matrix expression.
 * \tparam Rhs  Type of the rignt-hand side, a matrix expression.
 */
template<typename Lhs, typename Rhs>
class KroneckerProduct : public KroneckerProductBase<KroneckerProduct<Lhs,Rhs> >
{
  private:
    typedef KroneckerProductBase<KroneckerProduct> Base;
    using Base::m_A;
    using Base::m_B;

  public:
    /*! \brief Constructor. */
    KroneckerProduct(const Lhs& A, const Rhs& B)
      : Base(A, B)
    {}

    /*! \brief Evaluate the Kronecker tensor product. */
    template<typename Dest> void evalTo(Dest& dst) const;
};

/*!
 * \ingroup KroneckerProduct_Module
 *
 * \brief Kronecker tensor product helper class for sparse matrices
 *
 * If at least one of the operands is a sparse matrix expression,
 * then this class is returned and evaluates into a sparse matrix.
 *
 * This class is the return value of kroneckerProduct(EigenBase,
 * EigenBase). Use the function rather than construct this class
 * directly to avoid specifying template prarameters.
 *
 * \tparam Lhs  Type of the left-hand side, a matrix expression.
 * \tparam Rhs  Type of the rignt-hand side, a matrix expression.
 */
template<typename Lhs, typename Rhs>
class KroneckerProductSparse : public KroneckerProductBase<KroneckerProductSparse<Lhs,Rhs> >
{
  private:
    typedef KroneckerProductBase<KroneckerProductSparse> Base;
    using Base::m_A;
    using Base::m_B;

  public:
    /*! \brief Constructor. */
    KroneckerProductSparse(const Lhs& A, const Rhs& B)
      : Base(A, B)
    {}

    /*! \brief Evaluate the Kronecker tensor product. */
    template<typename Dest> void evalTo(Dest& dst) const;
};

template<typename Lhs, typename Rhs>
template<typename Dest>
void KroneckerProduct<Lhs,Rhs>::evalTo(Dest& dst) const
{
  const int BlockRows = Rhs::RowsAtCompileTime,
            BlockCols = Rhs::ColsAtCompileTime;
  const Index Br = m_B.rows(),
              Bc = m_B.cols();
  for (Index i=0; i < m_A.rows(); ++i)
    for (Index j=0; j < m_A.cols(); ++j)
      Block<Dest,BlockRows,BlockCols>(dst,i*Br,j*Bc,Br,Bc) = m_A.coeff(i,j) * m_B;
}

template<typename Lhs, typename Rhs>
template<typename Dest>
void KroneckerProductSparse<Lhs,Rhs>::evalTo(Dest& dst) const
{
  Index Br = m_B.rows(), Bc = m_B.cols();
  dst.resize(this->rows(), this->cols());
  dst.resizeNonZeros(0);

  // 1 - evaluate the operands if needed:
  typedef typename internal::nested_eval<Lhs,Dynamic>::type Lhs1;
  typedef typename internal::remove_all<Lhs1>::type Lhs1Cleaned;
  const Lhs1 lhs1(m_A);
  typedef typename internal::nested_eval<Rhs,Dynamic>::type Rhs1;
  typedef typename internal::remove_all<Rhs1>::type Rhs1Cleaned;
  const Rhs1 rhs1(m_B);

  // 2 - construct respective iterators
  typedef Eigen::InnerIterator<Lhs1Cleaned> LhsInnerIterator;
  typedef Eigen::InnerIterator<Rhs1Cleaned> RhsInnerIterator;

  // compute number of non-zeros per innervectors of dst
  {
    // TODO VectorXi is not necessarily big enough!
    VectorXi nnzA = VectorXi::Zero(Dest::IsRowMajor ? m_A.rows() : m_A.cols());
    for (Index kA=0; kA < m_A.outerSize(); ++kA)
      for (LhsInnerIterator itA(lhs1,kA); itA; ++itA)
        nnzA(Dest::IsRowMajor ? itA.row() : itA.col())++;

    VectorXi nnzB = VectorXi::Zero(Dest::IsRowMajor ? m_B.rows() : m_B.cols());
    for (Index kB=0; kB < m_B.outerSize(); ++kB)
      for (RhsInnerIterator itB(rhs1,kB); itB; ++itB)
        nnzB(Dest::IsRowMajor ? itB.row() : itB.col())++;

    Matrix<int,Dynamic,Dynamic,ColMajor> nnzAB = nnzB * nnzA.transpose();
    dst.reserve(VectorXi::Map(nnzAB.data(), nnzAB.size()));
  }

  for (Index kA=0; kA < m_A.outerSize(); ++kA)
  {
    for (Index kB=0; kB < m_B.outerSize(); ++kB)
    {
      for (LhsInnerIterator itA(lhs1,kA); itA; ++itA)
      {
        for (RhsInnerIterator itB(rhs1,kB); itB; ++itB)
        {
          Index i = itA.row() * Br + itB.row(),
                j = itA.col() * Bc + itB.col();
          dst.insert(i,j) = itA.value() * itB.value();
        }
      }
    }
  }
}

namespace internal {

template<typename _Lhs, typename _Rhs>
struct traits<KroneckerProduct<_Lhs,_Rhs> >
{
  typedef typename remove_all<_Lhs>::type Lhs;
  typedef typename remove_all<_Rhs>::type Rhs;
  typedef typename scalar_product_traits<typename Lhs::Scalar, typename Rhs::Scalar>::ReturnType Scalar;
  typedef typename promote_index_type<typename Lhs::StorageIndex, typename Rhs::StorageIndex>::type StorageIndex;

  enum {
    Rows = size_at_compile_time<traits<Lhs>::RowsAtCompileTime, traits<Rhs>::RowsAtCompileTime>::ret,
    Cols = size_at_compile_time<traits<Lhs>::ColsAtCompileTime, traits<Rhs>::ColsAtCompileTime>::ret,
    MaxRows = size_at_compile_time<traits<Lhs>::MaxRowsAtCompileTime, traits<Rhs>::MaxRowsAtCompileTime>::ret,
    MaxCols = size_at_compile_time<traits<Lhs>::MaxColsAtCompileTime, traits<Rhs>::MaxColsAtCompileTime>::ret
  };

  typedef Matrix<Scalar,Rows,Cols> ReturnType;
};

template<typename _Lhs, typename _Rhs>
struct traits<KroneckerProductSparse<_Lhs,_Rhs> >
{
  typedef MatrixXpr XprKind;
  typedef typename remove_all<_Lhs>::type Lhs;
  typedef typename remove_all<_Rhs>::type Rhs;
  typedef typename scalar_product_traits<typename Lhs::Scalar, typename Rhs::Scalar>::ReturnType Scalar;
  typedef typename cwise_promote_storage_type<typename traits<Lhs>::StorageKind, typename traits<Rhs>::StorageKind, scalar_product_op<typename Lhs::Scalar, typename Rhs::Scalar> >::ret StorageKind;
  typedef typename promote_index_type<typename Lhs::StorageIndex, typename Rhs::StorageIndex>::type StorageIndex;

  enum {
    LhsFlags = Lhs::Flags,
    RhsFlags = Rhs::Flags,

    RowsAtCompileTime = size_at_compile_time<traits<Lhs>::RowsAtCompileTime, traits<Rhs>::RowsAtCompileTime>::ret,
    ColsAtCompileTime = size_at_compile_time<traits<Lhs>::ColsAtCompileTime, traits<Rhs>::ColsAtCompileTime>::ret,
    MaxRowsAtCompileTime = size_at_compile_time<traits<Lhs>::MaxRowsAtCompileTime, traits<Rhs>::MaxRowsAtCompileTime>::ret,
    MaxColsAtCompileTime = size_at_compile_time<traits<Lhs>::MaxColsAtCompileTime, traits<Rhs>::MaxColsAtCompileTime>::ret,

    EvalToRowMajor = (LhsFlags & RhsFlags & RowMajorBit),
    RemovedBits = ~(EvalToRowMajor ? 0 : RowMajorBit),

    Flags = ((LhsFlags | RhsFlags) & HereditaryBits & RemovedBits)
          | EvalBeforeNestingBit | EvalBeforeAssigningBit,
    CoeffReadCost = HugeCost
  };

  typedef SparseMatrix<Scalar, 0, StorageIndex> ReturnType;
};

} // end namespace internal

/*!
 * \ingroup KroneckerProduct_Module
 *
 * Computes Kronecker tensor product of two dense matrices
 *
 * \warning If you want to replace a matrix by its Kronecker product
 *          with some matrix, do \b NOT do this:
 * \code
 * A = kroneckerProduct(A,B); // bug!!! caused by aliasing effect
 * \endcode
 * instead, use eval() to work around this:
 * \code
 * A = kroneckerProduct(A,B).eval();
 * \endcode
 *
 * \param a  Dense matrix a
 * \param b  Dense matrix b
 * \return   Kronecker tensor product of a and b
 */
template<typename A, typename B>
KroneckerProduct<A,B> kroneckerProduct(const MatrixBase<A>& a, const MatrixBase<B>& b)
{
  return KroneckerProduct<A, B>(a.derived(), b.derived());
}

/*!
 * \ingroup KroneckerProduct_Module
 *
 * Computes Kronecker tensor product of two matrices, at least one of
 * which is sparse
 *
 * \warning If you want to replace a matrix by its Kronecker product
 *          with some matrix, do \b NOT do this:
 * \code
 * A = kroneckerProduct(A,B); // bug!!! caused by aliasing effect
 * \endcode
 * instead, use eval() to work around this:
 * \code
 * A = kroneckerProduct(A,B).eval();
 * \endcode
 *
 * \param a  Dense/sparse matrix a
 * \param b  Dense/sparse matrix b
 * \return   Kronecker tensor product of a and b, stored in a sparse
 *           matrix
 */
template<typename A, typename B>
KroneckerProductSparse<A,B> kroneckerProduct(const EigenBase<A>& a, const EigenBase<B>& b)
{
  return KroneckerProductSparse<A,B>(a.derived(), b.derived());
}

} // end namespace Eigen

#endif // KRONECKER_TENSOR_PRODUCT_H

{'repo_name': 'zju3dv/pvnet', 'stars': '549', 'repo_language': 'Jupyter Notebook', 'file_name': 'ransac_voting_kernel.cu', 'mime_type': 'text/x-c', 'hash': -4296632754152552272, 'source_dataset': 'data'}


//------------------------------------------------------------------------------
// <copyright file="_AuthenticationManager2.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Net
{
    using System;
    using System.Collections;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Net.Configuration;
    using System.Reflection;
    using System.Security.Authentication.ExtendedProtection;

    internal class AuthenticationManager2 : AuthenticationManagerBase
    {
        private PrefixLookup moduleBinding = null;
        private ConcurrentDictionary<string, IAuthenticationModule> moduleList = null;

        public AuthenticationManager2()
        {
            this.moduleBinding = new PrefixLookup();
            InitializeModuleList();
        }

        public AuthenticationManager2(int maxPrefixLookupEntries)
        {
            this.moduleBinding = new PrefixLookup(maxPrefixLookupEntries);
            InitializeModuleList();
        }

        /// <devdoc>
        ///    <para>Call each registered authentication module to determine the first module that
        ///       can respond to the authentication request.</para>
        /// </devdoc>
        public override Authorization Authenticate(string challenge, WebRequest request, ICredentials credentials)
        {
            //
            // parameter validation
            //
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }

            if (challenge == null)
            {
                throw new ArgumentNullException("challenge");
            }

            GlobalLog.Print("AuthenticationManager::Authenticate() challenge:[" + challenge + "]");

            Authorization response = null;

            HttpWebRequest httpWebRequest = request as HttpWebRequest;
            if (httpWebRequest != null && httpWebRequest.CurrentAuthenticationState.Module != null)
            {
                response =
                    httpWebRequest.CurrentAuthenticationState.Module.Authenticate(challenge, request, credentials);
            }
            else
            {
                // This is the case where we would try to find the module on the first server challenge
                foreach (IAuthenticationModule authenticationModule in this.moduleList.Values)
                {
                    //
                    // the AuthenticationModule will
                    // 1) return a valid string on success
                    // 2) return null if it knows it cannot respond
                    // 3) throw if it could have responded but unexpectedly failed to do so
                    //
                    if (httpWebRequest != null)
                    {
                        httpWebRequest.CurrentAuthenticationState.Module = authenticationModule;
                    }

                    response = authenticationModule.Authenticate(challenge, request, credentials);

                    if (response != null)
                    {
                        //
                        // found the Authentication Module, return it
                        //
                        GlobalLog.Print("AuthenticationManager::Authenticate() found IAuthenticationModule:["
                                        + authenticationModule.AuthenticationType + "]");
                        break;
                    }
                }
            }

            return response;
        }

        /// <devdoc>
        ///    <para>Pre-authenticates a request.</para>
        /// </devdoc>
        public override Authorization PreAuthenticate(WebRequest request, ICredentials credentials)
        {
            GlobalLog.Print("AuthenticationManager::PreAuthenticate() request:"
                + ValidationHelper.HashString(request) + " credentials:" + ValidationHelper.HashString(credentials));

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (credentials == null)
            {
                return null;
            }

            HttpWebRequest httpWebRequest = request as HttpWebRequest;
            IAuthenticationModule authenticationModule;
            if (httpWebRequest == null)
            {
                return null;
            }

            //
            // PrefixLookup is thread-safe
            //
            string moduleName = moduleBinding.Lookup(httpWebRequest.ChallengedUri.AbsoluteUri) as string;
            GlobalLog.Print("AuthenticationManager::PreAuthenticate() s_ModuleBinding.Lookup returns:"
                            + ValidationHelper.ToString(moduleName));

            if (moduleName == null)
            {
                return null;
            }

            if (!this.moduleList.TryGetValue(moduleName.ToUpperInvariant(), out authenticationModule))
            {
                // The module could have been unregistered
                // No preauthentication is possible
                return null;
            }

            // prepopulate the channel binding token so we can try preauth (but only for modules that actually need it!)
            if (httpWebRequest.ChallengedUri.Scheme == Uri.UriSchemeHttps)
            {
                object binding = httpWebRequest.ServicePoint.CachedChannelBinding;

#if DEBUG
                // the ModuleRequiresChannelBinding method is only compiled in DEBUG so the assert must be restricted to DEBUG
                // as well

                // If the authentication module does CBT, we require that it also caches channel bindings.
                System.Diagnostics.Debug.Assert(!(binding == null && ModuleRequiresChannelBinding(authenticationModule)));
#endif

                // can also be DBNull.Value, indicating "we previously succeeded without getting a CBT."
                // (ie, unpatched SSP talking to a partially-hardened server)
                ChannelBinding channelBinding = binding as ChannelBinding;
                if (channelBinding != null)
                {
                    httpWebRequest.CurrentAuthenticationState.TransportContext =
                        new CachedTransportContext(channelBinding);
                }
            }

            // Otherwise invoke the PreAuthenticate method
            // we're guaranteed that CanPreAuthenticate is true because we check before calling BindModule()
            Authorization authorization = authenticationModule.PreAuthenticate(request, credentials);

            if (authorization != null && !authorization.Complete && httpWebRequest != null)
            {
                httpWebRequest.CurrentAuthenticationState.Module = authenticationModule;
            }

            GlobalLog.Print(
                "AuthenticationManager::PreAuthenticate() IAuthenticationModule.PreAuthenticate()"
                + " returned authorization:" + ValidationHelper.HashString(authorization));

            return authorization;
        }

        /// <devdoc>
        ///    <para>Registers an authentication module with the authentication manager.</para>
        /// </devdoc>
        public override void Register(IAuthenticationModule authenticationModule)
        {
            if (authenticationModule == null)
            {
                throw new ArgumentNullException("authenticationModule");
            }

            GlobalLog.Print(
                "AuthenticationManager::Register() registering :[" + authenticationModule.AuthenticationType + "]");

            string normalizedAuthenticationType = authenticationModule.AuthenticationType.ToUpperInvariant();

            this.moduleList.AddOrUpdate(
                normalizedAuthenticationType,
                authenticationModule,
                (key, value) => authenticationModule);
        }

        /// <devdoc>
        ///    <para>Unregisters authentication modules for an authentication scheme.</para>
        /// </devdoc>
        public override void Unregister(IAuthenticationModule authenticationModule)
        {
            if (authenticationModule == null)
            {
                throw new ArgumentNullException("authenticationModule");
            }

            GlobalLog.Print(
                "AuthenticationManager::Unregister() unregistering :["
                + authenticationModule.AuthenticationType + "]");

            string normalizedAuthenticationType = authenticationModule.AuthenticationType.ToUpperInvariant();
            UnregisterInternal(normalizedAuthenticationType);
        }

        /// <devdoc>
        ///    <para>Unregisters authentication modules for an authentication scheme.</para>
        /// </devdoc>
        public override void Unregister(string authenticationScheme)
        {
            if (authenticationScheme == null)
            {
                throw new ArgumentNullException("authenticationScheme");
            }

            GlobalLog.Print("AuthenticationManager::Unregister() unregistering :[" + authenticationScheme + "]");

            string normalizedAuthenticationType = authenticationScheme.ToUpperInvariant();
            UnregisterInternal(normalizedAuthenticationType);
        }

        /// <devdoc>
        ///    <para>
        ///       Returns a list of registered authentication modules.
        ///    </para>
        /// </devdoc>
        public override IEnumerator RegisteredModules
        {
            get
            {
                return this.moduleList.Values.GetEnumerator();
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Binds an authentication response to a request for pre-authentication.
        ///    </para>
        /// </devdoc>
        // Create binding between an authorization response and the module
        // generating that response
        // This association is used for deciding which module to invoke
        // for preauthentication purposes
        public override void BindModule(Uri uri, Authorization response, IAuthenticationModule module)
        {
            GlobalLog.Assert(
                module.CanPreAuthenticate,
                "AuthenticationManager::BindModule()|module.CanPreAuthenticate == false");

            if (response.ProtectionRealm != null)
            {
                // The authentication module specified which Uri prefixes
                // will be preauthenticated
                string[] prefix = response.ProtectionRealm;

                for (int k = 0; k < prefix.Length; k++)
                {
                    //
                    // PrefixLookup is thread-safe
                    //
                    moduleBinding.Add(prefix[k], module.AuthenticationType.ToUpperInvariant());
                }
            }
            else
            {
                // Otherwise use the default policy for "fabricating"
                // some protection realm generalizing the particular Uri
                string prefix = generalize(uri);
                //
                // PrefixLookup is thread-safe
                //
                moduleBinding.Add(prefix, module.AuthenticationType);
            }
        }

        [SuppressMessage(
            "Microsoft.Design",
            "CA1031",
            Justification = "Previous behavior of AuthenticationManager is to catch all exceptions thrown by all " +
            "IAuthenticationModule plugins.")]
#if !TRAVE
        [SuppressMessage(
            "Microsoft.Performance",
            "CA1804",
            Justification = "Variable exception is used for logging purposes.")]
#endif
        private void InitializeModuleList()
        {
            GlobalLog.Print(
                "AuthenticationManager::Initialize(): calling ConfigurationManager.GetSection()");

            // This will never come back as null. Additionally, it will
            // have the items the user wants available.
            List<Type> authenticationModuleTypes =
                AuthenticationModulesSectionInternal.GetSection().AuthenticationModules;

            //
            // Should be registered in a growing list of encryption/algorithm strengths
            //  basically, walk through a list of Types, and create new Auth objects
            //  from them.
            //
            // order is meaningful here:
            // load the registered list of auth types
            // with growing level of encryption.
            //

            this.moduleList = new ConcurrentDictionary<string, IAuthenticationModule>();
            IAuthenticationModule moduleToRegister;
            foreach (Type type in authenticationModuleTypes)
            {
                try
                {
                    moduleToRegister = Activator.CreateInstance(type,
                                        BindingFlags.CreateInstance
                                        | BindingFlags.Instance
                                        | BindingFlags.NonPublic
                                        | BindingFlags.Public,
                                        null,          // Binder
                                        new object[0], // no arguments
                                        CultureInfo.InvariantCulture
                                        ) as IAuthenticationModule;
                    if (moduleToRegister != null)
                    {
                        GlobalLog.Print(
                            "WebRequest::Initialize(): Register:" + moduleToRegister.AuthenticationType);

                        string normalizedAuthenticationType =
                            moduleToRegister.AuthenticationType.ToUpperInvariant();

                        this.moduleList.AddOrUpdate(
                            normalizedAuthenticationType,
                            moduleToRegister,
                            (key, value) => moduleToRegister);
                    }
                }
                catch (Exception exception)
                {
                    //
                    // ignore failure (log exception for debugging)
                    //
                    GlobalLog.Print(
                        "AuthenticationManager::constructor failed to initialize: "
                        + exception.ToString());
                }
            }
        }

        private void UnregisterInternal(string normalizedAuthenticationType)
        {
            IAuthenticationModule removedModule;
            if (!this.moduleList.TryRemove(normalizedAuthenticationType, out removedModule))
            {
                throw new InvalidOperationException(SR.GetString(SR.net_authmodulenotregistered));
            }
        }
    } // class AuthenticationManager2
} // namespace System.Net

{'repo_name': 'microsoft/referencesource', 'stars': '2229', 'repo_language': 'C#', 'file_name': 'SecurityTokenServiceDescriptor.cs', 'mime_type': 'text/plain', 'hash': -6645679019022569916, 'source_dataset': 'data'}


/*******************************************************************************
Copyright (c) 2006-2009 by Tensilica Inc.  ALL RIGHTS RESERVED.
These coded instructions, statements, and computer programs are the
copyrighted works and confidential proprietary information of Tensilica Inc.
They may not be modified, copied, reproduced, distributed, or disclosed to
third parties in any manner, medium, or form, in whole or in part, without
the prior written consent of Tensilica Inc.
--------------------------------------------------------------------------------

        RTOS-SPECIFIC INFORMATION FOR XTENSA RTOS ASSEMBLER SOURCES

This header is the primary glue between generic Xtensa RTOS support
sources and a specific RTOS port for Xtensa.  It contains definitions
and macros for use primarily by Xtensa assembly coded source files.

Macros in this header map callouts from generic Xtensa files to specific
RTOS functions. It may also be included in C source files.

Xtensa RTOS ports support all RTOS-compatible configurations of the Xtensa
architecture, using the Xtensa hardware abstraction layer (HAL) to deal
with configuration specifics.

Should be included by all Xtensa generic and RTOS port-specific sources.

*******************************************************************************/

#ifndef XTENSA_RTOS_H
#define XTENSA_RTOS_H

#ifdef __ASSEMBLER__
#include    <xtensa/coreasm.h>
#else
#include    <xtensa/config/core.h>
#endif

#include    <xtensa/corebits.h>
#include    <xtensa/config/system.h>
#include    <xtensa/simcall.h>

/*
Include any RTOS specific definitions that are needed by this header.
*/

#ifdef XCHAL_EXCM_LEVEL
#undef XCHAL_EXCM_LEVEL
#define XCHAL_EXCM_LEVEL 3
#endif

/*
Name of RTOS (for messages).
*/
#define XT_RTOS_NAME    FreeRTOS

/*
Check some Xtensa configuration requirements and report error if not met.
Error messages can be customize to the RTOS port.
*/

#if !XCHAL_HAVE_XEA2
#error "FreeRTOS/Xtensa requires XEA2 (exception architecture 2)."
#endif

/*******************************************************************************

RTOS CALLOUT MACROS MAPPED TO RTOS PORT-SPECIFIC FUNCTIONS.

Define callout macros used in generic Xtensa code to interact with the RTOS.
The macros are simply the function names for use in calls from assembler code.
Some of these functions may call back to generic functions in xtensa_context.h .

*******************************************************************************/

/*
Inform RTOS of entry into an interrupt handler that will affect it.
Allows RTOS to manage switch to any system stack and count nesting level.
Called after minimal context has been saved, with interrupts disabled.
RTOS port can call0 _xt_context_save to save the rest of the context.
May only be called from assembly code by the 'call0' instruction.
*/
// void XT_RTOS_INT_ENTER(void)
#define XT_RTOS_INT_ENTER   _xt_int_enter

/*
Inform RTOS of completion of an interrupt handler, and give control to
RTOS to perform thread/task scheduling, switch back from any system stack
and restore the context, and return to the exit dispatcher saved in the
stack frame at XT_STK_EXIT. RTOS port can call0 _xt_context_restore
to save the context saved in XT_RTOS_INT_ENTER via _xt_context_save,
leaving only a minimal part of the context to be restored by the exit
dispatcher. This function does not return to the place it was called from.
May only be called from assembly code by the 'call0' instruction.
*/
// void XT_RTOS_INT_EXIT(void)
#define XT_RTOS_INT_EXIT    _xt_int_exit

/*
Inform RTOS of the occurrence of a tick timer interrupt.
If RTOS has no tick timer, leave XT_RTOS_TIMER_INT undefined.
May be coded in or called from C or assembly, per ABI conventions.
RTOS may optionally define XT_TICK_PER_SEC in its own way (eg. macro).
*/
// void XT_RTOS_TIMER_INT(void)
#define XT_RTOS_TIMER_INT   _xt_timer_int

/*
Return in a15 the base address of the co-processor state save area for the
thread that triggered a co-processor exception, or 0 if no thread was running.
The state save area is structured as defined in xtensa_context.h and has size
XT_CP_SIZE. Co-processor instructions should only be used in thread code, never
in interrupt handlers or the RTOS kernel. May only be called from assembly code
and by the 'call0' instruction. A result of 0 indicates an unrecoverable error.
The implementation may use only a2-4, a15 (all other regs must be preserved).
*/
// void* XT_RTOS_CP_STATE(void)

/*******************************************************************************

HOOKS TO DYNAMICALLY INSTALL INTERRUPT AND EXCEPTION HANDLERS PER LEVEL.

This Xtensa RTOS port provides hooks for dynamically installing exception
and interrupt handlers to facilitate automated testing where each test
case can install its own handler for user exceptions and each interrupt
priority (level). This consists of an array of function pointers indexed
by interrupt priority, with index 0 being the user exception handler hook.
Each entry in the array is initially 0, and may be replaced by a function
pointer of type XT_INTEXC_HOOK. A handler may be uninstalled by installing 0.

The handler for low and medium priority obeys ABI conventions so may be coded
in C. For the exception handler, the cause is the contents of the EXCCAUSE
reg, and the result is -1 if handled, else the cause (still needs handling).
For interrupt handlers, the cause is a mask of pending enabled interrupts at
that level, and the result is the same mask with the bits for the handled
interrupts cleared (those not cleared still need handling). This allows a test
case to either pre-handle or override the default handling for the exception
or interrupt level (see xtensa_vectors.S).

High priority handlers (including NMI) must be coded in assembly, are always
called by 'call0' regardless of ABI, must preserve all registers except a0,
and must not use or modify the interrupted stack. The hook argument 'cause'
is not passed and the result is ignored, so as not to burden the caller with
saving and restoring a2 (it assumes only one interrupt per level - see the
discussion in high priority interrupts in xtensa_vectors.S). The handler
therefore should be coded to prototype 'void h(void)' even though it plugs
into an array of handlers of prototype 'unsigned h(unsigned)'.

To enable interrupt/exception hooks, compile the RTOS with '-DXT_INTEXC_HOOKS'.

*******************************************************************************/

#define XT_INTEXC_HOOK_NUM  (1 + XCHAL_NUM_INTLEVELS + XCHAL_HAVE_NMI)

#ifndef __ASSEMBLER__
typedef unsigned (*XT_INTEXC_HOOK)(unsigned cause);
extern  volatile XT_INTEXC_HOOK _xt_intexc_hooks[XT_INTEXC_HOOK_NUM];
#endif

/*******************************************************************************

CONVENIENCE INCLUSIONS.

Ensures RTOS specific files need only include this one Xtensa-generic header.
These headers are included last so they can use the RTOS definitions above.

*******************************************************************************/

#include    "xtensa_context.h"

#ifdef XT_RTOS_TIMER_INT
#include    "xtensa_timer.h"
#endif

#endif /* XTENSA_RTOS_H */

{'repo_name': 'Nicholas3388/LuaNode', 'stars': '558', 'repo_language': 'C', 'file_name': 'README.md', 'mime_type': 'text/plain', 'hash': 1567923344788388948, 'source_dataset': 'data'}


[Home](./index.md) > [@antv/dw-random](./dw-random.md) > [Random](./dw-random.random.md)

## Random interface

Random Interface

Signature:

```typescript
export interface Random extends TextRandom, WebRandom, ColorRandom, LocationRandom, DateTimeRandom, ChAddressRandom
```

## Remarks

[BasicRandom](./dw-random.basicrandom.md) [TextRandom](./dw-random.textrandom.md) [WebRandom](./dw-random.webrandom.md) [ColorRandom](./dw-random.colorrandom.md) [ChAddressRandom](./dw-random.chaddressrandom.md)

## Properties

|  Property | Type | Description |
|  --- | --- | --- |
|  [database](./dw-random.random.database.md) | Database | 所有database的合并 |

{'repo_name': 'antvis/AVA', 'stars': '737', 'repo_language': 'TypeScript', 'file_name': 'EXAMPLES.zh-CN.md', 'mime_type': 'text/plain', 'hash': 1704293963602647115, 'source_dataset': 'data'}


// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Google Inc. 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 COPYRIGHT HOLDERS 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 COPYRIGHT
// OWNER 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.

#ifndef GOOGLE_PROTOBUF_MACROS_H__
#define GOOGLE_PROTOBUF_MACROS_H__

#include <google/protobuf/stubs/port.h>

namespace google {
namespace protobuf {

#undef GOOGLE_DISALLOW_EVIL_CONSTRUCTORS
#define GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeName)    \
  TypeName(const TypeName&);                           \
  void operator=(const TypeName&)

#undef GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS
#define GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
  TypeName();                                           \
  TypeName(const TypeName&);                            \
  void operator=(const TypeName&)

// ===================================================================
// from google3/base/basictypes.h

// The GOOGLE_ARRAYSIZE(arr) macro returns the # of elements in an array arr.
// The expression is a compile-time constant, and therefore can be
// used in defining new arrays, for example.
//
// GOOGLE_ARRAYSIZE catches a few type errors.  If you see a compiler error
//
//   "warning: division by zero in ..."
//
// when using GOOGLE_ARRAYSIZE, you are (wrongfully) giving it a pointer.
// You should only use GOOGLE_ARRAYSIZE on statically allocated arrays.
//
// The following comments are on the implementation details, and can
// be ignored by the users.
//
// ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in
// the array) and sizeof(*(arr)) (the # of bytes in one array
// element).  If the former is divisible by the latter, perhaps arr is
// indeed an array, in which case the division result is the # of
// elements in the array.  Otherwise, arr cannot possibly be an array,
// and we generate a compiler error to prevent the code from
// compiling.
//
// Since the size of bool is implementation-defined, we need to cast
// !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
// result has type size_t.
//
// This macro is not perfect as it wrongfully accepts certain
// pointers, namely where the pointer size is divisible by the pointee
// size.  Since all our code has to go through a 32-bit compiler,
// where a pointer is 4 bytes, this means all pointers to a type whose
// size is 3 or greater than 4 will be (righteously) rejected.
//
// Kudos to Jorg Brown for this simple and elegant implementation.

#undef GOOGLE_ARRAYSIZE
#define GOOGLE_ARRAYSIZE(a) \
  ((sizeof(a) / sizeof(*(a))) / \
   static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))

// The COMPILE_ASSERT macro can be used to verify that a compile time
// expression is true. For example, you could use it to verify the
// size of a static array:
//
//   COMPILE_ASSERT(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES,
//                  content_type_names_incorrect_size);
//
// or to make sure a struct is smaller than a certain size:
//
//   COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
//
// The second argument to the macro is the name of the variable. If
// the expression is false, most compilers will issue a warning/error
// containing the name of the variable.

namespace internal {

template <bool>
struct CompileAssert {
};

}  // namespace internal

#define GOOGLE_COMPILE_ASSERT(expr, msg) static_assert(expr, #msg)

}  // namespace protobuf
}  // namespace google

#endif  // GOOGLE_PROTOBUF_MACROS_H__

{'repo_name': 'dothq/browser', 'stars': '280', 'repo_language': 'TypeScript', 'file_name': 'settings.json', 'mime_type': 'text/plain', 'hash': -1391367922835690632, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder.AppleTV.XIB" version="3.0" toolsVersion="10116" systemVersion="15E65" targetRuntime="AppleTV" propertyAccessControl="none" useAutolayout="YES">
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
    </dependencies>
    <objects>
        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
        <view contentMode="scaleToFill" id="iN0-l3-epB" customClass="WidgetTemplateView" customModule="GCBUtilitiesBundle" customModuleProvider="target">
            <rect key="frame" x="0.0" y="0.0" width="640" height="540"/>
            <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
            <subviews>
                <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="KXO-ig-m9j">
                    <rect key="frame" x="0.0" y="0.0" width="640" height="540"/>
                    <color key="backgroundColor" red="0.12549020349979401" green="0.12549020349979401" blue="0.12549020349979401" alpha="1" colorSpace="custom" customColorSpace="calibratedRGB"/>
                </view>
                <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="uj0-3F-gEn">
                    <rect key="frame" x="0.0" y="0.0" width="640" height="91"/>
                    <subviews>
                        <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="WIDGET" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="6ee-IO-aQx" customClass="LabelWithSpacing" customModule="GCBUtilities">
                            <rect key="frame" x="26" y="19" width="588" height="36"/>
                            <fontDescription key="fontDescription" type="system" pointSize="30"/>
                            <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="calibratedRGB"/>
                            <nil key="highlightedColor"/>
                            <userDefinedRuntimeAttributes>
                                <userDefinedRuntimeAttribute type="number" keyPath="kerning">
                                    <real key="value" value="4"/>
                                </userDefinedRuntimeAttribute>
                            </userDefinedRuntimeAttributes>
                        </label>
                        <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="WIDGET DESCRIPTION" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="0fN-aj-bf4" customClass="LabelWithSpacing" customModule="GCBUtilities">
                            <rect key="frame" x="26" y="59" width="588" height="24"/>
                            <fontDescription key="fontDescription" type="system" pointSize="20"/>
                            <color key="textColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="calibratedRGB"/>
                            <nil key="highlightedColor"/>
                            <userDefinedRuntimeAttributes>
                                <userDefinedRuntimeAttribute type="number" keyPath="kerning">
                                    <real key="value" value="2.8999999999999999"/>
                                </userDefinedRuntimeAttribute>
                            </userDefinedRuntimeAttributes>
                        </label>
                        <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="zYE-fA-fPI" userLabel="Separator">
                            <rect key="frame" x="27" y="89" width="587" height="2"/>
                            <color key="backgroundColor" red="0.13725490868091583" green="0.81568628549575806" blue="0.64705884456634521" alpha="1" colorSpace="custom" customColorSpace="calibratedRGB"/>
                            <constraints>
                                <constraint firstAttribute="width" constant="587" id="9MC-Nu-Wrc"/>
                                <constraint firstAttribute="height" constant="2" id="YjE-76-Xi1"/>
                            </constraints>
                        </view>
                    </subviews>
                    <constraints>
                        <constraint firstItem="6ee-IO-aQx" firstAttribute="top" secondItem="uj0-3F-gEn" secondAttribute="top" constant="19" id="2T9-jP-d2U"/>
                        <constraint firstItem="0fN-aj-bf4" firstAttribute="top" secondItem="6ee-IO-aQx" secondAttribute="bottom" constant="4" id="3mo-BN-62t"/>
                        <constraint firstAttribute="bottom" secondItem="zYE-fA-fPI" secondAttribute="bottom" id="EQ1-d8-Xts"/>
                        <constraint firstAttribute="height" constant="91" id="ISH-ps-CeA"/>
                        <constraint firstAttribute="trailing" secondItem="6ee-IO-aQx" secondAttribute="trailing" constant="26" id="M8c-Lb-G73"/>
                        <constraint firstItem="0fN-aj-bf4" firstAttribute="trailing" secondItem="6ee-IO-aQx" secondAttribute="trailing" id="lnx-Si-Jau"/>
                        <constraint firstItem="zYE-fA-fPI" firstAttribute="centerX" secondItem="uj0-3F-gEn" secondAttribute="centerX" id="ptz-ik-dd8"/>
                        <constraint firstItem="6ee-IO-aQx" firstAttribute="leading" secondItem="uj0-3F-gEn" secondAttribute="leading" constant="26" id="r7a-jS-jCZ"/>
                        <constraint firstItem="0fN-aj-bf4" firstAttribute="leading" secondItem="6ee-IO-aQx" secondAttribute="leading" id="vFS-2H-gvo"/>
                    </constraints>
                </view>
            </subviews>
            <color key="backgroundColor" red="0.12549020349979401" green="0.12549020349979401" blue="0.12549020349979401" alpha="1" colorSpace="custom" customColorSpace="calibratedRGB"/>
            <constraints>
                <constraint firstItem="KXO-ig-m9j" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" id="3TS-Fp-gLn"/>
                <constraint firstAttribute="trailing" secondItem="uj0-3F-gEn" secondAttribute="trailing" id="GPf-x3-PIs"/>
                <constraint firstAttribute="bottom" secondItem="KXO-ig-m9j" secondAttribute="bottom" id="S3J-pY-qPC"/>
                <constraint firstItem="KXO-ig-m9j" firstAttribute="top" secondItem="iN0-l3-epB" secondAttribute="top" id="X1f-3O-YBX"/>
                <constraint firstItem="uj0-3F-gEn" firstAttribute="top" secondItem="iN0-l3-epB" secondAttribute="top" id="mjW-h5-gGc"/>
                <constraint firstItem="KXO-ig-m9j" firstAttribute="top" secondItem="uj0-3F-gEn" secondAttribute="bottom" priority="999" id="nhU-Gn-za1"/>
                <constraint firstItem="uj0-3F-gEn" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" id="z0y-MN-erE"/>
                <constraint firstAttribute="trailing" secondItem="KXO-ig-m9j" secondAttribute="trailing" id="z1k-i1-Lpu"/>
            </constraints>
            <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
            <connections>
                <outlet property="containerTopConstraint" destination="X1f-3O-YBX" id="9rd-lA-Kmz"/>
                <outlet property="containerTopToHeaderBottomConstraint" destination="nhU-Gn-za1" id="Yf2-2a-4eT"/>
                <outlet property="contentViewContainer" destination="KXO-ig-m9j" id="bXM-bf-agd"/>
                <outlet property="descriptionLabel" destination="0fN-aj-bf4" id="KgT-Df-tfq"/>
                <outlet property="titleLabel" destination="6ee-IO-aQx" id="I5t-gI-YaK"/>
            </connections>
        </view>
    </objects>
</document>

{'repo_name': 'macoscope/GrandCentralBoard', 'stars': '207', 'repo_language': 'Swift', 'file_name': 'Source.swift', 'mime_type': 'text/plain', 'hash': -5308062272348450133, 'source_dataset': 'data'}


package org.gradle.integtests.IdeaIntegrationTest.webservice.src.main.java.org.gradle.webservice;

public class TestTest {

}

{'repo_name': 'gradle/gradle', 'stars': '10712', 'repo_language': 'Groovy', 'file_name': 'DefaultRuleActionAdapterTest.groovy', 'mime_type': 'text/plain', 'hash': 3600077458310878141, 'source_dataset': 'data'}


module Refactor.OrganizeImports.Reorder where

import Control.Monad ((>>=))
import Data.List (intersperse)

x = intersperse '-' "abc"
y = Just () >>= \_ -> Nothing

{'repo_name': 'haskell-tools/haskell-tools', 'stars': '256', 'repo_language': 'Haskell', 'file_name': 'data-to-newtype.md', 'mime_type': 'text/plain', 'hash': -7069666784209766384, 'source_dataset': 'data'}


docdown

A simple JSDoc to Markdown documentation generator.

node bin/docdown index.js doc/README.md style=github title="docdown v${npm_package_version}" url=https://github.com/jdalton/docdown/blob/${npm_package_version}/index.js

{'repo_name': 'jdalton/docdown', 'stars': '188', 'repo_language': 'JavaScript', 'file_name': 'README.md', 'mime_type': 'text/html', 'hash': -4614578848137363194, 'source_dataset': 'data'}


import logging

from pip._vendor import requests

from pip._vendor.cachecontrol.adapter import CacheControlAdapter
from pip._vendor.cachecontrol.cache import DictCache
from pip._vendor.cachecontrol.controller import logger

from argparse import ArgumentParser

def setup_logging():
    logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler()
    logger.addHandler(handler)

def get_session():
    adapter = CacheControlAdapter(
        DictCache(),
        cache_etags=True,
        serializer=None,
        heuristic=None,
    )
    sess = requests.Session()
    sess.mount('http://', adapter)
    sess.mount('https://', adapter)

    sess.cache_controller = adapter.controller
    return sess

def get_args():
    parser = ArgumentParser()
    parser.add_argument('url', help='The URL to try and cache')
    return parser.parse_args()

def main(args=None):
    args = get_args()
    sess = get_session()

    # Make a request to get a response
    resp = sess.get(args.url)

    # Turn on logging
    setup_logging()

    # try setting the cache
    sess.cache_controller.cache_response(resp.request, resp.raw)

    # Now try to get it
    if sess.cache_controller.cached_request(resp.request):
        print('Cached!')
    else:
        print('Not cached :(')

if __name__ == '__main__':
    main()

{'repo_name': 'mrlesmithjr/Ansible', 'stars': '146', 'repo_language': 'Python', 'file_name': 'provision_vms.yml', 'mime_type': 'text/x-c++', 'hash': 1166821018765551083, 'source_dataset': 'data'}


#!/bin/bash

# This is the script buildbot.libsdl.org uses to cross-compile SDL2 from
#  x86 Linux to Raspberry Pi.

# The final tarball can be unpacked in the root directory of a RPi,
#  so the SDL2 install lands in /usr/local. Run ldconfig, and then
#  you should be able to build and run SDL2-based software on your
#  Pi. Standard configure scripts should be able to find SDL and
#  build against it, and sdl2-config should work correctly on the
#  actual device.

TARBALL="$1"
if [ -z $1 ]; then
    TARBALL=sdl-raspberrypi.tar.xz
fi

OSTYPE=`uname -s`
if [ "$OSTYPE" != "Linux" ]; then
    # !!! FIXME
    echo "This only works on x86 or x64-64 Linux at the moment." 1>&2
    exit 1
fi

if [ "x$MAKE" == "x" ]; then
    NCPU=`cat /proc/cpuinfo |grep vendor_id |wc -l`
    let NCPU=$NCPU+1
    MAKE="make -j$NCPU"
fi

BUILDBOTDIR="raspberrypi-buildbot"
PARENTDIR="$PWD"

set -e
set -x
rm -f $TARBALL
rm -rf $BUILDBOTDIR
mkdir -p $BUILDBOTDIR
pushd $BUILDBOTDIR

SYSROOT="/opt/rpi-sysroot"
export CC="ccache /opt/rpi-tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-gcc --sysroot=$SYSROOT -I$SYSROOT/opt/vc/include -I$SYSROOT/usr/include -I$SYSROOT/opt/vc/include/interface/vcos/pthreads -I$SYSROOT/opt/vc/include/interface/vmcs_host/linux -L$SYSROOT/opt/vc/lib"
# -L$SYSROOT/usr/lib/arm-linux-gnueabihf"
# !!! FIXME: shouldn't have to --disable-* things here.
../configure --with-sysroot=$SYSROOT --host=arm-raspberry-linux-gnueabihf --prefix=$PWD/rpi-sdl2-installed --disable-pulseaudio --disable-esd --disable-video-mir --disable-video-wayland
$MAKE
$MAKE install
# Fix up a few things to a real install path on a real Raspberry Pi...
perl -w -pi -e "s#$PWD/rpi-sdl2-installed#/usr/local#g;" ./rpi-sdl2-installed/lib/libSDL2.la ./rpi-sdl2-installed/lib/pkgconfig/sdl2.pc ./rpi-sdl2-installed/bin/sdl2-config
mkdir -p ./usr
mv ./rpi-sdl2-installed ./usr/local

popd
tar -cJvvf $TARBALL -C $BUILDBOTDIR usr
rm -rf $BUILDBOTDIR

set +x
echo "All done. Final installable is in $TARBALL ...";

{'repo_name': 'wheybags/freeablo', 'stars': '2050', 'repo_language': 'C++', 'file_name': 'levelimplstub.h', 'mime_type': 'text/x-c++', 'hash': 6282560534608091963, 'source_dataset': 'data'}