text:
package alluxio.master.journal.ufs;

import alluxio.AlluxioURI;
import alluxio.Configuration;
import alluxio.Constants;
import alluxio.LocalAlluxioClusterResource;
import alluxio.PropertyKey;
import alluxio.BaseIntegrationTest;
import alluxio.client.WriteType;
import alluxio.client.file.FileOutStream;
import alluxio.client.file.FileSystem;
import alluxio.client.file.URIStatus;
import alluxio.client.file.options.CreateDirectoryOptions;
import alluxio.client.file.options.CreateFileOptions;
import alluxio.client.file.options.DeleteOptions;
import alluxio.client.file.options.SetAttributeOptions;
import alluxio.master.LocalAlluxioCluster;
import alluxio.master.MasterRegistry;
import alluxio.master.MasterTestUtils;
import alluxio.master.file.FileSystemMaster;
import alluxio.master.file.options.GetStatusOptions;
import alluxio.master.file.options.ListStatusOptions;
import alluxio.master.journal.JournalWriter;
import alluxio.master.journal.options.JournalWriterOptions;
import alluxio.security.authentication.AuthenticatedClientUser;
import alluxio.security.authorization.Mode;
import alluxio.security.group.GroupMappingService;
import alluxio.underfs.UfsStatus;
import alluxio.underfs.UnderFileSystem;
import alluxio.util.CommonUtils;
import alluxio.util.IdUtils;
import alluxio.util.WaitForOptions;
import alluxio.util.io.PathUtils;
import alluxio.wire.FileInfo;
import alluxio.wire.LoadMetadataType;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Test master journal, including checkpoint and entry log.
 */
public class UfsJournalIntegrationTest extends BaseIntegrationTest {
  @Rule
  public LocalAlluxioClusterResource mLocalAlluxioClusterResource =
      new LocalAlluxioClusterResource.Builder()
          .setProperty(PropertyKey.MASTER_JOURNAL_LOG_SIZE_BYTES_MAX,
              Integer.toString(Constants.KB))
          .setProperty(PropertyKey.MASTER_JOURNAL_CHECKPOINT_PERIOD_ENTRIES, "2")
          .setProperty(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_ENABLED, "false").build();

  @Rule
  public TemporaryFolder mTestFolder = new TemporaryFolder();

  private LocalAlluxioCluster mLocalAlluxioCluster;
  private FileSystem mFileSystem;
  private AlluxioURI mRootUri = new AlluxioURI(AlluxioURI.SEPARATOR);

  @Before
  public final void before() throws Exception {
    mLocalAlluxioCluster = mLocalAlluxioClusterResource.get();
    mFileSystem = mLocalAlluxioCluster.getClient();
  }

  /**
   * Tests adding a block.
   */
  @Test
  public void addBlock() throws Exception {
    AlluxioURI uri = new AlluxioURI("/xyz");
    CreateFileOptions options = CreateFileOptions.defaults().setBlockSizeBytes(64);
    FileOutStream os = mFileSystem.createFile(uri, options);
    for (int k = 0; k < 1000; k++) {
      os.write(k);
    }
    os.close();
    URIStatus status = mFileSystem.getStatus(uri);
    mLocalAlluxioCluster.stopFS();
    addBlockTestUtil(status);
  }

  private void addBlockTestUtil(URIStatus status) throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);

    long rootId = fsMaster.getFileId(mRootUri);
    Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(1, fsMaster.listStatus(mRootUri,
        ListStatusOptions.defaults().setLoadMetadataType(LoadMetadataType.Never)).size());
    long xyzId = fsMaster.getFileId(new AlluxioURI("/xyz"));
    Assert.assertTrue(xyzId != IdUtils.INVALID_FILE_ID);
    FileInfo fsMasterInfo = fsMaster.getFileInfo(xyzId);
    Assert.assertEquals(0, fsMaster.getFileInfo(xyzId).getInMemoryPercentage());
    Assert.assertEquals(status.getBlockIds(), fsMasterInfo.getBlockIds());
    Assert.assertEquals(status.getBlockSizeBytes(), fsMasterInfo.getBlockSizeBytes());
    Assert.assertEquals(status.getLength(), fsMasterInfo.getLength());
    registry.stop();
  }

  /**
   * Tests flushing the journal multiple times, without writing any data.
   */
  @Test
  @LocalAlluxioClusterResource.Config(
      confParams = {PropertyKey.Name.MASTER_JOURNAL_LOG_SIZE_BYTES_MAX, "0"})
  public void multipleFlush() throws Exception {
    String journalFolder = mLocalAlluxioCluster.getLocalAlluxioMaster().getJournalFolder();
    mLocalAlluxioCluster.stop();
    UfsJournal journal = new UfsJournal(
        new URI(PathUtils.concatPath(journalFolder, Constants.FILE_SYSTEM_MASTER_NAME)));

    UfsStatus[] paths = UnderFileSystem.Factory.create(journalFolder)
        .listStatus(journal.getLogDir().toString());
    int expectedSize = paths == null ? 0 : paths.length;

    try (JournalWriter writer =
        journal.getWriter(JournalWriterOptions.defaults().setPrimary(true))) {
      // Flush multiple times, without writing to the log.
      writer.flush();
      writer.flush();
      writer.flush();
    }
    paths = UnderFileSystem.Factory.create(journalFolder)
        .listStatus(journal.getLogDir().toString());
    int actualSize = paths == null ? 0 : paths.length;
    // No new files are created.
    Assert.assertEquals(expectedSize, actualSize);
  }

  /**
   * Tests loading metadata.
   */
  @Test
  public void loadMetadata() throws Exception {
    String ufsRoot = Configuration.get(PropertyKey.MASTER_MOUNT_TABLE_ROOT_UFS);
    UnderFileSystem ufs = UnderFileSystem.Factory.createForRoot();
    ufs.create(ufsRoot + "/xyz").close();
    mFileSystem.loadMetadata(new AlluxioURI("/xyz"));
    URIStatus status = mFileSystem.getStatus(new AlluxioURI("/xyz"));
    mLocalAlluxioCluster.stopFS();
    loadMetadataTestUtil(status);
    deleteFsMasterJournalLogs();
    loadMetadataTestUtil(status);
  }

  private void loadMetadataTestUtil(URIStatus status) throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);

    long rootId = fsMaster.getFileId(mRootUri);
    Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(1, fsMaster.listStatus(mRootUri,
        ListStatusOptions.defaults().setLoadMetadataType(LoadMetadataType.Never)).size());
    Assert.assertTrue(fsMaster.getFileId(new AlluxioURI("/xyz")) != IdUtils.INVALID_FILE_ID);
    FileInfo fsMasterInfo = fsMaster.getFileInfo(fsMaster.getFileId(new AlluxioURI("/xyz")));
    Assert.assertEquals(status, new URIStatus(fsMasterInfo.setMountId(status.getMountId())));
    registry.stop();
  }

  /**
   * Tests completed edit log deletion.
   */
  @Test
  public void completedEditLogDeletion() throws Exception {
    for (int i = 0; i < 124; i++) {
      mFileSystem.createFile(new AlluxioURI("/a" + i),
          CreateFileOptions.defaults().setBlockSizeBytes((i + 10) / 10 * 64)).close();
    }
    mLocalAlluxioCluster.stopFS();

    String journalFolder = PathUtils
        .concatPath(mLocalAlluxioCluster.getLocalAlluxioMaster().getJournalFolder(),
            Constants.FILE_SYSTEM_MASTER_NAME);
    UfsJournal journal = new UfsJournal(new URI(journalFolder));
    URI completedLocation = journal.getLogDir();
    Assert.assertTrue(UnderFileSystem.Factory.create(completedLocation)
        .listStatus(completedLocation.toString()).length > 1);
    multiEditLogTestUtil();
    Assert.assertTrue(UnderFileSystem.Factory.create(completedLocation)
        .listStatus(completedLocation.toString()).length > 1);
    multiEditLogTestUtil();
  }

  /**
   * Tests file and directory creation and deletion.
   */
  @Test
  public void delete() throws Exception {
    CreateDirectoryOptions recMkdir = CreateDirectoryOptions.defaults().setRecursive(true);
    DeleteOptions recDelete = DeleteOptions.defaults().setRecursive(true);
    for (int i = 0; i < 10; i++) {
      String dirPath = "/i" + i;
      mFileSystem.createDirectory(new AlluxioURI(dirPath), recMkdir);
      for (int j = 0; j < 10; j++) {
        CreateFileOptions option = CreateFileOptions.defaults().setBlockSizeBytes((i + j + 1) * 64);
        String filePath = dirPath + "/j" + j;
        mFileSystem.createFile(new AlluxioURI(filePath), option).close();
        if (j >= 5) {
          mFileSystem.delete(new AlluxioURI(filePath), recDelete);
        }
      }
      if (i >= 5) {
        mFileSystem.delete(new AlluxioURI(dirPath), recDelete);
      }
    }
    mLocalAlluxioCluster.stopFS();
    deleteTestUtil();
    deleteFsMasterJournalLogs();
    deleteTestUtil();
  }

  private void deleteTestUtil() throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);
    long rootId = fsMaster.getFileId(mRootUri);
    Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(5, fsMaster.listStatus(mRootUri,
        ListStatusOptions.defaults().setLoadMetadataType(LoadMetadataType.Never)).size());
    for (int i = 0; i < 5; i++) {
      for (int j = 0; j < 5; j++) {
        Assert.assertTrue(
            fsMaster.getFileId(new AlluxioURI("/i" + i + "/j" + j)) != IdUtils.INVALID_FILE_ID);
      }
    }
    registry.stop();
  }

  @Test
  public void emptyImage() throws Exception {
    Assert.assertEquals(0, mFileSystem.listStatus(mRootUri).size());
    mLocalAlluxioCluster.stopFS();
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);
    long rootId = fsMaster.getFileId(mRootUri);
    Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(0, fsMaster.listStatus(mRootUri,
        ListStatusOptions.defaults().setLoadMetadataType(LoadMetadataType.Never)).size());
    registry.stop();
  }

  /**
   * Tests file and directory creation.
   */
  @Test
  public void fileDirectory() throws Exception {
    for (int i = 0; i < 10; i++) {
      mFileSystem.createDirectory(new AlluxioURI("/i" + i));
      for (int j = 0; j < 10; j++) {
        CreateFileOptions option = CreateFileOptions.defaults().setBlockSizeBytes((i + j + 1) * 64);
        mFileSystem.createFile(new AlluxioURI("/i" + i + "/j" + j), option).close();
      }
    }
    mLocalAlluxioCluster.stopFS();
    fileDirectoryTestUtil();
    deleteFsMasterJournalLogs();
    fileDirectoryTestUtil();
  }

  private void fileDirectoryTestUtil() throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);
    long rootId = fsMaster.getFileId(mRootUri);
    Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(10, fsMaster.listStatus(mRootUri,
        ListStatusOptions.defaults().setLoadMetadataType(LoadMetadataType.Never)).size());
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {
        Assert.assertTrue(
            fsMaster.getFileId(new AlluxioURI("/i" + i + "/j" + j)) != IdUtils.INVALID_FILE_ID);
      }
    }
    registry.stop();
  }

  /**
   * Tests file creation.
   */
  @Test
  public void file() throws Exception {
    CreateFileOptions option = CreateFileOptions.defaults().setBlockSizeBytes(64);
    AlluxioURI filePath = new AlluxioURI("/xyz");
    mFileSystem.createFile(filePath, option).close();
    URIStatus status = mFileSystem.getStatus(filePath);
    mLocalAlluxioCluster.stopFS();
    fileTestUtil(status);
    deleteFsMasterJournalLogs();
    fileTestUtil(status);
  }

  private void fileTestUtil(URIStatus status) throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);
    long rootId = fsMaster.getFileId(mRootUri);
    Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(1, fsMaster.listStatus(mRootUri,
        ListStatusOptions.defaults().setLoadMetadataType(LoadMetadataType.Never)).size());
    long fileId = fsMaster.getFileId(new AlluxioURI("/xyz"));
    Assert.assertTrue(fileId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(
        status, new URIStatus(fsMaster.getFileInfo(fileId).setMountId(status.getMountId())));
    registry.stop();
  }

  /**
   * Tests journalling of inodes being pinned.
   */
  @Test
  public void pin() throws Exception {
    SetAttributeOptions setPinned = SetAttributeOptions.defaults().setPinned(true);
    SetAttributeOptions setUnpinned = SetAttributeOptions.defaults().setPinned(false);
    AlluxioURI dirUri = new AlluxioURI("/myFolder");
    mFileSystem.createDirectory(dirUri);
    mFileSystem.setAttribute(dirUri, setPinned);

    AlluxioURI file0Path = new AlluxioURI("/myFolder/file0");
    CreateFileOptions op = CreateFileOptions.defaults().setBlockSizeBytes(64);
    mFileSystem.createFile(file0Path, op).close();
    mFileSystem.setAttribute(file0Path, setUnpinned);

    AlluxioURI file1Path = new AlluxioURI("/myFolder/file1");
    mFileSystem.createFile(file1Path, op).close();

    URIStatus directoryStatus = mFileSystem.getStatus(dirUri);
    URIStatus file0Status = mFileSystem.getStatus(file0Path);
    URIStatus file1Status = mFileSystem.getStatus(file1Path);

    mLocalAlluxioCluster.stopFS();

    pinTestUtil(directoryStatus, file0Status, file1Status);
    deleteFsMasterJournalLogs();
    pinTestUtil(directoryStatus, file0Status, file1Status);
  }

  private void pinTestUtil(URIStatus directory, URIStatus file0, URIStatus file1) throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);

    FileInfo info = fsMaster.getFileInfo(fsMaster.getFileId(new AlluxioURI("/myFolder")));
    Assert.assertEquals(directory, new URIStatus(info.setMountId(directory.getMountId())));
    Assert.assertTrue(info.isPinned());

    info = fsMaster.getFileInfo(fsMaster.getFileId(new AlluxioURI("/myFolder/file0")));
    Assert.assertEquals(file0, new URIStatus(info.setMountId(file0.getMountId())));
    Assert.assertFalse(info.isPinned());

    info = fsMaster.getFileInfo(fsMaster.getFileId(new AlluxioURI("/myFolder/file1")));
    Assert.assertEquals(file1, new URIStatus(info.setMountId(file1.getMountId())));
    Assert.assertTrue(info.isPinned());

    registry.stop();
  }

  /**
   * Tests directory creation.
   */
  @Test
  public void directory() throws Exception {
    AlluxioURI directoryPath = new AlluxioURI("/xyz");
    mFileSystem.createDirectory(directoryPath);
    URIStatus status = mFileSystem.getStatus(directoryPath);
    mLocalAlluxioCluster.stopFS();
    directoryTestUtil(status);
    deleteFsMasterJournalLogs();
    directoryTestUtil(status);
  }

  private void directoryTestUtil(URIStatus status) throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);
    long rootId = fsMaster.getFileId(mRootUri);
    Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(1, fsMaster.listStatus(mRootUri,
        ListStatusOptions.defaults().setLoadMetadataType(LoadMetadataType.Never)).size());
    long fileId = fsMaster.getFileId(new AlluxioURI("/xyz"));
    Assert.assertTrue(fileId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(
        status, new URIStatus(fsMaster.getFileInfo(fileId).setMountId(status.getMountId())));
    registry.stop();
  }

  @Test
  public void persistDirectoryLater() throws Exception {
    String[] directories = new String[] {
        "/d11", "/d11/d21", "/d11/d22",
        "/d12", "/d12/d21", "/d12/d22",
    };

    CreateDirectoryOptions options =
        CreateDirectoryOptions.defaults().setRecursive(true).setWriteType(WriteType.MUST_CACHE);
    for (String directory : directories) {
      mFileSystem.createDirectory(new AlluxioURI(directory), options);
    }

    options.setWriteType(WriteType.CACHE_THROUGH).setAllowExists(true);
    for (String directory : directories) {
      mFileSystem.createDirectory(new AlluxioURI(directory), options);
    }

    Map<String, URIStatus> directoryStatuses = new HashMap<>();
    for (String directory : directories) {
      directoryStatuses.put(directory, mFileSystem.getStatus(new AlluxioURI(directory)));
    }
    mLocalAlluxioCluster.stopFS();
    persistDirectoryLaterTestUtil(directoryStatuses);
    deleteFsMasterJournalLogs();
    persistDirectoryLaterTestUtil(directoryStatuses);
  }

  private void persistDirectoryLaterTestUtil(Map<String, URIStatus> directoryStatuses)
      throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);
    for (Map.Entry<String, URIStatus> directoryStatus : directoryStatuses.entrySet()) {
      Assert.assertEquals(
          directoryStatus.getValue(),
          new URIStatus(fsMaster.getFileInfo(fsMaster.getFileId(new AlluxioURI(directoryStatus
              .getKey()))).setMountId(directoryStatus.getValue().getMountId())));
    }
    registry.stop();
  }

  /**
   * Tests files creation.
   */
  @Test
  public void manyFile() throws Exception {
    for (int i = 0; i < 10; i++) {
      CreateFileOptions option = CreateFileOptions.defaults().setBlockSizeBytes((i + 1) * 64);
      mFileSystem.createFile(new AlluxioURI("/a" + i), option).close();
    }
    mLocalAlluxioCluster.stopFS();
    manyFileTestUtil();
    deleteFsMasterJournalLogs();
    manyFileTestUtil();
  }

  private void manyFileTestUtil() throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);
    long rootId = fsMaster.getFileId(mRootUri);
    Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(10, fsMaster.listStatus(mRootUri,
        ListStatusOptions.defaults().setLoadMetadataType(LoadMetadataType.Never)).size());
    for (int k = 0; k < 10; k++) {
      Assert.assertTrue(fsMaster.getFileId(new AlluxioURI("/a" + k)) != IdUtils.INVALID_FILE_ID);
    }
    registry.stop();
  }

  /**
   * Tests the situation where a checkpoint mount entry is replayed by a standby master.
   */
  @Test
  public void mountEntryCheckpoint() throws Exception {
    final AlluxioURI mountUri = new AlluxioURI("/local_mnt/");
    final AlluxioURI ufsUri = new AlluxioURI(mTestFolder.newFolder("test_ufs").getAbsolutePath());

    // Create a mount point, which will journal a mount entry.
    mFileSystem.mount(mountUri, ufsUri);
    mLocalAlluxioCluster.stopFS();

    // Start a leader master with a mount entry.
    MasterTestUtils.createLeaderFileSystemMasterFromJournal().stop();

    // Start a standby master, which will replay the mount entry from the journal.
    MasterRegistry registry = MasterTestUtils.createStandbyFileSystemMasterFromJournal();
    final FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);
    try {
      CommonUtils.waitFor("standby journal checkpoint replay", new Function<Void, Boolean>() {
        @Override
        public Boolean apply(Void input) {
          try {
            fsMaster.listStatus(mountUri, ListStatusOptions.defaults());
            return true;
          } catch (Exception e) {
            return false;
          }
        }
      }, WaitForOptions.defaults().setTimeoutMs(60 * Constants.SECOND_MS));
    } finally {
      registry.stop();
    }
  }

  /**
   * Tests reading multiple edit logs.
   */
  @Test
  public void multiEditLog() throws Exception {
    for (int i = 0; i < 124; i++) {
      CreateFileOptions op = CreateFileOptions.defaults().setBlockSizeBytes((i + 10) / 10 * 64);
      mFileSystem.createFile(new AlluxioURI("/a" + i), op).close();
    }
    mLocalAlluxioCluster.stopFS();
    multiEditLogTestUtil();
    deleteFsMasterJournalLogs();
    multiEditLogTestUtil();
  }

  private void multiEditLogTestUtil() throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);
    long rootId = fsMaster.getFileId(mRootUri);
    Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(124, fsMaster.listStatus(mRootUri,
        ListStatusOptions.defaults().setLoadMetadataType(LoadMetadataType.Never)).size());
    for (int k = 0; k < 124; k++) {
      Assert.assertTrue(fsMaster.getFileId(new AlluxioURI("/a" + k)) != IdUtils.INVALID_FILE_ID);
    }
    registry.stop();
  }

  /**
   * Tests file and directory creation, and rename.
   */
  @Test
  public void rename() throws Exception {
    for (int i = 0; i < 10; i++) {
      mFileSystem.createDirectory(new AlluxioURI("/i" + i));
      for (int j = 0; j < 10; j++) {
        CreateFileOptions option = CreateFileOptions.defaults().setBlockSizeBytes((i + j + 1) * 64);
        AlluxioURI path = new AlluxioURI("/i" + i + "/j" + j);
        mFileSystem.createFile(path, option).close();
        mFileSystem.rename(path, new AlluxioURI("/i" + i + "/jj" + j));
      }
      mFileSystem.rename(new AlluxioURI("/i" + i), new AlluxioURI("/ii" + i));
    }
    mLocalAlluxioCluster.stopFS();
    renameTestUtil();
    deleteFsMasterJournalLogs();
    renameTestUtil();
  }

  private void renameTestUtil() throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);
    long rootId = fsMaster.getFileId(mRootUri);
    Assert.assertTrue(rootId != IdUtils.INVALID_FILE_ID);
    Assert.assertEquals(10, fsMaster.listStatus(mRootUri,
        ListStatusOptions.defaults().setLoadMetadataType(LoadMetadataType.Never)).size());
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {
        Assert.assertTrue(
            fsMaster.getFileId(new AlluxioURI("/ii" + i + "/jj" + j)) != IdUtils.INVALID_FILE_ID);
      }
    }
    registry.stop();
  }

  @Test
  @LocalAlluxioClusterResource.Config(confParams = {
      PropertyKey.Name.SECURITY_AUTHENTICATION_TYPE, "SIMPLE",
      PropertyKey.Name.SECURITY_AUTHORIZATION_PERMISSION_ENABLED, "true",
      PropertyKey.Name.SECURITY_GROUP_MAPPING_CLASS, FakeUserGroupsMapping.FULL_CLASS_NAME})
  public void setAcl() throws Exception {
    AlluxioURI filePath = new AlluxioURI("/file");

    String user = "alluxio";
    Configuration.set(PropertyKey.SECURITY_LOGIN_USERNAME, user);
    CreateFileOptions op = CreateFileOptions.defaults().setBlockSizeBytes(64);
    mFileSystem.createFile(filePath, op).close();

    // TODO(chaomin): also setOwner and setGroup once there's a way to fake the owner/group in UFS.
    mFileSystem.setAttribute(filePath,
        SetAttributeOptions.defaults().setMode(new Mode((short) 0400)).setRecursive(false));

    URIStatus status = mFileSystem.getStatus(filePath);

    mLocalAlluxioCluster.stopFS();

    aclTestUtil(status, user);
    deleteFsMasterJournalLogs();
    aclTestUtil(status, user);
  }

  private void aclTestUtil(URIStatus status, String user) throws Exception {
    MasterRegistry registry = createFsMasterFromJournal();
    FileSystemMaster fsMaster = registry.get(FileSystemMaster.class);
    AuthenticatedClientUser.set(user);
    FileInfo info = fsMaster.getFileInfo(new AlluxioURI("/file"), GetStatusOptions.defaults());
    Assert.assertEquals(status, new URIStatus(info.setMountId(status.getMountId())));
    registry.stop();
  }

  private MasterRegistry createFsMasterFromJournal() throws Exception {
    return MasterTestUtils.createLeaderFileSystemMasterFromJournal();
  }

  private void deleteFsMasterJournalLogs() throws Exception {
    String journalFolder = mLocalAlluxioCluster.getLocalAlluxioMaster().getJournalFolder();
    UfsJournal journal = new UfsJournal(
        new URI(PathUtils.concatPath(journalFolder, Constants.FILE_SYSTEM_MASTER_NAME)));
    if (UfsJournalSnapshot.getCurrentLog(journal) != null) {
      UnderFileSystem.Factory.create(journalFolder)
          .deleteFile(UfsJournalSnapshot.getCurrentLog(journal).getLocation().toString());
    }
  }

  /**
   * Test class implements {@link GroupMappingService} providing user-to-groups mapping.
   */
  public static class FakeUserGroupsMapping implements GroupMappingService {
    // The fullly qualified class name of this group mapping service. This is needed to configure
    // the alluxio cluster
    public static final String FULL_CLASS_NAME =
        "alluxio.master.journal.ufs.UfsJournalIntegrationTest$FakeUserGroupsMapping";

    private HashMap<String, String> mUserGroups = new HashMap<>();

    /**
     * Constructor of {@link FakeUserGroupsMapping} to put the user and groups in user-to-groups
     * HashMap.
     */
    public FakeUserGroupsMapping() {
      mUserGroups.put("alluxio", "supergroup");
      mUserGroups.put("user1", "group1");
      mUserGroups.put("others", "anygroup");
    }

    @Override
    public List<String> getGroups(String user) throws IOException {
      if (mUserGroups.containsKey(user)) {
        return Lists.newArrayList(mUserGroups.get(user).split(","));
      }
      return Lists.newArrayList(mUserGroups.get("others").split(","));
    }
  }
}


text:
/*
 * ------------------------------------------
 * 项目Regualar模块基类实现文件
 * @author   sensen(hzzhaoyusen@corp.netease.com)
 * ------------------------------------------
 */
/** @module util/dispatcher/regularModule */
NEJ.define([
    'base/klass',
    'base/event',
    'util/template/tpl',
    'util/dispatcher/module'
],function(_k,_v,_t,_m,_p){
    var _pro;
    /**
     * Regular模块基类对象
     *
     * @class   {_$$RegularModule}
     * @extends {_$$ModuleAbstract}
     */
    _p._$$RegularModule = _k._$klass();
    _pro = _p._$$RegularModule._$extend(_m._$$ModuleAbstract);
    /**
     * 构建Regular组件
     *
     * @protected
     * @method module:util/dispatcher/regularModule._$$RegularModule#__build
     * @return {Void}
     */
    _pro.__build = function(){
        this._$innerModule = new this._$$InnerModule().$inject(this.__body);
        this.__export.parent = this._$innerModule.$refs.view;

        this._$innerModule.__doSendMessage = this.__doSendMessage._$bind(this);
    }
    /**
     * 控件初始化
     *
     * @protected
     * @method module:util/dispatcher/regularModule._$$RegularModule#__init
     * @return {Void}
     */
    _pro.__init = function(_options){
        this.__super(_options);
        this.__nodeKey = _t._$addNodeTemplate('

');
        this.__body = _t._$getNodeTemplate(this.__nodeKey);

        this.__build();
    }
    /**
     * 显示模块触发事件,子类可重写具体逻辑
     *
     * @protected
     * @method module:util/dispatcher/regularModule._$$RegularModule#__onShow
     * @param  {Object} arg0 - 事件对象
     * @return {Void}
     */
    _pro.__onShow = function(_options){
        // 如果Regular组件被destroy了,就重新构建
        if(this._$innerModule._watchers === null)
            this.__build();

        this.__super(_options);
        if(this._$innerModule.__onShow){
            this._$innerModule.data.$param = _options.param;
            this._$innerModule.data.$params = _options.href.split('?')[1];
            this._$innerModule.__onShow(_options);
            this._$innerModule.$update();
        }
    }
    /**
     * 显示模块触发事件,子类实现具体逻辑
     *
     * @protected
     * @method module:util/dispatcher/regularModule._$$RegularModule#__onRefresh
     * @param  {Object} arg0 - 事件对象
     * @return {Void}
     */
    _pro.__onRefresh = function(_options){
        this.__super(_options);
        if(this._$innerModule.__onRefresh){
            this._$innerModule.data.$param = _options.param;
            this._$innerModule.data.$params = _options.href.split('?')[1];
            this._$innerModule.__onRefresh(_options);
            this._$innerModule.$update();
        }
    }
    /**
     * 接受到消息触发事件,子类实现具体逻辑
     *
     * @abstract
     * @method module:util/dispatcher/regularModule._$$RegularModule#__onMessage
     * @param  {Object} arg0 - 事件对象
     * @return {Void}
     */
    _pro.__onMessage = function(_options){
        this.__super(_options);
        if(this._$innerModule.__onMessage){
            this._$innerModule.__onMessage(_options);
            this._$innerModule.$update();
        }
    }
    /**
     * 模块退出前触发事件,通过阻止输入的事件做退出验证,子类实现具体逻辑
     *
     * @abstract
     * @method module:util/dispatcher/regularModule._$$RegularModule#__onBeforeHide
     * @param  {Object} arg0 - 事件对象
     * @return {Void}
     */
    _pro.__onBeforeHide = function(_options){
        this.__super(_options);
        if(this._$innerModule.__onBeforeHide){
            this._$innerModule.__onBeforeHide(_options);
            this._$innerModule.$update();
        }
    }
    /**
     * 隐藏模块触发事件,子类实现具体逻辑
     *
     * @protected
     * @method module:util/dispatcher/regularModule._$$RegularModule#__onHide
     * @return {Void}
     */
    _pro.__onHide = function(){
        this.__super();
        if(this._$innerModule.__onHide){
            this._$innerModule.__onHide();
            this._$innerModule.$update();
        }
    }
    /**
     * 控件销毁
     *
     * @protected
     * @method module:util/dispatcher/regularModule._$$RegularModule#__destroy
     * @return {Void}
     */
    _pro.__destroy = function(){
        this.__body = _t._$getNodeTemplate(this.__nodeKey);
        this._$innerModule.destroy();
        delete this.__nodeKey;
        this.__super();
    };

    /**
     * 注册RegularModule
     *
     * @public
     * @method module:util/dispatcher/regularModule._$build
     * @param  {String}  arg0 - 模块UMI或者别名
     * @param  {Regular} arg1 - Regular组件模块
     * @return {_$$RegularModule} RegularModule模块
     */
    _p._$regist = function(_umiAlias, _$$InnerModule){
        /**
         * Regular模块对象
         *
         * @class   {_$$OuterModule}
         * @extends {_$$RegularModule}
         */
        var _$$OuterModule = _k._$klass();
        var _pro = _$$OuterModule._$extend(_p._$$RegularModule);

        _pro.__init = function(){
            this.__umiAlias = _umiAlias;
            this._$$InnerModule = _$$InnerModule;
            this.__super();
        }

        _v._$addEvent(document, 'templateready', function(){
            _m._$regist(_umiAlias, _$$OuterModule);
        });

        return _$$OuterModule;
    }

    return _p;
});

redpajama_set_name: RedPajamaGithub


text:
package edu.clemson.resolve.semantics.query;

import org.jetbrains.annotations.NotNull;
import edu.clemson.resolve.semantics.MathSymbolTable.FacilityStrategy;
import edu.clemson.resolve.semantics.MathSymbolTable.ImportStrategy;
import edu.clemson.resolve.semantics.UnqualifiedPath;
import edu.clemson.resolve.semantics.searchers.NameSearcher;
import edu.clemson.resolve.semantics.symbol.Symbol;

public class UnqualifiedNameQuery extends BaseMultimatchSymbolQuery<Symbol> {

    public UnqualifiedNameQuery(@NotNull String searchString,
                                @NotNull ImportStrategy importStrategy,
                                @NotNull FacilityStrategy facilityStrategy,
                                boolean stopAfterFirst,
                                boolean localPriority) {
        super(new UnqualifiedPath(importStrategy, facilityStrategy, localPriority),
                new NameSearcher(searchString, stopAfterFirst));
    }

    public UnqualifiedNameQuery(@NotNull String searchString) {
        this(searchString, ImportStrategy.IMPORT_NAMED, FacilityStrategy.FACILITY_IGNORE, true, true);
    }
}


text:
import os
import codecs
from setuptools import setup

here = os.path.abspath(os.path.dirname(__file__))

def read_file(names, encoding="utf-8"):
    file_path = os.path.join(here, *names)
    if encoding:
        with codecs.open(file_path, encoding=encoding) as f:
            return f.read()
    else:
        with open(file_path, "rb") as f:
            return f.read()

def exec_file(names):
    code = read_file(names, encoding=None)
    result = {}
    exec(code, result)
    return result

setup(
    name="pushbaby",
    version=exec_file(("pushbaby", "version.py",))["__version__"],
    packages=['pushbaby'],
    license="Apache License, Version 2.0",
    description="APNS library using gevent",
    url="https://github.com/matrix-org/pushbaby",
    author="matrix.org",
    author_email="dave@matrix.org",
    long_description=read_file(("README.rst",)),
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: Python :: 2",
    ],
    keywords="apns push",
    install_requires=[
        "gevent>=1.0.1",
    ],
)


text:
package io.github.microcks.util.el;

/**
 * Represent an exception that occurs during expression parsing.
 * @author laurent
 */
public class ParseException extends RuntimeException {

   protected String expressionString = null;

   protected int position = 0;

   /**
    * Create a new default expression parsing exception.
    * @param message description of the problem that occurred
    */
   public ParseException(String message) {
      super(message);
   }

   /**
    * Create a new expression parsing exception.
    * @param expressionString the expression string that could not be parsed
    * @param position the position in the expression string where the problem occurred
    * @param message description of the problem that occurred
    */
   public ParseException(String expressionString, int position, String message) {
      super(message);
      this.expressionString = expressionString;
      this.position = position;
   }
}


text:
""" Specify the TreeNode object with its action, context-menus """
# Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and
# University Hospital Center and University of Lausanne (UNIL-CHUV)
#
# Modified BSD License

# Standard library imports
import os

# Enthought library imports
from traits.api import Instance, Str, Any
from traitsui.api import TreeNode
from traitsui.menu import Menu, Action, Separator

# ConnectomeViewer imports
from cviewer.plugins.cff2.cscript import CScript

# Logging import
import logging
logger = logging.getLogger('root.'+__name__)

class CScriptTreeNode(TreeNode):

    # The object that contains the container ;^)
    parent = Any

    # the network associated with this node
    node_for=[CScript]

    # a default icons
    # Name of group item icon
    icon_group = Str('script.png')
    # Name of leaf item icon
    icon_item=Str('script.png')
    # Name of opened group item icon
    icon_open=Str('script.png')

    # labels
    label='dname'

    ###
    # Private Traits

    # activate / deactivate logic
    # if the node is activated, this means that there exists a
    # corresponding RenderManager instance

    _OpenFile = Instance(Action,
                               kw={'name': 'Open File in Editor',
                                   'action': 'object.open_file',
                                   'tooltip': 'Open the file in editor'}, )

    # the menu shown after right-click
    menu = Instance(Menu, transient=True)

    def get_children(self, object):
        """ Get the object's children. """
        pass

    ######################################################################
    # Non-public interface
    ######################################################################

    def _menu_default(self):
        """ Standard menus for network nodes """

        menu_actions = [Separator(), \
                        self._OpenFile]

        return Menu( *menu_actions)


text:
#include "proxygen/lib/http/codec/CodecProtocol.h"

#include <glog/logging.h>

namespace proxygen {

namespace {
static const std::string http_1_1 = "http/1.1";
static const std::string spdy_2 = "spdy/2";
static const std::string spdy_3 = "spdy/3";
static const std::string spdy_3_1 = "spdy/3.1";
static const std::string spdy_3_1_hpack = "spdy/3.1-hpack";
static const std::string http_2 = "http/2";
static const std::string empty = "";
}

extern const std::string& getCodecProtocolString(CodecProtocol proto) {
  switch (proto) {
    case CodecProtocol::HTTP_1_1: return http_1_1;
    case CodecProtocol::SPDY_2: return spdy_2;
    case CodecProtocol::SPDY_3: return spdy_3;
    case CodecProtocol::SPDY_3_1: return spdy_3_1;
    case CodecProtocol::SPDY_3_1_HPACK: return spdy_3_1_hpack;
    case CodecProtocol::HTTP_2: return http_2;
  }
  LOG(FATAL) << "Unreachable";
  return empty;
}

extern bool isValidCodecProtocolStr(const std::string& protocolStr) {
  return protocolStr == http_1_1 ||
         protocolStr == spdy_2 ||
         protocolStr == spdy_3 ||
         protocolStr == spdy_3_1 ||
         protocolStr == spdy_3_1_hpack ||
         protocolStr == http_2;
}

extern CodecProtocol getCodecProtocolFromStr(const std::string& protocolStr) {
  if (protocolStr == http_1_1) {
    return CodecProtocol::HTTP_1_1;
  } else if (protocolStr == spdy_2) {
    return CodecProtocol::SPDY_2;
  } else if (protocolStr == spdy_3) {
    return CodecProtocol::SPDY_3;
  } else if (protocolStr == spdy_3_1) {
    return CodecProtocol::SPDY_3_1;
  } else if (protocolStr == spdy_3_1_hpack) {
    return CodecProtocol::SPDY_3_1_HPACK;
  } else if (protocolStr == http_2) {
    return CodecProtocol::HTTP_2;
  } else {
    // return default protocol
    return CodecProtocol::HTTP_1_1;
  }
}

extern bool isSpdyCodecProtocol(CodecProtocol protocol) {
  return protocol == CodecProtocol::SPDY_2 ||
         protocol == CodecProtocol::SPDY_3 ||
         protocol == CodecProtocol::SPDY_3_1 ||
         protocol == CodecProtocol::SPDY_3_1_HPACK;
}

extern uint8_t maxProtocolPriority(CodecProtocol protocol) {
  // Priorities per protocol
  switch (protocol) {
    case CodecProtocol::SPDY_2:
      // SPDY 2 Max Priority
      return 3;
    case CodecProtocol::SPDY_3:
    case CodecProtocol::SPDY_3_1:
    case CodecProtocol::SPDY_3_1_HPACK:
      // SPDY 3 Max Priority
      return 7;
    case CodecProtocol::HTTP_1_1:
    case CodecProtocol::HTTP_2:
      //HTTP doesn't support priorities
      return 0;
  }
  return 0;
}
}


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var world_service_1 = require("./world.service");
var WorldComponent = (function () {
    function WorldComponent() {
    }
    WorldComponent.prototype.ngOnInit = function () {
    };
    WorldComponent = __decorate([
        core_1.Component({
            selector: 'bsp-world',
            templateUrl: './world.component.html',
            styleUrls: ['./world.component.css'],
            providers: [world_service_1.WorldService]
        })
    ], WorldComponent);
    return WorldComponent;
}());
exports.WorldComponent = WorldComponent;
//# sourceMappingURL=world.component.js.map


text:
package org.zelo.ast;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.zelo.ast.expression.*;
import org.zelo.ast.expression.literal.*;
import org.zelo.ast.function.*;
import org.zelo.ast.expression.essential_functions.*;
import org.zelo.ast.module.*;
import org.zelo.ast.name.Name;
import org.zelo.ast.name.Names;
import org.zelo.ast.name.QualifiedName;
import org.zelo.ast.name.QualifiedNameList;
import org.zelo.ast.type.*;
import org.zelo.syntax.concrete.ZeloBaseVisitor;
import org.zelo.syntax.concrete.ZeloLexer;
import org.zelo.syntax.concrete.ZeloParser;
import org.zelo.syntax.concrete.ZeloVisitor;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static org.zelo.ast.util.SourceLocationHydrator.*;
import static org.zelo.ast.util.StringUnquoter.unquoteString;

public class ASTBuilder extends ZeloBaseVisitor<Node> implements ZeloVisitor<Node> {

    public Module buildAST(InputStream inputStream) throws IOException {
        return (Module) visit(createParser(inputStream).module());
    }

    public Module buildAST(String input) throws IOException {
        return (Module) visit(createParser(input).module());
    }

    private ZeloParser createParser(String input) {
        return new ZeloParser(new CommonTokenStream(new ZeloLexer(new ANTLRInputStream(input))));
    }

    private ZeloParser createParser(InputStream inputStream) throws IOException {
        return new ZeloParser(new CommonTokenStream(new ZeloLexer(new ANTLRInputStream(inputStream))));
    }

    @Override
    public Module visitModuleWithExports(ZeloParser.ModuleWithExportsContext ctx) {
        return hydrateSourceLocation(new Module(
            visitQualifiedName(ctx.qualifiedName()),
            visitExports(ctx.exports()),
            visitImports(ctx.use()),
            visitFunctions(ctx.function())
        ), ctx);
    }

    @Override
    public Module visitModuleWithoutExports(ZeloParser.ModuleWithoutExportsContext ctx) {
        return hydrateSourceLocation(new Module(
            visitQualifiedName(ctx.qualifiedName()),
            new Names(new ArrayList<>()),
            visitImports(ctx.use()),
            visitFunctions(ctx.function())
        ), ctx);
    }

    @Override
    public Names visitExports(ZeloParser.ExportsContext ctx) {
        return visitNames(ctx.names());
    }

    private FunctionList visitFunctions(List<ZeloParser.FunctionContext> functionContexts) {
        List<Function> functions = new ArrayList<>();

        functionContexts.forEach(functionContext -> functions.add((Function) visit(functionContext)));

        return new FunctionList(functions);
    }

    private QualifiedNameList visitImports(List<ZeloParser.UseContext> useContexts) {
        List<QualifiedName> imports = new ArrayList<>();

        useContexts.forEach(useContext -> imports.add(visitQualifiedName(useContext.qualifiedName())));

        return new QualifiedNameList(imports);
    }

    private Name visitName(Token name) {
        return hydrateSourceLocation(new Name(name.getText()), name);
    }

    @Override
    public Names visitNames(ZeloParser.NamesContext ctx) {
        List<Name> nameList = new ArrayList<>();

        ctx.nameList.forEach(name -> nameList.add(visitName(name)));

        return hydrateSourceLocation(new Names(nameList), ctx);
    }

    @Override
    public Node visitUse(ZeloParser.UseContext ctx) {
        return null;
    }

    @Override
    public QualifiedName visitQualifiedName(ZeloParser.QualifiedNameContext ctx) {
        return hydrateSourceLocation(new QualifiedName(visitNames(ctx.parts), visitName(ctx.finalName)), ctx);
    }

    private Names visitNames(List<Token> parts) {
        List<Name> names = new ArrayList<>();
        parts.forEach(name -> names.add(visitName(name)));
        return new Names(names);
    }

    private DeclarationList visitDeclarations(List<ZeloParser.DeclarationContext> declarationContexts) {
        List<Declaration> declarations = new ArrayList<>();

        declarationContexts.forEach(declarationContext -> declarations.add(visitDeclaration(declarationContext)));

        return new DeclarationList(declarations);
    }

    @Override
    public Declaration visitDeclaration(ZeloParser.DeclarationContext ctx) {
        return hydrateSourceLocation(
            new Declaration(visitSignature(ctx.signature), (Expression) visit(ctx.expression())), ctx);
    }

    private PatternList visitSignature(ZeloParser.PatternsContext patternsContext) {
        List<Pattern> patterns = new ArrayList<>();

        patternsContext.patternList.forEach(patternContext -> patterns.add((Pattern) visit(patternContext)));

        return hydrateSourceLocation(new PatternList(patterns), patternsContext);
    }

    @Override
    public TypedArgument visitTypedArgumentPattern(ZeloParser.TypedArgumentPatternContext ctx) {
        return hydrateSourceLocation(new TypedArgument((Type) visit(ctx.type()), visitName(ctx.NAME())), ctx);
    }

    private Name visitName(TerminalNode name) {
        return visitName(name.getSymbol());
    }

    @Override
    public LiteralPattern visitLiteralPattern(ZeloParser.LiteralPatternContext ctx) {
        return hydrateSourceLocation(new LiteralPattern((Literal) visit(ctx.literal())), ctx);
    }

    @Override
    public BooleanTrue visitBooleanTrueLiteral(ZeloParser.BooleanTrueLiteralContext ctx) {
        return hydrateSourceLocation(new BooleanTrue(), ctx);
    }

    @Override
    public BooleanFalse visitBooleanFalseLiteral(ZeloParser.BooleanFalseLiteralContext ctx) {
        return hydrateSourceLocation(new BooleanFalse(), ctx);
    }

    @Override
    public IntegerLiteral visitIntegerLiteral(ZeloParser.IntegerLiteralContext ctx) {
        return hydrateSourceLocation(new IntegerLiteral(Integer.parseInt(ctx.getText())), ctx);
    }

    @Override
    public FloatLiteral visitFloatLiteral(ZeloParser.FloatLiteralContext ctx) {
        return hydrateSourceLocation(new FloatLiteral(new BigDecimal(ctx.getText())), ctx);
    }

    @Override
    public StringLiteral visitStringLiteral(ZeloParser.StringLiteralContext ctx) {
        return hydrateSourceLocation(new StringLiteral(unquoteString(ctx.getText())), ctx);
    }

    @Override
    public Call visitCallDefined(ZeloParser.CallDefinedContext ctx) {
        List<Expression> argumentList = new ArrayList<>();

        ctx.args.forEach(arg -> argumentList.add((Expression) visit(arg)));

        ExpressionList arguments = hydrateSourceLocation(new ExpressionList(argumentList), ctx);

        return hydrateSourceLocation(new Call((Expression) visit(ctx.caller), arguments), ctx);
    }

    @Override
    public Composition visitComposition(ZeloParser.CompositionContext ctx) {
        return hydrateSourceLocation(new Composition((Expression) visit(ctx.lhs), (Expression) visit(ctx.rhs)), ctx);
    }

    @Override
    public NativeCall visitCallNative(ZeloParser.CallNativeContext ctx) {
        List<Expression> arguments = new ArrayList<>();

        ctx.args.forEach(arg -> arguments.add((Expression) visit(arg)));

        return hydrateSourceLocation(new NativeCall(
            (Essential) visit(ctx.nativeFunction()),
            new ExpressionList(arguments)
        ), ctx);
    }

    @Override
    public Function visitUntypedFunction(ZeloParser.UntypedFunctionContext ctx) {
        return hydrateSourceLocation(new Function(
            visitName(ctx.name),
            visitDeclarations(ctx.declarations)
        ), ctx);
    }

    @Override
    public TypedFunction visitTypedFunction(ZeloParser.TypedFunctionContext ctx) {
        return hydrateSourceLocation(new TypedFunction(
            (Type) visit(ctx.type()),
            visitName(ctx.name),
            visitDeclarations(ctx.declarations)
        ), ctx);
    }

    @Override
    public Essential visitNegation(ZeloParser.NegationContext ctx) {
        return hydrateSourceLocation(new Negation(), ctx);
    }

    @Override
    public Essential visitAddition(ZeloParser.AdditionContext ctx) {
        return hydrateSourceLocation(new Addition(), ctx);
    }

    @Override
    public Essential visitSubtraction(ZeloParser.SubtractionContext ctx) {
        return hydrateSourceLocation(new Subtraction(), ctx);
    }

    @Override
    public Essential visitIncrement(ZeloParser.IncrementContext ctx) {
        return hydrateSourceLocation(new Increment(), ctx);
    }

    @Override
    public Essential visitDecrement(ZeloParser.DecrementContext ctx) {
        return hydrateSourceLocation(new Decrement(), ctx);
    }

    @Override
    public Essential visitMultiplication(ZeloParser.MultiplicationContext ctx) {
        return hydrateSourceLocation(new Multiplication(), ctx);
    }

    @Override
    public Essential visitDivision(ZeloParser.DivisionContext ctx) {
        return hydrateSourceLocation(new Division(), ctx);
    }

    @Override
    public Essential visitGreaterThan(ZeloParser.GreaterThanContext ctx) {
        return hydrateSourceLocation(new GreaterThan(), ctx);
    }

    @Override
    public Essential visitLowerThan(ZeloParser.LowerThanContext ctx) {
        return hydrateSourceLocation(new LowerThan(), ctx);
    }

    @Override
    public Essential visitEqual(ZeloParser.EqualContext ctx) {
        return hydrateSourceLocation(new Equal(), ctx);
    }

    @Override
    public Essential visitNotEqual(ZeloParser.NotEqualContext ctx) {
        return hydrateSourceLocation(new NotEqual(), ctx);
    }

    @Override
    public Essential visitLowerThanOrEqual(ZeloParser.LowerThanOrEqualContext ctx) {
        return hydrateSourceLocation(new LowerThanOrEqual(), ctx);
    }

    @Override
    public Essential visitGreaterThanOrEqual(ZeloParser.GreaterThanOrEqualContext ctx) {
        return hydrateSourceLocation(new GreaterThanOrEqual(), ctx);
    }

    @Override
    public Essential visitLogicalAnd(ZeloParser.LogicalAndContext ctx) {
        return hydrateSourceLocation(new LogicalAnd(), ctx);
    }

    @Override
    public Essential visitLogicalOr(ZeloParser.LogicalOrContext ctx) {
        return hydrateSourceLocation(new LogicalOr(), ctx);
    }

    @Override
    public Literal visitLiteralExpression(ZeloParser.LiteralExpressionContext ctx) {
        return (Literal) visit(ctx.literal());
    }

    @Override
    public StringType visitTypeString(ZeloParser.TypeStringContext ctx) {
        return hydrateSourceLocation(new StringType(), ctx);
    }

    @Override
    public IntegerType visitTypeInteger(ZeloParser.TypeIntegerContext ctx) {
        return hydrateSourceLocation(new IntegerType(), ctx);
    }

    @Override
    public RealType visitTypeReal(ZeloParser.TypeRealContext ctx) {
        return hydrateSourceLocation(new RealType(), ctx);
    }

    @Override
    public BooleanType visitTypeBoolean(ZeloParser.TypeBooleanContext ctx) {
        return hydrateSourceLocation(new BooleanType(), ctx);
    }

    @Override
    public Symbol visitSymbol(ZeloParser.SymbolContext ctx) {
        return hydrateSourceLocation(new Symbol(visitName(ctx.NAME())), ctx);
    }
}


text:
<!DOCTYPE HTML>

<title>algorithms.connected</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2022-11-23">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Package algorithms.connected

Interface Summary

Interface
Description

IConnectedValuesGroupFinder

given a set of points, finds the connected among them and places them into
 groups.

Class Summary

Class
Description

ConnectedValuesGroupFinder

given a set of points, finds the connected among them and places them into
 groups.

ConnectedValuesGroupFinder2

This version is similar to ConnectedValuesGroupFinder.java
 except that uses smaller amount of space at the
 expense of a few more O(1) iterations when merging groups.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.


text:
<?php

namespace LiteCQRS\Commanding;

/**
 * Accept and process commands by passing them along to a matching command handler.
 */
interface CommandBus
{
    public function handle($command);
}


text:
"use strict";

import React from "react";

export default class PartSimple extends React.Component {

  static propTypes = {
    part: React.PropTypes.shape({
      type: React.PropTypes.string.isRequired,
      realType: React.PropTypes.string.isRequired,
      content: React.PropTypes.string.isRequired,
      style: React.PropTypes.object
    }).isRequired,
    style: React.PropTypes.object.isRequired
  };

  static defaultProps = {
    style: {
      marginLeft: ".3em"
    }
  };

  shouldComponentUpdate(nextProps) {
    return nextProps.part !== this.props.part;
  }

  render() {
    const style = {
      ...this.props.style,
      ...this.props.part.style
    };
    return {this.props.part.content};
  }

}


text:
package ingvar.android.processor.memory.test;

import android.util.LruCache;

import junit.framework.TestCase;

import java.util.Arrays;
import java.util.List;

import ingvar.android.processor.memory.persistence.MemoryRepository;
import ingvar.android.processor.persistence.CompositeKey;
import ingvar.android.processor.persistence.Time;

/**
 * Created by Igor Zubenko on 2015.03.20.
 */
public class DecorationTest extends TestCase {

    private MemoryRepository decorated;
    private MemoryRepository repo;
    private LruCache<String, MemoryRepository.Entry<String>> decoratedLru;
    private LruCache<String, MemoryRepository.Entry<String>> repoLru;

    public DecorationTest() {
        decoratedLru = new LruCache<>(4);
        decorated = new MemoryRepository(decoratedLru);
        repoLru = new LruCache<>(2);
        repo = new MemoryRepository(repoLru, decorated);
    }

    public void testDecoration() {
        String key = "test";
        String value = "test_value";

        repo.persist(key, value);

        assertEquals(1, decoratedLru.size());
        assertEquals(1, repoLru.size());
        assertEquals(value, repo.obtain(key, Time.ALWAYS_RETURNED));
        assertEquals(value, decorated.obtain(key, Time.ALWAYS_RETURNED));
    }

    public void testFromDecorated() {
        repo.persist("test1", "value1");
        assertEquals(1, repoLru.size());
        assertEquals(1, decoratedLru.size());

        repo.persist("test2", "value2");
        repo.persist("test3", "value3");
        assertEquals(2, repoLru.size());
        assertEquals("value2", repo.obtain("test2", Time.ALWAYS_RETURNED));
        assertEquals(3, decoratedLru.size());
        assertEquals("value1", repo.obtain("test1", Time.ALWAYS_RETURNED));
        assertEquals("value1", repoLru.get("test1").getValue());
    }

    public void testCacheList() {
        CompositeKey key = new CompositeKey<>("group1", "child1", "child2");
        List<String> data = Arrays.asList("value1", "value2");

        repo.persist(key, data);

        assertEquals(data, repo.obtain(key, Time.ALWAYS_RETURNED));
        assertEquals(data, decorated.obtain(key, Time.ALWAYS_RETURNED));
        assertEquals(Arrays.asList("value1"), repo.obtain(new CompositeKey<>("group1", "child1"), Time.ALWAYS_RETURNED));
    }

    public void testCacheListWithoutParent() {
        CompositeKey key = new CompositeKey<>(null, "child1", "child2");
        List<String> data = Arrays.asList("value1", "value2");

        repo.persist(key, data);

        assertEquals(data, repo.obtain(key, Time.ALWAYS_RETURNED));
        assertEquals(data, decorated.obtain(key, Time.ALWAYS_RETURNED));
        assertEquals("value1", repo.obtain("child1", Time.ALWAYS_RETURNED));
    }

}


text:
'use strict';

/**
 * Requirements
 * @ignore
 */
const Base = require('../Base.js').Base;
const BaseRoute = require('./routes/BaseRoute.js').BaseRoute;
const ModelSynchronizer = require('../watch/ModelSynchronizer.js').ModelSynchronizer;
const CliLogger = require('../cli/CliLogger.js').CliLogger;
const assertParameter = require('../utils/assert.js').assertParameter;
const express = require('express');
const fs = require('fs');
const http = require('http');
const spdy = require('spdy');
const basicAuth = require('basic-auth-connect');
const compression = require('compression');
const bodyParser = require('body-parser');

/**
 * @memberOf server
 */
class Server extends Base
{
    /**
     * @param {CliLogger} cliLogger
     * @param {ModelSynchronizer} modelSynchronizer
     * @param {object} [routes]
     * @param {object} [options]
     */
    constructor(cliLogger, modelSynchronizer, routes, options)
    {
        super();

        // Check params
        assertParameter(this, 'cliLogger', cliLogger, true, CliLogger);

        // Add initial values
        const opts = options || {};
        this._cliLogger = cliLogger;
        this._modelSynchronizer = modelSynchronizer;
        this._http2 = opts.http2 || false;
        this._port = opts.port || 3000;
        this._express = express();
        this._routes = [];
        this._sslKey = opts.sslKey || (__dirname + '/localhost.key');
        this._sslCert = opts.sslCert || (__dirname + '/localhost.crt');

        // Add settings
        this._express.use(compression());
        this._express.use(bodyParser.json());

        // Add basic auth
        if (opts.authentication === true)
        {
            const credentials = opts.credentials || { username: 'entoj', password: 'entoj' };
            this._express.use(basicAuth(credentials.username, credentials.password));
        }

        // Add routes
        if (Array.isArray(routes))
        {
            for (const route of routes)
            {
                this.addRoute(route);
            }
        }
    }

    /**
     * @inheritDoc
     */
    static get injections()
    {
        return { 'parameters': [CliLogger, ModelSynchronizer, 'server/Server.routes', 'server/Server.options'] };
    }

    /**
     * @inheritDocs
     */
    static get className()
    {
        return 'server/Server';
    }

    /**
     * @let {String}
     */
    get port()
    {
        return this._port;
    }

    /**
     * @let {Express}
     */
    get express()
    {
        return this._express;
    }

    /**
     * @let {Array}
     */
    get routes()
    {
        return this._routes;
    }

    /**
     * @param {server.routes.BaseRoute}
     */
    addRoute(route)
    {
        // Check params
        assertParameter(this, 'route', route, true, BaseRoute);

        // Register
        this._routes.push(route);
        route.register(this.express);
    }

    /**
     * @returns {Promise.<Express>}
     */
    start()
    {
        const scope = this;
        return new Promise(function(resolve, reject)
        {
            if (scope._http2)
            {
                const options =
                {
                    key: fs.readFileSync(scope._sslKey),
                    cert: fs.readFileSync(scope._sslCert)
                };
                const work = scope._cliLogger.work('Starting <http/2> server at <https://localhost:' + scope.port + '>');
                scope._server = spdy.createServer(options, scope.express).listen(scope.port);
                scope._cliLogger.end(work);
            }
            else
            {
                const work = scope._cliLogger.info('Starting <http> server at <http://localhost:' + scope.port + '>');
                scope._server = http.createServer(scope.express).listen(scope.port);
                scope._cliLogger.end(work);
            }

            if (scope._modelSynchronizer)
            {
                const startSyncer = scope._cliLogger.info('Starting <Synchronizer>');
                scope._modelSynchronizer.start()
                    .then(function()
                    {
                        scope._cliLogger.end(startSyncer);
                        resolve(scope._server);
                    });
            }
            else
            {
                resolve(scope._server);
            }
        });
    }

    /**
     * @returns {Promise.<Bool>}
     */
    stop()
    {
        const scope = this;
        return new Promise(function(resolve, reject)
        {
            if (scope._server)
            {
                scope._cliLogger.info('Server: Stopping');
                scope._server.close(function()
                {
                    resolve(scope._server);
                });
            }
            else
            {
                resolve(false);
            }
        });
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.Server = Server;


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>java-tools</groupId>
  <artifactId>java-tools</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>java-tools</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!--common-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.6</version>
    </dependency>
    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.9.3</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.7</version>
    </dependency>
    <!--common-->
    <!---->
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk15on</artifactId>
      <version>1.58</version>
    </dependency>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcpkix-jdk15on</artifactId>
      <version>1.58</version>
    </dependency>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcpg-jdk15on</artifactId>
      <version>1.58</version>
    </dependency>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcmail-jdk15on</artifactId>
      <version>1.58</version>
    </dependency>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-ext-jdk15on</artifactId>
      <version>1.58</version>
    </dependency>
    <!---->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.7</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>3.2.2</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.amqp</groupId>
      <artifactId>spring-rabbit</artifactId>
      <version>1.7.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.3.10.RELEASE</version>
    </dependency>

  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.0.2</version>
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <classpathPrefix>lib/</classpathPrefix>
              <mainClass>com.me.common.Application</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
from os.path import abspath, dirname, join

from tornado.ioloop import IOLoop
from tornado.web import StaticFileHandler
from tornado.websocket import WebSocketHandler, WebSocketClosedError

from .nt_serial import NTSerial

import logging

logger = logging.getLogger("net2js")

__all__ = ["get_handlers", "NetworkTablesWebSocket", "NonCachingStaticFileHandler"]

class NetworkTablesWebSocket(WebSocketHandler):
    """
        A tornado web handler that forwards values between NetworkTables
        and a webpage via a websocket
    """

    ntserial = None

    def open(self):
        logger.info("NetworkTables websocket opened")
        self.ioloop = IOLoop.current()
        self.ntserial = NTSerial(self.send_msg_threadsafe)

    def check_origin(self, origin):
        """
            Allow CORS requests
        """
        return True

    def on_message(self, message):
        if self.ntserial is not None:
            self.ntserial.process_update(message)

    def send_msg(self, msg):
        try:
            self.write_message(msg, binary=True)
        except WebSocketClosedError:
            logger.warning("websocket closed when sending message")

    def send_msg_threadsafe(self, data):
        self.ioloop.add_callback(self.send_msg, data)

    def on_close(self):
        logger.info("NetworkTables websocket closed")
        if self.ntserial is not None:
            self.ntserial.close()

class NonCachingStaticFileHandler(StaticFileHandler):
    """
        This static file handler disables caching, to allow for easy
        development of your Dashboard
    """

    # This is broken in tornado, disable it
    def check_etag_header(self):
        return False

    def set_extra_headers(self, path):
        # Disable caching
        self.set_header(
            "Cache-Control", "no-store, no-cache, must-revalidate, max-age=0"
        )

def get_handlers():
    """
        Returns a list that can be concatenated to the list of handlers
        passed to the ``tornado.web.Application`` object. This list contains
        handlers for the NetworkTables websocket and the necessary javascript
        to use it.

        Example usage::

            import pynetworktables2js
            import tornado.web

            ...

            app = tornado.web.Application(
                pynetworktables2js.get_handlers() + [
                    # tornado handlers here
                ])
    """

    js_path_opts = {"path": abspath(join(dirname(__file__), "js"))}

    return [
        ("/networktables/ws", NetworkTablesWebSocket),
        ("/networktables/(.*)", NonCachingStaticFileHandler, js_path_opts),
    ]


text:
. `dirname $0`/../helper_scripts/cosmic/helperlib.sh

set -e

function usage {
  echo "This script prepares the required infrastructure for integration tests, based on a marvin configuration file"
  printf "Usage: %s: -m marvin_config \n" $(basename $0) >&2
}

say "Running script: $0"

# Options
cloudstack_deploy_mode=0
while getopts 'cm:' OPTION
do
  case $OPTION in
  m)    marvin_config="$OPTARG"
        ;;
  c)    cloudstack_deploy_mode=1
        ;;
  esac
done

say "Received arguments:"
say "marvin_config = ${marvin_config}"

# Check if a marvin dc file was specified
if [ -z ${marvin_config} ]; then
  say "No Marvin config specified. Quiting."
  usage
  exit 1
else
  say "Using Marvin config '${marvin_config}'."
fi

if [ ! -f "${marvin_config}" ]; then
    say "Supplied Marvin config not found!"
    exit 1
fi

parse_marvin_config ${marvin_config}

mkdir -p ${primarystorage}

# CloudStack flag
CLOUDSTACKFLAG=""
if [ ${cloudstack_deploy_mode} -eq 1 ]; then
  CLOUDSTACKFLAG="--cloudstack"
fi

if [ ${hypervisor} = "kvm" ]; then
  say "Found hypervisor: ${hypervisor}; changing MTU to 1600"
  for h in `ls /sys/devices/virtual/net/virbr0/brif/`; do sudo /usr/sbin/ip link set dev ${h} mtu 1600; done
  sudo /usr/sbin/ip link set dev virbr0 mtu 1600
  sudo /usr/sbin/ip link set dev virbr0.50 mtu 1600
fi
if [ ${hypervisor} = "xenserver" ]; then
  say "Found hypervisor: ${hypervisor}; changing MTU to 1500"
  for h in `ls /sys/devices/virtual/net/virbr0/brif/`; do sudo /usr/sbin/ip link set dev ${h} mtu 1500; done
  sudo /usr/sbin/ip link set dev virbr0 mtu 1500
  sudo /usr/sbin/ip link set dev virbr0.50 mtu 1500
fi

# Make sure bridge is up
sudo /usr/sbin/ifup virbr0.50

tries="3"
currenttry="0"

set +e
while [ $currenttry -lt $tries ]; do
  say "Creating hosts"

  timeout 900 /data/shared/deploy/kvm_local_deploy.py -m ${marvin_config} --force ${CLOUDSTACKFLAG} 2>&1
  if [ $? -gt 0 ]; then
    say "Timeout while creating :("
  else
    say "Creating hosts went ok!"
    exit 0
  fi
  currenttry=$[$currenttry+1]
done


text:
using OpenLiveWriter.ApplicationFramework;
using System.ComponentModel;

namespace OpenLiveWriter.PostEditor.Commands
{
	/// <summary>
	/// Summary description for CommandDiagnosticsConsole.
	/// </summary>
	public class CommandDiagnosticsConsole : Command
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private Container components = null;

		public CommandDiagnosticsConsole(IContainer container)
		{
			///
			/// Required for Windows.Forms Class Composition Designer support
			///
			container.Add(this);
			InitializeComponent();

			//
			//
			//
		}

		public CommandDiagnosticsConsole()
		{
			///
			/// Required for Windows.Forms Class Composition Designer support
			///
			InitializeComponent();

			//
			//
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Component Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			//
			// CommandDiagnosticsConsole
			//
			this.Identifier = "OpenLiveWriter.PostEditor.Commands.DiagnosticsConsole";
			this.MenuText = "Show Diagnostics Console";
			this.Text = "Show Diagnostics Console";

		}
		#endregion
	}
}


text:
package service

import (
	"context"
	"fmt"
	"time"

	"github.com/pkg/errors"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/tsuru/config"
	"github.com/tsuru/tsuru/api/shutdown"
	"github.com/tsuru/tsuru/app/bind"
	tsuruErrors "github.com/tsuru/tsuru/errors"
	"github.com/tsuru/tsuru/event"
	"github.com/tsuru/tsuru/log"
	"github.com/tsuru/tsuru/permission"
)

var (
	syncOperations = prometheus.NewCounterVec(prometheus.CounterOpts{
		Name: "tsuru_service_sync_operations_total",
		Help: "The total number of sync operations.",
	}, []string{"op"})

	syncErrors = prometheus.NewCounterVec(prometheus.CounterOpts{
		Name: "tsuru_service_sync_operations_errors_total",
		Help: "The total number of sync errors.",
	}, []string{"op"})

	syncDuration = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "tsuru_service_sync_last_duration",
		Help: "The duration of the last sync operation.",
	})
)

func init() {
	prometheus.MustRegister(syncOperations, syncErrors, syncDuration)
}

func InitializeSync(appLister func() ([]bind.App, error)) error {
	interval, _ := config.GetDuration("service:sync:interval")
	if interval <= 0 {
		interval = time.Minute * 5
	}
	syncer := &bindSyncer{
		interval:  interval,
		appLister: appLister,
	}
	err := syncer.start()
	if err != nil {
		return err
	}
	shutdown.Register(syncer)
	return nil
}

type bindSyncer struct {
	interval  time.Duration
	appLister func() ([]bind.App, error)

	started  bool
	shutdown chan struct{}
	done     chan struct{}
}

// start starts the sync process on a different goroutine
func (b *bindSyncer) start() error {
	if b.started {
		return errors.New("syncer already started")
	}
	if b.appLister == nil {
		return errors.New("must set app lister function")
	}
	if b.interval == 0 {
		b.interval = 5 * time.Minute
	}
	b.shutdown = make(chan struct{}, 1)
	b.done = make(chan struct{})
	b.started = true
	fmt.Printf("[bind-syncer] starting. Running every %s.\n", b.interval)
	go func(d time.Duration) {
		for {
			select {
			case <-time.After(d):
				start := time.Now()
				log.Debug("[bind-syncer] starting run")
				apps, err := b.appLister()
				if err != nil {
					log.Errorf("[bind-syncer] error listing apps: %v. Aborting sync.", err)
					syncDuration.Set(time.Since(start).Seconds())
					break
				}
				for _, a := range apps {
					err = b.sync(a)
					if err != nil {
						log.Errorf("[bind-syncer] error syncing app %q: %v", a.GetName(), err)
					}
					if len(b.shutdown) > 0 {
						break
					}
				}
				log.Debugf("[bind-syncer] finished running. Synced %d apps.", len(apps))
				d = b.interval
				syncDuration.Set(time.Since(start).Seconds())
			case <-b.shutdown:
				b.done <- struct{}{}
				return
			}
		}
	}(time.Millisecond * 100)
	return nil
}

// Shutdown shutdowns bindSyncer waiting for the current sync
// to complete
func (b *bindSyncer) Shutdown(ctx context.Context) error {
	if !b.started {
		return nil
	}
	b.shutdown <- struct{}{}
	select {
	case <-b.done:
	case <-ctx.Done():
	}
	b.started = false
	return ctx.Err()
}

func (b *bindSyncer) sync(a bind.App) (err error) {
	binds := make(map[string][]string)
	unbinds := make(map[string][]string)
	evt, err := event.NewInternal(&event.Opts{
		Target:       event.Target{Type: event.TargetTypeApp, Value: a.GetName()},
		InternalKind: "bindsyncer",
		Allowed:      event.Allowed(permission.PermAppReadEvents, permission.Context(permission.CtxApp, a.GetName())),
	})
	if err != nil {
		if _, ok := err.(event.ErrEventLocked); ok {
			log.Debugf("[bind-syncer] skipping sync for app %q: event locked", a.GetName())
			return nil
		}
		return errors.Wrap(err, "error trying to insert bind sync event, aborted")
	}
	defer func() {
		if len(binds)+len(unbinds) > 0 || err != nil {
			evt.DoneCustomData(err, map[string]interface{}{
				"binds":   binds,
				"unbinds": unbinds,
			})
			return
		}
		evt.Logf("nothing to do for %q", a.GetName())
		evt.Abort()
	}()
	log.Debugf("[bind-syncer] starting sync for app %q", a.GetName())
	appUnits, err := a.GetUnits()
	if err != nil {
		return errors.Wrap(err, "error getting units from app")
	}
	units := make([]Unit, len(appUnits))
	for i := range appUnits {
		units[i] = Unit{AppName: a.GetName(), ID: appUnits[i].GetID(), IP: appUnits[i].GetIp()}
	}
	instances, err := GetServiceInstancesBoundToApp(a.GetName())
	if err != nil {
		return errors.WithMessage(err, "error retrieving service instances bound to app")
	}
	multiErr := tsuruErrors.NewMultiError()
	for _, instance := range instances {
		boundUnits := make(map[Unit]struct{})
		for _, u := range instance.BoundUnits {
			if u.AppName != a.GetName() {
				continue
			}
			boundUnits[u] = struct{}{}
		}
		for _, u := range units {
			if _, ok := boundUnits[u]; ok {
				delete(boundUnits, u)
			} else {
				log.Debugf("[bind-syncer] binding unit %q from app %q from %s:%s\n", u.ID, a.GetName(), instance.ServiceName, instance.Name)
				err = instance.BindUnit(a, u)
				binds[instance.Name] = append(binds[instance.Name], u.GetID())
				if err != nil {
					err = errors.Wrapf(err, "failed to bind unit %q for %s(%s)", u.ID, instance.ServiceName, instance.Name)
					multiErr.Add(err)
					syncErrors.WithLabelValues("bind").Inc()
				}
				syncOperations.WithLabelValues("bind").Inc()
			}
		}
		for u := range boundUnits {
			log.Debugf("[bind-syncer] unbinding unit %q from app %q from %s:%s\n", u.ID, a.GetName(), instance.ServiceName, instance.Name)
			err = instance.UnbindUnit(a, u)
			unbinds[instance.Name] = append(unbinds[instance.Name], u.GetID())
			if err != nil {
				err = errors.Wrapf(err, "failed to unbind unit %q for %s(%s)", u.ID, instance.ServiceName, instance.Name)
				multiErr.Add(err)
				syncErrors.WithLabelValues("unbind").Inc()
			}
			syncOperations.WithLabelValues("unbind").Inc()
		}
	}
	log.Debugf("[bind-syncer] finished sync for app %q", a.GetName())
	return multiErr.ToError()
}


text:
<!doctype html>

    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A layout example that shows off a blog page with a list of posts.">

    <title>{% block title %} Raighne_Blog {% endblock %}</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css">
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/grids-responsive-min.css">
    <link rel="stylesheet" href="http://picturebag.qiniudn.com/blog.css">
    <link rel="stylesheet" href="http://picturebag.qiniudn.com/monokai.css">

Raighne_Blog

Has man a future?

                        主页

                        归档

                        Github

                        Twitter

                        专题

                    <form class="pure-form" action="/search/" method="get">
                    <input class="pure-input-3-3" type="text" name="s" placeholder="search">
                    </form>

                        About Me

                        RSS

            {% block content %}
            {% endblock %}

About Me

Twitter

GitHub


text:
package edu.iltu.itk275.assignment4.msanto2;

public class OdometerTest {

    public static void main(String[] args) {
        test1();
        test2();
    }

    public static void test1() {
        System.out.println("Creating odometer with efficiency equal to 5.");
        Odometer odometer = new Odometer(5);

        System.out.println("Adding 100 miles.");
        System.out.println("Miles before: " + odometer.getTotalMiles());
        odometer.addMiles(100);
        System.out.println("Miles after: " + odometer.getTotalMiles());

        System.out.println("Reseting miles.");
        odometer.resetMiles();
        System.out.println("Miles after: " + odometer.getTotalMiles());

        System.out.println("Adding 200 miles.");
        System.out.println("Miles before: " + odometer.getTotalMiles());
        odometer.addMiles(200);
        System.out.println("Miles after: " + odometer.getTotalMiles());

        System.out.println("Gallons consumed: " + odometer.getGallons());
    }

    public static void test2() {
        System.out.println("Creating odometer with efficiency equal to 1.");
        Odometer odometer = new Odometer(1);

        System.out.println("Adding 500 miles.");
        System.out.println("Miles before: " + odometer.getTotalMiles());
        odometer.addMiles(500);
        System.out.println("Miles after: " + odometer.getTotalMiles());

        System.out.println("Reseting miles.");
        odometer.resetMiles();
        System.out.println("Miles after: " + odometer.getTotalMiles());

        System.out.println("Adding 350 miles.");
        System.out.println("Miles before: " + odometer.getTotalMiles());
        odometer.addMiles(350);
        System.out.println("Miles after: " + odometer.getTotalMiles());

        System.out.println("Gallons consumed: " + odometer.getGallons());
    }

}


text:
package org.uberfire.client.docks.view.items;

import com.google.gwt.resources.client.ImageResource;
import com.google.gwtmockito.GwtMockitoTestRunner;
import org.gwtbootstrap3.client.ui.Button;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.uberfire.client.workbench.docks.UberfireDock;
import org.uberfire.client.workbench.docks.UberfireDockPosition;
import org.uberfire.mvp.ParameterizedCommand;
import org.uberfire.mvp.PlaceRequest;

import static org.mockito.Mockito.*;

@RunWith(GwtMockitoTestRunner.class)
public class SideDockItemTest {

    @Mock
    private ImageResource imageResource, imageResourceFocused;

    @Mock
    private PlaceRequest placeRequest;

    private ParameterizedCommand<String> emptyCommand;

    private UberfireDock dockWithFontIcon, dockWithImageIcon;

    private SideDockItem sideDockWithFontIcon, sideDockWithImageIcon;

    @Before
    public void setup() {
        dockWithFontIcon = new UberfireDock( UberfireDockPosition.EAST, "BRIEFCASE", placeRequest, "" ).withSize( 450 ).withLabel( "dock" );
        dockWithImageIcon = new UberfireDock( UberfireDockPosition.EAST, imageResource, imageResourceFocused, placeRequest, "" ).withSize( 450 ).withLabel( "dock" );

        sideDockWithFontIcon = spy( new SideDockItem( dockWithFontIcon, emptyCommand, emptyCommand ) );
        sideDockWithImageIcon = spy( new SideDockItem( dockWithImageIcon, emptyCommand, emptyCommand ) );

        emptyCommand = new ParameterizedCommand<String>() {
            @Override
            public void execute( final String parameter ) {

            }
        };
    }

    @Test
    public void createSideDockItemWithFontIconTest() {
        sideDockWithFontIcon.createButton();

        verify( sideDockWithFontIcon ).configureIcon( any( Button.class ), eq( (ImageResource) null ) );
        verify( sideDockWithFontIcon, never() ).configureImageIcon( any( Button.class ), any( ImageResource.class ) );
    }

    @Test
    public void createSideDockItemFocusedWithFontIconTest() {
        sideDockWithFontIcon.getPopup().createButton( sideDockWithFontIcon );

        verify( sideDockWithFontIcon ).configureIcon( any( Button.class ), eq( (ImageResource) null ) );
        verify( sideDockWithFontIcon, never() ).configureImageIcon( any( Button.class ), any( ImageResource.class ) );
    }

    @Test
    public void selectSideDockItemWithFontIconTest() {
        sideDockWithFontIcon.select();

        verify( sideDockWithFontIcon, never() ).configureImageIcon( any( Button.class ), any( ImageResource.class ) );
    }

    @Test
    public void deselectSideDockItemWithFontIconTest() {
        sideDockWithFontIcon.deselect();

        verify( sideDockWithFontIcon, never() ).configureImageIcon( any( Button.class ), any( ImageResource.class ) );
    }

    @Test
    public void createSideDockItemWithImageIconTest() {
        sideDockWithImageIcon.createButton();

        verify( sideDockWithImageIcon ).configureIcon( any( Button.class ), eq( imageResource ) );
        verify( sideDockWithImageIcon ).configureImageIcon( any( Button.class ), eq( imageResource ) );
    }

    @Test
    public void createSideDockItemFocusedWithImageIconTest() {
        sideDockWithImageIcon.getPopup().createButton( sideDockWithImageIcon );

        verify( sideDockWithImageIcon ).configureIcon( any( Button.class ), eq( imageResourceFocused ) );
        verify( sideDockWithImageIcon ).configureImageIcon( any( Button.class ), eq( imageResourceFocused ) );
    }

    @Test
    public void selectSouthDockItemWithImageIconTest() {
        sideDockWithImageIcon.select();

        verify( sideDockWithImageIcon ).configureImageIcon( any( Button.class ), eq( imageResourceFocused ) );
    }

    @Test
    public void deselectSouthDockItemWithImageIconTest() {
        sideDockWithImageIcon.deselect();

        verify( sideDockWithImageIcon ).configureImageIcon( any( Button.class ), eq( imageResource ) );
    }
}


text:
#ifndef _STDLIB_H_
#define _STDLIB_H_

#include <stddef.h>  /* For size_t, NULL */
#include <malloc.h>  /* "Listen to what the man says" */

long atol(const char *__str);
#define atoi(str) ((int)atol(str))

long strtol(const char *__p, char **__out_p, int __base);
unsigned long strtoul(const char *__p, char **__out_p, int __base);

#define RAND_MAX 0x80000000
int rand(void);
void srand(unsigned new_seed);

int abs(int val);

void qsort(void *a, size_t n, size_t es, int (*cmp)());

void panic(const char *, ...);

#endif


text:
from tests.product.mode_installers import StandaloneModeInstaller
from tests.product.prestoadmin_installer import PrestoadminInstaller
from tests.product.topology_installer import TopologyInstaller
from tests.product.standalone.presto_installer import StandalonePrestoInstaller

STANDALONE_BARE_CLUSTER = 'bare'
BARE_CLUSTER = 'bare'
STANDALONE_PA_CLUSTER = 'pa_only_standalone'
STANDALONE_PRESTO_CLUSTER = 'presto'

cluster_types = {
    BARE_CLUSTER: [],
    STANDALONE_PA_CLUSTER: [PrestoadminInstaller,
                            StandaloneModeInstaller],
    STANDALONE_PRESTO_CLUSTER: [PrestoadminInstaller,
                                StandaloneModeInstaller,
                                TopologyInstaller,
                                StandalonePrestoInstaller],
}


text:
class ListsController < ApplicationController
  def new
    @list = List.new
  end

  def create
    @list = List.new(list_params)
    if @list.save
      redirect_to list_path(@list)
    else
      render :new
    end
  end

  def show
    @list = List.find(params[:id])
  end

  private

  def list_params
    params.require(:list).permit(:name, :description)
  end
end


text:
class AnalyzersController < ApplicationController

  helper_method :selected_analyzer_ids
  helper_method :all_analyzer_ids
  helper_method :all_analyzers

  def index
    if params[:text].blank?
      @analyzers = []
      render :index and return
    end

    @analyzers = selected_analyzer_ids.map do |analyzer_id|
      analyzer = Analyzer.find(analyzer_id)
      AnalyzerDecorator.new(analyzer, text: text)
    end
  end

  private

  def text
    params[:text]
  end

  def selected_analyzer_ids
    params[:analyzer_ids] || []
  end

  def all_analyzer_ids
    Analyzer.all.map(&:id)
  end

  def all_analyzers
    Analyzer.all
  end
end


text:
class Game;
class SceneRace : public Scene {
public:
	SceneRace(Game* g, sf::RenderWindow* w);
	~SceneRace();

	void init(int nPlayers);
	void update(float deltaTime);
	void render(sf::RenderTarget* target);
	void processInput();
private:
	Background* _background;
	std::vector<Player> _players;
	int _nPlayers;

	sf::RectangleShape _rect;
	sf::RectangleShape _rect2;
	sf::RectangleShape _rect3;
	sf::IntRect _groundBounds;
	float _targetRotation;
	float _rotation;
	float _speed;

	void setRotation(float rotation);
};

#endif


text:
namespace tulip { namespace test {

struct _test {
  static void call_pyfuns(const tulip::TulipDict& d, const char* method) {
    PyObject* v{};
    py::ssize_t pos{};
    while (PyDict_Next(d.ptr(), &pos, nullptr, &v))
      py::call_method<void>(v, method);
  }

  static void wrap(void) {
    py::scope in_test =
      py::class_<_test, boost::shared_ptr<_test>>("_test")
        .def("call_pyfuns", &_test::call_pyfuns).staticmethod("call_pyfuns")
        ;

    tulip::VectorWrap<std::vector<int>>::wrap("ivec");
    tulip::SetWrap<std::set<int>>::wrap("iset");
    tulip::MapWrap<std::map<int, std::string>>::wrap("ismap");
  }
};

}}

void tulip_debug_wrap(void) {
  tulip::test::_test::wrap();
}


text:
package org.elasticsearch.common;

import org.elasticsearch.test.ESTestCase;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.collection.IsArrayContainingInAnyOrder.arrayContainingInAnyOrder;

public class ParseFieldTests extends ESTestCase {
    public void testParse() {
        String name = "foo_bar";
        ParseField field = new ParseField(name);
        String[] deprecated = new String[]{"barFoo", "bar_foo", "Foobar"};
        ParseField withDeprecations = field.withDeprecation(deprecated);
        assertThat(field, not(sameInstance(withDeprecations)));
        assertThat(field.match(name), is(true));
        assertThat(field.match("foo bar"), is(false));
        for (String deprecatedName : deprecated) {
            assertThat(field.match(deprecatedName), is(false));
        }

        assertThat(withDeprecations.match(name), is(true));
        assertThat(withDeprecations.match("foo bar"), is(false));
        for (String deprecatedName : deprecated) {
            assertThat(withDeprecations.match(deprecatedName), is(true));
            assertWarnings("Deprecated field [" + deprecatedName + "] used, expected [foo_bar] instead");
        }
    }

    public void testAllDeprecated() {
        String name = "like_text";
        String[] deprecated = new String[]{"text", "same_as_text"};
        ParseField field = new ParseField(name).withDeprecation(deprecated).withAllDeprecated("like");
        assertFalse(field.match("not a field name"));
        assertTrue(field.match("text"));
        assertWarnings("Deprecated field [text] used, replaced by [like]");
        assertTrue(field.match("same_as_text"));
        assertWarnings("Deprecated field [same_as_text] used, replaced by [like]");
        assertTrue(field.match("like_text"));
        assertWarnings("Deprecated field [like_text] used, replaced by [like]");
    }

    public void testGetAllNamesIncludedDeprecated() {
        ParseField parseField = new ParseField("terms", "in");
        assertThat(parseField.getAllNamesIncludedDeprecated(), arrayContainingInAnyOrder("terms", "in"));

        parseField = new ParseField("more_like_this", "mlt");
        assertThat(parseField.getAllNamesIncludedDeprecated(), arrayContainingInAnyOrder("more_like_this", "mlt"));
    }
}


text:
package cli_version_check_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestCliVersionCheck(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "CliVersionCheck Suite")
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.04.05 at 03:08:21 PM BRT
//

package semanticsco.interactions.basictypes;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for IncludedServiceStructure complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="IncludedServiceStructure">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="IncludedServiceID" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="IncludedServiceFunction" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "IncludedServiceStructure", propOrder = {
    "includedServiceID",
    "includedServiceFunction"
})
public class IncludedServiceStructure {

    @XmlElement(name = "IncludedServiceID", required = true)
    protected String includedServiceID;
    @XmlElement(name = "IncludedServiceFunction", required = true)
    protected String includedServiceFunction;

    /**
     * Gets the value of the includedServiceID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getIncludedServiceID() {
        return includedServiceID;
    }

    /**
     * Sets the value of the includedServiceID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setIncludedServiceID(String value) {
        this.includedServiceID = value;
    }

    /**
     * Gets the value of the includedServiceFunction property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getIncludedServiceFunction() {
        return includedServiceFunction;
    }

    /**
     * Sets the value of the includedServiceFunction property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setIncludedServiceFunction(String value) {
        this.includedServiceFunction = value;
    }

}


text:
require "web_assets"

WebAssets::Runner.new(ARGV).run


text:
///<reference path="IAdaptiveRPGroup.ts"/>
///<reference path="IBasePIM.ts"/>
///<reference path="IMessagingCallback.ts"/>
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
//# sourceMappingURL=IMessaging.js.map


text:
@interface TTIdentify()
@end

@implementation TTIdentify
{
    NSMutableSet *_userProperties;
}

- (id)init
{
    if (self = [super init]) {
        _userPropertyOperations = [[NSMutableDictionary alloc] init];
        _userProperties = [[NSMutableSet alloc] init];
    }
    return self;
}

+ (instancetype)identify
{
    return SAFE_ARC_AUTORELEASE([[self alloc] init]);
}

- (void)dealloc
{
    SAFE_ARC_RELEASE(_userPropertyOperations);
    SAFE_ARC_RELEASE(_userProperties);
    SAFE_ARC_SUPER_DEALLOC();
}

- (TTIdentify*)add:(NSString*) property value:(NSObject*) value
{
    if ([value isKindOfClass:[NSNumber class]] || [value isKindOfClass:[NSString class]]) {
        [self addToUserProperties:TT_OP_ADD property:property value:value];
    } else {
        NSLog(@"Unsupported value type for ADD operation, expecting NSNumber or NSString");
    }
    return self;
}

- (TTIdentify*)set:(NSString*) property value:(NSObject*) value
{
    [self addToUserProperties:TT_OP_SET property:property value:value];
    return self;
}

- (TTIdentify*)setOnce:(NSString*) property value:(NSObject*) value
{
    [self addToUserProperties:TT_OP_SET_ONCE property:property value:value];
    return self;
}

- (TTIdentify*)unset:(NSString*) property
{
    [self addToUserProperties:TT_OP_UNSET property:property value:@"-"];
    return self;
}

- (void)addToUserProperties:(NSString*)operation property:(NSString*) property value:(NSObject*) value
{
    // check if property already used in a previous operation
    if ([_userProperties containsObject:property]) {
        NSLog(@"Already used property '%@' in previous operation, ignoring for operation '%@'", property, operation);
        return;
    }

    NSMutableDictionary *operations = [_userPropertyOperations objectForKey:operation];
    if (operations == nil) {
        operations = [NSMutableDictionary dictionary];
        [_userPropertyOperations setObject:operations forKey:operation];
    }
    [operations setObject:value forKey:property];
    [_userProperties addObject:property];
}

@end


text:
title: Add Remove Theme Files
page_title: Add Remove Theme Files - RadThemeManager
description: This article shows how you can edit the list of XML files loaded into a Theme Manager.
slug: winforms/tools/visual-style-builder/adding-custom-themes-to-your-application/editing-themes
tags: editing,themes
published: True
position: 4
previous_url: tools-visual-style-builder-adding-custom-themes-to-your-application-editing-themes
---

# Add Remove Theme Files

>important RadThemeManager cannot load the theme if it is saved as package (tssp file). This is shown in the following article: [using custom themes](https://docs.telerik.com/devtools/winforms/styling-and-appearance/using-custom-themes)
To edit the list of themes loaded into a Theme Manager, follow these steps:

1. Select the RadThemeManager control, and then open its __Smart Tag__ menu.

    ![tools-visual-style-builder-adding-custom-themes-to-your-application-editing-themes 001](images/tools-visual-style-builder-adding-custom-themes-to-your-application-editing-themes001.png)

1. Select __Edit Themes__ to open the __ThemeSource Collection Editor__.

    ![tools-visual-style-builder-adding-custom-themes-to-your-application-editing-themes 002](images/tools-visual-style-builder-adding-custom-themes-to-your-application-editing-themes002.png)

1. Click __OK__ when you are finished working in the editor.

## To Add a New Theme to the Theme Manager

1. Click __Add__.

1. Choose the __StorageType__ for the theme. Select __Resource__ or __File__.

1. Set the __ThemeLocation__ (resource name or file location).

## To Remove a Theme from the Resource Manager

1. Select the theme that you wish to remove.

1. Click __Remove__.

## To Change the Properties for an Existing Theme

1. Select the theme that you wish to edit.

1. Set the __StorageType__ and __ThemeLocation__ properties to your desired values.

>caution When setting the __ThemeLocation__ for a __Resource__ storage type be sure to include the project namespace. The naming convention for ThemeManager to find the resource is \<my project namespace\>.\<theme name\>.xml. In project "MyProject" with theme resource file "MyTheme.xml", the fully qualified resource name should be entered as "MyProject.MyTheme.XML".
>

# See Also
* [Adding RadThemeManager to a Form]({%slug winforms/tools/visual-style-builder/adding-custom-themes-to-your-application/adding-radthememanager-to-a-form%})

* [Applying a Theme to a Control]({%slug winforms/tools/visual-style-builder/adding-custom-themes-to-your-application/applying-a-theme-to-a-control%})

* [Load Themes from a Resource]({%slug winforms/tools/visual-style-builder/adding-custom-themes-to-your-application/load-themes-from-a-resource%})

* [Load Themes from an External File]({%slug winforms/tools/visual-style-builder/adding-custom-themes-to-your-application/load-themes-from-an-external-file%})


text:
Mastodon client for CLI.

## Setup

Require [composer](https://getcomposer.org).
Clone or download repository, then run `composer install`.

```
$ git clone https://github.com/TomckySan/Gyudon.git
$ cd ./Gyudon
$ composer install
```

Add the path to environment variable.

## Authorization

Login to mastodon instance, and approve this app.

```
$ gyudon auth
```

Input mastodon instance url, email and password for login.

## Usage

### timeline

Retrieving recent posts from timeline:

```
$ gyudon timeline
```
You can specify the number of posts to get.

```
$ gyudon timeline 10
```

### toot

Posting new status:

```
$ gyudon toot "I want to eat Gyudon."
```

### bt

Reblogging a status:

```
$ gyudon bt 12345
```

The number is status id.

### fav

Favouriting a status:

```
$ gyudon fav 12345
```

The number is status id.

## TODO

## License

MIT


text:
TEST_STRING=java

###
# Test if the etherpad instance is alive by checking for
# the process in etherpad/data/etherpad.pid
#
# Use that PID to see if there are any processes running
# and if the command of that process matches $TEST_STRING
#
# If it matches kill the $PID,
# wait and see if the process ended.
#
# Exits 0 on success, 1 on failure

ETHERPADDIR="$(cd "$(dirname "$0")/.."; pwd)"
PID_FILE="${ETHERPADDIR}/etherpad/data/etherpad.pid"

PID=`cat ${PID_FILE}`
RUNNING_CMD="ps -o pid,ruser,ucmd --no-headers -p ${PID}"

function check_if_alive_by_pid {
	result=`ps -o pid,ruser,ucmd --no-headers -p ${1}`
	if [[ "${result}" =~ "${TEST_STRING}" ]] ; then
		return 0
	else
		return 1
	fi
}

i=0
while [ $i -le 10 ] ; do
	check_if_alive_by_pid $PID
	if [[ $? -eq 0 ]] ; then
		kill -9 $PID
		sleep 5
	else
		exit 0
	fi

	i=$(( $i + 1 ))
done

# Should only get here if we've tried restarting the
# Etherpad process 10 times unsuccessfully
exit 1