text:
package com.android.tools.idea.configurations;

import com.android.ide.common.resources.configuration.*;
import com.android.io.IAbstractFile;
import com.android.resources.*;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.devices.Device;
import com.android.sdklib.devices.State;
import com.android.tools.idea.rendering.AppResourceRepository;
import com.android.tools.idea.rendering.LocalResourceRepository;
import com.android.tools.idea.rendering.Locale;
import com.android.tools.idea.rendering.ResourceHelper;
import com.android.utils.SparseIntArray;
import com.google.common.collect.Maps;
import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.android.uipreview.VirtualFileWrapper;
import org.jetbrains.android.util.BufferingFileWrapper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.*;

import static com.android.SdkConstants.FD_RES_LAYOUT;

/**
 * Produces matches for configurations.
 *

 * See algorithm described here:
 * http://developer.android.com/guide/topics/resources/providing-resources.html#BestMatch
 *

 * This class was ported from ADT and could probably use a rewrite.
 */
public class ConfigurationMatcher {
  private static final Logger LOG = Logger.getInstance("#com.android.tools.idea.rendering.ConfigurationMatcher");

  private final Configuration myConfiguration;
  private final ConfigurationManager myManager;
  private final VirtualFile myFile;
  private final LocalResourceRepository myResources;

  public ConfigurationMatcher(@NotNull Configuration configuration,
                       @Nullable LocalResourceRepository resources,
                       @Nullable VirtualFile file) {
    myConfiguration = configuration;
    myFile = file;
    myResources = resources;

    myManager = myConfiguration.getConfigurationManager();
  }

  // ---- Finding matching configurations ----

  private static class ConfigBundle {
    private final FolderConfiguration config;
    private int localeIndex;
    private int dockModeIndex;
    private int nightModeIndex;

    private ConfigBundle() {
      config = new FolderConfiguration();
    }

    private ConfigBundle(ConfigBundle bundle) {
      config = new FolderConfiguration();
      config.set(bundle.config);
      localeIndex = bundle.localeIndex;
      dockModeIndex = bundle.dockModeIndex;
      nightModeIndex = bundle.nightModeIndex;
    }

    @Override
    public String toString() {
      return config.getUniqueKey();
    }
  }

  private static class ConfigMatch {
    final FolderConfiguration testConfig;
    final Device device;
    final State state;
    final ConfigBundle bundle;

    public ConfigMatch(@NotNull FolderConfiguration testConfig,
                       @NotNull Device device,
                       @NotNull State state,
                       @NotNull ConfigBundle bundle) {
      this.testConfig = testConfig;
      this.device = device;
      this.state = state;
      this.bundle = bundle;
    }

    @Override
    public String toString() {
      return device.getDisplayName() + " - " + state.getName() + " - " + bundle;
    }
  }

  /**
  * Checks whether the current edited file is the best match for a given config.
  *

  * This tests against other versions of the same layout in the project.
  *

  * The given config must be compatible with the current edited file.
  *
  * @param config the config to test.
  * @return true if the current edited file is the best match in the project for the
  *         given config.
  */
  public boolean isCurrentFileBestMatchFor(@NotNull FolderConfiguration config) {
    if (myResources != null && myFile != null) {
      VirtualFile match = myResources.getMatchingFile(myFile, getResourceType(), config);
      if (match != null) {
        return myFile.equals(match);
      }
      else {
        // if we stop here that means the current file is not even a match!
        LOG.info("Current file is not a match for the given config.");
      }
    }

    return false;
  }

  private ResourceType getResourceType() {
    // We're usually using the ConfigurationMatcher for layouts, but support other types too
    ResourceType type = ResourceType.LAYOUT;
    VirtualFile parent = myFile.getParent();
    if (parent != null) {
      String parentName = parent.getName();
      if (!parentName.startsWith(FD_RES_LAYOUT)) {
        ResourceFolderType folderType = ResourceHelper.getFolderType(myFile);
        if (folderType != null) {
          List<ResourceType> related = FolderTypeRelationship.getRelatedResourceTypes(folderType);
          if (!related.isEmpty()) {
            type = related.get(0); // the primary type is always first
          }
        }
      }
    }
    return type;
  }

  @Nullable
  public static VirtualFile getVirtualFile(@NotNull IAbstractFile file) {
    if (file instanceof VirtualFileWrapper) {
      return ((VirtualFileWrapper)file).getFile();
    } else if (file instanceof BufferingFileWrapper) {
      BufferingFileWrapper wrapper = (BufferingFileWrapper)file;
      File ioFile = wrapper.getFile();
      return LocalFileSystem.getInstance().findFileByIoFile(ioFile);
    } else {
      LOG.warn("Unexpected type of match file: " + file.getClass().getName());
    }
    return null;
  }

  /**
   * Returns a list of {@link VirtualFile} which best match the configuration.
   */
  @NotNull
  public List<VirtualFile> getBestFileMatches() {
    if (myResources != null && myFile != null) {
      FolderConfiguration config = myConfiguration.getFullConfig();
      VersionQualifier prevQualifier = config.getVersionQualifier();
      try {
        config.setVersionQualifier(null);
        return myResources.getMatchingFiles(myFile, getResourceType(), config);
      }
      finally {
        config.setVersionQualifier(prevQualifier);
      }
    }
    return Collections.emptyList();
  }

  /** Like {@link ConfigurationManager#getLocales()}, but ensures that the currently selected locale is first in the list */
  @NotNull
  public List<Locale> getPrioritizedLocales() {
    List<Locale> projectLocales = myManager.getLocales();
    List<Locale> locales = new ArrayList<Locale>(projectLocales.size() + 1); // Locale.ANY is not in getLocales() list
    Locale current = myManager.getLocale();
    locales.add(current);
    for (Locale locale : projectLocales) {
      if (!locale.equals(current)) {
        locales.add(locale);
      }
    }

    return locales;
  }

  /**
   * Adapts the current device/config selection so that it's compatible with
   * the configuration.
   *

   * If the current selection is compatible, nothing is changed.
   *

   * If it's not compatible, configs from the current devices are tested.
   *

   * If none are compatible, it reverts to
   * {@link #findAndSetCompatibleConfig(boolean)}
   */
  void adaptConfigSelection(boolean needBestMatch) {
    // check the device config (ie sans locale)
    boolean needConfigChange = true; // if still true, we need to find another config.
    boolean currentConfigIsCompatible = false;
    State selectedState = myConfiguration.getDeviceState();
    FolderConfiguration editedConfig = myConfiguration.getEditedConfig();
    Module module = myConfiguration.getModule();
    if (selectedState != null) {
      FolderConfiguration currentConfig = Configuration.getFolderConfig(module, selectedState, myConfiguration.getLocale(),
                                                                        myConfiguration.getTarget());
      if (currentConfig != null && editedConfig.isMatchFor(currentConfig)) {
        currentConfigIsCompatible = true; // current config is compatible
        if (!needBestMatch || isCurrentFileBestMatchFor(currentConfig)) {
          needConfigChange = false;
        }
      }
    }

    if (needConfigChange) {
      List<Locale> localeList = getPrioritizedLocales();

      // if the current state/locale isn't a correct match, then
      // look for another state/locale in the same device.
      FolderConfiguration testConfig = new FolderConfiguration();

      // first look in the current device.
      State matchState = null;
      int localeIndex = -1;
      Device device = myConfiguration.getDevice();
      IAndroidTarget target = myConfiguration.getTarget();
      if (device != null && target != null) {
        VersionQualifier versionQualifier = new VersionQualifier(target.getVersion().getFeatureLevel());
        mainloop:
        for (State state : device.getAllStates()) {
          testConfig.set(Configuration.getFolderConfig(module, state, myConfiguration.getLocale(), target));
          testConfig.setVersionQualifier(versionQualifier);

          // loop on the locales.
          for (int i = 0; i < localeList.size(); i++) {
            Locale locale = localeList.get(i);

            // update the test config with the locale qualifiers
            testConfig.setLocaleQualifier(locale.qualifier);

            if (editedConfig.isMatchFor(testConfig) && isCurrentFileBestMatchFor(testConfig)) {
              matchState = state;
              localeIndex = i;
              break mainloop;
            }
          }
        }
      }

      if (matchState != null) {
        myConfiguration.startBulkEditing();
        myConfiguration.setDeviceState(matchState);
        myConfiguration.setEffectiveDevice(device, matchState);
        myConfiguration.finishBulkEditing();
      }
      else {
        // no match in current device with any state/locale
        // attempt to find another device that can display this
        // particular state.
        findAndSetCompatibleConfig(currentConfigIsCompatible);
      }
    }
  }

  /**
   * Finds a device/config that can display a configuration.
   *

   * Once found the device and config combos are set to the config.
   *

   * If there is no compatible configuration, a custom one is created.
   *
   * @param favorCurrentConfig if true, and no best match is found, don't
   *                           change the current config. This must only be true if the
   *                           current config is compatible.
   */
  void findAndSetCompatibleConfig(boolean favorCurrentConfig) {
    List<Locale> localeList = getPrioritizedLocales();
    List<Device> deviceList = myManager.getDevices();
    FolderConfiguration editedConfig = myConfiguration.getEditedConfig();
    FolderConfiguration currentConfig = myConfiguration.getFullConfig();

    // list of compatible device/state/locale
    List<ConfigMatch> anyMatches = new ArrayList<ConfigMatch>();

    // list of actual best match (ie the file is a best match for the
    // device/state)
    List<ConfigMatch> bestMatches = new ArrayList<ConfigMatch>();

    // get a locale that matches the host locale roughly (may not be exact match on the region.)
    int localeHostMatch = getLocaleMatch();

    // build a list of combinations of non standard qualifiers to add to each device's
    // qualifier set when testing for a match.
    // These qualifiers are: locale, night-mode, car dock.
    List<ConfigBundle> configBundles = new ArrayList<ConfigBundle>(200);

    // If the edited file has locales, then we have to select a matching locale from
    // the list.
    // However, if it doesn't, we don't randomly take the first locale, we take one
    // matching the current host locale (making sure it actually exist in the project)
    int start, max;
    if (editedConfig.getLocaleQualifier() != null || localeHostMatch == -1) {
      // add all the locales
      start = 0;
      max = localeList.size();
    }
    else {
      // only add the locale host match
      start = localeHostMatch;
      max = localeHostMatch + 1; // test is <
    }

    for (int i = start; i < max; i++) {
      Locale l = localeList.get(i);

      ConfigBundle bundle = new ConfigBundle();
      bundle.config.setLocaleQualifier(l.qualifier);
      bundle.localeIndex = i;
      configBundles.add(bundle);
    }

    // add the dock mode to the bundle combinations.
    addDockModeToBundles(configBundles);

    // add the night mode to the bundle combinations.
    addNightModeToBundles(configBundles);

    addRenderTargetToBundles(configBundles);

    Locale currentLocale = myConfiguration.getLocale();
    IAndroidTarget currentTarget = myConfiguration.getTarget();
    Module module = myConfiguration.getModule();

    for (Device device : deviceList) {
      for (State state : device.getAllStates()) {

        // loop on the list of config bundles to create full
        // configurations.
        FolderConfiguration stateConfig = Configuration.getFolderConfig(module, state, currentLocale, currentTarget);
        for (ConfigBundle bundle : configBundles) {
          // create a new config with device config
          FolderConfiguration testConfig = new FolderConfiguration();
          testConfig.set(stateConfig);

          // add on top of it, the extra qualifiers from the bundle
          testConfig.add(bundle.config);

          if (editedConfig.isMatchFor(testConfig)) {
            // this is a basic match. record it in case we don't
            // find a match
            // where the edited file is a best config.
            anyMatches.add(new ConfigMatch(testConfig, device, state, bundle));

            if (isCurrentFileBestMatchFor(testConfig)) {
              // this is what we want.
              bestMatches.add(new ConfigMatch(testConfig, device, state, bundle));
            }
          }
        }
      }
    }

    if (bestMatches.size() == 0) {
      if (favorCurrentConfig) {
        // quick check
        if (!editedConfig.isMatchFor(currentConfig)) {
          LOG.warn("favorCurrentConfig can only be true if the current config is compatible");
        }

        // just display the warning
        LOG.warn(String.format("'%1$s' is not a best match for any device/locale combination for %2$s.\n" +
                               "Displaying it with '%3$s'.",
                               editedConfig.toDisplayString(), myConfiguration.getFile(), currentConfig.toDisplayString()));
      }
      else if (anyMatches.size() > 0) {
        // select the best device anyway.
        ConfigMatch match = selectConfigMatch(anyMatches);

        myConfiguration.startBulkEditing();
        myConfiguration.setEffectiveDevice(match.device, match.state);
        myConfiguration.setUiMode(UiMode.getByIndex(match.bundle.dockModeIndex));
        myConfiguration.setNightMode(NightMode.getByIndex(match.bundle.nightModeIndex));
        myConfiguration.finishBulkEditing();

        // TODO: display a better warning!
        LOG.warn(String.format("'%1$s' is not a best match for any device/locale combination for %2$s.\n" +
                               "Displaying it with\n" +
                               "  %3$s\n" +
                               "which is compatible, but will actually be displayed with " +
                               "another more specific version of the layout.", editedConfig.toDisplayString(),
                               myConfiguration.getFile(), currentConfig.toDisplayString()));
      }
      else {
        // TODO: there is no device/config able to display the layout, create one.
        // For the base config values, we'll take the first device and state,
        // and replace whatever qualifier required by the layout file.
      }
    }
    else {
      ConfigMatch match = selectConfigMatch(bestMatches);

      myConfiguration.startBulkEditing();
      myConfiguration.setEffectiveDevice(match.device, match.state);
      myConfiguration.setUiMode(UiMode.getByIndex(match.bundle.dockModeIndex));
      myConfiguration.setNightMode(NightMode.getByIndex(match.bundle.nightModeIndex));
      myConfiguration.finishBulkEditing();
    }
  }

  private void addRenderTargetToBundles(List<ConfigBundle> configBundles) {
    IAndroidTarget target = myManager.getTarget();
    if (target != null) {
      int apiLevel = target.getVersion().getFeatureLevel();
      for (ConfigBundle bundle : configBundles) {
        bundle.config.setVersionQualifier(new VersionQualifier(apiLevel));
      }
    }
  }

  private static void addDockModeToBundles(List<ConfigBundle> addConfig) {
    ArrayList<ConfigBundle> list = new ArrayList<ConfigBundle>();

    // loop on each item and for each, add all variations of the dock modes
    for (ConfigBundle bundle : addConfig) {
      int index = 0;
      for (UiMode mode : UiMode.values()) {
        ConfigBundle b = new ConfigBundle(bundle);
        b.config.setUiModeQualifier(new UiModeQualifier(mode));
        b.dockModeIndex = index++;
        list.add(b);
      }
    }

    addConfig.clear();
    addConfig.addAll(list);
  }

  private static void addNightModeToBundles(List<ConfigBundle> addConfig) {
    ArrayList<ConfigBundle> list = new ArrayList<ConfigBundle>();

    // loop on each item and for each, add all variations of the night modes
    for (ConfigBundle bundle : addConfig) {
      int index = 0;
      for (NightMode mode : NightMode.values()) {
        ConfigBundle b = new ConfigBundle(bundle);
        b.config.setNightModeQualifier(new NightModeQualifier(mode));
        b.nightModeIndex = index++;
        list.add(b);
      }
    }

    addConfig.clear();
    addConfig.addAll(list);
  }

  private int getLocaleMatch() {
    java.util.Locale defaultLocale = java.util.Locale.getDefault();
    if (defaultLocale != null) {
      String currentLanguage = defaultLocale.getLanguage();
      String currentRegion = defaultLocale.getCountry();

      List<Locale> localeList = myManager.getLocales();
      final int count = localeList.size();
      for (int l = 0; l < count; l++) {
        Locale locale = localeList.get(l);
        LocaleQualifier qualifier = locale.qualifier;

        // there's always a ##/Other or ##/Any (which is the same, the region
        // contains FAKE_REGION_VALUE). If we don't find a perfect region match
        // we take the fake region. Since it's last in the list, this makes the
        // test easy.
        if (qualifier.getLanguage().equals(currentLanguage) &&
            (qualifier.getRegion() == null || qualifier.getRegion().equals(currentRegion))) {
          return l;
        }
      }

      // If no exact region match, try to just match on the language
      for (int l = 0; l < count; l++) {
        Locale locale = localeList.get(l);
        LocaleQualifier qualifier = locale.qualifier;

        // there's always a ##/Other or ##/Any (which is the same, the region
        // contains FAKE_REGION_VALUE). If we don't find a perfect region match
        // we take the fake region. Since it's last in the list, this makes the
        // test easy.
        if (qualifier.getLanguage().equals(currentLanguage)) {
          return l;
        }
      }
    }

    // Nothing found: use the first one (which should be the current locale); see
    // getPrioritizedLocales()
    return 0;
  }

  @NotNull
  private ConfigMatch selectConfigMatch(@NotNull List<ConfigMatch> matches) {
    List<String> deviceIds = myManager.getStateManager().getProjectState().getDeviceIds();
    Map<String, Integer> idRank = Maps.newHashMapWithExpectedSize(deviceIds.size());
    int rank = 0;
    for (String id : deviceIds) {
      idRank.put(id, rank++);
    }

    // API 11-13: look for a x-large device
    Comparator<ConfigMatch> comparator = null;
    IAndroidTarget projectTarget = myManager.getProjectTarget();
    if (projectTarget != null) {
      int apiLevel = projectTarget.getVersion().getFeatureLevel();
      if (apiLevel >= 11 && apiLevel < 14) {
        // TODO: Maybe check the compatible-screen tag in the manifest to figure out
        // what kind of device should be used for display.
        comparator = new TabletConfigComparator(idRank);
      }
    }

    if (comparator == null) {
      // lets look for a high density device
      comparator = new PhoneConfigComparator(idRank);
    }

    Collections.sort(matches, comparator);

    // Look at the currently active editor to see if it's a layout editor, and if so,
    // look up its configuration and if the configuration is in our match list,
    // use it. This means we "preserve" the current configuration when you open
    // new layouts.
    // TODO: This is running too late for the layout preview; the new editor has
    // already taken over so getSelectedTextEditor() returns self. Perhaps we
    // need to fish in the open editors instead.

    //Editor activeEditor = ApplicationManager.getApplication().runReadAction(new Computable<Editor>() {
    //  @Override
    //  public Editor compute() {
    //    FileEditorManager editorManager = FileEditorManager.getInstance(myManager.getProject());
    //    return editorManager.getSelectedTextEditor();
    //  }
    //});

    // TODO: How do I redispatch without risking lock?
    //Editor activeEditor = AndroidUtils.getSelectedEditor(myManager.getProject());
    if (ApplicationManager.getApplication().isDispatchThread()) {
      FileEditorManager editorManager = FileEditorManager.getInstance(myManager.getProject());
      Editor activeEditor = editorManager.getSelectedTextEditor();
      if (activeEditor != null) {
        FileDocumentManager documentManager = FileDocumentManager.getInstance();
        VirtualFile file = documentManager.getFile(activeEditor.getDocument());
        if (file != null && !file.equals(myFile) && file.getFileType() == XmlFileType.INSTANCE
            && ResourceHelper.getFolderType(myFile) == ResourceHelper.getFolderType(file)) {
          Configuration configuration = myManager.getConfiguration(file);
          FolderConfiguration fullConfig = configuration.getFullConfig();
          for (ConfigMatch match : matches) {
            if (fullConfig.equals(match.testConfig)) {
              return match;
            }
          }
        }
      }
    }

    // the list has been sorted so that the first item is the best config
    return matches.get(0);
  }

  /**
   * Returns a different file which is a better match for the given device, orientation, target version, etc
   * than the current one. You can supply {@code null} for all parameters; in that case, the current value
   * in the configuration is used.
   */
  @Nullable
  public static VirtualFile getBetterMatch(@NotNull Configuration configuration, @Nullable Device device, @Nullable String stateName,
                                           @Nullable Locale locale, @Nullable IAndroidTarget target) {
    VirtualFile file = configuration.getFile();
    Module module = configuration.getModule();
    if (file != null && module != null) {
      if (device == null) {
        device = configuration.getDevice();
      }
      if (stateName == null) {
        State deviceState = configuration.getDeviceState();
        stateName = deviceState != null ? deviceState.getName() : null;
      }
      State selectedState = ConfigurationFileState.getState(device, stateName);
      if (selectedState == null) {
        return null; // Invalid state name passed in for the current device
      }
      if (locale == null) {
        locale = configuration.getLocale();
      }
      if (target == null) {
        target = configuration.getTarget();
      }
      FolderConfiguration currentConfig = Configuration.getFolderConfig(module, selectedState, locale, target);
      if (currentConfig != null) {
        LocalResourceRepository resources = AppResourceRepository.getAppResources(module, true);
        if (resources != null) {
          ResourceFolderType folderType = ResourceHelper.getFolderType(file);
          if (folderType != null) {
            List<ResourceType> types = FolderTypeRelationship.getRelatedResourceTypes(folderType);
            if (!types.isEmpty()) {
              ResourceType type = types.get(0);
              List<VirtualFile> matches = resources.getMatchingFiles(file, type, currentConfig);
              if (!matches.contains(file) && !matches.isEmpty()) {
                return matches.get(0);
              }
            }
          }
        }
      }
    }

    return null;
  }

  /**
   * Note: this comparator imposes orderings that are inconsistent with equals.
   */
  private static class TabletConfigComparator implements Comparator<ConfigMatch> {
    private final Map<String, Integer> mIdRank;
    private static final String PREFERRED_ID = "Nexus 10";

    private TabletConfigComparator(Map<String, Integer> idRank) {
      mIdRank = idRank;
    }

    @Override
    public int compare(ConfigMatch o1, ConfigMatch o2) {
      FolderConfiguration config1 = o1 != null ? o1.testConfig : null;
      FolderConfiguration config2 = o2 != null ? o2.testConfig : null;
      if (config1 == null) {
        if (config2 == null) {
          return 0;
        }
        else {
          return -1;
        }
      }
      else if (config2 == null) {
        return 1;
      }

      String n1 = o1.device.getId();
      String n2 = o2.device.getId();

      Integer rank1 = mIdRank.get(o1.device.getId());
      Integer rank2 = mIdRank.get(o2.device.getId());
      if (rank1 != null) {
        if (rank2 != null) {
          int delta = rank1 - rank2;
          if (delta != 0) {
            return delta;
          }
        } else {
          return -1;
        }
      } else if (rank2 != null) {
        return 1;
      }

      // Default to a modern device
      if (n1.equals(PREFERRED_ID)) {
        return n2.equals(PREFERRED_ID) ? 0 : -1;
      } else if (n2.equals(PREFERRED_ID)) {
        return 1;
      }

      ScreenSizeQualifier size1 = config1.getScreenSizeQualifier();
      ScreenSizeQualifier size2 = config2.getScreenSizeQualifier();
      ScreenSize ss1 = size1 != null ? size1.getValue() : ScreenSize.NORMAL;
      ScreenSize ss2 = size2 != null ? size2.getValue() : ScreenSize.NORMAL;

      // X-LARGE is better than all others (which are considered identical)
      // if both X-LARGE, then LANDSCAPE is better than all others (which are identical)

      if (ss1 == ScreenSize.XLARGE) {
        if (ss2 == ScreenSize.XLARGE) {
          ScreenOrientationQualifier orientation1 = config1.getScreenOrientationQualifier();
          ScreenOrientation so1 = orientation1.getValue();
          if (so1 == null) {
            so1 = ScreenOrientation.PORTRAIT;
          }
          ScreenOrientationQualifier orientation2 = config2.getScreenOrientationQualifier();
          ScreenOrientation so2 = orientation2.getValue();
          if (so2 == null) {
            so2 = ScreenOrientation.PORTRAIT;
          }

          if (so1 == ScreenOrientation.LANDSCAPE) {
            if (so2 == ScreenOrientation.LANDSCAPE) {
              return 0;
            }
            else {
              return -1;
            }
          }
          else if (so2 == ScreenOrientation.LANDSCAPE) {
            return 1;
          }
          else {
            return 0;
          }
        }
        else {
          return -1;
        }
      }
      else if (ss2 == ScreenSize.XLARGE) {
        return 1;
      }
      else {
        return 0;
      }
    }
  }

  /**
   * Note: this comparator imposes orderings that are inconsistent with equals.
   */
  private static class PhoneConfigComparator implements Comparator<ConfigMatch> {
    // Default phone. Not picking the Nexus 5 yet since it has much higher resolution
    // (which will on a typical desktop rendering of the layout be scaled back down again anyway)
    // so it's just extra work.
    private static final String PREFERRED_ID = "Nexus 4";

    private final SparseIntArray mDensitySort = new SparseIntArray(4);
    private final Map<String, Integer> mIdRank;

    public PhoneConfigComparator(Map<String, Integer> idRank) {
      int i = 0;
      mDensitySort.put(Density.HIGH.getDpiValue(), ++i);
      mDensitySort.put(Density.MEDIUM.getDpiValue(), ++i);
      mDensitySort.put(Density.XHIGH.getDpiValue(), ++i);
      mDensitySort.put(Density.DPI_400.getDpiValue(), ++i);
      mDensitySort.put(Density.XXHIGH.getDpiValue(), ++i);
      mDensitySort.put(Density.DPI_560.getDpiValue(), ++i);
      mDensitySort.put(Density.XXXHIGH.getDpiValue(), ++i);
      mDensitySort.put(Density.DPI_280.getDpiValue(), ++i);
      mDensitySort.put(Density.TV.getDpiValue(), ++i);
      mDensitySort.put(Density.LOW.getDpiValue(), ++i);

      mIdRank = idRank;
    }

    @Override
    public int compare(ConfigMatch o1, ConfigMatch o2) {
      FolderConfiguration config1 = o1 != null ? o1.testConfig : null;
      FolderConfiguration config2 = o2 != null ? o2.testConfig : null;
      if (config1 == null) {
        if (config2 == null) {
          return 0;
        }
        else {
          return -1;
        }
      }
      else if (config2 == null) {
        return 1;
      }

      String n1 = o1.device.getId();
      String n2 = o2.device.getId();

      Integer rank1 = mIdRank.get(o1.device.getId());
      Integer rank2 = mIdRank.get(o2.device.getId());
      if (rank1 != null) {
        if (rank2 != null) {
          int delta = rank1 - rank2;
          if (delta != 0) {
            return delta;
          }
        } else {
          return -1;
        }
      } else if (rank2 != null) {
        return 1;
      }

      // Default to a modern device
      if (n1.equals(PREFERRED_ID)) {
        return n2.equals(PREFERRED_ID) ? 0 : -1;
      } else if (n2.equals(PREFERRED_ID)) {
        return 1;
      }

      int dpi1 = Density.DEFAULT_DENSITY;
      int dpi2 = Density.DEFAULT_DENSITY;

      DensityQualifier dpiQualifier1 = config1.getDensityQualifier();
      if (dpiQualifier1 != null) {
        Density value = dpiQualifier1.getValue();
        dpi1 = value != null ? value.getDpiValue() : Density.DEFAULT_DENSITY;
      }
      dpi1 = mDensitySort.get(dpi1, 100 /* valueIfKeyNotFound*/);

      DensityQualifier dpiQualifier2 = config2.getDensityQualifier();
      if (dpiQualifier2 != null) {
        Density value = dpiQualifier2.getValue();
        dpi2 = value != null ? value.getDpiValue() : Density.DEFAULT_DENSITY;
      }
      dpi2 = mDensitySort.get(dpi2, 100 /* valueIfKeyNotFound*/);

      if (dpi1 == dpi2) {
        // portrait is better
        ScreenOrientation so1 = ScreenOrientation.PORTRAIT;
        ScreenOrientationQualifier orientationQualifier1 = config1.getScreenOrientationQualifier();
        if (orientationQualifier1 != null) {
          so1 = orientationQualifier1.getValue();
          if (so1 == null) {
            so1 = ScreenOrientation.PORTRAIT;
          }
        }
        ScreenOrientation so2 = ScreenOrientation.PORTRAIT;
        ScreenOrientationQualifier orientationQualifier2 = config2.getScreenOrientationQualifier();
        if (orientationQualifier2 != null) {
          so2 = orientationQualifier2.getValue();
          if (so2 == null) {
            so2 = ScreenOrientation.PORTRAIT;
          }
        }

        if (so1 == ScreenOrientation.PORTRAIT) {
          if (so2 == ScreenOrientation.PORTRAIT) {
            return 0;
          }
          else {
            return -1;
          }
        }
        else if (so2 == ScreenOrientation.PORTRAIT) {
          return 1;
        }
        else {
          return 0;
        }
      }

      return dpi1 - dpi2;
    }
  }
}


text:
#region License

#endregion

#region Imports

using System;
using System.Runtime.Serialization;

#endregion

namespace Spring.Dao
{
	/// <summary>
	/// Root for exceptions thrown when we use a data access resource incorrectly.
	/// </summary>
	/// <remarks>
	/// <p>
	/// Thrown for example on specifying bad SQL when using a RDBMS.
	/// Resource-specific subclasses will probably be supplied by data access packages.
	/// </p>
	/// </remarks>
	/// <author>Rod Johnson</author>
	/// <author>Griffin Caprio (.NET)</author>
	[Serializable]
	public class InvalidDataAccessResourceUsageException : DataAccessException
	{
		/// <summary>
		/// Creates a new instance of the
		/// <see cref="Spring.Dao.InvalidDataAccessResourceUsageException"/> class.
		/// </summary>
		public InvalidDataAccessResourceUsageException() {}

		/// <summary>
		/// Creates a new instance of the
		/// <see cref="Spring.Dao.InvalidDataAccessResourceUsageException"/> class.
		/// </summary>
		/// <param name="message">
		/// A message about the exception.
		/// </param>
		public InvalidDataAccessResourceUsageException( string message ) : base( message ) {}

		/// <summary>
		/// Creates a new instance of the
		/// <see cref="Spring.Dao.InvalidDataAccessResourceUsageException"/> class.
		/// </summary>
		/// <param name="message">
		/// A message about the exception.
		/// </param>
		/// <param name="rootCause">
		/// The root exception (from the underlying data access API, such as ADO.NET).
		/// </param>
		public InvalidDataAccessResourceUsageException( string message, Exception rootCause)
			: base( message , rootCause ) {}

		/// <summary>
		/// Creates a new instance of the
		/// <see cref="Spring.Dao.InvalidDataAccessResourceUsageException"/> class.
		/// </summary>
		/// <param name="info">
		/// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
		/// that holds the serialized object data about the exception being thrown.
		/// </param>
		/// <param name="context">
		/// The <see cref="System.Runtime.Serialization.StreamingContext"/>
		/// that contains contextual information about the source or destination.
		/// </param>
		protected InvalidDataAccessResourceUsageException(
			SerializationInfo info, StreamingContext context ) : base( info, context ) {}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package net.catchpole.scene.overlay;

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

import net.catchpole.scene.Milieu;
import net.catchpole.scene.Resizable;
import net.catchpole.scene.spacial.Coordinate2D;

import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class OverlayManager implements Resizable, Iterable<Overlay> {
    private final int border = 25;
    private final List<Overlay> overlays = new ArrayList<Overlay>();
    private int width;
    private int height;

    public OverlayManager() {
    }

    public Iterator<Overlay> iterator() {
        return overlays.iterator();
    }

    public void addOverlay(Overlay overlay) {
        overlays.add(overlay);
    }

    public void resize(Milieu milieu, int width, int height) {
        this.width = width;
        this.height = height;

        float x = border;
        for (Overlay overlay : overlays) {
            Coordinate2D coordinate2D = overlay.getCoordinate2D();
            coordinate2D.setX(x);
            coordinate2D.setY(height - border - overlay.getHeight());
            x += overlay.getWidth() + border;
        }
    }

    public void render(Milieu milieu) {
        GL2 gl2 = milieu.getGL().getGL2();

        gl2.glMatrixMode(GL2.GL_PROJECTION);
        gl2.glPushMatrix();
        gl2.glLoadIdentity();
        milieu.getGLU().gluOrtho2D(0, width, 0, height);
        gl2.glScalef(1, -1, 1);
        gl2.glTranslatef(0, -height, 0);
        gl2.glMatrixMode(GL2.GL_MODELVIEW);
        gl2.glPushMatrix();
        gl2.glLoadIdentity();

        gl2.glEnable(GL.GL_BLEND);
        gl2.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);

        for (Overlay overlay : overlays) {
            overlay.render(milieu);
        }

        gl2.glPopMatrix();
        gl2.glMatrixMode(GL2.GL_PROJECTION);
        gl2.glPopMatrix();
        gl2.glMatrixMode(GL2.GL_MODELVIEW);
    }
}


text:
class CreateJoinTableCategoriesListings < ActiveRecord::Migration[5.2]
  def change
    create_join_table :categories, :listings do |t|
      # t.index [:category_id, :listing_id]
      # t.index [:listing_id, :category_id]
    end
  end
end


text:
package gh2011.models

case class SHA(id: Option[String], mail: Option[String], message: Option[String])


text:
@interface IMYWebLoader ()

@end


text:
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'pingscript'
require 'spec'
require 'spec/autorun'

Spec::Runner.configure do |config|

end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="@VisualScript" category="Core" version="3.2">
	<brief_description>
		Built-in visual script functions.
	</brief_description>
	<description>
		A list of built-in visual script functions, see [VisualScriptBuiltinFunc] and [VisualScript].
	</description>
	<tutorials>
	</tutorials>
	<methods>
	</methods>
	<constants>
	</constants>
</class>


text:
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor.FileDescriptor(
  name='POGOProtos/Settings/Master/PlayerLevelSettings.proto',
  package='POGOProtos.Settings.Master',
  syntax='proto3',
  serialized_pb=_b('\n4POGOProtos/Settings/Master/PlayerLevelSettings.proto\x12\x1aPOGOProtos.Settings.Master\"\x9d\x01\n\x13PlayerLevelSettings\x12\x10\n\x08rank_num\x18\x01 \x03(\x05\x12\x1b\n\x13required_experience\x18\x02 \x03(\x05\x12\x15\n\rcp_multiplier\x18\x03 \x03(\x02\x12\x1c\n\x14max_egg_player_level\x18\x04 \x01(\x05\x12\"\n\x1amax_encounter_player_level\x18\x05 \x01(\x05\x62\x06proto3')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)

_PLAYERLEVELSETTINGS = _descriptor.Descriptor(
  name='PlayerLevelSettings',
  full_name='POGOProtos.Settings.Master.PlayerLevelSettings',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='rank_num', full_name='POGOProtos.Settings.Master.PlayerLevelSettings.rank_num', index=0,
      number=1, type=5, cpp_type=1, label=3,
      has_default_value=False, default_value=[],
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='required_experience', full_name='POGOProtos.Settings.Master.PlayerLevelSettings.required_experience', index=1,
      number=2, type=5, cpp_type=1, label=3,
      has_default_value=False, default_value=[],
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='cp_multiplier', full_name='POGOProtos.Settings.Master.PlayerLevelSettings.cp_multiplier', index=2,
      number=3, type=2, cpp_type=6, label=3,
      has_default_value=False, default_value=[],
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='max_egg_player_level', full_name='POGOProtos.Settings.Master.PlayerLevelSettings.max_egg_player_level', index=3,
      number=4, type=5, cpp_type=1, label=1,
      has_default_value=False, default_value=0,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='max_encounter_player_level', full_name='POGOProtos.Settings.Master.PlayerLevelSettings.max_encounter_player_level', index=4,
      number=5, type=5, cpp_type=1, label=1,
      has_default_value=False, default_value=0,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  syntax='proto3',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=85,
  serialized_end=242,
)

DESCRIPTOR.message_types_by_name['PlayerLevelSettings'] = _PLAYERLEVELSETTINGS

PlayerLevelSettings = _reflection.GeneratedProtocolMessageType('PlayerLevelSettings', (_message.Message,), dict(
  DESCRIPTOR = _PLAYERLEVELSETTINGS,
  __module__ = 'POGOProtos.Settings.Master.PlayerLevelSettings_pb2'
  # @@protoc_insertion_point(class_scope:POGOProtos.Settings.Master.PlayerLevelSettings)
  ))
_sym_db.RegisterMessage(PlayerLevelSettings)

# @@protoc_insertion_point(module_scope)


text:
Finds containers which exceed the specified CPU and memory limits or do not specify any.

## General Usage

```
kubeaudit limits [flags]
```

### Flags
| Short   | Long      | Description                                               | Default                          |
| :------ | :-------- | :-------------------------------------------------------- | :------------------------------- |
|         | --cpu     | Max CPU limit                                             |                                  |
|         | --memory  | Max memory limit                                          |                                  |

Also see [Global Flags](/README.md#global-flags)

## Examples

The max CPU is specified using the `--cpu` flag:
```
$ kubeaudit limits --cpu 600m -f "auditors/limits/fixtures/resources-limit.yml"

---------------- Results for ---------------

  apiVersion: v1
  kind: Pod
  metadata:
    name: pod

--------------------------------------------

-- [warning] LimitsCPUExceeded
   Message: CPU limit exceeded. It is set to '750m' which exceeds the max CPU limit of '600m'.
   Metadata:
      Container: container
      ContainerCpuLimit: 750m
      MaxCPU: 600m
```

The max memory is specified using the `--memory` flag:
```
$ kubeaudit limits --memory 384 -f "auditors/limits/fixtures/resources-limit.yml"

---------------- Results for ---------------

  apiVersion: v1
  kind: Pod
  metadata:
    name: pod

--------------------------------------------

-- [warning] LimitsMemoryExceeded
   Message: Memory limit exceeded. It is set to '512Mi' which exceeds the max Memory limit of '384'.
   Metadata:
      MaxMemory: 384
      Container: container
      ContainerMemoryLimit: 512Mi
```

The CPU and memory can be audited at the same time by including both the `--cpu` and `--memory` flags:
```
$ kubeaudit limits --cpu 600m --memory 384 -f "auditors/limits/fixtures/resources-limit.yml"

---------------- Results for ---------------

  apiVersion: v1
  kind: Pod
  metadata:
    name: pod

--------------------------------------------

-- [warning] LimitsCPUExceeded
   Message: CPU limit exceeded. It is set to '750m' which exceeds the max CPU limit of '600m'.
   Metadata:
      Container: container
      ContainerCpuLimit: 750m
      MaxCPU: 600m

-- [warning] LimitsMemoryExceeded
   Message: Memory limit exceeded. It is set to '512Mi' which exceeds the max Memory limit of '384'.
   Metadata:
      Container: container
      ContainerMemoryLimit: 512Mi
      MaxMemory: 384
```

The `limits` auditor can be used to find all containers which do not specify a max CPU or memory by omitting the `--cpu` and `--memory` flags:
```
$ kubeaudit limits  -f "auditors/limits/fixtures/resources-limit-nil.yml"

---------------- Results for ---------------

  apiVersion: v1
  kind: Pod
  metadata:
    name: pod

--------------------------------------------

-- [warning] LimitsNotSet
   Message: Resource limits not set.
   Metadata:
      Container: container
```

## Override Errors

Overrides are not currently supported for `limits`.


text:
package repo

import (
	"path"

	"github.com/Unknwon/com"

	api "github.com/gogits/go-gogs-client"

	"github.com/gogits/gogs/models"
	"github.com/gogits/gogs/modules/auth"
	"github.com/gogits/gogs/modules/log"
	"github.com/gogits/gogs/modules/middleware"
	"github.com/gogits/gogs/modules/setting"
	"github.com/gogits/gogs/routers/api/v1/convert"
)

// https://github.com/gogits/go-gogs-client/wiki/Repositories#search-repositories
func Search(ctx *middleware.Context) {
	opt := models.SearchOption{
		Keyword: path.Base(ctx.Query("q")),
		Uid:     com.StrTo(ctx.Query("uid")).MustInt64(),
		Limit:   com.StrTo(ctx.Query("limit")).MustInt(),
	}
	if opt.Limit == 0 {
		opt.Limit = 10
	}

	// Check visibility.
	if ctx.IsSigned && opt.Uid > 0 {
		if ctx.User.Id == opt.Uid {
			opt.Private = true
		} else {
			u, err := models.GetUserByID(opt.Uid)
			if err != nil {
				ctx.JSON(500, map[string]interface{}{
					"ok":    false,
					"error": err.Error(),
				})
				return
			}
			if u.IsOrganization() && u.IsOwnedBy(ctx.User.Id) {
				opt.Private = true
			}
			// FIXME: how about collaborators?
		}
	}

	repos, err := models.SearchRepositoryByName(opt)
	if err != nil {
		ctx.JSON(500, map[string]interface{}{
			"ok":    false,
			"error": err.Error(),
		})
		return
	}

	results := make([]*api.Repository, len(repos))
	for i := range repos {
		if err = repos[i].GetOwner(); err != nil {
			ctx.JSON(500, map[string]interface{}{
				"ok":    false,
				"error": err.Error(),
			})
			return
		}
		results[i] = &api.Repository{
			Id:       repos[i].ID,
			FullName: path.Join(repos[i].Owner.Name, repos[i].Name),
		}
	}

	ctx.JSON(200, map[string]interface{}{
		"ok":   true,
		"data": results,
	})
}

// https://github.com/gogits/go-gogs-client/wiki/Repositories#list-your-repositories
func ListMyRepos(ctx *middleware.Context) {
	ownRepos, err := models.GetRepositories(ctx.User.Id, true)
	if err != nil {
		ctx.APIError(500, "GetRepositories", err)
		return
	}
	numOwnRepos := len(ownRepos)

	accessibleRepos, err := ctx.User.GetRepositoryAccesses()
	if err != nil {
		ctx.APIError(500, "GetRepositoryAccesses", err)
		return
	}

	repos := make([]*api.Repository, numOwnRepos+len(accessibleRepos))
	for i := range ownRepos {
		repos[i] = convert.ToApiRepository(ctx.User, ownRepos[i], api.Permission{true, true, true})
	}
	i := numOwnRepos

	for repo, access := range accessibleRepos {
		repos[i] = convert.ToApiRepository(repo.Owner, repo, api.Permission{
			Admin: access >= models.ACCESS_MODE_ADMIN,
			Push:  access >= models.ACCESS_MODE_WRITE,
			Pull:  true,
		})
		i++
	}

	ctx.JSON(200, &repos)
}

func CreateUserRepo(ctx *middleware.Context, owner *models.User, opt api.CreateRepoOption) {
	repo, err := models.CreateRepository(owner, models.CreateRepoOptions{
		Name:        opt.Name,
		Description: opt.Description,
		Gitignores:  opt.Gitignores,
		License:     opt.License,
		Readme:      opt.Readme,
		IsPrivate:   opt.Private,
		AutoInit:    opt.AutoInit,
	})
	if err != nil {
		if models.IsErrRepoAlreadyExist(err) ||
			models.IsErrNameReserved(err) ||
			models.IsErrNamePatternNotAllowed(err) {
			ctx.APIError(422, "", err)
		} else {
			if repo != nil {
				if err = models.DeleteRepository(ctx.User.Id, repo.ID); err != nil {
					log.Error(4, "DeleteRepository: %v", err)
				}
			}
			ctx.APIError(500, "CreateRepository", err)
		}
		return
	}

	ctx.JSON(201, convert.ToApiRepository(owner, repo, api.Permission{true, true, true}))
}

// https://github.com/gogits/go-gogs-client/wiki/Repositories#create
func Create(ctx *middleware.Context, opt api.CreateRepoOption) {
	// Shouldn't reach this condition, but just in case.
	if ctx.User.IsOrganization() {
		ctx.APIError(422, "", "not allowed creating repository for organization")
		return
	}
	CreateUserRepo(ctx, ctx.User, opt)
}

func CreateOrgRepo(ctx *middleware.Context, opt api.CreateRepoOption) {
	org, err := models.GetOrgByName(ctx.Params(":org"))
	if err != nil {
		if models.IsErrUserNotExist(err) {
			ctx.APIError(422, "", err)
		} else {
			ctx.APIError(500, "GetOrgByName", err)
		}
		return
	}

	if !org.IsOwnedBy(ctx.User.Id) {
		ctx.APIError(403, "", "Given user is not owner of organization.")
		return
	}
	CreateUserRepo(ctx, org, opt)
}

// https://github.com/gogits/go-gogs-client/wiki/Repositories#migrate
func Migrate(ctx *middleware.Context, form auth.MigrateRepoForm) {
	ctxUser := ctx.User
	// Not equal means context user is an organization,
	// or is another user/organization if current user is admin.
	if form.Uid != ctxUser.Id {
		org, err := models.GetUserByID(form.Uid)
		if err != nil {
			if models.IsErrUserNotExist(err) {
				ctx.APIError(422, "", err)
			} else {
				ctx.APIError(500, "GetUserByID", err)
			}
			return
		}
		ctxUser = org
	}

	if ctx.HasError() {
		ctx.APIError(422, "", ctx.GetErrMsg())
		return
	}

	if ctxUser.IsOrganization() && !ctx.User.IsAdmin {
		// Check ownership of organization.
		if !ctxUser.IsOwnedBy(ctx.User.Id) {
			ctx.APIError(403, "", "Given user is not owner of organization.")
			return
		}
	}

	remoteAddr, err := form.ParseRemoteAddr(ctx.User)
	if err != nil {
		if models.IsErrInvalidCloneAddr(err) {
			addrErr := err.(models.ErrInvalidCloneAddr)
			switch {
			case addrErr.IsURLError:
				ctx.APIError(422, "", err)
			case addrErr.IsPermissionDenied:
				ctx.APIError(422, "", "You are not allowed to import local repositories.")
			case addrErr.IsInvalidPath:
				ctx.APIError(422, "", "Invalid local path, it does not exist or not a directory.")
			default:
				ctx.APIError(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error())
			}
		} else {
			ctx.APIError(500, "ParseRemoteAddr", err)
		}
		return
	}

	repo, err := models.MigrateRepository(ctxUser, models.MigrateRepoOptions{
		Name:        form.RepoName,
		Description: form.Description,
		IsPrivate:   form.Private || setting.Repository.ForcePrivate,
		IsMirror:    form.Mirror,
		RemoteAddr:  remoteAddr,
	})
	if err != nil {
		if repo != nil {
			if errDelete := models.DeleteRepository(ctxUser.Id, repo.ID); errDelete != nil {
				log.Error(4, "DeleteRepository: %v", errDelete)
			}
		}
		ctx.APIError(500, "MigrateRepository", models.HandleCloneUserCredentials(err.Error(), true))
		return
	}

	log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName)
	ctx.JSON(201, convert.ToApiRepository(ctxUser, repo, api.Permission{true, true, true}))
}

func parseOwnerAndRepo(ctx *middleware.Context) (*models.User, *models.Repository) {
	owner, err := models.GetUserByName(ctx.Params(":username"))
	if err != nil {
		if models.IsErrUserNotExist(err) {
			ctx.APIError(422, "", err)
		} else {
			ctx.APIError(500, "GetUserByName", err)
		}
		return nil, nil
	}

	repo, err := models.GetRepositoryByName(owner.Id, ctx.Params(":reponame"))
	if err != nil {
		if models.IsErrRepoNotExist(err) {
			ctx.Error(404)
		} else {
			ctx.APIError(500, "GetRepositoryByName", err)
		}
		return nil, nil
	}

	return owner, repo
}

// https://github.com/gogits/go-gogs-client/wiki/Repositories#get
func Get(ctx *middleware.Context) {
	owner, repo := parseOwnerAndRepo(ctx)
	if ctx.Written() {
		return
	}

	ctx.JSON(200, convert.ToApiRepository(owner, repo, api.Permission{true, true, true}))
}

// https://github.com/gogits/go-gogs-client/wiki/Repositories#delete
func Delete(ctx *middleware.Context) {
	owner, repo := parseOwnerAndRepo(ctx)
	if ctx.Written() {
		return
	}

	if owner.IsOrganization() && !owner.IsOwnedBy(ctx.User.Id) {
		ctx.APIError(403, "", "Given user is not owner of organization.")
		return
	}

	if err := models.DeleteRepository(owner.Id, repo.ID); err != nil {
		ctx.APIError(500, "DeleteRepository", err)
		return
	}

	log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name)
	ctx.Status(204)
}


text:
People-iOS
==========

Get to know CI&Ts


text:
package azkaban.utils;

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.comparator.NameFileComparator;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class FileIOUtilsTest {

  @Rule
  public TemporaryFolder temp = new TemporaryFolder();
  private File sourceDir, destDir, baseDir;

  @Before
  public void setUp() throws Exception {
    // setup base dir
    this.baseDir = this.temp.newFolder("base");
    final File file1 = new File(this.baseDir.getAbsolutePath() + "/a.out");
    final File file2 = new File(this.baseDir.getAbsolutePath() + "/testdir");
    final File file3 = new File(file2.getAbsolutePath() + "/b.out");
    file1.createNewFile();
    file2.mkdir();
    file3.createNewFile();

    byte[] fileData = new byte[]{1, 2, 3};
    FileOutputStream out = new FileOutputStream(file1);
    out.write(fileData);
    out.close();

    fileData = new byte[]{2, 3, 4};
    out = new FileOutputStream(file3);
    out.write(fileData);
    out.close();

    this.sourceDir = this.temp.newFolder("src");
    FileUtils.copyDirectory(this.baseDir, this.sourceDir);

    // setup target dir
    this.destDir = this.temp.newFolder("dest");
  }

  @After
  public void tearDown() throws Exception {
    this.temp.delete();
    FileUtils.deleteDirectory(this.baseDir);
    FileUtils.deleteDirectory(this.sourceDir);
    FileUtils.deleteDirectory(this.destDir);
  }

  @Test
  public void testHardlinkCopy() throws IOException {
    FileIOUtils.createDeepHardlink(this.sourceDir, this.destDir);
    assertTrue(areDirsEqual(this.sourceDir, this.destDir, true));
    FileUtils.deleteDirectory(this.destDir);
    assertTrue(areDirsEqual(this.baseDir, this.sourceDir, true));
  }

  @Test
  public void testHardlinkCopyNonSource() {
    boolean exception = false;
    try {
      FileIOUtils.createDeepHardlink(new File(this.sourceDir, "idonotexist"), this.destDir);
    } catch (final IOException e) {
      System.out.println(e.getMessage());
      System.out.println("Handled this case nicely.");
      exception = true;
    }

    assertTrue(exception);
  }

  private boolean areDirsEqualUtil(final File file1, final File file2, final boolean isRoot,
      final boolean ignoreRoot)
      throws IOException {
    if (!file1.getName().equals(file2.getName())) {
      if (!isRoot && ignoreRoot) {
        return false;
      }
    }
    if (file1.isDirectory() && file2.isDirectory()) {
      if (file1.listFiles().length != file2.listFiles().length) {
        return false;
      }
      final File[] fileList1 = file1.listFiles();
      final File[] fileList2 = file2.listFiles();
      Arrays.sort(fileList1, NameFileComparator.NAME_COMPARATOR);
      Arrays.sort(fileList2, NameFileComparator.NAME_COMPARATOR);

      for (int i = 0; i < fileList1.length; i++) {
        if (!areDirsEqualUtil(fileList1[i], fileList2[i], false, ignoreRoot)) {
          return false;
        }
      }
      return true;
    } else if (file1.isFile() && file2.isFile()) {
      return file1.getName().equals(file2.getName()) && FileUtils.contentEquals(file1, file2);
    } else {
      return false;
    }
  }

  // check if two dirs are structurally same and contains files of same content
  private boolean areDirsEqual(final File file1, final File file2, final boolean ignoreRoot)
      throws IOException {
    return areDirsEqualUtil(file1, file2, true, ignoreRoot);
  }

  @Test
  public void testAsciiUTF() throws IOException {
    final String foreignText = "abcdefghijklmnopqrstuvwxyz";
    final byte[] utf8ByteArray = createUTF8ByteArray(foreignText);

    final int length = utf8ByteArray.length;
    System.out.println("char length:" + foreignText.length() +
        " utf8BytesLength:" + utf8ByteArray.length + " for:" + foreignText);

    final Pair<Integer, Integer> pair = FileIOUtils.getUtf8Range(utf8ByteArray, 1,
        length - 6);
    System.out.println("Pair :" + pair.toString());

    final String recreatedString = new String(utf8ByteArray, 1, length - 6, "UTF-8");
    System.out.println("recreatedString:" + recreatedString);

    final String correctString = new String(utf8ByteArray, pair.getFirst(),
        pair.getSecond(), "UTF-8");
    System.out.println("correctString:" + correctString);

    assertEquals(pair, new Pair<>(1, 20));
    // Two characters stripped from this.
    assertEquals(correctString.length(), foreignText.length() - 6);

  }

  @Test
  public void testForeignUTF() throws IOException {
    final String foreignText = "안녕하세요, 제 이름은 박병호입니다";
    final byte[] utf8ByteArray = createUTF8ByteArray(foreignText);

    final int length = utf8ByteArray.length;
    System.out.println("char length:" + foreignText.length()
        + " utf8BytesLength:" + utf8ByteArray.length + " for:" + foreignText);

    final Pair<Integer, Integer> pair = FileIOUtils.getUtf8Range(utf8ByteArray, 1,
        length - 6);
    System.out.println("Pair :" + pair.toString());

    final String recreatedString = new String(utf8ByteArray, 1, length - 6, "UTF-8");
    System.out.println("recreatedString:" + recreatedString);

    String correctString = new String(utf8ByteArray, pair.getFirst(),
        pair.getSecond(), "UTF-8");
    System.out.println("correctString:" + correctString);

    assertEquals(pair, new Pair<>(3, 40));
    // Two characters stripped from this.
    assertEquals(correctString.length(), foreignText.length() - 3);

    // Testing mixed bytes
    final String mixedText = "abc안녕하세요, 제 이름은 박병호입니다";
    final byte[] mixedBytes = createUTF8ByteArray(mixedText);
    final Pair<Integer, Integer> pair2 = FileIOUtils.getUtf8Range(mixedBytes, 1,
        length - 4);
    correctString = new String(mixedBytes, pair2.getFirst(), pair2.getSecond(),
        "UTF-8");
    System.out.println("correctString:" + correctString);
    assertEquals(pair2, new Pair<>(1, 45));
    // Two characters stripped from this.
    assertEquals(correctString.length(), mixedText.length() - 3);
  }

  private byte[] createUTF8ByteArray(final String text) {
    byte[] textBytes = null;
    try {
      textBytes = text.getBytes("UTF-8");
    } catch (final UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return textBytes;
  }
}


text:
package com.ahamed.sample.common.model;

public class SelectableItem {

  private int id;
  private String content;

  public SelectableItem(int id, String content) {
    this.id = id;
    this.content = content;
  }

  public String getContent() {
    return content;
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<tlp:Contacts
  xmlns:tlp="http://www.timelog.com/XML/Schema/tlp/v4_4"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.timelog.com/XML/Schema/tlp/v4_4 http://www.timelog.com/api/xsd/ContactsRaw.xsd">
  <tlp:Contact ID="3353">
    <tlp:Salutation>Mr.</tlp:Salutation>
    <tlp:FirstName>John</tlp:FirstName>
    <tlp:LastName>Smith</tlp:LastName>
    <tlp:FullName>John Smith</tlp:FullName>
    <tlp:CustomerID>1</tlp:CustomerID>
    <tlp:CustomerName>Microsoft</tlp:CustomerName>
    <tlp:CustomerNo>02.0000</tlp:CustomerNo>
    <tlp:Title>Sales manager</tlp:Title>
    <tlp:Phone>+1 9999 9999</tlp:Phone>
    <tlp:Mobile>+1 9999 9999</tlp:Mobile>
    <tlp:PrivatePhone>+1 9999 9999</tlp:PrivatePhone>
    <tlp:Email>j.smith@micorsoft.com</tlp:Email>
    <tlp:Address1>One Microsoft Way</tlp:Address1>
    <tlp:Address2>Two Microsoft Way</tlp:Address2>
    <tlp:ZipCode>WA 98052-6399</tlp:ZipCode>
    <tlp:City>Redmond</tlp:City>
    <tlp:State>Washington</tlp:State>
    <tlp:Birthday>1980-12-01</tlp:Birthday>
    <tlp:Country>USA</tlp:Country>
    <tlp:Comment>Note</tlp:Comment>
    <tlp:AccountManagerID>14</tlp:AccountManagerID>
    <tlp:AccountManagerFullName>Anders Egede Brandstrup</tlp:AccountManagerFullName>
    <tlp:CreatedAt>2010-06-12T13:24:52</tlp:CreatedAt>
    <tlp:CreatedByEmployeeId>414</tlp:CreatedByEmployeeId>
    <tlp:CreatedBy>MHE</tlp:CreatedBy>
    <tlp:LastModifiedAt>2010-06-12T13:24:52</tlp:LastModifiedAt>
    <tlp:LastModifiedByEmployeeId>414</tlp:LastModifiedByEmployeeId>
    <tlp:LastModifiedBy>MHE</tlp:LastModifiedBy>
    <tlp:IsActive>1</tlp:IsActive>
    <tlp:Department>Engineering</tlp:Department>
  </tlp:Contact>
</tlp:Contacts>


text:
<?php
namespace empire\framework\tests\loader\abstrwrap\test1;

use empire\framework\tests\loader\TestBaseAbstract;

class Test1TestBaseAbstract extends TestBaseAbstract {

	public function testMethod() {
		return null;
	}

}


text:
var SERVER = location.protocol + "//" + location.host;

function Get(path,callback,errorCallback)
{
	$.ajax
	({
		url: SERVER + path,
		type:"GET",
		cache: false,
		processData:false,

		success: function(data, textStatus, jqXHR)
		{
			callback(data);
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
			errorCallback(JSON.parse(jqXHR.responseText));
		}
	});
}

function Post(path,obj,callback,errorCallback)
{
	$.ajax
	({
		url: SERVER + path,
		type:"POST",
		data:JSON.stringify(obj),
		contentType: "application/json",
		cache: false,
		processData:false,

		success: function(data, textStatus, jqXHR)
		{
			callback(data);
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
			errorCallback(JSON.parse(jqXHR.responseText));
		}
	});
}

var errorCallback = function()
{
	alert("error");
}


text:
namespace carcassonne {

class Game
{
public:
   Game();
   int run();

   Player* getPlayer(int index);

   db::DB& getConfigurationDB();
   const gfx::GraphicsConfiguration& getGraphicsConfiguration() const;
   AssetManager& getAssetManager();
   Scenario* getScenario() const;

   void onMouseMoved(const glm::ivec2& window_coords);
   void onMouseWheel(int delta);
   void onMouseButton(sf::Mouse::Button button, bool down);

   void onKey(const sf::Event::KeyEvent& event, bool down);
   void onCharacter(const sf::Event::TextEvent& event);

   void onResized(const glm::ivec2& new_size);
   void onBlurred();
   void onClosed();

   void close();
   void reloadGraphicsConfiguration();

   void newScenario(ScenarioInit& options);
   void endScenario();

   void pushMenu(const std::string& name);
   void pushMenu(std::unique_ptr<gui::Menu>&& menu);
   void popMenu();
   void clearMenus();
   void setMenu(const std::string& name);
   void setMenu(std::unique_ptr<gui::Menu>&& menu);

   scheduling::Unifier unifier;

private:
   void graphicsConfigChanged();
   void createWindow();
   void initOpenGL();

   void update();
   void draw();

   db::DB config_db_;
   gfx::GraphicsConfiguration gfx_cfg_;
   sf::Window window_;
   AssetManager assets_;

   gfx::OrthoCamera menu_camera_;
   std::vector<std::unique_ptr<gui::Menu> > menu_stack_;

   std::unique_ptr<Scenario> scenario_;

   std::vector<std::unique_ptr<Player> > players_;

};

} // namespace carcassonne

#endif


text:
package libp2p

// This file contains all the default configuration options.

import (
	"crypto/rand"

	"github.com/libp2p/go-libp2p/p2p/muxer/yamux"
	"github.com/libp2p/go-libp2p/p2p/net/connmgr"
	"github.com/libp2p/go-libp2p/p2p/security/noise"
	tls "github.com/libp2p/go-libp2p/p2p/security/tls"
	quic "github.com/libp2p/go-libp2p/p2p/transport/quic"
	"github.com/libp2p/go-libp2p/p2p/transport/tcp"
	ws "github.com/libp2p/go-libp2p/p2p/transport/websocket"

	"github.com/libp2p/go-libp2p-core/crypto"

	"github.com/libp2p/go-libp2p-peerstore/pstoremem"
	rcmgr "github.com/libp2p/go-libp2p-resource-manager"
	"github.com/multiformats/go-multiaddr"
)

// DefaultSecurity is the default security option.
//
// Useful when you want to extend, but not replace, the supported transport
// security protocols.
var DefaultSecurity = ChainOptions(
	Security(noise.ID, noise.New),
	Security(tls.ID, tls.New),
)

// DefaultMuxers configures libp2p to use the stream connection multiplexers.
//
// Use this option when you want to *extend* the set of multiplexers used by
// libp2p instead of replacing them.
var DefaultMuxers = Muxer("/yamux/1.0.0", yamux.DefaultTransport)

// DefaultTransports are the default libp2p transports.
//
// Use this option when you want to *extend* the set of transports used by
// libp2p instead of replacing them.
var DefaultTransports = ChainOptions(
	Transport(tcp.NewTCPTransport),
	Transport(quic.NewTransport),
	Transport(ws.New),
)

// DefaultPeerstore configures libp2p to use the default peerstore.
var DefaultPeerstore Option = func(cfg *Config) error {
	ps, err := pstoremem.NewPeerstore()
	if err != nil {
		return err
	}
	return cfg.Apply(Peerstore(ps))
}

// RandomIdentity generates a random identity. (default behaviour)
var RandomIdentity = func(cfg *Config) error {
	priv, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, rand.Reader)
	if err != nil {
		return err
	}
	return cfg.Apply(Identity(priv))
}

// DefaultListenAddrs configures libp2p to use default listen address.
var DefaultListenAddrs = func(cfg *Config) error {
	defaultIP4ListenAddr, err := multiaddr.NewMultiaddr("/ip4/0.0.0.0/tcp/0")
	if err != nil {
		return err
	}

	defaultIP6ListenAddr, err := multiaddr.NewMultiaddr("/ip6/::/tcp/0")
	if err != nil {
		return err
	}
	return cfg.Apply(ListenAddrs(
		defaultIP4ListenAddr,
		defaultIP6ListenAddr,
	))
}

// DefaultEnableRelay enables relay dialing and listening by default.
var DefaultEnableRelay = func(cfg *Config) error {
	return cfg.Apply(EnableRelay())
}

var DefaultResourceManager = func(cfg *Config) error {
	// Default memory limit: 1/8th of total memory, minimum 128MB, maximum 1GB
	limiter := rcmgr.NewDefaultLimiter()
	SetDefaultServiceLimits(limiter)

	mgr, err := rcmgr.NewResourceManager(limiter)
	if err != nil {
		return err
	}

	return cfg.Apply(ResourceManager(mgr))
}

// DefaultConnManager creates a default connection manager
var DefaultConnectionManager = func(cfg *Config) error {
	mgr, err := connmgr.NewConnManager(160, 192)
	if err != nil {
		return err
	}

	return cfg.Apply(ConnectionManager(mgr))
}

// Complete list of default options and when to fallback on them.
//
// Please *DON'T* specify default options any other way. Putting this all here
// makes tracking defaults *much* easier.
var defaults = []struct {
	fallback func(cfg *Config) bool
	opt      Option
}{
	{
		fallback: func(cfg *Config) bool { return cfg.Transports == nil && cfg.ListenAddrs == nil },
		opt:      DefaultListenAddrs,
	},
	{
		fallback: func(cfg *Config) bool { return cfg.Transports == nil },
		opt:      DefaultTransports,
	},
	{
		fallback: func(cfg *Config) bool { return cfg.Muxers == nil },
		opt:      DefaultMuxers,
	},
	{
		fallback: func(cfg *Config) bool { return !cfg.Insecure && cfg.SecurityTransports == nil },
		opt:      DefaultSecurity,
	},
	{
		fallback: func(cfg *Config) bool { return cfg.PeerKey == nil },
		opt:      RandomIdentity,
	},
	{
		fallback: func(cfg *Config) bool { return cfg.Peerstore == nil },
		opt:      DefaultPeerstore,
	},
	{
		fallback: func(cfg *Config) bool { return !cfg.RelayCustom },
		opt:      DefaultEnableRelay,
	},
	{
		fallback: func(cfg *Config) bool { return cfg.ResourceManager == nil },
		opt:      DefaultResourceManager,
	},
	{
		fallback: func(cfg *Config) bool { return cfg.ConnManager == nil },
		opt:      DefaultConnectionManager,
	},
}

// Defaults configures libp2p to use the default options. Can be combined with
// other options to *extend* the default options.
var Defaults Option = func(cfg *Config) error {
	for _, def := range defaults {
		if err := cfg.Apply(def.opt); err != nil {
			return err
		}
	}
	return nil
}

// FallbackDefaults applies default options to the libp2p node if and only if no
// other relevant options have been applied. will be appended to the options
// passed into New.
var FallbackDefaults Option = func(cfg *Config) error {
	for _, def := range defaults {
		if !def.fallback(cfg) {
			continue
		}
		if err := cfg.Apply(def.opt); err != nil {
			return err
		}
	}
	return nil
}


text:
<!doctype html>

    <link rel="stylesheet" href="componentmother.css" type="text/css">

Component Mother

Mother Content


text:
You're probably reading this article, because you want to keep ownership of your code, host and run your own continous integration and deployment tool. [Strider](https://github.com/Strider-CD/strider) is an open source platform doing exactly this job. It's written in Node.JS and depends on MongoDB as data store.

![Strider Open Source Continuous Integration & Deployment Server]()

Strider is highly extensible and offers many plugins to enhance the platforms functionality. The platform integrates and composes of plugins. You can find more information about the [Strider Extension Loader](https://github.com/Strider-CD/strider-extension-loader) GitHub repository.

## Installation & Requirements

The [Strider repository describes the platfor m setup](https://github.com/Strider-CD/strider#general-requirements) very well. If you're interested to install Strider, just head over to the repository and follow the steps.

We're skipping the how to guide for initial Strider installation process and start with a ready-to-go platform.

## Integration with Services via Plugins

Strider integrates seamless with **GitHub**, **GitHub Enterprise**, **Bitbucket**, **GitLab**, **Heroku**, **Slack**, and many more. You can connect your GitHub and Bitbucket accounts to Strider and test your hosted repositories. Deploy you successfully tested code to Heroku and get notified in your Slack chat afterwards.

All plugins are [available on GitHub](https://github.com/Strider-CD) and you can, of course, add your own.

## How to Manually Add a Repository

Even though Strider integrates code hosting platforms like GitHub, Bitbucket and GitLab, you might want to add a personal repository hosted on another platform or your own server. You find the add repository view when navigating to `Projects -> Manuall Add` (the screenshot below shows the view). Strider asks for some information while adding your repository:

- URL to the repository (if available)
- Namespace (GitHub style like `username/repository-name`)
- Repository URL (SSH or HTTPS)
- Auth type: SSH or HTTPS

In case you provide an SSH url to your repository, you can define private and public key. Strider automatically generates project specific keys if you leave the input fields empty.

Adding a HTTP(S) url requires you to add username and password so Strider can authenticate correctly for the repository.

![Strider Manual Add a Repository]()

## Authentication Issues

Strider prints bash output for every job. Testing your repository with wrong credentials or missing SSH keys for the repository will end in an `Error: Git clone failed with code 500` error. The output will look like this

    git clone --recursive git@url.to:your/repo.git . -b master

    Cloning into '.'...
    Permission denied, please try again.
    Permission denied, please try again.
    Permission denied (publickey,password).
    fatal: Could not read from remote repository.

    Please make sure you have the correct access rights
    and the repository exists.

Solve this problem by either provide the correct user credentials or add the SSH public key to the user that has access to the git repository.

A good way to run integrations is a **buildbot**. Concretely, add a **buildbot** user to your git server and add the given SSH public key for the repository you want to test.


text:
package org.apache.activemq.artemis.tests.integration.cluster.reattach;

import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.config.Configuration;

public class NettyMultiThreadRandomReattachTest extends MultiThreadRandomReattachTest {

   @Override
   protected void start() throws Exception {
      Configuration liveConf = createDefaultNettyConfig();
      server = createServer(false, liveConf);
      server.start();
      waitForServerToStart(server);
   }

   @Override
   protected ServerLocator createLocator() throws Exception {
      return createNettyNonHALocator().setReconnectAttempts(-1).setConfirmationWindowSize(1024 * 1024).setAckBatchSize(0);
   }

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="Molly White">
  <link rel="icon" href="images/favicon.ico">

  <title>MBTA</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
  <link rel="stylesheet" href="build.min.css">


text:
import luigi
from luigi.target import FileSystemTarget, FileSystem
from urlparse import urlparse

import XRootD.client as client

class XRootDFileSystem(FileSystem):

    def __init__(self, url):
        self._fs = client.FileSystem(url)

    def exists(self, path):
        resp, info = self._fs.stat(path)
        if resp.errno == 3011:
            # File not found
            return False
        elif resp.code == 0:
            return True
        else:
            raise RuntimeError(str(resp))

    def remove(self, path, recursive=True):
        if recursive:
            self._fs.rmdir(path)
        else:
            self._fs.rm(path)

    def mkdir(self, path):
        self._fs.mkdir(path)

    def isdir(self, path):
        if self.exists(path):
            try:
                self.listdir(path)
            except ValueError:
                return False
            return True
        return False

    def listdir(self, path):
        resp, info = self._fs.dirlist(path)
        if resp.errno:
            raise ValueError(str(resp))
        else:
            return map(lambda x: x.name, info)

class XRootDTarget(FileSystemTarget):

    def __init__(self, url, fs=None):
        self._url = url
        result = urlparse(url)
        if result.scheme != 'root':
            raise ValueError('A url of the form root://... is expected')
        self._host = result.netloc
        self.path = result.path

        if fs is None:
            self._fs = XRootDFileSystem('root://{}'.format(self._host))
        else:
            self._fs = fs

    @property
    def fs(self):
        return self._fs

    def open(self, mode='r'):
        f = client.File()

        flags = None

        if mode == 'r':
            flags = client.flags.OpenFlags.READ
        elif mode == 'w':
            if self.exists():
                flags = client.flags.OpenFlags.UPDATE
            else:
                flags = client.flags.OpenFlags.NEW
        else:
            raise ValueError("Unsupported open mode '%s'" % mode)

        resp, _ = f.open(self._url, flags)
        if resp.error:
            raise RuntimeError(str(resp))

        return f


text:
@interface REDNoteRepositoryFactoryImpl ()

@property (setter=injected:) id<REDUserProtocol> user;

@end

@implementation REDNoteRepositoryFactoryImpl

-(id<REDNoteRepository>)repository {
    if ([self.user isSyncable]) {
        return [[REDSyncNoteRepository alloc] init];
    }
    return [[REDLocalNoteRepository alloc] init];
}

@end


text:
class DomainsGenerator < Rails::Generators::NamedBase
  source_root File.expand_path('../templates', __FILE__)

  def create_initializer_file
    empty_directory "app/domains/#{file_name}"
    create_file "app/domains/#{file_name}/.keep"
  end
end


text:
//  MemoryTest.cs  (c) 2002 Kari Laitinen

using System ;

class PointerSimple
{
   unsafe static void Main()
   {
      int  first_integer   =  0x44, second_integer  =  0x66,
           third_integer   =  0x88 ;

      third_integer  =  sizeof( int ) ;

      int*  pointer_to_integer ;

      Console.Write( "\n Address of first_integer:  {0}" +
                     "\n Address of second_integer: {1}" +
                     "\n Address of third_integer:  {2}",
                    (int) &first_integer, (int) &second_integer,
                    (int) &third_integer ) ;

      int   memory_positions_printed   =  0 ;
      byte*  memory_pointer  = (byte*) &first_integer ;

      while ( memory_positions_printed  <  16 )
      {
         Console.Write( "\n Memory address "
                      + ((int) memory_pointer).ToString("X")
                      + " contains "
                      + ( *memory_pointer ).ToString("X") ) ;
         memory_pointer ++ ;
         memory_positions_printed  ++ ;
      }
   }
}


text:
maygaserver-nodejs
==================
A nodejs wrapper for mayga (mayga.me) messaging API to enable in app messaging

Installation Instructions :
===========================

Download and Install lib/maygaserver.js in your lib

or

use "npm install maygaserver -g"

Usage :
=======
if installed by downloading the file

	var maygaserver = require('./lib/maygaserver');

for NPM based install

	var maygaserver = require('maygaserver');

Then initialize the library

	maygaserver.initialize(credentials, options);

The parameters to the initialize call are :

	(required) credentials :
        	(required) clientId from mayga.me
        	(required) clientSecret from mayga.me

	(optional) options :
		(optional) debugOn = true / false
        	(optional) server = restify or express server object
        	(optional) endpoint = endpoint url to expose this api default : /integration/mayga/getToken/:userEmail

List of API's supported by the library.
=======================================

###Add a new User

        maygaserver.addNewAppUser(userEmail,callback)

###Get Authroization Token for server side integration

        maygaserver.getAuthToken(callback);

###Get Authroization Token on behalf of the user for client side integration

        maygaserver.getUserToken(email, callback);

###Example :

	maygaserver.initialize({clientId:"abcdeg",clientSecret:"qwerty"},{debugOn:true});

	maygaserver.addNewAppUser("welcometomayga@mayga.me",function(err,user) {
        	console.dir(user);
        	maygaserver.getUserToken("welcometomayga@mayga.me",function(err,token) {
                	console.dir(token);
        	});
	});


text:
//---------------------------------------------------------------------
// <copyright file="ClientPreferenceTests.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace AstoriaUnitTests.TDD.Tests.Server
{
    using System;
    using Microsoft.OData.Service;
    using FluentAssertions;
    using Microsoft.OData.Core;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class ClientPreferenceTests
    {
        [TestMethod]
        public void AnnotationFilterShouldNotBeSetAndRequiredResponseVersionShouldBe10WhenTheODataAnnotationsPreferenceIsMissing()
        {
            RequestDescription descrption = new RequestDescription(RequestTargetKind.Link, RequestTargetSource.ServiceOperation, new Uri("http://service/set"));
            IODataRequestMessage requestMessage = new ODataRequestMessageSimulator();
            ClientPreference preference = new ClientPreference(descrption, HttpVerbs.None, requestMessage, effectiveMaxResponseVersion: VersionUtil.Version4Dot0);
            preference.AnnotationFilter.Should().BeNull();
            preference.RequiredResponseVersion.Should().Be(VersionUtil.Version4Dot0);
        }

        [TestMethod]
        public void AnnotationFilterShouldBeSetWithODataAnnotationsPreferenceAndRequiredResponseVersionShouldBe30WhenEffectiveMaxResponseVersionIs30()
        {
            RequestDescription descrption = new RequestDescription(RequestTargetKind.Link, RequestTargetSource.ServiceOperation, new Uri("http://service/set"));
            IODataRequestMessage requestMessage = new ODataRequestMessageSimulator();
            requestMessage.PreferHeader().AnnotationFilter = "*";
            ClientPreference preference = new ClientPreference(descrption, HttpVerbs.None, requestMessage, effectiveMaxResponseVersion: VersionUtil.Version4Dot0);
            preference.AnnotationFilter.Should().Be("*");
            preference.RequiredResponseVersion.Should().Be(VersionUtil.Version4Dot0);
        }
    }
}


text:
package subreddit.android.appstore.backend.github;

import com.google.gson.annotations.SerializedName;

import java.util.Date;
import java.util.List;

import io.reactivex.Observable;
import retrofit2.http.GET;

public interface GithubApi {
    String BASEURL = "https://api.github.com/";

    @GET("repos/d4rken/reddit-android-appstore/releases/latest")
    Observable<Release> getLatestRelease();

    @GET("repos/d4rken/reddit-android-appstore/contributors")
    Observable<List<Contributor>> getContributors();

    class Release {
        @SerializedName("url") public String releaseUrl;
        @SerializedName("tag_name") public String tagName;
        @SerializedName("name") public String releaseName;
        @SerializedName("body") public String releaseDescription;
        public boolean prerelease;
        @SerializedName("published_at") public Date publishDate;
        public List<Assets> assets;

        public static class Assets {
            @SerializedName("browser_download_url") public String downloadUrl;
            public long size;
        }
    }

    class Contributor {
        @SerializedName("login") public String username;
    }
}


text:
[home](../README.md) > [`without`](http://ramdajs.com/docs/#without)

[Solutions](./solutions.md)


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Oncidium riopalenqueanum Dodson

### Remarks
null


text:
using BattleGame.Server.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BattleGame.Server.Models
{
    public class UnitFactory
    {
        private const string WarriorType = "warrior";
        private const int WarriorHitPoints = 15;
        private const int WarriorAttack = 8;
        private const int WarriorArmor = 3;
        private const int WarriorRange = 1;
        private const int WarriorSpeed = 2;

        private const string RangerType = "ranger";
        private const int RangerHitPoints = 10;
        private const int RangerAttack = 8;
        private const int RangerArmor = 1;
        private const int RangerRange = 3;
        private const int RangerSpeed = 1;

        private static Unit GetRanger(UnitType type, int x, int y)
        {
            var ranger = new Unit()
            {
                PositionX = x,
                PositionY = y,
                HitPoints = RangerHitPoints,
                Attack = RangerAttack,
                Armor = RangerArmor,
                Range = RangerRange,
                Speed = RangerSpeed,
                UnitType = type
            };
            return ranger;
        }

        private static Unit GetWarrior(UnitType type, int x, int y)
        {
            var warrior = new Unit()
            {
                PositionX = x,
                PositionY = y,
                HitPoints = WarriorHitPoints,
                Attack = WarriorAttack,
                Armor = WarriorArmor,
                Range = WarriorRange,
                Speed = WarriorSpeed,
                UnitType = type
            };
            return warrior;
        }

        public static Unit GetUnit(UnitType unitType, int x, int y)
        {
            if (unitType.Value == WarriorType)
            {
                return GetWarrior(unitType,x, y);
            }
            else if (unitType.Value == RangerType)
            {
                return GetRanger(unitType, x, y);
            }
            else
            {
                throw new ArgumentOutOfRangeException("Unit type", "No such unit type");
            }
        }

    }
}


text:
import { EventEmitter } from '@angular/core';
import { ChartEvent } from './ChartEvent';

const chartEvents = [
    //'click', works by default as a native DOM click
    'addSeries',
    'afterPrint',
    'beforePrint',
    'drilldown',
    'drillup',
    'load',
    'redraw',
    'selection'
];

const seriesEvents = [
    'click',
    'afterAnimate',
    'checkboxClick',
    'hide',
    'legendItemClick',
    'mouseOut',
    'mouseOver',
    'show'
];

const pointEvents = [
    'click',
    'remove',
    'select',
    'unselect',
    'mouseOut',
    'mouseOver',
    'update'
];

const xAxisEvents = [
    'afterBreaks',
    'afterSetExtremes',
    'pointBreak',
    'pointInBreak',
    'setExtremes'
];

const yAxisEvents = [
    'afterBreaks',
    'afterSetExtremes',
    'pointBreak',
    'pointInBreak',
    'setExtremes'
];

export function createBaseOpts(chartCmp, seriesCmp, pointCmp, xAxisCmp, yAxisCmp, element) {
    let opts = {
        chart : {
            renderTo : element,
            events :{}
        },
        plotOptions : {
            series : {
                events : { },
                point : {
                    events : { }
                }
            }
        },
        xAxis : {
            events : { }
        },
        yAxis : {
            events : { }
        }
    };
    chartEvents.forEach(function (eventName) {
        opts.chart.events[eventName] = opts.chart.events[eventName] || function (event: any) {
            chartCmp[eventName].emit(new ChartEvent(event, this));
        }
    });
    if (seriesCmp) {
        seriesEvents.forEach(function (eventName) {
            opts.plotOptions.series.events[eventName] = opts.plotOptions.series.events[eventName] || function (event: any) {
                seriesCmp[eventName].emit(new ChartEvent(event, this));
            }
        });
    }
    if (pointCmp) {
        pointEvents.forEach(function (eventName) {
            opts.plotOptions.series.point.events[eventName] = opts.plotOptions.series.point.events[eventName] || function (event: any) {
                pointCmp[eventName].emit(new ChartEvent(event, this));
            }
        });
    }
    if (xAxisCmp) {
        xAxisEvents.forEach(function (eventName) {
            opts.xAxis.events[eventName] = opts.xAxis.events[eventName] || function (event: any) {
                xAxisCmp[eventName].emit(new ChartEvent(event, this));
            }
        });
    }
    if (yAxisCmp) {
        yAxisEvents.forEach(function (eventName) {
            opts.yAxis.events[eventName] = opts.yAxis.events[eventName] || function (event: any) {
                yAxisCmp[eventName].emit(new ChartEvent(event, this));
            }
        });
    }

    return opts;
}


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

<title>OGRE Manual v1.8 ('Byatis'): 3.1.7 OpenGL GLSL</title>

<meta name="description" content="OGRE Manual v1.8 ('Byatis'): 3.1.7 OpenGL GLSL">
<meta name="keywords" content="OGRE Manual v1.8 ('Byatis'): 3.1.7 OpenGL GLSL">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="texi2html 1.70">
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">

[ < ]
[ > ]

[ << ]
[ Up ]
[ >> ]

[Top]
[Contents]
[Index]
[ ? ]

 3.1.7 OpenGL GLSL

OpenGL GLSL has a similar language syntax to HLSL but is tied to the OpenGL API. The are a few benefits over Cg in that it only requires the OpenGL render system plugin, not any additional plugins. Declaring a OpenGL GLSL program is similar to Cg but simpler. Here's an example:

vertex_program myGLSLVertexProgram glsl
{
    source myGLSLVertexProgram.txt
}

In GLSL, no entry point needs to be defined since it is always 'main()' and there is no target definition since GLSL source is compiled into native GPU code and not intermediate assembly.

GLSL supports the use of modular shaders.  This means you can write GLSL external functions that can be used in multiple shaders.

vertex_program myExternalGLSLFunction1 glsl
{
    source myExternalGLSLfunction1.txt
}

vertex_program myExternalGLSLFunction2 glsl
{
    source myExternalGLSLfunction2.txt
}

vertex_program myGLSLVertexProgram1 glsl
{
    source myGLSLfunction.txt
    attach myExternalGLSLFunction1 myExternalGLSLFunction2
}

vertex_program myGLSLVertexProgram2 glsl
{
    source myGLSLfunction.txt
    attach myExternalGLSLFunction1
}

External GLSL functions are attached to the program that needs them by using 'attach' and including the names of all external programs required on the same line separated by spaces.  This can be done for both vertex and fragment programs.

 GLSL Texture Samplers

To pass texture unit index values from the material script to texture samplers in glsl use 'int' type named parameters.  See the example below:

excerpt from GLSL example.frag source:

varying vec2 UV;
uniform sampler2D diffuseMap;

void main(void)
{
	gl_FragColor = texture2D(diffuseMap, UV);
}

In material script:

fragment_program myFragmentShader glsl
{
  source example.frag
}

material exampleGLSLTexturing
{
  technique
  {
    pass
    {
      fragment_program_ref myFragmentShader
      {
        param_named diffuseMap int 0
      }

      texture_unit
      {
        texture myTexture.jpg 2d
      }
    }
  }
}

An index value of 0 refers to the first texture unit in the pass, an index value of 1 refers to the second unit in the pass and so on.

 Matrix parameters

Here are some examples of passing matrices to GLSL mat2, mat3, mat4 uniforms:

material exampleGLSLmatrixUniforms
{
  technique matrix_passing
  {
    pass examples
    {
      vertex_program_ref myVertexShader
      {
        // mat4 uniform
        param_named OcclusionMatrix matrix4x4 1 0 0 0  0 1 0 0  0 0 1 0  0 0 0 0
        // or
        param_named ViewMatrix float16 0 1 0 0  0 0 1 0  0 0 0 1  0 0 0 0

        // mat3
        param_named TextRotMatrix float9 1 0 0  0 1 0  0 0 1
      }

      fragment_program_ref myFragmentShader
      {
        // mat2 uniform
        param_named skewMatrix float4 0.5 0 -0.5 1.0
      }
    }
  }
}

 Accessing OpenGL states in GLSL

GLSL can access most of the GL states directly so you do not need to pass these states through param_named_auto in the material script.  This includes lights, material state, and all the matrices used in the openGL state i.e. model view matrix, worldview projection matrix etc.

 Binding vertex attributes

GLSL natively supports automatic binding of the most common incoming per-vertex attributes (e.g. gl_Vertex, gl_Normal, gl_MultiTexCoord0 etc). However, there are some which are not automatically bound, which must be declared in the shader using the 'attribute <type> <name>' syntax, and the vertex data bound to it by Ogre.

In addition to the built in attributes described in section 7.3 of the GLSL manual, Ogre supports a number of automatically bound custom vertex attributes. There are some drivers that do not behave correctly when mixing built-in vertex attributes like gl_Normal and custom vertex attributes, so for maximum compatibility you may well wish to use all custom attributes in shaders where you need at least one (e.g. for skeletal animation).

 vertex

Binds VES_POSITION, declare as 'attribute vec4 vertex;'.

 normal

Binds VES_NORMAL, declare as 'attribute vec3 normal;'.

 colour

Binds VES_DIFFUSE, declare as 'attribute vec4 colour;'.

 secondary_colour

Binds VES_SPECULAR, declare as 'attribute vec4 secondary_colour;'.

 uv0 - uv7

Binds VES_TEXTURE_COORDINATES, declare as 'attribute vec4 uv0;'. Note that uv6 and uv7 share attributes with tangent and binormal respectively so cannot both be present.

 tangent

Binds VES_TANGENT, declare as 'attribute vec3 tangent;'.

 binormal

Binds VES_BINORMAL, declare as 'attribute vec3 binormal;'.

 blendIndices

Binds VES_BLEND_INDICES, declare as 'attribute vec4 blendIndices;'.

 blendWeights

Binds VES_BLEND_WEIGHTS, declare as 'attribute vec4 blendWeights;'.

 Preprocessor definitions

GLSL supports using preprocessor definitions in your code - some are defined by the implementation, but you can also define your own, say in order to use the same source code for a few different variants of the same technique. In order to use this feature, include preprocessor conditions in your GLSL code, of the kind #ifdef SYMBOL, #if SYMBOL==2 etc. Then in your program definition, use the 'preprocessor_defines' option, following it with a string if definitions.  Definitions are separated by ';' or ',' and may optionally have a '=' operator within them to specify a definition value. Those without an '=' will implicitly have a definition of 1. For example:

// in your GLSL

#ifdef CLEVERTECHNIQUE
	// some clever stuff here
#else
	// normal technique
#endif

#if NUM_THINGS==2
	// Some specific code
#else
	// something else
#endif

// in  your program definition
preprocessor_defines CLEVERTECHNIQUE,NUMTHINGS=2

This way you can use the same source code but still include small variations, each one defined as a different Ogre program name but based on the same source code.

 GLSL Geometry shader specification

GLSL allows the same shader to run on different types of geometry primitives. In order to properly link the shaders together, you have to specify which primitives it will receive as input, which primitives it will emit and how many vertices a single run of the shader can generate. The GLSL geometry_program definition requires three additional parameters :

 input_operation_type

The operation type of the geometry that the shader will receive. Can be 'point_list', 'line_list', 'line_strip', 'triangle_list', 'triangle_strip' or 'triangle_fan'.

 output_operation_type

The operation type of the geometry that the shader will emit. Can be 'point_list', 'line_strip' or 'triangle_strip'.

 max_output_vertices

The maximum number of vertices that the shader can emit. There is an upper limit for this value, it is exposed in the render system capabilities.

For example:

geometry_program Ogre/GPTest/Swizzle_GP_GLSL glsl
{
	source SwizzleGP.glsl
	input_operation_type triangle_list
	output_operation_type line_strip
	max_output_vertices 6
}

[ < ]
[ > ]

[ << ]
[ Up ]
[ >> ]

[Top]
[Contents]
[Index]
[ ? ]

  This document was generated by David Rogers on May, 26 2012 using texi2html 1.70.


text:
class Color;
class ExeData;
class Random;
class TextureManager;

struct TextureAssetReference;

// Various functions for working with the original game's weather.

namespace ArenaWeatherUtils
{
	constexpr int RAINDROP_FAST_COUNT = 20;
	constexpr int RAINDROP_MEDIUM_COUNT = 20;
	constexpr int RAINDROP_SLOW_COUNT = 20;
	constexpr int RAINDROP_TOTAL_COUNT = RAINDROP_FAST_COUNT + RAINDROP_MEDIUM_COUNT + RAINDROP_SLOW_COUNT;

	constexpr int RAINDROP_FAST_PIXELS_PER_FRAME_Y =
		static_cast<int>((3.0 / 25.0) * ArenaRenderUtils::SCREEN_HEIGHT_REAL);
	constexpr int RAINDROP_MEDIUM_PIXELS_PER_FRAME_Y =
		static_cast<int>((1.0 / 10.0) * ArenaRenderUtils::SCREEN_HEIGHT_REAL);
	constexpr int RAINDROP_SLOW_PIXELS_PER_FRAME_Y =
		static_cast<int>((2.0 / 25.0) * ArenaRenderUtils::SCREEN_HEIGHT_REAL);

	constexpr int RAINDROP_FAST_PIXELS_PER_FRAME_X = -RAINDROP_FAST_PIXELS_PER_FRAME_Y / 2;
	constexpr int RAINDROP_MEDIUM_PIXELS_PER_FRAME_X = -RAINDROP_MEDIUM_PIXELS_PER_FRAME_Y / 2;
	constexpr int RAINDROP_SLOW_PIXELS_PER_FRAME_X = -RAINDROP_SLOW_PIXELS_PER_FRAME_Y / 2;

	constexpr double THUNDERSTORM_SKY_FLASH_SECONDS = 0.35;
	constexpr double THUNDERSTORM_BOLT_SECONDS = 0.20;

	constexpr int SNOWFLAKE_FAST_COUNT = 20;
	constexpr int SNOWFLAKE_MEDIUM_COUNT = 30;
	constexpr int SNOWFLAKE_SLOW_COUNT = 50;
	constexpr int SNOWFLAKE_TOTAL_COUNT = SNOWFLAKE_FAST_COUNT + SNOWFLAKE_MEDIUM_COUNT + SNOWFLAKE_SLOW_COUNT;

	constexpr int SNOWFLAKE_FAST_PIXELS_PER_FRAME_Y =
		static_cast<int>((1.0 / 25.0) * ArenaRenderUtils::SCREEN_HEIGHT_REAL);
	constexpr int SNOWFLAKE_MEDIUM_PIXELS_PER_FRAME_Y =
		static_cast<int>((3.0 / 100.0) * ArenaRenderUtils::SCREEN_HEIGHT_REAL);
	constexpr int SNOWFLAKE_SLOW_PIXELS_PER_FRAME_Y =
		static_cast<int>((1.0 / 50.0) * ArenaRenderUtils::SCREEN_HEIGHT_REAL);

	constexpr int SNOWFLAKE_PIXELS_PER_FRAME_X = 2; // Either left or right.

	constexpr int SNOWFLAKE_FAST_SIZE = 2;
	constexpr int SNOWFLAKE_MEDIUM_SIZE = 2;
	constexpr int SNOWFLAKE_SLOW_SIZE = 1;

	constexpr double SNOWFLAKE_MIN_SECONDS_BEFORE_DIRECTION_CHANGE =
		1.0 / static_cast<double>(ArenaRenderUtils::FRAMES_PER_SECOND);

	// Helper functions for determining what category a weather type falls into.
	bool isClear(ArenaTypes::WeatherType weatherType);
	bool isOvercast(ArenaTypes::WeatherType weatherType);
	bool isRain(ArenaTypes::WeatherType weatherType);
	bool isSnow(ArenaTypes::WeatherType weatherType);

	// Returns whether existing fog on a given day in a month is extra heavy.
	bool fogIsHeavy(int currentDay);

	// Returns whether rainy weather is also a thunderstorm.
	bool rainIsThunderstorm(Random &random);

	// Whether an individual snowflake should randomly switch between left/right at this point in time
	// (not sure how frequently this is checked).
	bool shouldSnowflakeChangeDirection(Random &random);

	// Returns a filtered version of the given weather so that, i.e., deserts can't have snow.
	ArenaTypes::WeatherType getFilteredWeatherType(ArenaTypes::WeatherType weatherType,
		ArenaTypes::ClimateType climateType);

	// Gets the fog distance associated with the given weather type.
	double getFogDistanceFromWeather(ArenaTypes::WeatherType weatherType);

	// Creates a sky color buffer from the given weather. This covers the entire day and night.
	Buffer<Color> makeSkyColors(ArenaTypes::WeatherType weatherType, TextureManager &textureManager);

	// Creates a color buffer for thunderstorm flashes in the sky.
	Buffer<uint8_t> makeThunderstormColors(const ExeData &exeData);

	// Creates a buffer of texture asset references for lightning bolts.
	Buffer<Buffer<TextureAssetReference>> makeLightningBoltTextureAssetRefs(TextureManager &textureManager);
}

#endif