text:
// Copyright 2000-2021 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 org.jetbrains.idea.maven.importing;

import com.google.common.collect.ImmutableMap;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.externalSystem.model.project.ProjectId;
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.importing.tree.MavenModuleType;
import org.jetbrains.idea.maven.importing.tree.MavenTreeModuleImportData;
import org.jetbrains.idea.maven.importing.tree.dependency.*;
import org.jetbrains.idea.maven.model.MavenArtifact;
import org.jetbrains.idea.maven.model.MavenConstants;
import org.jetbrains.idea.maven.project.*;
import org.jetbrains.idea.maven.utils.MavenLog;
import org.jetbrains.idea.maven.utils.MavenUtil;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public final class MavenModuleImporter {
  public static final String SUREFIRE_PLUGIN_LIBRARY_NAME = "maven-surefire-plugin urls";
  public static final Set<String> IMPORTED_CLASSIFIERS = Set.of("client");

  private static final Map<String, LanguageLevel> MAVEN_IDEA_PLUGIN_LEVELS = ImmutableMap.of(
    "JDK_1_3", LanguageLevel.JDK_1_3,
    "JDK_1_4", LanguageLevel.JDK_1_4,
    "JDK_1_5", LanguageLevel.JDK_1_5,
    "JDK_1_6", LanguageLevel.JDK_1_6,
    "JDK_1_7", LanguageLevel.JDK_1_7);

  private final Module myModule;
  private final MavenProjectsTree myMavenTree;
  private final MavenProject myMavenProject;

  @Nullable
  private final MavenProjectChanges myMavenProjectChanges;
  private final Map<MavenProject, String> myMavenProjectToModuleName;
  private final MavenImportingSettings mySettings;
  private final ModifiableModelsProviderProxy myModifiableModelsProvider;
  @Nullable
  private final MavenModuleType myModuleType;
  private MavenRootModelAdapter myRootModelAdapter;

  private IdeModifiableModelsProvider myProviderForExtensions;

  public MavenModuleImporter(Module module,
                             MavenProjectsTree mavenTree,
                             MavenProject mavenProject,
                             @Nullable MavenProjectChanges changes,
                             Map<MavenProject, String> mavenProjectToModuleName,
                             MavenImportingSettings settings,
                             ModifiableModelsProviderProxy modifiableModelsProvider,
                             @Nullable MavenModuleType moduleType) {
    myModule = module;
    myMavenTree = mavenTree;
    myMavenProject = mavenProject;
    myMavenProjectChanges = changes;
    myMavenProjectToModuleName = mavenProjectToModuleName;
    mySettings = settings;
    myModifiableModelsProvider = modifiableModelsProvider;
    myModuleType = moduleType;
    VirtualFile pomFile = mavenProject.getFile();
    if (!FileUtil.namesEqual("pom", pomFile.getNameWithoutExtension())) {
      MavenPomPathModuleService.getInstance(module).setPomFileUrl(pomFile.getUrl());
    }
  }

  public MavenModuleImporter(Module module,
                             MavenProjectsTree mavenTree,
                             MavenProject mavenProject,
                             @Nullable MavenProjectChanges changes,
                             Map<MavenProject, String> mavenProjectToModuleName,
                             MavenImportingSettings settings,
                             ModifiableModelsProviderProxy modifiableModelsProvider) {
    this(module, mavenTree, mavenProject, changes, mavenProjectToModuleName, settings, modifiableModelsProvider, null);
  }

  public ModifiableRootModel getRootModel() {
    return myRootModelAdapter.getRootModel();
  }

  void setRootModelAdapter(MavenRootModelAdapter mavenRootModelAdapter) { // need for new worskapce model
    myRootModelAdapter = mavenRootModelAdapter;
  }

  public void config(MavenRootModelAdapter mavenRootModelAdapter) {
    myRootModelAdapter = mavenRootModelAdapter;

    configFolders();
    configDependencies();
    configLanguageLevel();
  }

  public void config(MavenRootModelAdapter mavenRootModelAdapter, MavenTreeModuleImportData importData) {
    myRootModelAdapter = mavenRootModelAdapter;

    configFolders();
    configDependencies(importData.getDependencies());
    LanguageLevel level = MavenModelUtil.getLanguageLevel(myMavenProject, () -> importData.getModuleData().getSourceLanguageLevel());
    configLanguageLevel(level);
  }

  public void configMainAndTestAggregator(MavenRootModelAdapter mavenRootModelAdapter, MavenTreeModuleImportData importData) {
    assert importData.getModuleData().getType() == MavenModuleType.AGGREGATOR_MAIN_TEST;
    myRootModelAdapter = mavenRootModelAdapter;

    new MavenFoldersImporter(myMavenProject, mySettings, myRootModelAdapter).configMainAndTestAggregator();
    configDependencies(importData.getDependencies());
    LanguageLevel level = MavenModelUtil.getLanguageLevel(myMavenProject, () -> importData.getModuleData().getSourceLanguageLevel());
    configLanguageLevel(level);
  }

  public void configMainAndTest(MavenRootModelAdapter mavenRootModelAdapter, MavenTreeModuleImportData importData) {
    MavenModuleType type = importData.getModuleData().getType();
    assert type == MavenModuleType.MAIN || type == MavenModuleType.TEST;
    myRootModelAdapter = mavenRootModelAdapter;
    new MavenFoldersImporter(myMavenProject, mySettings, myRootModelAdapter).configMainAndTest(type);
    configDependencies(importData.getDependencies());
    LanguageLevel level = MavenModelUtil.getLanguageLevel(myMavenProject, () -> importData.getModuleData().getSourceLanguageLevel());
    configLanguageLevel(level);
  }

  public void preConfigFacets() {
    MavenUtil.invokeAndWaitWriteAction(myModule.getProject(), () -> {
      if (myModule.isDisposed()) return;

      final ModuleType moduleType = ModuleType.get(myModule);

      for (final MavenImporter importer : getSuitableImporters()) {
        try {
          final MavenProjectChanges changes;
          if (myMavenProjectChanges == null) {
            if (importer.processChangedModulesOnly()) continue;
            changes = MavenProjectChanges.NONE;
          }
          else {
            changes = myMavenProjectChanges;
          }

          if (importer.getModuleType() == moduleType) {
            importer.preProcess(myModule, myMavenProject, changes, myProviderForExtensions);
          }
        }
        catch (Exception e) {
          MavenLog.LOG.error(e);
        }
      }
    });
  }

  public void configFacets(final List<MavenProjectsProcessorTask> postTasks) {
    MavenUtil.smartInvokeAndWait(myModule.getProject(), ModalityState.defaultModalityState(), () -> {
      if (myModule.isDisposed()) return;

      final ModuleType moduleType = ModuleType.get(myModule);

      ApplicationManager.getApplication().runWriteAction(() -> {
        for (final MavenImporter importer : getSuitableImporters()) {
          final MavenProjectChanges changes;
          if (myMavenProjectChanges == null) {
            if (importer.processChangedModulesOnly()) continue;
            changes = MavenProjectChanges.NONE;
          }
          else {
            changes = myMavenProjectChanges;
          }

          if (importer.getModuleType() == moduleType) {
            try {
              importer.process(myProviderForExtensions,
                               myModule,
                               myRootModelAdapter,
                               myMavenTree,
                               myMavenProject,
                               changes,
                               myMavenProjectToModuleName,
                               postTasks);
            }
            catch (Exception e) {
              MavenLog.LOG.error(e);
            }
          }
        }
      });
    });
  }

  public void postConfigFacets() {
    MavenUtil.invokeAndWaitWriteAction(myModule.getProject(), () -> {
      if (myModule.isDisposed()) return;

      final ModuleType moduleType = ModuleType.get(myModule);

      for (final MavenImporter importer : getSuitableImporters()) {
        try {
          final MavenProjectChanges changes;
          if (myMavenProjectChanges == null) {
            if (importer.processChangedModulesOnly()) continue;
            changes = MavenProjectChanges.NONE;
          }
          else {
            changes = myMavenProjectChanges;
          }

          if (importer.getModuleType() == moduleType) {
            importer.postProcess(myModule, myMavenProject, changes, myProviderForExtensions);
          }
        } catch(Exception e) {
          MavenLog.LOG.error(e);
        }

      }
    });
  }

  private List<MavenImporter> getSuitableImporters() {
    return myMavenProject.getSuitableImporters();
  }

  private void configFolders() {
    new MavenFoldersImporter(myMavenProject, mySettings, myRootModelAdapter).config();
  }

  private void configDependencies() {
    Set<String> dependencyTypesFromSettings = new HashSet<>();

    if (!ReadAction.compute(()->{
      if (myModule.getProject().isDisposed()) return false;

      dependencyTypesFromSettings.addAll(MavenProjectsManager.getInstance(myModule.getProject()).getImportingSettings().getDependencyTypesAsSet());
      return true;
    })) return;

    for (MavenArtifact artifact : myMavenProject.getDependencies()) {
      String dependencyType = artifact.getType();

      if (!dependencyTypesFromSettings.contains(dependencyType)
          && !myMavenProject.getDependencyTypesFromImporters(SupportedRequestType.FOR_IMPORT).contains(dependencyType)) {
        continue;
      }

      DependencyScope scope = selectScope(artifact.getScope());

      MavenProject depProject = myMavenTree.findProject(artifact.getMavenId());

      if (depProject != null) {
        if (depProject == myMavenProject) continue;

        String moduleName = myMavenProjectToModuleName.get(depProject);

        if (moduleName == null || myMavenTree.isIgnored(depProject)) {
          MavenArtifact projectsArtifactInRepository = createCopyForLocalRepo(artifact, myMavenProject);

          myRootModelAdapter.addLibraryDependency(projectsArtifactInRepository, scope, myModifiableModelsProvider, myMavenProject);
        }
        else {
          boolean isTestJar = MavenConstants.TYPE_TEST_JAR.equals(dependencyType) || "tests".equals(artifact.getClassifier());
          myRootModelAdapter.addModuleDependency(moduleName, scope, isTestJar);

          Element buildHelperCfg = depProject.getPluginGoalConfiguration("org.codehaus.mojo", "build-helper-maven-plugin", "attach-artifact");
          if (buildHelperCfg != null) {
            addAttachArtifactDependency(buildHelperCfg, scope, depProject, artifact);
          }

          String classifier = artifact.getClassifier();
          if (classifier != null && IMPORTED_CLASSIFIERS.contains(classifier)
              && !isTestJar
              && !"system".equals(artifact.getScope())
              && !"false".equals(System.getProperty("idea.maven.classifier.dep"))) {
            MavenArtifact a = createCopyForLocalRepo(artifact, myMavenProject);

            myRootModelAdapter.addLibraryDependency(a, scope, myModifiableModelsProvider, myMavenProject);
          }
        }
      }
      else if ("system".equals(artifact.getScope())) {
        myRootModelAdapter.addSystemDependency(artifact, scope);
      }
      else {
        if ("bundle".equals(dependencyType)) {
          artifact = new MavenArtifact(
            artifact.getGroupId(),
            artifact.getArtifactId(),
            artifact.getVersion(),
            artifact.getBaseVersion(),
            "jar",
            artifact.getClassifier(),
            artifact.getScope(),
            artifact.isOptional(),
            "jar",
            null,
            myMavenProject.getLocalRepository(),
            false, false
          );
        }
        LibraryOrderEntry libraryOrderEntry =
          myRootModelAdapter.addLibraryDependency(artifact, scope, myModifiableModelsProvider, myMavenProject);
        myModifiableModelsProvider.trySubstitute(
          myModule, libraryOrderEntry, new ProjectId(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()));
      }
    }

    configSurefirePlugin();
  }

  public void configDependencies(@NotNull List<MavenImportDependency<?>> dependencies) {
    for (MavenImportDependency<?> dependency : dependencies) {
      if (dependency instanceof SystemDependency) {
        myRootModelAdapter.addSystemDependency(((SystemDependency)dependency).getArtifact(), dependency.getScope());
      }
      else if (dependency instanceof LibraryDependency) {
        myRootModelAdapter.addLibraryDependency(((LibraryDependency)dependency).getArtifact(), dependency.getScope(),
                                                myModifiableModelsProvider, myMavenProject);
      }
      else if (dependency instanceof ModuleDependency) {
        ModuleDependency moduleDependency = (ModuleDependency)dependency;
        myRootModelAdapter.addModuleDependency(moduleDependency.getArtifact(), dependency.getScope(), moduleDependency.isTestJar());
      }
      else if (dependency instanceof BaseDependency) {
        MavenArtifact artifact = ((BaseDependency)dependency).getArtifact();
        LibraryOrderEntry libraryOrderEntry =
          myRootModelAdapter.addLibraryDependency(artifact, dependency.getScope(), myModifiableModelsProvider, myMavenProject);
        myModifiableModelsProvider.trySubstitute(
          myModule, libraryOrderEntry, new ProjectId(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()));
      }
    }
  }

  @NotNull
  public static MavenArtifact createCopyForLocalRepo(@NotNull MavenArtifact artifact, @NotNull MavenProject project) {
    return new MavenArtifact(
      artifact.getGroupId(),
      artifact.getArtifactId(),
      artifact.getVersion(),
      artifact.getBaseVersion(),
      artifact.getType(),
      artifact.getClassifier(),
      artifact.getScope(),
      artifact.isOptional(),
      artifact.getExtension(),
      null,
      project.getLocalRepository(),
      false, false
    );
  }

  private void configSurefirePlugin() {
    // Remove "maven-surefire-plugin urls" library created by previous version of IDEA.
    // todo remove this code after 01.06.2013
    LibraryTable moduleLibraryTable = myRootModelAdapter.getRootModel().getModuleLibraryTable();

    Library library = moduleLibraryTable.getLibraryByName(SUREFIRE_PLUGIN_LIBRARY_NAME);
    if (library != null) {
      moduleLibraryTable.removeLibrary(library);
    }
  }

  //TODO: Rewrite
  private void addAttachArtifactDependency(@NotNull Element buildHelperCfg,
                                           @NotNull DependencyScope scope,
                                           @NotNull MavenProject mavenProject,
                                           @NotNull MavenArtifact artifact) {
    Library.ModifiableModel libraryModel = null;

    for (Element artifactsElement : buildHelperCfg.getChildren("artifacts")) {
      for (Element artifactElement : artifactsElement.getChildren("artifact")) {
        String typeString = artifactElement.getChildTextTrim("type");
        if (typeString != null && !typeString.equals("jar")) continue;

        OrderRootType rootType = OrderRootType.CLASSES;

        String classifier = artifactElement.getChildTextTrim("classifier");
        if ("sources".equals(classifier)) {
          rootType = OrderRootType.SOURCES;
        }
        else if ("javadoc".equals(classifier)) {
          rootType = JavadocOrderRootType.getInstance();
        }

        String filePath = artifactElement.getChildTextTrim("file");
        if (StringUtil.isEmpty(filePath)) continue;

        VirtualFile file = VfsUtil.findRelativeFile(filePath, mavenProject.getDirectoryFile());
        if (file == null) continue;

        file = JarFileSystem.getInstance().getJarRootForLocalFile(file);
        if (file == null) continue;

        if (libraryModel == null) {
          String libraryName = getAttachedJarsLibName(artifact);

          Library library = myModifiableModelsProvider.getLibraryByName(libraryName);
          if (library == null) {
            library = myModifiableModelsProvider.createLibrary(libraryName, MavenRootModelAdapter.getMavenExternalSource());
          }
          libraryModel = myModifiableModelsProvider.getModifiableLibraryModel(library);

          LibraryOrderEntry entry = myRootModelAdapter.getRootModel().addLibraryEntry(library);
          entry.setScope(scope);
        }

        if (libraryModel != null) {
          libraryModel.addRoot(file, rootType);
        }
      }
    }
  }

  public IdeModifiableModelsProvider getModifiableModelsProvider() {
    return myProviderForExtensions;
  }

  public void setModifiableModelsProvider(IdeModifiableModelsProvider providerForExtensions) {
    myProviderForExtensions = providerForExtensions;
    MavenRootModelAdapter mavenRootModelAdapter = new MavenRootModelAdapter(
      new MavenRootModelAdapterLegacyImpl(myMavenProject, myModule, new ModifiableModelsProviderProxyWrapper(myProviderForExtensions)));
    setRootModelAdapter(mavenRootModelAdapter);
  }

  @NotNull
  public static String getAttachedJarsLibName(@NotNull MavenArtifact artifact) {
    String libraryName = artifact.getLibraryName();
    assert libraryName.startsWith(MavenArtifact.MAVEN_LIB_PREFIX);
    libraryName = MavenArtifact.MAVEN_LIB_PREFIX + "ATTACHED-JAR: " + libraryName.substring(MavenArtifact.MAVEN_LIB_PREFIX.length());
    return libraryName;
  }

  @NotNull
  public static DependencyScope selectScope(String mavenScope) {
    if (MavenConstants.SCOPE_RUNTIME.equals(mavenScope)) return DependencyScope.RUNTIME;
    if (MavenConstants.SCOPE_TEST.equals(mavenScope)) return DependencyScope.TEST;
    if (MavenConstants.SCOPE_PROVIDED.equals(mavenScope)) return DependencyScope.PROVIDED;
    return DependencyScope.COMPILE;
  }

  private void configLanguageLevel() {
    if ("false".equalsIgnoreCase(System.getProperty("idea.maven.configure.language.level"))) return;

    LanguageLevel level = getLanguageLevel(myMavenProject);
    myRootModelAdapter.setLanguageLevel(level);
  }

  private void configLanguageLevel(@NotNull LanguageLevel level) {
    if ("false".equalsIgnoreCase(System.getProperty("idea.maven.configure.language.level"))) return;
    myRootModelAdapter.setLanguageLevel(level);
  }

  /**
   * @deprecated use {@link MavenModelUtil#getSourceLanguageLevel(MavenProject)}
   */
  @Deprecated
  public static @NotNull LanguageLevel getLanguageLevel(MavenProject mavenProject) {
    return MavenModelUtil.getSourceLanguageLevel(mavenProject);
  }

  /**
   * @deprecated use {@link MavenModelUtil#getDefaultLevel(MavenProject)}
   */
  @Deprecated
  @NotNull
  public static LanguageLevel getDefaultLevel(MavenProject mavenProject) {
    return MavenModelUtil.getDefaultLevel(mavenProject);
  }

  public boolean isModuleDisposed() {
    return myModule.isDisposed();
  }

  public boolean isAggregatorMainTestModule() {
    return myModuleType == MavenModuleType.AGGREGATOR_MAIN_TEST;
  }
}


text:
package com.zimbra.qa.unittest;

import java.util.concurrent.Callable;

import junit.framework.TestCase;

import com.zimbra.common.util.TaskScheduler;

public class TestTaskScheduler
extends TestCase
{
    private class TestTask
    implements Callable<Integer> {
        int mNumCalls = 0;
        String mName;

        public Integer call() throws Exception {
            mNumCalls++;
            return mNumCalls;
        }
    }

    /**
     * Submits two tasks and confirms that they were executed the correct
     * number of times.
     */
    public void testTaskScheduler()
    throws Exception {

        TaskScheduler<Integer> scheduler = null;

        // Run test.
        TestTask task1 = new TestTask();
        TestTask task2 = new TestTask();
        scheduler = new TaskScheduler<Integer>("TestTaskScheduler", 1, 2);
        scheduler.schedule(1, task1, true, 1000, 0);
        scheduler.schedule(2, task2, true, 1500, 1500);
        Thread.sleep(1800);
        scheduler.cancel(2, false);
        scheduler.cancel(1, false);

        // Wait some more to make sure no more tasks run.
        Thread.sleep(1000);

        // Validate number of calls.
        assertEquals("Task 1 calls", 2, scheduler.getLastResult(1).intValue());
        assertEquals("Task 2 calls", 1, scheduler.getLastResult(2).intValue());
    }

    public static void main(String[] args)
    throws Exception {
        TestUtil.cliSetup();
        TestUtil.runTest(TestTaskScheduler.class);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Linq;

namespace MIConvexHull
{
    /// <summary>
    /// Simple interface to unify different types of triangulations in the future.
    /// </summary>
    /// <typeparam name="TVertex">The type of the t vertex.</typeparam>
    /// <typeparam name="TCell">The type of the t cell.</typeparam>
    public interface ITriangulation<TVertex, TCell>
        where TCell : TriangulationCell<TVertex, TCell>, new()
        where TVertex : IVertex
    {
        /// <summary>
        /// Triangulation simplexes. For 2D - triangles, 3D - tetrahedrons, etc ...
        /// </summary>
        /// <value>The cells.</value>
        IEnumerable<TCell> Cells { get; }
    }

    /// <summary>
    /// Factory class for creating triangulations.
    /// </summary>
    public static class Triangulation
    {
        /// <summary>
        /// Creates the Delaunay triangulation of the input data.
        /// </summary>
        /// <typeparam name="TVertex">The type of the t vertex.</typeparam>
        /// <param name="data">The data.</param>
        /// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
        /// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
        /// <returns>ITriangulation<TVertex, DefaultTriangulationCell<TVertex>>.</returns>
        public static ITriangulation<TVertex, DefaultTriangulationCell<TVertex>> CreateDelaunay<TVertex>(
            IList<TVertex> data,
            double PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
            where TVertex : IVertex
        {
            return DelaunayTriangulation<TVertex, DefaultTriangulationCell<TVertex>>.Create(data, PlaneDistanceTolerance);
        }

        /// <summary>
        /// Creates the Delaunay triangulation of the input data.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
        /// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
        /// <returns>ITriangulation<DefaultVertex, DefaultTriangulationCell<DefaultVertex>>.</returns>
        public static ITriangulation<DefaultVertex, DefaultTriangulationCell<DefaultVertex>> CreateDelaunay(
            IList<double[]> data,
            double PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
        {
            var points = data.Select(p => new DefaultVertex { Position = p }).ToList();
            return DelaunayTriangulation<DefaultVertex, DefaultTriangulationCell<DefaultVertex>>.Create(points, PlaneDistanceTolerance);
        }

        /// <summary>
        /// Creates the Delaunay triangulation of the input data.
        /// </summary>
        /// <typeparam name="TVertex">The type of the t vertex.</typeparam>
        /// <typeparam name="TFace">The type of the t face.</typeparam>
        /// <param name="data">The data.</param>
        /// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
        /// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
        /// <returns>ITriangulation<TVertex, TFace>.</returns>
        public static ITriangulation<TVertex, TFace> CreateDelaunay<TVertex, TFace>(IList<TVertex> data,
            double PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
            where TVertex : IVertex
            where TFace : TriangulationCell<TVertex, TFace>, new()
        {
            return DelaunayTriangulation<TVertex, TFace>.Create(data, PlaneDistanceTolerance);
        }

        /// <summary>
        /// Create the voronoi mesh.
        /// </summary>
        /// <typeparam name="TVertex">The type of the t vertex.</typeparam>
        /// <typeparam name="TCell">The type of the t cell.</typeparam>
        /// <typeparam name="TEdge">The type of the t edge.</typeparam>
        /// <param name="data">The data.</param>
        /// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
        /// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
        /// <returns>VoronoiMesh<TVertex, TCell, TEdge>.</returns>
        public static VoronoiMesh<TVertex, TCell, TEdge> CreateVoronoi<TVertex, TCell, TEdge>(IList<TVertex> data,
            double PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
            where TCell : TriangulationCell<TVertex, TCell>, new()
            where TVertex : IVertex
            where TEdge : VoronoiEdge<TVertex, TCell>, new()
        {
            return VoronoiMesh<TVertex, TCell, TEdge>.Create(data, PlaneDistanceTolerance);
        }

        /// <summary>
        /// Create the voronoi mesh.
        /// </summary>
        /// <typeparam name="TVertex">The type of the t vertex.</typeparam>
        /// <param name="data">The data.</param>
        /// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
        /// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
        /// <returns>VoronoiMesh<TVertex, DefaultTriangulationCell<TVertex>, VoronoiEdge<TVertex, DefaultTriangulationCell<TVertex>>>.</returns>
        public static
            VoronoiMesh
                <TVertex, DefaultTriangulationCell<TVertex>, VoronoiEdge<TVertex, DefaultTriangulationCell<TVertex>>>
            CreateVoronoi<TVertex>(IList<TVertex> data,
                double PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
            where TVertex : IVertex
        {
            return
                VoronoiMesh
                    <TVertex, DefaultTriangulationCell<TVertex>, VoronoiEdge<TVertex, DefaultTriangulationCell<TVertex>>
                        >.Create(data, PlaneDistanceTolerance);
        }

        /// <summary>
        /// Create the voronoi mesh.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
        /// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
        /// <returns>VoronoiMesh<DefaultVertex, DefaultTriangulationCell<DefaultVertex>, VoronoiEdge<DefaultVertex, DefaultTriangulationCell<DefaultVertex>>>.</returns>
        public static
            VoronoiMesh
                <DefaultVertex, DefaultTriangulationCell<DefaultVertex>,
                    VoronoiEdge<DefaultVertex, DefaultTriangulationCell<DefaultVertex>>>
            CreateVoronoi(IList<double[]> data,
                double PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
        {
            var points = data.Select(p => new DefaultVertex { Position = p.ToArray() }).ToList();
            return
                VoronoiMesh
                    <DefaultVertex, DefaultTriangulationCell<DefaultVertex>,
                        VoronoiEdge<DefaultVertex, DefaultTriangulationCell<DefaultVertex>>>.Create(points, PlaneDistanceTolerance);
        }

        /// <summary>
        /// Create the voronoi mesh.
        /// </summary>
        /// <typeparam name="TVertex">The type of the t vertex.</typeparam>
        /// <typeparam name="TCell">The type of the t cell.</typeparam>
        /// <param name="data">The data.</param>
        /// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
        /// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
        /// <returns>VoronoiMesh<TVertex, TCell, VoronoiEdge<TVertex, TCell>>.</returns>
        public static VoronoiMesh<TVertex, TCell, VoronoiEdge<TVertex, TCell>> CreateVoronoi<TVertex, TCell>(
            IList<TVertex> data,
            double PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
            where TVertex : IVertex
            where TCell : TriangulationCell<TVertex, TCell>, new()
        {
            return VoronoiMesh<TVertex, TCell, VoronoiEdge<TVertex, TCell>>.Create(data, PlaneDistanceTolerance);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2015, dhis2
  ~ All rights reserved.
  ~
  ~ 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.
  ~
  ~ 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 HOLDER 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.
  -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <org.hisp.dhis.android.sdk.utils.ui.views.FontTextView
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawablePadding="8dp"
        android:gravity="center_vertical|start"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingBottom="6dp"
        android:paddingTop="6dp"
        android:textColor="@color/spinner_text_grey"
        android:background="@color/White"
        android:textSize="@dimen/medium_text_size"/>

</LinearLayout>


text:
		Filename: GamepadMenu.lua
		Written by: jeditkacheff
		Version 1.1
		Description: Controls the radial menu that appears when pressing menu button on gamepad
--]]

--NOTICE: This file has been branched! If you're implementing changes in this file, please consider also implementing them in the other
--version.

--Handle branching early so we do as little work as possible:
local useNewRadialMenuSuccess, useNewRadialMenuValue = pcall(function() return settings():GetFFlag("UseNewRadialMenu") end)
local FFlagUseNewRadialMenu = useNewRadialMenuSuccess and useNewRadialMenuValue
if not FFlagUseNewRadialMenu then
	--This file is now inactive because the flag IS NOT on
	return
end

local fixGamePadPlayerlistSuccess, fixGamePadPlayerlistValue = pcall(function() return settings():GetFFlag("FixGamePadPlayerlist") end)
local fixGamePadPlayerlist = fixGamePadPlayerlistSuccess and fixGamePadPlayerlistValue

--[[ SERVICES ]]
local GuiService = game:GetService('GuiService')
local CoreGuiService = game:GetService('CoreGui')
local InputService = game:GetService('UserInputService')
local ContextActionService = game:GetService('ContextActionService')
local HttpService = game:GetService('HttpService')
local StarterGui = game:GetService('StarterGui')
local Players = game:GetService('Players')
local GuiRoot = CoreGuiService:WaitForChild('RobloxGui')
local TextService = game:GetService('TextService')
local VRService = game:GetService('VRService')
--[[ END OF SERVICES ]]

--[[ MODULES ]]
local tenFootInterface = require(GuiRoot.Modules.TenFootInterface)
local utility = require(GuiRoot.Modules.Settings.Utility)
local recordPage = require(GuiRoot.Modules.Settings.Pages.Record)
local businessLogic = require(GuiRoot.Modules.BusinessLogic)
local Panel3D = require(GuiRoot.Modules.VR.Panel3D)

--[[ VARIABLES ]]
local gamepadSettingsFrame = nil
local isVisible = false
local smallScreen = utility:IsSmallTouchScreen()
local isTenFootInterface = tenFootInterface:IsEnabled()
local radialButtons = {}
local radialButtonsByName = {}
local lastInputChangedCon = nil
local vrPanel = nil

--[[ CONSTANTS ]]
local NON_VR_FRAME_HIDDEN_SIZE = UDim2.new(0, 102, 0, 102)
local NON_VR_FRAME_SIZE = UDim2.new(0, 408, 0, 408)

local VR_FRAME_HIDDEN_SIZE = UDim2.new(0.125, 0, 0.125, 0)
local VR_FRAME_SIZE = UDim2.new(0.75, 0, 0.75, 0)

local PANEL_SIZE_STUDS = 3
local PANEL_RESOLUTION = 250

--[[ Fast Flags ]]--
local getRadialMenuAfterLoadingScreen, radialMenuAfterLoadingScreenValue = pcall(function() return settings():GetFFlag("RadialMenuAfterLoadingScreen2") end)
local radialMenuAfterLoadingScreen = getRadialMenuAfterLoadingScreen and radialMenuAfterLoadingScreenValue

local function getImagesForSlot(slot)
	if slot == 1 then		return "rbxasset://textures/ui/Settings/Radial/Top.png", "rbxasset://textures/ui/Settings/Radial/TopSelected.png",
									"rbxasset://textures/ui/Settings/Radial/Menu.png",
									UDim2.new(0.5,-26,0,18), UDim2.new(0,52,0,41),
									UDim2.new(0,150,0,100), UDim2.new(0.5,-75,0,0)
	elseif slot == 2 then	return "rbxasset://textures/ui/Settings/Radial/TopRight.png", "rbxasset://textures/ui/Settings/Radial/TopRightSelected.png",
									"rbxasset://textures/ui/Settings/Radial/PlayerList.png",
									UDim2.new(1,-90,0,90), UDim2.new(0,52,0,52),
									UDim2.new(0,108,0,150), UDim2.new(1,-110,0,50)
	elseif slot == 3 then	return "rbxasset://textures/ui/Settings/Radial/BottomRight.png", "rbxasset://textures/ui/Settings/Radial/BottomRightSelected.png",
									"rbxasset://textures/ui/Settings/Radial/Alert.png",
									UDim2.new(1,-85,1,-150), UDim2.new(0,42,0,58),
									UDim2.new(0,120,0,150), UDim2.new(1,-120,1,-200)
	elseif slot == 4 then 	return "rbxasset://textures/ui/Settings/Radial/Bottom.png", "rbxasset://textures/ui/Settings/Radial/BottomSelected.png",
									"rbxasset://textures/ui/Settings/Radial/Leave.png",
									UDim2.new(0.5,-20,1,-62), UDim2.new(0,55,0,46),
									UDim2.new(0,150,0,100), UDim2.new(0.5,-75,1,-100)
	elseif slot == 5 then	return "rbxasset://textures/ui/Settings/Radial/BottomLeft.png", "rbxasset://textures/ui/Settings/Radial/BottomLeftSelected.png",
									"rbxasset://textures/ui/Settings/Radial/Backpack.png",
									UDim2.new(0,40,1,-150), UDim2.new(0,44,0,56),
									UDim2.new(0,110,0,150), UDim2.new(0,0,0,205)
	elseif slot == 6 then	return "rbxasset://textures/ui/Settings/Radial/TopLeft.png", "rbxasset://textures/ui/Settings/Radial/TopLeftSelected.png",
									"rbxasset://textures/ui/Settings/Radial/Chat.png",
									UDim2.new(0,35,0,100), UDim2.new(0,56,0,53),
									UDim2.new(0,110,0,150), UDim2.new(0,0,0,50)
	end

	return "", "", "", UDim2.new(0,0,0,0), UDim2.new(0,0,0,0)
end

local vrSlotImages = {}
local vrSlotBackgroundImage = "rbxasset://textures/ui/VR/Radial/SliceBackground.png"
local vrSlotActiveImage = "rbxasset://textures/ui/VR/Radial/SliceActive.png"
local vrSlotDisabledImage = "rbxasset://textures/ui/VR/Radial/SliceDisabled.png"
local vrNumSlots = 8
for i = 1, vrNumSlots do
	vrSlotImages[i] = {
		background = vrSlotBackgroundImage,
		active = vrSlotActiveImage,
		disabled = vrSlotDisabledImage,
		rotation = (360 / vrNumSlots) * (i - 1)
	}
end
vrSlotImages[1].icon = "rbxasset://textures/ui/Settings/Radial/Menu.png"
vrSlotImages[1].iconPosition = UDim2.new(0.5,-26,0,18)
vrSlotImages[1].iconSize = UDim2.new(0,52,0,41)
vrSlotImages[2].icon = "rbxasset://textures/ui/Settings/Radial/PlayerList.png"
vrSlotImages[2].iconPosition = UDim2.new(0.71, 5, 0.29, -60)
vrSlotImages[2].iconSize = UDim2.new(0, 52, 0, 52)
vrSlotImages[3].icon = "rbxasset://textures/ui/VR/Radial/Icons/Recenter.png"
vrSlotImages[3].iconPosition = UDim2.new(1, -60, 0.5, -25)
vrSlotImages[3].iconSize = UDim2.new(0, 50, 0, 50)
vrSlotImages[4].icon = "rbxasset://textures/ui/Settings/Radial/Alert.png"
vrSlotImages[4].iconPosition = UDim2.new(0.71, 12, 0.71, 5)
vrSlotImages[4].iconSize = UDim2.new(0, 42, 0, 58)
vrSlotImages[5].icon = "rbxasset://textures/ui/Settings/Radial/Leave.png"
vrSlotImages[5].iconPosition = UDim2.new(0.5,-20,1,-58)
vrSlotImages[5].iconSize = UDim2.new(0,55,0,46)
vrSlotImages[6].icon = "rbxasset://textures/ui/VR/Radial/Icons/Backpack.png"
vrSlotImages[6].iconPosition = UDim2.new(0.29, -50, 0.71, 4)
vrSlotImages[6].iconSize = UDim2.new(0, 42, 0, 56)
vrSlotImages[7].icon = "rbxasset://textures/ui/VR/Radial/Icons/2DUI.png"
vrSlotImages[7].iconPosition = UDim2.new(0, 10, 0.5, -25)
vrSlotImages[7].iconSize = UDim2.new(0, 50, 0, 50)
vrSlotImages[8].icon = "rbxasset://textures/ui/Settings/Radial/Chat.png"
vrSlotImages[8].iconPosition = UDim2.new(0.29, -60, 0.29, -52)
vrSlotImages[8].iconSize = UDim2.new(0, 56, 0, 53)

local radialButtonLayout = {
	PlayerList 		= { Range = { Begin = 36, 	End = 96 } },
	Notifications 	= { Range = { Begin = 96, 	End = 156 } },
	LeaveGame 		= { Range = { Begin = 156,	End = 216 } },
	Backpack 		= { Range = { Begin = 216,	End = 276 } },
	Chat 			= { Range = { Begin = 276, 	End = 336 } },
	Settings 		= { Range = { Begin = 336, 	End = 36 } },
}
local vrButtonLayout = {
	PlayerList 		= { Range = { Begin = 22.5,  End = 67.5 } },
	Recenter 		= { Range = { Begin = 67.5,  End = 112.5 } },
	Notifications 	= { Range = { Begin = 112.5, End = 157.5 } },
	LeaveGame 		= { Range = { Begin = 157.5, End = 202.5 } },
	Backpack 		= { Range = { Begin = 202.5, End = 247.5 } },
	ToggleUI 		= { Range = { Begin = 247.5, End = 292.5 } },
	Chat 			= { Range = { Begin = 292.5, End = 337.5 } },
	Settings 		= { Range = { Begin = 337.5, End = 22.5 } }
}

local freezeControllerActionName = "doNothingAction"
local radialSelectActionName = "RadialSelectAction"
local thumbstick2RadialActionName = "Thumbstick2RadialAction"
local radialCancelActionName = "RadialSelectCancel"
local radialAcceptActionName = "RadialSelectAccept"
local toggleMenuActionName = "RBXToggleMenuAction"

local noOpFunc = function() end
local doGamepadMenuButton = nil
local toggleCoreGuiRadial = nil

local function getSelectedObjectFromAngle(angle)
	local closest = nil
	local closestDistance = 30 -- threshold of 30 for selecting the closest radial button
	local currentLayout = VRService.VREnabled and vrButtonLayout or radialButtonLayout
	for radialKey, buttonLayout in pairs(currentLayout) do
		if radialButtons[gamepadSettingsFrame[radialKey]]["Disabled"] == false then
			--Check for exact match
			if buttonLayout.Range.Begin < buttonLayout.Range.End then
				if angle > buttonLayout.Range.Begin and angle <= buttonLayout.Range.End then
					return gamepadSettingsFrame[radialKey]
				end
			else
				if angle > buttonLayout.Range.Begin or angle <= buttonLayout.Range.End then
					return gamepadSettingsFrame[radialKey]
				end
			end
			--Check if this is the closest button so far
			local distanceBegin = math.min(math.abs((buttonLayout.Range.Begin + 360) - angle), math.abs(buttonLayout.Range.Begin - angle))
			local distanceEnd = math.min(math.abs((buttonLayout.Range.End + 360) - angle), math.abs(buttonLayout.Range.End - angle))
			local distance = math.min(distanceBegin, distanceEnd)
			if distance < closestDistance then
				closestDistance = distance
				closest = gamepadSettingsFrame[radialKey]
			end
		end
	end
	return closest
end

local function setSelectedRadialButton(selectedObject)
	for button, buttonTable in pairs(radialButtons) do
		local isVisible = (button == selectedObject)
		button:FindFirstChild("Selected").Visible = isVisible
		button:FindFirstChild("RadialLabel").Visible = isVisible

		if VRService.VREnabled then
			button.ImageTransparency = isVisible and 1 or 0
		end
	end
end

local function activateSelectedRadialButton()
	for button, buttonTable in pairs(radialButtons) do
		if button:FindFirstChild("Selected").Visible then
			buttonTable["Function"]()
			return true
		end
	end

	return false
end

local function radialSelectAccept(name, state, input)
	if gamepadSettingsFrame.Visible and state == Enum.UserInputState.Begin then
		activateSelectedRadialButton()
	end
end

local function radialSelectCancel(name, state, input)
	if gamepadSettingsFrame.Visible and state == Enum.UserInputState.Begin then
		toggleCoreGuiRadial()
	end
end

local function radialSelect(name, state, input)
	local inputVector = Vector2.new(0, 0)

	if input.KeyCode == Enum.KeyCode.Thumbstick1 then
		inputVector = Vector2.new(input.Position.x, input.Position.y)
	elseif input.KeyCode == Enum.KeyCode.DPadUp or input.KeyCode == Enum.KeyCode.DPadDown or input.KeyCode == Enum.KeyCode.DPadLeft or input.KeyCode == Enum.KeyCode.DPadRight then
		local D_PAD_BUTTONS = {
			[Enum.KeyCode.DPadUp] = false;
			[Enum.KeyCode.DPadDown] = false;
			[Enum.KeyCode.DPadLeft] = false;
			[Enum.KeyCode.DPadRight] = false;
		}

		--set D_PAD_BUTTONS status: button down->true, button up->false
		local gamepadState = InputService:GetGamepadState(input.UserInputType)
		for index, value in ipairs(gamepadState) do
			if value.KeyCode == Enum.KeyCode.DPadUp or value.KeyCode == Enum.KeyCode.DPadDown or value.KeyCode == Enum.KeyCode.DPadLeft or value.KeyCode == Enum.KeyCode.DPadRight then
				D_PAD_BUTTONS[value.KeyCode] = (value.UserInputState == Enum.UserInputState.Begin)
			end
		end

		if VRService.VREnabled then
			for index, value in pairs(D_PAD_BUTTONS) do
				if value then
					inputVector = inputVector + D_PAD_VR_DIRS[index]
				end
			end
		else
			if D_PAD_BUTTONS[Enum.KeyCode.DPadUp] or D_PAD_BUTTONS[Enum.KeyCode.DPadDown] then
				inputVector = D_PAD_BUTTONS[Enum.KeyCode.DPadUp] and Vector2.new(0, 1) or Vector2.new(0, -1)
				if D_PAD_BUTTONS[Enum.KeyCode.DPadLeft] then
					inputVector = Vector2.new(-1, inputVector.Y)
				elseif D_PAD_BUTTONS[Enum.KeyCode.DPadRight] then
					inputVector = Vector2.new(1, inputVector.Y)
				end
			end
		end

		inputVector = inputVector.unit
	end

	local selectedObject = nil

	if inputVector.magnitude > 0.8 then

		local angle =  math.deg(math.atan2(inputVector.X, inputVector.Y))
		if angle < 0 then
			angle = angle + 360
		end

		selectedObject = getSelectedObjectFromAngle(angle)

		setSelectedRadialButton(selectedObject)
	end
end

local function unbindAllRadialActions()
	GuiService.CoreGuiNavigationEnabled = true

	ContextActionService:UnbindCoreAction(radialSelectActionName)
	ContextActionService:UnbindCoreAction(radialCancelActionName)
	ContextActionService:UnbindCoreAction(radialAcceptActionName)
	ContextActionService:UnbindCoreAction(freezeControllerActionName)
	ContextActionService:UnbindCoreAction(thumbstick2RadialActionName)
	ContextActionService:UnbindCoreAction(radialSelectActionName .. "VR")
end

local function bindAllRadialActions()
	GuiService.CoreGuiNavigationEnabled = false

	ContextActionService:BindCoreAction(freezeControllerActionName, noOpFunc, false, Enum.UserInputType.Gamepad1)
	ContextActionService:BindCoreAction(radialAcceptActionName, radialSelectAccept, false, Enum.KeyCode.ButtonA)
	ContextActionService:BindCoreAction(radialCancelActionName, radialSelectCancel, false, Enum.KeyCode.ButtonB)
	ContextActionService:BindCoreAction(radialSelectActionName, radialSelect, false, Enum.KeyCode.Thumbstick1, Enum.KeyCode.DPadUp, Enum.KeyCode.DPadDown, Enum.KeyCode.DPadLeft, Enum.KeyCode.DPadRight)
	ContextActionService:BindCoreAction(thumbstick2RadialActionName, noOpFunc, false, Enum.KeyCode.Thumbstick2)
	ContextActionService:BindCoreAction(toggleMenuActionName, doGamepadMenuButton, false, Enum.KeyCode.ButtonStart)

	if VRService.VREnabled then
		ContextActionService:BindCoreAction(radialAcceptActionName .. "VR", radialSelectAccept, false, Enum.KeyCode.ButtonL3)
	end
end

local function setOverrideMouseIconBehavior(override)
	if override then
		if InputService:GetLastInputType() == Enum.UserInputType.Gamepad1 then
			InputService.OverrideMouseIconBehavior = Enum.OverrideMouseIconBehavior.ForceHide
		else
			InputService.OverrideMouseIconBehavior = Enum.OverrideMouseIconBehavior.ForceShow
		end
	else
		InputService.OverrideMouseIconBehavior = Enum.OverrideMouseIconBehavior.None
	end
end

toggleCoreGuiRadial = function(goingToSettings)
	isVisible = not gamepadSettingsFrame.Visible

	updateGuiVisibility()

	if isVisible then
		setOverrideMouseIconBehavior(true)
		lastInputChangedCon = InputService.LastInputTypeChanged:connect(function() setOverrideMouseIconBehavior(true) end)

		gamepadSettingsFrame.Visible = isVisible

		local settingsChildren = gamepadSettingsFrame:GetChildren()
		for i = 1, #settingsChildren do
			if settingsChildren[i]:IsA("GuiButton") then
				utility:TweenProperty(settingsChildren[i], "ImageTransparency", 1, 0, 0.1, utility:GetEaseOutQuad(), nil)
			end
		end
		local desiredSize = VRService.VREnabled and VR_FRAME_SIZE or NON_VR_FRAME_SIZE
		gamepadSettingsFrame:TweenSizeAndPosition(desiredSize, UDim2.new(0.5,0,0.5,0),
													Enum.EasingDirection.Out, Enum.EasingStyle.Back, 0.18, true,
			function()
				updateGuiVisibility()
			end)
	else
		if lastInputChangedCon ~= nil then
			lastInputChangedCon:disconnect()
			lastInputChangedCon = nil
		end

		local settingsChildren = gamepadSettingsFrame:GetChildren()
		for i = 1, #settingsChildren do
			if settingsChildren[i]:IsA("GuiButton") then
				utility:TweenProperty(settingsChildren[i], "ImageTransparency", 0, 1, 0.1, utility:GetEaseOutQuad(), nil)
			end
		end
		local desiredSize = VRService.VREnabled and VR_FRAME_HIDDEN_SIZE or NON_VR_FRAME_HIDDEN_SIZE
		gamepadSettingsFrame:TweenSizeAndPosition(desiredSize, UDim2.new(0.5,0,0.5,0),
													Enum.EasingDirection.Out, Enum.EasingStyle.Sine, 0.1, true,
			function()
				if not VRService.VREnabled then
					setOverrideMouseIconBehavior(false)
				end
				if not goingToSettings and not isVisible then GuiService:SetMenuIsOpen(false) end
				gamepadSettingsFrame.Visible = isVisible

				if vrPanel then
					vrPanel:SetVisible(false)
				end
			end)
	end

	if isVisible then
		setSelectedRadialButton(nil)
		GuiService:SetMenuIsOpen(true)
		bindAllRadialActions()
	else
		unbindAllRadialActions()
	end

	return gamepadSettingsFrame.Visible
end

local function setButtonEnabled(button, enabled)
	if radialButtons[button]["Disabled"] == not enabled then return end

	if button:FindFirstChild("Selected").Visible == true then
		setSelectedRadialButton(nil)
	end

	local vrEnabled = VRService.VREnabled

	if enabled then
		if vrEnabled then
			button.Image = vrSlotBackgroundImage
		else
			button.Image = string.gsub(button.Image, "rbxasset://textures/ui/Settings/Radial/Empty", "rbxasset://textures/ui/Settings/Radial/")
		end
		button.ImageTransparency = 0
		button.RadialIcon.ImageTransparency = 0
	else
		if vrEnabled then
			button.Image = vrSlotDisabledImage
		else
			button.Image = string.gsub(button.Image, "rbxasset://textures/ui/Settings/Radial/", "rbxasset://textures/ui/Settings/Radial/Empty")
		end
		button.ImageTransparency = 0
		button.RadialIcon.ImageTransparency = 1
	end

	radialButtons[button]["Disabled"] = not enabled
end

local function setButtonVisible(button, visible)
	button.Visible = visible
	if not visible then
		setButtonEnabled(button, false)
	end
end

local kidSafeHint = nil;
local function getVRKidSafeHint()
	if not kidSafeHint then
		local text = businessLogic.GetVisibleAgeForPlayer(Players.LocalPlayer)
		local textSize = TextService:GetTextSize(text, 24, Enum.Font.SourceSansBold, Vector2.new(800,800))

		local bubble = utility:Create'ImageLabel'
		{
			Name = "AccountTypeBubble";
			Size = UDim2.new(0, textSize.x + 20, 0, 50);
			Image = "rbxasset://textures/ui/TopBar/Round.png";
			ScaleType = Enum.ScaleType.Slice;
			SliceCenter = Rect.new(10, 10, 10, 10);
			ImageTransparency = 0.3;
			BackgroundTransparency = 1;
			Parent = container;
		}
		bubble.Position = UDim2.new(0.5, -bubble.Size.X.Offset/2, 1, 10);

		local accountTypeTextLabel = utility:Create'TextLabel'{
			Name = "AccountTypeText";
			Text = text;
			Size = UDim2.new(1, -20, 1, -20);
			Position = UDim2.new(0, 10, 0, 10);
			Font = Enum.Font.SourceSansBold;
			FontSize = Enum.FontSize.Size24;
			BackgroundTransparency = 1;
			TextColor3 = Color3.new(1,1,1);
			TextYAlignment = Enum.TextYAlignment.Center;
			TextXAlignment = Enum.TextXAlignment.Center;
			Parent = bubble;
		}
		kidSafeHint = bubble
	end

	return kidSafeHint
end

local function toggleVR(vrEnabled)
	if vrEnabled then
		gamepadSettingsFrame.Size = VR_FRAME_SIZE

		vrPanel = Panel3D.Get("GamepadMenu")
		vrPanel:SetEnabled(true)
		vrPanel:SetVisible(false)
		vrPanel:SetCanFade(false)
		vrPanel:ResizeStuds(PANEL_SIZE_STUDS, PANEL_SIZE_STUDS, PANEL_RESOLUTION)
		vrPanel:SetType(Panel3D.Type.Standard, { CFrame = CFrame.new(0, 0, 0.5) })
		gamepadSettingsFrame.Parent = vrPanel:GetGUI()

		function vrPanel:OnUpdate(dt)
			if not vrPanel:IsVisible() then
				return
			end

			local lookAtPixel = vrPanel.lookAtPixel
			local lookAtScale = lookAtPixel / vrPanel.gui.AbsoluteSize
			local inputVector = (lookAtScale - Vector2.new(0.5, 0.5)) * 2

			if inputVector.magnitude > 0.4 and inputVector.magnitude < 0.8 then
				local angle = math.deg(math.atan2(inputVector.X, -inputVector.Y))
				if angle < 0 then
					angle = angle + 360
				end

				local button = getSelectedObjectFromAngle(angle)
				if button then
					setSelectedRadialButton(button)
				end
			end
		end

		for button, info in pairs(radialButtons) do
			if info.VRSlot then
				local slotImages = vrSlotImages[info.VRSlot]

				button.Parent = gamepadSettingsFrame
				button.Image = info.Disabled and slotImages.disabled or slotImages.background
				button.Rotation = slotImages.rotation
				button.RadialIcon.Image = slotImages.icon
				button.RadialIcon.Position = UDim2.new(0.5, 0, 0.09, 0)
				button.RadialIcon.AnchorPoint = Vector2.new(0.5, 0.5)
				button.RadialIcon.Size = slotImages.iconSize
				button.RadialIcon.Rotation = -slotImages.rotation
				button.RadialLabel.Rotation = -slotImages.rotation
				button.RadialLabel.AnchorPoint = Vector2.new(0.5, 0.5)
				button.RadialLabel.Position = UDim2.new(0.5, 0, 0.5, 0)

				local selectedImage = button:FindFirstChild("Selected")
				if selectedImage then
					selectedImage.Image = slotImages.active
				end

				button.MouseFrame.Visible = false
			end
		end

		local healthbarFrame = utility:Create("Frame") {
			Parent = gamepadSettingsFrame,
			Position = UDim2.new(0.8, 0, 0, 0),
			Size = UDim2.new(0, 192, 0, 32),
			BackgroundTransparency = 1
		}

		local hint = getVRKidSafeHint()
		hint.Parent = gamepadSettingsFrame

		local chatButton = radialButtonsByName.Chat
		if chatButton then
			setButtonEnabled(chatButton, false)
		end
	else
		gamepadSettingsFrame.Size = NON_VR_FRAME_SIZE
		if vrPanel then
			vrPanel:SetEnabled(false)
		end
		vrPanel = nil
		for button, info in pairs(radialButtons) do
			if info.Slot then
				local backgroundImage, activeImage, iconImage, iconPosition, iconSize = getImagesForSlot(info.Slot)
				if info.Disabled then
					backgroundImage = string.gsub(backgroundImage, "rbxasset://textures/ui/Settings/Radial/", "rbxasset://textures/ui/Settings/Radial/Empty")
				end

				button.Image = backgroundImage
				button.Rotation = 0
				button.RadialIcon.Position = iconPosition
				button.RadialIcon.Size = iconSize
				button.RadialIcon.Image = iconImage
				button.RadialIcon.Rotation = 0
				button.RadialIcon.AnchorPoint = Vector2.new(0, 0)

				button.MouseFrame.Visible = true
			else
				button.Parent = nil
			end
		end
		if kidSafeHint then
			kidSafeHint.Parent = nil
		end

		local chatButton = radialButtonsByName.Chat
		if chatButton then
			setButtonEnabled(chatButton, not isTenFootInterface)
		end
	end

	if gamepadSettingsFrame.Visible then
		toggleCoreGuiRadial()
	end
end

local emptySelectedImageObject = utility:Create'ImageLabel'
{
	BackgroundTransparency = 1,
	Size = UDim2.new(1,0,1,0),
	Image = ""
};

local function createRadialButton(name, text, slot, vrSlot, disabled, coreGuiType, activateFunc)
	local slotImage, selectedSlotImage, slotIcon,
			slotIconPosition, slotIconSize, mouseFrameSize, mouseFramePos = getImagesForSlot(slot)

	local radialButton = utility:Create'ImageButton'
	{
		Name = name,
		Position = UDim2.new(0.5,0,0.5,0),
		Size = UDim2.new(1,0,1,0),
		AnchorPoint = Vector2.new(0.5, 0.5),
		BackgroundTransparency = 1,
		Image = slotImage,
		ZIndex = 2,
		SelectionImageObject = emptySelectedImageObject,
		Selectable = false,
		Parent = gamepadSettingsFrame
	};
	if disabled then
		radialButton.Image = string.gsub(radialButton.Image, "rbxasset://textures/ui/Settings/Radial/", "rbxasset://textures/ui/Settings/Radial/Empty")
	end

	local selectedRadial = utility:Create'ImageLabel'
	{
		Name = "Selected",
		Position = UDim2.new(0,0,0,0),
		Size = UDim2.new(1,0,1,0),
		BackgroundTransparency = 1,
		Image = selectedSlotImage,
		ZIndex = 2,
		Visible = false,
		Parent = radialButton
	};

	local radialIcon = utility:Create'ImageLabel'
	{
		Name = "RadialIcon",
		Position = slotIconPosition,
		Size = slotIconSize,
		BackgroundTransparency = 1,
		Image = slotIcon,
		ZIndex = 3,
		ImageTransparency = disabled and 1 or 0,
		Parent = radialButton
	};

	local nameLabel = utility:Create'TextLabel'
	{

		Size = UDim2.new(0,220,0,50),
		Position = UDim2.new(0.5, -110, 0.5, -25),
		BackgroundTransparency = 1,
		Text = text,
		Font = Enum.Font.SourceSansBold,
		FontSize = Enum.FontSize.Size14,
		TextColor3 = Color3.new(1,1,1),
		Name = "RadialLabel",
		Visible = false,
		ZIndex = 3,
		Parent = radialButton
	};
	if not smallScreen then
		nameLabel.FontSize = Enum.FontSize.Size36
		nameLabel.Size = UDim2.new(nameLabel.Size.X.Scale, nameLabel.Size.X.Offset, nameLabel.Size.Y.Scale, nameLabel.Size.Y.Offset + 4)
	end
	local nameBackgroundImage = utility:Create'ImageLabel'
	{
		Name = text .. "BackgroundImage",
		Size = UDim2.new(1,0,1,0),
		Position = UDim2.new(0,0,0,2),
		BackgroundTransparency = 1,
		Image = "rbxasset://textures/ui/Settings/Radial/RadialLabel@2x.png",
		ScaleType = Enum.ScaleType.Slice,
		SliceCenter = Rect.new(24,4,130,42),
		ZIndex = 2,
		Parent = nameLabel
	};

	local mouseFrame = utility:Create'ImageButton'
	{
		Name = "MouseFrame",
		Position = mouseFramePos,
		Size = mouseFrameSize,
		ZIndex = 3,
		BackgroundTransparency = 1,
		SelectionImageObject = emptySelectedImageObject,
		Parent = radialButton
	};

	mouseFrame.MouseEnter:connect(function()
		if not radialButtons[radialButton]["Disabled"] then
			setSelectedRadialButton(radialButton)
		end
	end)
	mouseFrame.MouseLeave:connect(function()
		setSelectedRadialButton(nil)
	end)

	mouseFrame.MouseButton1Click:connect(function()
		if selectedRadial.Visible then
			activateFunc()
		end
	end)

	radialButtons[radialButton] = { ["Function"] = activateFunc, ["Disabled"] = disabled, ["CoreGuiType"] = coreGuiType, ["Slot"] = slot, ["VRSlot"] = vrSlot }
	radialButtonsByName[name] = radialButton
	return radialButton
end

local function createGamepadMenuGui()
	--If we've already created the gamepadSettingsFrame, don't
	--do it again
	if gamepadSettingsFrame then
		return
	end

	gamepadSettingsFrame = utility:Create'Frame'
	{
		Name = "GamepadSettingsFrame",
		Position = UDim2.new(0.5,0,0.5,0),
		BackgroundTransparency = 1,
		BorderSizePixel = 0,
		Size = NON_VR_FRAME_SIZE,
		AnchorPoint = Vector2.new(0.5, 0.5),
		Visible = false,
		Parent = GuiRoot
	};

	---------------------------------
	-------- Settings Menu ----------
	local function settingsFunc()
		toggleCoreGuiRadial(true)
		local MenuModule = require(GuiRoot.Modules.Settings.SettingsHub)
		MenuModule:SetVisibility(true, nil, MenuModule.Instance.GameSettingsPage, true)
	end
	local settingsRadial = createRadialButton("Settings", "Settings", 1, 1, false, nil, settingsFunc)
	settingsRadial.Parent = gamepadSettingsFrame

	---------------------------------
	-------- Player List ------------
	local function playerListFunc()
		if VRService.VREnabled then
			toggleCoreGuiRadial(true)
			local MenuModule = require(GuiRoot.Modules.Settings.SettingsHub)
			MenuModule:SetVisibility(true, nil, MenuModule.Instance.PlayersPage, true)
		else
			if not fixGamePadPlayerlist then
				toggleCoreGuiRadial(true)
				local PlayerListModule = require(GuiRoot.Modules.PlayerlistModule)
				if PlayerListModule and not PlayerListModule:IsOpen() then
					PlayerListModule:ToggleVisibility()
				end
			else
				local PlayerListModule = require(GuiRoot.Modules.PlayerlistModule)
				if PlayerListModule and not PlayerListModule:IsOpen() then
					toggleCoreGuiRadial(true)
					PlayerListModule:ToggleVisibility()
				else
					toggleCoreGuiRadial()
				end
			end
		end
	end
	local playerListRadial = createRadialButton("PlayerList", "Playerlist", 2, 2, not StarterGui:GetCoreGuiEnabled(Enum.CoreGuiType.PlayerList), Enum.CoreGuiType.PlayerList, playerListFunc)
	playerListRadial.Parent = gamepadSettingsFrame

	---------------------------------
	-------- Notifications ----------
	local gamepadNotifications = Instance.new("BindableEvent")
	gamepadNotifications.Name = "GamepadNotifications"
	gamepadNotifications.Parent = script
	local notificationsFunc = function()
		toggleCoreGuiRadial()
		if VRService.VREnabled then
			local notificationHub = require(GuiRoot.Modules.VR.NotificationHub)
			notificationHub:SetVisible(not notificationHub:IsVisible())
		else
			gamepadNotifications:Fire(true)
		end
	end
	local notificationsRadial = createRadialButton("Notifications", "Notifications", 3, 4, false, nil, notificationsFunc)
	if isTenFootInterface then
		setButtonEnabled(notificationsRadial, false)
	end
	notificationsRadial.Parent = gamepadSettingsFrame

	---------------------------------
	---------- Leave Game -----------
	local function leaveGameFunc()
		toggleCoreGuiRadial(true)
		local MenuModule = require(GuiRoot.Modules.Settings.SettingsHub)
		MenuModule:SetVisibility(true, false, require(GuiRoot.Modules.Settings.Pages.LeaveGame), true)
	end
	local leaveGameRadial = createRadialButton("LeaveGame", "Leave Game", 4, 5, false, nil, leaveGameFunc)
	leaveGameRadial.Parent = gamepadSettingsFrame

	---------------------------------
	---------- Backpack -------------
	local function backpackFunc()
		toggleCoreGuiRadial(true)
		local BackpackModule = require(GuiRoot.Modules.BackpackScript)
		BackpackModule:OpenClose()
	end
	local backpackRadial = createRadialButton("Backpack", "Backpack", 5, 6, not StarterGui:GetCoreGuiEnabled(Enum.CoreGuiType.Backpack), Enum.CoreGuiType.Backpack, backpackFunc)
	backpackRadial.Parent = gamepadSettingsFrame

	---------------------------------
	------------ Chat ---------------
	local function chatFunc()
		toggleCoreGuiRadial()
		local ChatModule = require(GuiRoot.Modules.ChatSelector)
		ChatModule:ToggleVisibility()
	end
	local chatRadial = createRadialButton("Chat", "Chat", 6, 8, not StarterGui:GetCoreGuiEnabled(Enum.CoreGuiType.Chat), Enum.CoreGuiType.Chat, chatFunc)
	if isTenFootInterface then
		setButtonEnabled(chatRadial, false)
	end
	chatRadial.Parent = gamepadSettingsFrame

	--------------------------------
	------ Recenter (VR ONLY) ------
	local function recenterFunc()
		toggleCoreGuiRadial()
		local RecenterModule = require(GuiRoot.Modules.VR.Recenter)
		RecenterModule:SetVisible(not RecenterModule:IsVisible())
	end
	local recenterRadial = createRadialButton("Recenter", "Recenter", nil, 3, false, nil, recenterFunc)

	--------------------------------
	------- 2D UI (VR ONLY) --------
	local function toggleUIFunc()
		toggleCoreGuiRadial()
		local UserGuiModule = require(GuiRoot.Modules.VR.UserGui)
		UserGuiModule:SetVisible(not UserGuiModule:IsVisible())
	end
	local toggleUIRadial = createRadialButton("ToggleUI", "Toggle UI", nil, 7, false, nil, toggleUIFunc)

	---------------------------------
	--------- Close Button ----------
	local closeHintFrame = utility:Create'Frame'
	{
		Name = "CloseHintFrame",
		Position = UDim2.new(1,10,1,10),
		Size = UDim2.new(0, 103, 0, 60),
		AnchorPoint = Vector2.new(0.5, 0.5),
		BackgroundTransparency = 1,
		Parent = gamepadSettingsFrame
	}
	local closeHintImage = utility:Create'ImageLabel'
	{
		Name = "CloseHint",
		Position = UDim2.new(0,0,0.5,0),
		Size = UDim2.new(1,0,1,0),
		AnchorPoint = Vector2.new(0, 0.5),
		BackgroundTransparency = 1,
		Image = "rbxasset://textures/ui/Settings/Help/BButtonDark.png",
		Parent = closeHintFrame
	}
	utility:Create'UIAspectRatioConstraint'
	{
		AspectRatio = 1,
		Parent = closeHintImage
	}
	if isTenFootInterface then
		closeHintImage.Image = "rbxasset://textures/ui/Settings/Help/BButtonDark@2x.png"
		closeHintFrame.Size = UDim2.new(0,133,0,90)
	end

	local closeHintText = utility:Create'TextLabel'
	{
		Name = "closeHintText",
		Position = UDim2.new(1,0,0.5,0),
		Size = UDim2.new(0,43,0,24),
		AnchorPoint = Vector2.new(1, 0.5),
		Font = Enum.Font.SourceSansBold,
		FontSize = Enum.FontSize.Size24,
		BackgroundTransparency = 1,
		Text = "Back",
		TextColor3 = Color3.new(1,1,1),
		TextXAlignment = Enum.TextXAlignment.Left,
		Parent = closeHintFrame
	}
	if isTenFootInterface then
		closeHintText.FontSize = Enum.FontSize.Size36
	end

	------------------------------------------
	--------- Stop Recording Button ----------
	--todo: enable this when recording is not a verb
	--[[local stopRecordingImage = utility:Create'ImageLabel'
	{
		Name = "StopRecordingHint",
		Position = UDim2.new(0,-100,1,10),
		Size = UDim2.new(0,61,0,61),
		BackgroundTransparency = 1,
		Image = "rbxasset://textures/ui/Settings/Help/YButtonDark.png",
		Visible = recordPage:IsRecording(),
		Parent = gamepadSettingsFrame
	}
	local stopRecordingText = utility:Create'TextLabel'
	{
		Name = "stopRecordingHintText",
		Position = UDim2.new(1,10,0.5,-12),
		Size = UDim2.new(0,43,0,24),
		Font = Enum.Font.SourceSansBold,
		FontSize = Enum.FontSize.Size24,
		BackgroundTransparency = 1,
		Text = "Stop Recording",
		TextColor3 = Color3.new(1,1,1),
		TextXAlignment = Enum.TextXAlignment.Left,
		Parent = stopRecordingImage
	}

	recordPage.RecordingChanged:connect(function(isRecording)
		stopRecordingImage.Visible = isRecording
	end)]]

	GuiService:AddSelectionParent(HttpService:GenerateGUID(false), gamepadSettingsFrame)

	gamepadSettingsFrame:GetPropertyChangedSignal("Visible"):connect(function()
		if not gamepadSettingsFrame.Visible then
			unbindAllRadialActions()
		end
	end)

	VRService:GetPropertyChangedSignal("VREnabled"):connect(function() toggleVR(VRService.VREnabled) end)
	toggleVR(VRService.VREnabled)
end

local function isCoreGuiDisabled()
	for _, enumItem in pairs(Enum.CoreGuiType:GetEnumItems()) do
		if StarterGui:GetCoreGuiEnabled(enumItem) then
			return false
		end
	end

	return true
end

local D_PAD_VR_DIRS = {
	[Enum.KeyCode.DPadUp] = Vector2.new(0, 1),
	[Enum.KeyCode.DPadDown] = Vector2.new(0, -1),
	[Enum.KeyCode.DPadRight] = Vector2.new(1, 0),
	[Enum.KeyCode.DPadLeft] = Vector2.new(-1, 0)
}

function updateGuiVisibility()
	if VRService.VREnabled and vrPanel and isVisible then
		vrPanel:SetVisible(true, true)
	end

	local children = gamepadSettingsFrame:GetChildren()
	for i = 1, #children do
		if children[i]:FindFirstChild("RadialIcon") then
			children[i].RadialIcon.Visible = isVisible
		end
		if children[i]:FindFirstChild("RadialLabel") and not isVisible then
			children[i].RadialLabel.Visible = isVisible
		end
	end
end

doGamepadMenuButton = function(name, state, input)
	if state ~= Enum.UserInputState.Begin then return end

	if game.IsLoaded then
		if not toggleCoreGuiRadial() then
			unbindAllRadialActions()
		end
	end
end

if InputService:GetGamepadConnected(Enum.UserInputType.Gamepad1) then
	createGamepadMenuGui()
else
	InputService.GamepadConnected:connect(function(gamepadEnum)
		if gamepadEnum == Enum.UserInputType.Gamepad1 then
			createGamepadMenuGui()
		end
	end)
end

if radialMenuAfterLoadingScreen then
	local defaultLoadingGuiRemovedConnection = nil
	local loadedConnection = nil
	local isLoadingGuiRemoved = false
	local isPlayerAdded = false

	local function updateRadialMenuActionBinding()
		if isLoadingGuiRemoved and isPlayerAdded then
			createGamepadMenuGui()
			ContextActionService:BindCoreAction(toggleMenuActionName, doGamepadMenuButton, false, Enum.KeyCode.ButtonStart)
		end
	end

	local function handlePlayerAdded()
		loadedConnection:disconnect()
		isPlayerAdded = true
		updateRadialMenuActionBinding()
	end

	loadedConnection = Players.PlayerAdded:connect(
		function(plr)
			if Players.LocalPlayer and plr == Players.LocalPlayer then
				handlePlayerAdded()
			end
		end
	)

	if Players.LocalPlayer then
		handlePlayerAdded()
	end

	local function handleDefaultLoadingGuiRemoved()
		if defaultLoadingGuiRemovedConnection then
			defaultLoadingGuiRemovedConnection:disconnect()
		end
		isLoadingGuiRemoved = true
		updateRadialMenuActionBinding()
	end

	if game:GetService("ReplicatedFirst"):IsDefaultLoadingGuiRemoved() then
		handleDefaultLoadingGuiRemoved()
	else
		defaultLoadingGuiRemovedConnection = game:GetService("ReplicatedFirst").DefaultLoadingGuiRemoved:connect(handleDefaultLoadingGuiRemoved)
	end
else
	local loadedConnection
	local function enableRadialMenu()
		createGamepadMenuGui()
		ContextActionService:BindCoreAction(toggleMenuActionName, doGamepadMenuButton, false, Enum.KeyCode.ButtonStart)
		loadedConnection:disconnect()
	end

	loadedConnection = Players.PlayerAdded:connect(function(plr)
		if Players.LocalPlayer and plr == Players.LocalPlayer then
			enableRadialMenu()
		end
	end)

	if Players.LocalPlayer then
		enableRadialMenu()
	end
end

-- some buttons always show/hide depending on platform
local function canChangeButtonVisibleState(buttonType)
	if isTenFootInterface then
		if buttonType == Enum.CoreGuiType.Chat or buttonType == Enum.CoreGuiType.PlayerList then
			return false
		end
	end

	if VRService.VREnabled then
		if buttonType == Enum.CoreGuiType.Chat then
			return false
		end
	end

	return true
end

StarterGui.CoreGuiChangedSignal:connect(function(coreGuiType, enabled)
	for button, buttonTable in pairs(radialButtons) do
		local buttonType = buttonTable["CoreGuiType"]
		if buttonType then
			if coreGuiType == buttonType or coreGuiType == Enum.CoreGuiType.All then
				if canChangeButtonVisibleState(buttonType) then
					setButtonEnabled(button, enabled)
				end
			end
		end
	end
end)


text:
<?php

function createClassMap($base, $qcn_prefix, array $exclude_array = array())
{
    $function_class_map = array();

    $objects = new RecursiveIteratorIterator (
        new RecursiveDirectoryIterator($base),
        RecursiveIteratorIterator::SELF_FIRST
    );

    foreach ($objects as $file_path => $file_object) {

        $include = true;

        if (count($exclude_array) === 0) {
        } else {
            foreach ($exclude_array as $search_for) {
                if (strrpos($file_object->getPath(), $search_for) === false) {
                } else {
                    $include = false;
                }
            }
        }

        if ($file_object->getExtension() === 'php') {
        } else {
            $include = false;
        }

        if ($include === true) {
            $qcn                      = $qcn_prefix . $file_object->getBaseName('.php');
            $path                     = $file_object->getPath() . '/' . $file_object->getFileName();
            $function_class_map[$qcn] = $path;
        }
    }

    return $function_class_map;
}


text:
'use strict';

var Logger = function (loggerConfig) {

    var levels = {
        debug: 4,
        info: 3,
        warn: 2,
        error: 1,
        abort: 0
    };
    console.log('config:', loggerConfig);

    var currentLevel = levels[loggerConfig.level] || 2;

    this.debug = function(msg){
        if(currentLevel >= levels.debug){
            console.log('[debug]: ', msg);
        }
    };
    this.info = function(msg){
        if(currentLevel >= levels.info){
            console.log('[info]: ', msg);
        }
    };
    this.warn = function(msg){
        if(currentLevel >= levels.warn){
            console.log('[*warn*]: ', msg);
        }
    };
    this.error = function(msg){
        if(currentLevel >= levels.error){
            console.log('[**error**]: ', msg);
        }
    };
};

module.exports = Logger;


text:
package org.jboss.resteasy.core;

import org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext;
import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry;
import org.jboss.resteasy.core.interception.JaxrsInterceptorRegistryListener;
import org.jboss.resteasy.core.interception.ServerReaderInterceptorContext;
import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
import org.jboss.resteasy.spi.BadRequestException;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.MarshalledEntity;
import org.jboss.resteasy.spi.ReaderException;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.util.FindAnnotation;
import org.jboss.resteasy.util.InputStreamToByteArray;
import org.jboss.resteasy.util.ThreadLocalStack;
import org.jboss.resteasy.util.Types;

import javax.ws.rs.Encoded;
import javax.ws.rs.NotSupportedException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.ReaderInterceptor;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
@SuppressWarnings("unchecked")
public class MessageBodyParameterInjector implements ValueInjector, JaxrsInterceptorRegistryListener
{
   private static ThreadLocalStack<Object> bodyStack = new ThreadLocalStack<Object>();

   public static void pushBody(Object o)
   {
      bodyStack.push(o);
   }

   public static Object getBody()
   {
      return bodyStack.get();
   }

   public static Object popBody()
   {
      return bodyStack.pop();
   }

   public static int bodyCount()
   {
      return bodyStack.size();
   }

   public static void clearBodies()
   {
      bodyStack.clear();
   }

   private Class type;
   private Type genericType;
   private Annotation[] annotations;
   private ResteasyProviderFactory factory;
   private Class declaringClass;
   private AccessibleObject target;
   private ReaderInterceptor[] interceptors;
   private boolean isMarshalledEntity;

   public MessageBodyParameterInjector(Class declaringClass, AccessibleObject target, Class type, Type genericType, Annotation[] annotations, ResteasyProviderFactory factory)
   {
      this.factory = factory;
      this.target = target;
      this.declaringClass = declaringClass;

      if (type.equals(MarshalledEntity.class))
      {
         if (genericType == null || !(genericType instanceof ParameterizedType))
         {
            throw new RuntimeException(Messages.MESSAGES.marshalledEntityMustHaveTypeInfo());
         }
         isMarshalledEntity = true;
         ParameterizedType param = (ParameterizedType) genericType;
         this.genericType = param.getActualTypeArguments()[0];
         this.type = Types.getRawType(this.genericType);
      }
      else
      {
         this.type = type;
         this.genericType = genericType;
      }
      this.annotations = annotations;
      this.interceptors = factory
              .getServerReaderInterceptorRegistry().postMatch(
                      this.declaringClass, this.target);

      // this is for when an interceptor is added after the creation of the injector
      factory.getServerReaderInterceptorRegistry().getListeners().add(this);
   }

   public void registryUpdated(JaxrsInterceptorRegistry registry)
   {
      this.interceptors = factory
              .getServerReaderInterceptorRegistry().postMatch(
                      declaringClass, target);
   }

   public boolean isFormData(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
   {
      if (mediaType.isWildcardType() || mediaType.isWildcardSubtype() ||
         		  !mediaType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) return false;
      if (!MultivaluedMap.class.isAssignableFrom(type)) return false;
      if (genericType == null) return true;

      if (!(genericType instanceof ParameterizedType)) return false;
      ParameterizedType params = (ParameterizedType) genericType;
      if (params.getActualTypeArguments().length != 2) return false;
      return params.getActualTypeArguments()[0].equals(String.class) && params.getActualTypeArguments()[1].equals(String.class);
   }

   public Object inject(HttpRequest request, HttpResponse response)
   {
      Object o = getBody();
      if (o != null)
      {
         return o;
      }
      MediaType mediaType = request.getHttpHeaders().getMediaType();
      if (mediaType == null)
      {
         mediaType = MediaType.WILDCARD_TYPE;
         //throw new BadRequestException("content-type was null and expecting to extract a body into " + this.target);
      }

      try
      {
         InputStream is = request.getInputStream();
         if (isMarshalledEntity)
         {
            is = new InputStreamToByteArray(is);

         }
         AbstractReaderInterceptorContext messageBodyReaderContext = new ServerReaderInterceptorContext(interceptors, factory, type,
                 genericType, annotations, mediaType, request
                 .getHttpHeaders().getRequestHeaders(), is, request);
         final Object obj = messageBodyReaderContext.proceed();
         if (isMarshalledEntity)
         {
            InputStreamToByteArray isba = (InputStreamToByteArray) is;
            final byte[] bytes = isba.toByteArray();
            return new MarshalledEntity()
            {
               @Override
               public byte[] getMarshalledBytes()
               {
                  return bytes;
               }

               @Override
               public Object getEntity()
               {
                  return obj;
               }
            };
         }
         else
         {
            return obj;
         }
      }
      catch (Exception e)
      {
         if (e instanceof ReaderException)
         {
            throw (ReaderException) e;
         }
         else
         {
            throw new ReaderException(e);
         }
      }
   }

   public Object inject()
   {
      throw new RuntimeException(Messages.MESSAGES.illegalToInjectMessageBody(this.target));
   }
}


text:
{% load i18n %}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Read the Docs</title>

              {% block top-right %}{% endblock %}

              {% block header %}

              {% endblock %}

                    {% block salutation %}
                      {% trans "Hello!" %}
                    {% endblock %}

                    {% block content %}
                    {% endblock %}

                    {% block signature %}
                      {% trans "Keep documenting," %}

                      {% trans "Read the Docs" %}
                    {% endblock %}

                    {% block footer %}
                      Read the Docs

                      https://readthedocs.org

                    {% endblock %}


text:
/*
 * $Id: Graph.java,v 1.1 2004/12/27 16:15:19 luca Exp $
 *
 * This software is provided by NOAA for full, free and open release.  It is
 * understood by the recipient/user that NOAA assumes no liability for any
 * errors contained in the code.  Although this software is released without
 * conditions or restrictions in its use, it is expected that appropriate
 * credit be given to its author and to the National Oceanic and Atmospheric
 * Administration should the software be included by the recipient as an
 * element in other product development.
 */
package  gov.noaa.pmel.sgt;

import gov.noaa.pmel.util.Range2D;
import gov.noaa.pmel.util.SoTRange;
import gov.noaa.pmel.util.Debug;

import gov.noaa.pmel.sgt.dm.SGTData;

import java.awt.Graphics;
import java.awt.Event;
import java.awt.Point;
import java.beans.PropertyChangeListener;

/**
 * Abstract base class for all graphics drawn on a Layer.  The
 * Graph class defines the interfaces for the user to physical
 * coordinate, user to device, and physical to user coordinate systems.
 *

 * The following demonstrates how a {@link CartesianGraph} may be
 * used.
 *

 *

 *   // Create a CartesianGraph and transforms.
 *
 *    CartesianGraph graph;
 *    LinearTransform xt, yt;
 *    Range2D xPhysRange, xUserRange;
 *    Range2D yPhysRange, yUserRange;
 *    Point2D.Double origin;
 *
 *    graph = new CartesianGraph("Point Graph");
 *    layer.setGraph(graph);
 *    xt = new LinearTransform(xPhysRange, xUserRange);
 *    yt = new LinearTransform(yPhysRange, yUserRange);
 *    graph.setXTransform(xt);
 *    graph.setYTransform(yt);
 *    origin = new Point2D.Double(xUserRange.start,
 *                                yUserRange.start);
 *
 *     // Create the bottom axis, set its range in user units
 *     // and its origin. Add the axis to the graph.
 *
 *    PlainAxis xbot;
 *
 *    xbot = new PlainAxis("Botton Axis");
 *    xbot.setRangeU(xUserRange);
 *    xbot.setLocationU(origin);
 *    graph.addXAxis(xbot);
 *
 *     // Create the left axis, set its range in user units
 *     // and its origin. Add the axis to the graph.
 *
 *    PlainAxis yleft;
 *
 *    yleft = new PlainAxis("Left Axis");
 *    yleft.setRangeU(yUserRange);
 *    yleft.setLocationU(origin);
 *    graph.addYAxis(yleft);
 *
 *     // Create a PointAttribute for the display of the
 *     // Collection of points. The points will be marked
 *     // with a red triangle and labelled at the NE corner
 *     // in blue.
 *
 *    PointAttribute pattr;
 *
 *    pattr = new PointAttribute(10, Color.red);
 *
 *     // Associate the attribute and the point Collection
 *     // with the graph.
 *
 *    graph.setData(col, pattr);
 *

 *
 * @author Donald Denbo
 * @version $Revision: 1.1 $, $Date: 2004/12/27 16:15:19 $
 * @since 1.0
 * @see Layer
 * @see LinearTransform
 * @see PlainAxis
 * @see SGLabel
 * @see CartesianGraph
 */
public abstract class Graph implements PropertyChangeListener {
  private String ident_;
/** @directed
 * @label layer */
  protected Layer layer_;
  /**
   * Default constructor.
   **/
  public Graph() {
    this("");
  }
  /**
   * Constructor for Graph class.
   *
   * @param id identifier
   **/
  public Graph(String id) {
    ident_ = id;
  }
  /**
   * Copy the Graph object and all attached classes.
   */
  public abstract Graph copy();
  /**
   * Get the Graph identifier
   *
   * @return ident
   **/
  public String getId() {
    return ident_;
  }
  //
  abstract void draw(Graphics g);
  //
  void setLayer(Layer l) {
    layer_ = l;
  }
  /**
   * Get the associated Layer.
   *
   * @return Layer object
   **/
  public Layer getLayer() {
    return layer_;
  }
  /**
   * Return parent pane.
   * @since 2.0
   */
  public AbstractPane getPane() {
    return layer_.getPane();
  }
  /**
   * Used internally by sgt.
   * @since 2.0
   */
  public void modified(String mess) {
    if(layer_ != null)
      layer_.modified(mess);
  }
  /**
   * Compute a "nice" range from a range and number of intervals.
   *
   * @param range min and max values
   * @param num number of intervals
   * @return "nice" range
   */
  public static Range2D computeRange(Range2D range,int num) {
    return computeRange(range.start, range.end, num);
  }
  /**
   * Compute a "nice" range from a range and number of intervals.
   *
   * @since 2.0
   * @param range min and max values
   * @param num number of intervals
   * @return "nice" range
   */
  public static SoTRange computeRange(SoTRange range, int num) {
    if(!range.isTime()) {
      SoTRange.Double drange = (SoTRange.Double)range;
      return new SoTRange.Double(computeRange(drange.start,
                                              drange.end, num));
    }
    return null;
  }
  /**
   * Compute a "nice" range from the minimum, maximum, and number of intervals.
   *
   * @param min minimum value
   * @param max maximum value
   * @param num number of intervals
   * @return "nice" range
   *
   **/
  public static Range2D computeRange(double min,double max,int num) {
    int interval = Math.abs(num);
    double temp, pow, delta;
    int nt;
    boolean reversed = false;
    //
    // check inputs to make sure that they are valid
    //
    if(min == max) {
      if(min == 0.0) {
        min = -1.0;
        max = 1.0;
      } else {
        min = 0.9*max;
        max = 1.1*max;
      }
    }
    if(min > max) {
      temp = min;
      min = max;
      max = temp;
      reversed = true;
    }
    if(interval == 0) interval = 1;
    //
    // find the approximate size of the interval
    //
    temp = (max - min)/(double)interval;
    if(temp == 0.0) temp = max;
    if(temp == 0.0) {
      min = -1.0;
      max = 1.0;
      temp = 2.0/(double)interval;
    }
    //
    // scale the interval size by powers of ten to a value between
    // one and ten
    //
    nt = (int)log10(temp);
    if(temp < 1.0) nt--;
    pow = Math.pow(10.0, (double)nt);
    temp = temp/pow;
    //
    // find the closest permissible value for the interval size
    //
    if(temp < 1.414213562) {
      delta = pow;
    } else if(temp < 3.162277660) {
      delta = 2.0 * pow;
    } else if(temp < 7.071067812) {
      delta = 5.0 * pow;
    } else {
      delta = 10.0 * pow;
    }
    //
    // calculate the minimum value of the range
    //
    temp = min / delta;
    nt = (int) temp;
    if(temp < 0.0) nt--;
    min = delta*nt;
    //
    // calculate the maximum value of the range
    //
    temp = max /delta;
    nt = (int) temp;
    if(temp > 0.0) nt++;
    max = delta*nt;
    //
    if(reversed) {
      temp = min;
      min = max;
      max = temp;
      delta = -delta;
    }
    return new Range2D(min, max, delta);
  }
  static final double log10(double x) {
    return 0.4342944819*Math.log(x);
  }
  //
  abstract Object getObjectAt(Point pt);
  /**
   * Get a String representation of the
   * Graph.
   *
   * @return String representation
   */
  public String toString() {
    String name = getClass().getName();
    return name.substring(name.lastIndexOf(".")+1) + ": " + ident_;
  }
  /**
   * Find data at a Point
   * @since 3.0
   */
  public abstract SGTData getDataAt(Point pt);
}


text:
<?php

namespace Latte;

/**
 * Latte parser.
 *
 * @author     David Grudl
 */
class Parser extends Object
{
	/** @internal regular expression for single & double quoted PHP string */
	const RE_STRING = '\'(?:\\\\.|[^\'\\\\])*\'|"(?:\\\\.|[^"\\\\])*"';

	/** @internal special HTML attribute prefix */
	const N_PREFIX = 'n:';

	/** @var string default macro tag syntax */
	public $defaultSyntax = 'latte';

	/** @var bool */
	public $shortNoEscape = FALSE;

	/** @var array */
	public $syntaxes = array(
		'latte' => array('\\{(?![\\s\'"{}])', '\\}'), // {...}
		'double' => array('\\{\\{(?![\\s\'"{}])', '\\}\\}'), // {{...}}
		'asp' => array('<%\s*', '\s*%>'), /* <%...%> */
		'python' => array('\\{[{%]\s*', '\s*[%}]\\}'), // {% ... %} | {{ ... }}
		'off' => array('[^\x00-\xFF]', ''),
	);

	/** @var string[] */
	private $delimiters;

	/** @var string source template */
	private $input;

	/** @var Token[] */
	private $output;

	/** @var int  position on source template */
	private $offset;

	/** @var array */
	private $context;

	/** @var string */
	private $lastHtmlTag;

	/** @var string used by filter() */
	private $syntaxEndTag;

	/** @var int */
	private $syntaxEndLevel = 0;

	/** @var bool */
	private $xmlMode;

	/** @internal states */
	const CONTEXT_HTML_TEXT = 'htmlText',
		CONTEXT_CDATA = 'cdata',
		CONTEXT_HTML_TAG = 'htmlTag',
		CONTEXT_HTML_ATTRIBUTE = 'htmlAttribute',
		CONTEXT_RAW = 'raw',
		CONTEXT_HTML_COMMENT = 'htmlComment',
		CONTEXT_MACRO = 'macro';

	/**
	 * Process all {macros} and <tags/>.
	 * @param  string
	 * @return Token[]
	 */
	public function parse($input)
	{
		if (substr($input, 0, 3) === "\xEF\xBB\xBF") { // BOM
			$input = substr($input, 3);
		}
		if (!preg_match('##u', $input)) {
			throw new \InvalidArgumentException('Template is not valid UTF-8 stream.');
		}
		$input = str_replace("\r\n", "\n", $input);
		$this->input = $input;
		$this->output = array();
		$this->offset = $tokenCount = 0;

		$this->setSyntax($this->defaultSyntax);
		$this->setContext(self::CONTEXT_HTML_TEXT);
		$this->lastHtmlTag = $this->syntaxEndTag = NULL;

		while ($this->offset < strlen($input)) {
			if ($this->{"context".$this->context[0]}() === FALSE) {
				break;
			}
			while ($tokenCount < count($this->output)) {
				$this->filter($this->output[$tokenCount++]);
			}
		}
		if ($this->context[0] === self::CONTEXT_MACRO) {
			throw new CompileException('Malformed macro');
		}

		if ($this->offset < strlen($input)) {
			$this->addToken(Token::TEXT, substr($this->input, $this->offset));
		}
		return $this->output;
	}

	/**
	 * Handles CONTEXT_HTML_TEXT.
	 */
	private function contextHtmlText()
	{
		$matches = $this->match('~
			(?:(?<=\n|^)[ \t]*)?<(?P<closing>/?)(?P<tag>[a-z0-9:]+)|  ##  begin of HTML tag <tag </tag - ignores <!DOCTYPE
			<(?P<htmlcomment>!--(?!>))|     ##  begin of HTML comment <!--, but not <!-->
			(?P<macro>' . $this->delimiters[0] . ')
		~xsi');

		if (!empty($matches['htmlcomment'])) { // <!--
			$this->addToken(Token::HTML_TAG_BEGIN, $matches[0]);
			$this->setContext(self::CONTEXT_HTML_COMMENT);

		} elseif (!empty($matches['tag'])) { // <tag or </tag
			$token = $this->addToken(Token::HTML_TAG_BEGIN, $matches[0]);
			$token->name = $matches['tag'];
			$token->closing = (bool) $matches['closing'];
			$this->lastHtmlTag = $matches['closing'] . strtolower($matches['tag']);
			$this->setContext(self::CONTEXT_HTML_TAG);

		} else {
			return $this->processMacro($matches);
		}
	}

	/**
	 * Handles CONTEXT_CDATA.
	 */
	private function contextCData()
	{
		$matches = $this->match('~
			</(?P<tag>' . $this->lastHtmlTag . ')(?![a-z0-9:])| ##  end HTML tag </tag
			(?P<macro>' . $this->delimiters[0] . ')
		~xsi');

		if (!empty($matches['tag'])) { // </tag
			$token = $this->addToken(Token::HTML_TAG_BEGIN, $matches[0]);
			$token->name = $this->lastHtmlTag;
			$token->closing = TRUE;
			$this->lastHtmlTag = '/' . $this->lastHtmlTag;
			$this->setContext(self::CONTEXT_HTML_TAG);
		} else {
			return $this->processMacro($matches);
		}
	}

	/**
	 * Handles CONTEXT_HTML_TAG.
	 */
	private function contextHtmlTag()
	{
		$matches = $this->match('~
			(?P<end>\ ?/?>)([ \t]*\n)?|  ##  end of HTML tag
			(?P<macro>' . $this->delimiters[0] . ')|
			\s*(?P<attr>[^\s/>={]+)(?:\s*=\s*(?P<value>["\']|[^\s/>{]+))? ## beginning of HTML attribute
		~xsi');

		if (!empty($matches['end'])) { // end of HTML tag />
			$this->addToken(Token::HTML_TAG_END, $matches[0]);
			$this->setContext(!$this->xmlMode && in_array($this->lastHtmlTag, array('script', 'style'), TRUE) ? self::CONTEXT_CDATA : self::CONTEXT_HTML_TEXT);

		} elseif (isset($matches['attr']) && $matches['attr'] !== '') { // HTML attribute
			$token = $this->addToken(Token::HTML_ATTRIBUTE, $matches[0]);
			$token->name = $matches['attr'];
			$token->value = isset($matches['value']) ? $matches['value'] : '';

			if ($token->value === '"' || $token->value === "'") { // attribute = "'
				if (strncmp($token->name, self::N_PREFIX, strlen(self::N_PREFIX)) === 0) {
					$token->value = '';
					if ($m = $this->match('~(.*?)' . $matches['value'] . '~xsi')) {
						$token->value = $m[1];
						$token->text .= $m[0];
					}
				} else {
					$this->setContext(self::CONTEXT_HTML_ATTRIBUTE, $matches['value']);
				}
			}
		} else {
			return $this->processMacro($matches);
		}
	}

	/**
	 * Handles CONTEXT_HTML_ATTRIBUTE.
	 */
	private function contextHtmlAttribute()
	{
		$matches = $this->match('~
			(?P<quote>' . $this->context[1] . ')|  ##  end of HTML attribute
			(?P<macro>' . $this->delimiters[0] . ')
		~xsi');

		if (!empty($matches['quote'])) { // (attribute end) '"
			$this->addToken(Token::TEXT, $matches[0]);
			$this->setContext(self::CONTEXT_HTML_TAG);
		} else {
			return $this->processMacro($matches);
		}
	}

	/**
	 * Handles CONTEXT_HTML_COMMENT.
	 */
	private function contextHtmlComment()
	{
		$matches = $this->match('~
			(?P<htmlcomment>-->)|   ##  end of HTML comment
			(?P<macro>' . $this->delimiters[0] . ')
		~xsi');

		if (!empty($matches['htmlcomment'])) { // -->
			$this->addToken(Token::HTML_TAG_END, $matches[0]);
			$this->setContext(self::CONTEXT_HTML_TEXT);
		} else {
			return $this->processMacro($matches);
		}
	}

	/**
	 * Handles CONTEXT_RAW.
	 */
	private function contextRaw()
	{
		$matches = $this->match('~
			(?P<macro>' . $this->delimiters[0] . ')
		~xsi');
		return $this->processMacro($matches);
	}

	/**
	 * Handles CONTEXT_MACRO.
	 */
	private function contextMacro()
	{
		$matches = $this->match('~
			(?P<comment>\\*.*?\\*' . $this->delimiters[1] . '\n{0,2})|
			(?P<macro>(?:
				' . self::RE_STRING . '|
				\{(?:' . self::RE_STRING . '|[^\'"{}])*+\}|
				[^\'"{}]
			)+?)
			' . $this->delimiters[1] . '
			(?P<rmargin>[ \t]*(?=\n))?
		~xsiA');

		if (!empty($matches['macro'])) {
			$token = $this->addToken(Token::MACRO_TAG, $this->context[1][1] . $matches[0]);
			list($token->name, $token->value, $token->modifiers, $token->empty) = $this->parseMacroTag($matches['macro']);
			$this->context = $this->context[1][0];

		} elseif (!empty($matches['comment'])) {
			$this->addToken(Token::COMMENT, $this->context[1][1] . $matches[0]);
			$this->context = $this->context[1][0];

		} else {
			throw new CompileException('Malformed macro');
		}
	}

	private function processMacro($matches)
	{
		if (!empty($matches['macro'])) { // {macro} or {* *}
			$this->setContext(self::CONTEXT_MACRO, array($this->context, $matches['macro']));
		} else {
			return FALSE;
		}
	}

	/**
	 * Matches next token.
	 * @param  string
	 * @return array
	 */
	private function match($re)
	{
		if (!preg_match($re, $this->input, $matches, PREG_OFFSET_CAPTURE, $this->offset)) {
			if (preg_last_error()) {
				throw new RegexpException(NULL, preg_last_error());
			}
			return array();
		}

		$value = substr($this->input, $this->offset, $matches[0][1] - $this->offset);
		if ($value !== '') {
			$this->addToken(Token::TEXT, $value);
		}
		$this->offset = $matches[0][1] + strlen($matches[0][0]);
		foreach ($matches as $k => $v) {
			$matches[$k] = $v[0];
		}
		return $matches;
	}

	/**
	 * @return self
	 */
	public function setContentType($type)
	{
		if (strpos($type, 'html') !== FALSE) {
			$this->xmlMode = FALSE;
			$this->setContext(self::CONTEXT_HTML_TEXT);
		} elseif (strpos($type, 'xml') !== FALSE) {
			$this->xmlMode = TRUE;
			$this->setContext(self::CONTEXT_HTML_TEXT);
		} else {
			$this->setContext(self::CONTEXT_RAW);
		}
		return $this;
	}

	/**
	 * @return self
	 */
	public function setContext($context, $quote = NULL)
	{
		$this->context = array($context, $quote);
		return $this;
	}

	/**
	 * Changes macro tag delimiters.
	 * @param  string
	 * @return self
	 */
	public function setSyntax($type)
	{
		$type = $type ?: $this->defaultSyntax;
		if (isset($this->syntaxes[$type])) {
			$this->setDelimiters($this->syntaxes[$type][0], $this->syntaxes[$type][1]);
		} else {
			throw new \InvalidArgumentException("Unknown syntax '$type'");
		}
		return $this;
	}

	/**
	 * Changes macro tag delimiters.
	 * @param  string  left regular expression
	 * @param  string  right regular expression
	 * @return self
	 */
	public function setDelimiters($left, $right)
	{
		$this->delimiters = array($left, $right);
		return $this;
	}

	/**
	 * Parses macro tag to name, arguments a modifiers parts.
	 * @param  string {name arguments | modifiers}
	 * @return array
	 * @internal
	 */
	public function parseMacroTag($tag)
	{
		if (!preg_match('~^
			(
				(?P<name>\?|/?[a-z]\w*+(?:[.:]\w+)*+(?!::|\(|\\\\))|   ## ?, name, /name, but not function( or class:: or namespace\
				(?P<noescape>!?)(?P<shortname>/?[=\~#%^&_]?)      ## !expression, !=expression, ...
			)(?P<args>.*?)
			(?P<modifiers>\|[a-z](?:'.Parser::RE_STRING.'|[^\'"])*(?<!/))?
			(?P<empty>/?\z)
		()\z~isx', $tag, $match)) {
			if (preg_last_error()) {
				throw new RegexpException(NULL, preg_last_error());
			}
			return FALSE;
		}
		if ($match['name'] === '') {
			$match['name'] = $match['shortname'] ?: '=';
			if ($match['noescape']) {
				if (!$this->shortNoEscape) {
					trigger_error("The noescape shortcut {!...} is deprecated, use {...|noescape} modifier on line {$this->getLine()}.", E_USER_DEPRECATED);
				}
				$match['modifiers'] .= '|noescape';
			}
		}
		return array($match['name'], trim($match['args']), $match['modifiers'], (bool) $match['empty']);
	}

	private function addToken($type, $text)
	{
		$this->output[] = $token = new Token;
		$token->type = $type;
		$token->text = $text;
		$token->line = $this->getLine();
		return $token;
	}

	public function getLine()
	{
		return substr_count($this->input, "\n", 0, max(1, $this->offset - 1)) + 1;
	}

	/**
	 * Process low-level macros.
	 */
	protected function filter(Token $token)
	{
		if ($token->type === Token::MACRO_TAG && $token->name === '/syntax') {
			$this->setSyntax($this->defaultSyntax);
			$token->type = Token::COMMENT;

		} elseif ($token->type === Token::MACRO_TAG && $token->name === 'syntax') {
			$this->setSyntax($token->value);
			$token->type = Token::COMMENT;

		} elseif ($token->type === Token::HTML_ATTRIBUTE && $token->name === 'n:syntax') {
			$this->setSyntax($token->value);
			$this->syntaxEndTag = $this->lastHtmlTag;
			$this->syntaxEndLevel = 1;
			$token->type = Token::COMMENT;

		} elseif ($token->type === Token::HTML_TAG_BEGIN && $this->lastHtmlTag === $this->syntaxEndTag) {
			$this->syntaxEndLevel++;

		} elseif ($token->type === Token::HTML_TAG_END && $this->lastHtmlTag === ('/' . $this->syntaxEndTag) && --$this->syntaxEndLevel === 0) {
			$this->setSyntax($this->defaultSyntax);

		} elseif ($token->type === Token::MACRO_TAG && $token->name === 'contentType') {
			$this->setContentType($token->value);
		}
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.clover_studio.spikachatmodule.view.menu</title>
<meta name="date" content="2016-03-21">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

com.clover_studio.spikachatmodule.view.menu

Interfaces

OnMenuButtonsListener

OnMenuManageListener

Classes

MenuManager


text:
#ifndef INCLUDE_fetch_h__
#define INCLUDE_fetch_h__

#include "netops.h"

int git_fetch_negotiate(git_remote *remote, const git_fetch_options *opts);

int git_fetch_download_pack(git_remote *remote, const git_remote_callbacks *callbacks);

int git_fetch_setup_walk(git_revwalk **out, git_repository *repo);

#endif


text:
package proxy

type Status struct {
	Addresses []string
}

func NewStatus(proxy *Proxy) *Status {
	if proxy == nil {
		return nil
	}
	status := &Status{
		Addresses: proxy.normalisedAddrs,
	}
	return status
}