text:
/*
 *
 */
package org.ihtsdo.otf.ts.test.rest;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.Date;

import org.ihtsdo.otf.ts.ReleaseInfo;
import org.ihtsdo.otf.ts.helpers.AssociationReferenceRefSetMemberList;
import org.ihtsdo.otf.ts.helpers.AttributeValueRefSetMemberList;
import org.ihtsdo.otf.ts.helpers.ComplexMapRefSetMemberList;
import org.ihtsdo.otf.ts.helpers.ConceptList;
import org.ihtsdo.otf.ts.helpers.DescriptionList;
import org.ihtsdo.otf.ts.helpers.DescriptionTypeRefSetMemberList;
import org.ihtsdo.otf.ts.helpers.LanguageRefSetMemberList;
import org.ihtsdo.otf.ts.helpers.ModuleDependencyRefSetMemberList;
import org.ihtsdo.otf.ts.helpers.PfsParameterJpa;
import org.ihtsdo.otf.ts.helpers.RefsetDescriptorRefSetMemberList;
import org.ihtsdo.otf.ts.helpers.RelationshipList;
import org.ihtsdo.otf.ts.helpers.ReleaseInfoList;
import org.ihtsdo.otf.ts.helpers.SimpleMapRefSetMemberList;
import org.ihtsdo.otf.ts.helpers.SimpleRefSetMemberList;
import org.ihtsdo.otf.ts.jpa.ReleaseInfoJpa;
import org.ihtsdo.otf.ts.rf2.AssociationReferenceRefSetMember;
import org.ihtsdo.otf.ts.rf2.AttributeValueRefSetMember;
import org.ihtsdo.otf.ts.rf2.ComplexMapRefSetMember;
import org.ihtsdo.otf.ts.rf2.Concept;
import org.ihtsdo.otf.ts.rf2.Description;
import org.ihtsdo.otf.ts.rf2.DescriptionTypeRefSetMember;
import org.ihtsdo.otf.ts.rf2.LanguageRefSetMember;
import org.ihtsdo.otf.ts.rf2.ModuleDependencyRefSetMember;
import org.ihtsdo.otf.ts.rf2.RefsetDescriptorRefSetMember;
import org.ihtsdo.otf.ts.rf2.Relationship;
import org.ihtsdo.otf.ts.rf2.SimpleMapRefSetMember;
import org.ihtsdo.otf.ts.rf2.SimpleRefSetMember;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Implementation of the "History Service REST Normal Use" Test Cases.
 */
public class HistoryServiceRestNormalUseTest extends HistoryServiceRestTest {

  /**
   * Variables are re-used, but set to top-level for convenience of repeated
   * calls without declarations in each test method.
   */

  /** The terminology id for which to retrieve a test object */
  private static String testId;

  /** The test date/name for the release info routines */
  private static String currentDate;

  /** The minimum pfs parameter object */
  private static PfsParameterJpa pfs;

  /**
   * Create test fixtures per test.
   *
   * @throws Exception the exception
   */
  @Override
  @Before
  public void setup() throws Exception {

    // ensure terminology correctly set
    terminology = "SNOMEDCT";
    version = "latest";

    // release info testing (and teardown removal) information
    currentDate = dtFormat.format(new Date());

    // authentication -- use admin for this test
    authToken = securityService.authenticate(adminUser, adminPassword);

    // default paging
    pfs = new PfsParameterJpa();
    pfs.setStartIndex(0);
    pfs.setMaxResults(10);
  }

  /**
   * Test release info methods
   *
   * @throws Exception
   */
  @SuppressWarnings("static-method")
  @Test
  public void testNormalUseRestHistory001() throws Exception {

    ReleaseInfo releaseInfo = null;
    ReleaseInfoList releaseInfoList = null;

    // getReleaseHistory(String, String)
    // should be 36 release infos for SNOMEDCT
    try {
      releaseInfoList =
          historyService.getReleaseHistory(terminology, authToken);
      assertNotNull(releaseInfoList);
      assertTrue(releaseInfoList.getCount() == 36);
    } catch (Exception e) {
      fail("getReleaseHistory for " + terminology + ", " + authToken
          + " failed");
    }

    // getCurrentReleaseInfo(String, String)
    // should return the 20140731 release
    try {
      releaseInfo =
          historyService.getCurrentReleaseInfo(terminology, authToken);
      assertNotNull(releaseInfo);
      assertTrue(releaseInfo.getName().equals("20140731"));
    } catch (Exception e) {
      fail("getCurrentReleaseInfo for " + terminology + ", " + authToken
          + " failed)");
    }

    // getPlannedReleaseInfo(String, String)
    // should return the 20150131 release
    try {
      releaseInfo =
          historyService.getPlannedReleaseInfo(terminology, authToken);
      assertNotNull(releaseInfo);
      assertTrue(releaseInfo.getName().equals("20150131"));
    } catch (Exception e) {
      fail("getPlannedReleaseInfo for " + terminology + ", " + authToken
          + " failed)");
    }

    // getPreviousReleaseInfo(String, String)
    // this invocation should return the 20140131 release
    try {
      releaseInfo =
          historyService.getPreviousReleaseInfo(terminology, authToken);
      assertNotNull(releaseInfo);
      assertTrue(releaseInfo.getName().equals("20140131"));
    } catch (Exception e) {
      fail("getPreviousReleaseInfo for " + terminology + ", " + authToken
          + " failed)");
    }
  }

  /**
   * Test add/update/remove releaseInfo use rest history0011.
   *
   *
   * @throws Exception the exception
   */

  @Test
  public void testNormalUseRestHistory002() throws Exception {

    ReleaseInfo releaseInfo, releaseInfo2;

    // addReleaseInfo(ReleaseInfoJpa, String)
    releaseInfo = new ReleaseInfoJpa();
    releaseInfo.setDescription("test description");
    releaseInfo.setEffectiveTime(new Date());
    releaseInfo.setName(currentDate);
    releaseInfo.setPlanned(false);
    releaseInfo.setPublished(true);
    releaseInfo.setTerminology(terminology);
    releaseInfo.setTerminologyVersion(dtFormat.format(new Date()));

    try {
      releaseInfo =
          historyService
              .addReleaseInfo((ReleaseInfoJpa) releaseInfo, authToken);
      assertNotNull(releaseInfo);
      assertNotNull(releaseInfo.getId());
    } catch (Exception e) {
      e.printStackTrace();
      fail("addRelease info failed");

    }

    // wait to ensure object successfully added
    Thread.sleep(1000);

    // getReleaseInfo(String, String, String)
    releaseInfo2 = null;
    try {
      releaseInfo2 =
          historyService.getReleaseInfo(terminology, currentDate, authToken);
      assertNotNull(releaseInfo2);
      assertTrue(releaseInfo2.getName().equals(currentDate));
    } catch (Exception e) {
      e.printStackTrace();
      fail("getReleaseInfo failed");
    }

    // updateReleaseInfo(ReleaseInfoJpa, String)
    // only need to test one field, GetterSetterTest covers others
    try {
      releaseInfo2.setName("newTestName");
      historyService
          .updateReleaseInfo((ReleaseInfoJpa) releaseInfo2, authToken);
      releaseInfo2 =
          historyService.getReleaseInfo(terminology, "newTestName", authToken);
      assertFalse(releaseInfo.getName().equals(releaseInfo2.getName()));
    } catch (Exception e) {
      e.printStackTrace();
      fail("updateReleaseInfo failed");
    }

    // re-try getCurrent/PreviousReleaseInfo
    try {
      releaseInfo =
          historyService.getCurrentReleaseInfo(terminology, authToken);
      releaseInfo2 =
          historyService.getPreviousReleaseInfo(terminology, authToken);

      assertNotNull(releaseInfo);
      assertNotNull(releaseInfo2);
      assertFalse(releaseInfo.equals(releaseInfo2));
      assertTrue(releaseInfo2.getEffectiveTime().compareTo(
          releaseInfo.getEffectiveTime()) < 0);
    } catch (Exception e) {
      fail("Second get current/previous release info failed");
    }

    // removeReleaseInfo(Long, String)
    try {
      releaseInfo =
          historyService.getReleaseInfo(terminology, "newTestName", authToken);
      assertNotNull(releaseInfo);
      assertNotNull(releaseInfo.getId());
      historyService.removeReleaseInfo(releaseInfo.getId(), authToken);
      releaseInfo =
          historyService.getReleaseInfo(terminology, "newTestName", authToken);
      assertNull(releaseInfo);
    } catch (Exception e) {
      fail("Remove release info failed");
    }

    String releaseVersion = dtFormat.format(new Date());
    try {
      historyService.startEditingCycle(releaseVersion, terminology, version,
          authToken);
    } catch (Exception e) {
      fail("Unexpected exception trying to start the editing cycle");
    }

    /**
     * finishReleaseCycle not currently used, untested
     */
  }

  /**
   * Test concept methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory003() throws Exception {

    objectNames.remove("Concept");

    // The test id for this concept
    testId = "321087001";

    ConceptList results;

    // get the component
    Concept c =
        contentService
            .getSingleConcept(testId, terminology, version, authToken);

    // test all concepts modified over all time
    results =
        historyService.findConceptsModifiedSinceDate(terminology, "19700101",
            pfs, authToken);
    assertTrue(results.getTotalCount() == 10293);

    // test all concepts modified after lower bound date
    results =
        historyService.findConceptsModifiedSinceDate(terminology, "20080131",
            pfs, authToken);
    assertTrue(results.getTotalCount() == 2652);

    // test paging filtering sorting based on truncated set

    // set pfs to no max results -- find revisions methods currently do not
    // return total
    // count correctly
    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findConceptRevisions(c.getId().toString(), "19700101",
            currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 12);

    // test revisions method lower bound
    results =
        historyService.findConceptRevisions(c.getId().toString(), "20060131",
            currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 3);

    // test revisions method upper bound
    results =
        historyService.findConceptRevisions(c.getId().toString(), "19700101",
            "20040131", pfs, authToken);
    assertTrue(results.getTotalCount() == 9);

    // test retrieve release revision at specific release time
    // - time should match
    // - definition status id should match
    c =
        historyService.findConceptReleaseRevision(c.getId().toString(),
            "20060131", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20060131"));
    assertTrue(c.getDefinitionStatusId().equals("900000000000073002"));

    // NOTE: Concept has findDeepModified method, tested independently here
    // Only testing paging, as date restriction is tested individually
    // for each of the calls used by this routine

    results =
        historyService.findConceptsDeepModifiedSinceDate(terminology,
            "19700101", null, authToken);

    assertTrue(results.getCount() == 10293);

    // test paging
    pfs.setMaxResults(10);
    pfs.setStartIndex(0);
    ConceptList pagedResults =
        historyService.findConceptsDeepModifiedSinceDate(terminology,
            "19700101", pfs, authToken);

    assertTrue(results.getObjects().subList(0, 10)
        .equals(pagedResults.getObjects()));

    pfs.setMaxResults(10);
    pfs.setStartIndex(100);
    pagedResults =
        historyService.findConceptsDeepModifiedSinceDate(terminology,
            "19700101", pfs, authToken);

    assertTrue(results.getObjects().subList(100, 110)
        .equals(pagedResults.getObjects()));

    // test with date -- arbitrary
    // number validated through independent sql queries
    String testDate = "20130731";
    pfs.setMaxResults(-1);
    pfs.setStartIndex(-1);
    results =
        historyService.findConceptsDeepModifiedSinceDate(terminology, testDate,
            pfs, authToken);

    assertTrue(results.getCount() == 3096);

  }

  /**
   * Test description methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory004() throws Exception {

    objectNames.remove("Description");

    // The test id for this description
    testId = "387512014";

    DescriptionList results;

    // get the component
    Description c =
        contentService.getDescription(testId, terminology, version, authToken);

    // test all descriptions modified over all time
    results =
        historyService.findDescriptionsModifiedSinceDate(terminology,
            "19700101", pfs, authToken);
    assertTrue(results.getTotalCount() == 34105);

    // test all descriptions modified after lower bound date
    results =
        historyService.findDescriptionsModifiedSinceDate(terminology,
            "20080131", pfs, authToken);
    assertTrue(results.getTotalCount() == 6884);

    // set pfs to no max results
    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findDescriptionRevisions(c.getId().toString(),
            "19700101", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 5);

    // test revisions method lower bound
    results =
        historyService.findDescriptionRevisions(c.getId().toString(),
            "20030731", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 4);

    // test revisions method upper bound
    results =
        historyService.findDescriptionRevisions(c.getId().toString(),
            "19700731", "20030731", pfs, authToken);
    assertTrue(results.getTotalCount() == 4);

    // test retrieve release revision at specific release time
    // - time should match
    // - should be unpublished (previous version at same time published)
    c =
        historyService.findDescriptionReleaseRevision(c.getId().toString(),
            "20030731", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20030731"));
    assertTrue(c.isPublished() == false);

  }

  /**
   * Test relationship methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory005() throws Exception {

    objectNames.remove("Relationship");

    // The test id for this component
    testId = "501314023";

    RelationshipList results;

    // get the component
    Relationship c =
        contentService.getRelationship(testId, terminology, version, authToken);

    // test all relationships modified over all time
    results =
        historyService.findRelationshipsModifiedSinceDate(terminology,
            "19700101", pfs, authToken);
    assertTrue(results.getTotalCount() == 79098);

    // test all relationships modified after lower bound date
    results =
        historyService.findRelationshipsModifiedSinceDate(terminology,
            "20080131", pfs, authToken);
    assertTrue(results.getTotalCount() == 45453);

    // set pfs to no max results

    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findRelationshipRevisions(c.getId().toString(),
            "19700101", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 13);

    // test revisions method lower bound
    results =
        historyService.findRelationshipRevisions(c.getId().toString(),
            "20030731", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 10);

    // test revisions method upper bound
    results =
        historyService.findRelationshipRevisions(c.getId().toString(),
            "19700731", "20030731", pfs, authToken);
    assertTrue(results.getTotalCount() == 4);

    // test retrieve release revision at specific release time
    // - time should match
    // - should be unpublished (previous version at same time published)
    c =
        historyService.findRelationshipReleaseRevision(c.getId().toString(),
            "20020131", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20020131"));
    assertTrue(c.isPublished() == false);
  }

  /**
   * Test language ref set methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory006() throws Exception {

    objectNames.remove("LanguageRefSetMember");

    // The test id for this component
    testId = "e76075bd-3748-589f-b987-2ada691921ef";

    LanguageRefSetMemberList results;

    // get the component
    LanguageRefSetMember c = null;
    LanguageRefSetMemberList list =
        contentService.getLanguageRefSetMembersForDescription("456353019",
            terminology, version, authToken);
    for (LanguageRefSetMember a : list.getObjects()) {
      if (a.getTerminologyId().equals(testId)) {
        c = a;
      }
    }
    if (c == null)
      fail("Could not retrieve language ref set member");

    // test all descriptions modified over all time
    results =
        historyService.findLanguageRefSetMembersModifiedSinceDate(terminology,
            "19700101", pfs, authToken);
    assertTrue(results.getTotalCount() == 66653);

    // test all descriptions modified after lower bound date
    results =
        historyService.findLanguageRefSetMembersModifiedSinceDate(terminology,
            "20080131", pfs, authToken);
    assertTrue(results.getTotalCount() == 8763);

    // set pfs to no max results -- find methods currently do not return total
    // count correctly
    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findLanguageRefSetMemberRevisions(c.getId().toString(),
            "19700101", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 5);

    // test revisions method lower bound
    results =
        historyService.findLanguageRefSetMemberRevisions(c.getId().toString(),
            "20040731", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 4);

    // test revisions method upper bound
    results =
        historyService.findLanguageRefSetMemberRevisions(c.getId().toString(),
            "19700731", "20040731", pfs, authToken);
    assertTrue(results.getTotalCount() == 2);

    // test retrieve release revision at specific release time
    // - time should match
    // - should be unpublished (previous version at same time published)
    c =
        historyService.findLanguageRefSetMemberReleaseRevision(c.getId()
            .toString(), "20080731", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20080731"));
    assertTrue(c.isPublished() == false);
  }

  /**
   * Test association reference ref set methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory007() throws Exception {

    objectNames.remove("AssociationReferenceRefSetMember");

    // The test id for this association reference ref set member
    testId = "cf39de4d-bbb9-59c3-b049-82a6c31ce87a";

    AssociationReferenceRefSetMemberList results;

    // no direct REST call to get reference ref set member
    // instead call by refset id and cycle until test id matched
    AssociationReferenceRefSetMemberList list =
        contentService.getAssociationReferenceRefSetMembersForConcept(
            "398901001", terminology, version, authToken);
    AssociationReferenceRefSetMember<?> c = null;
    for (AssociationReferenceRefSetMember<?> a : list.getObjects()) {
      if (a.getTerminologyId().equals(testId)) {
        c = a;
      }
    }
    if (c == null)
      fail("Could not retrieve association reference ref set member");

    // test all relationships modified over all time
    results =
        historyService.findAssociationReferenceRefSetMembersModifiedSinceDate(
            terminology, "19700101", pfs, authToken);
    assertTrue(results.getTotalCount() == 435);

    // test all relationships modified after lower bound date
    results =
        historyService.findAssociationReferenceRefSetMembersModifiedSinceDate(
            terminology, "20080131", pfs, authToken);
    assertTrue(results.getTotalCount() == 134);

    // set pfs to no max results -- find methods currently do not return total
    // count correctly
    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findAssociationReferenceRefSetMemberRevisions(c.getId()
            .toString(), "19700101", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 2);

    // test revisions method lower bound
    results =
        historyService.findAssociationReferenceRefSetMemberRevisions(c.getId()
            .toString(), "20080731", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 1);

    // test revisions method upper bound
    results =
        historyService.findAssociationReferenceRefSetMemberRevisions(c.getId()
            .toString(), "19700731", "20080730", pfs, authToken);
    assertTrue(results.getTotalCount() == 1);

    // test retrieve release revision at specific release time
    // - time should match
    // - no other test, no examples of multiple revisions at same efffective
    // time
    c =
        historyService.findAssociationReferenceRefSetMemberReleaseRevision(c
            .getId().toString(), "20080731", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20080731"));
  }

  /**
   * Test attribute value ref set methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory008() throws Exception {

    objectNames.remove("AttributeValueRefSetMember");

    // The test id for this component
    testId = "de184ffc-03f3-5dae-9f2b-6c46020ede8a";

    AttributeValueRefSetMemberList results;

    // get the component
    AttributeValueRefSetMember<?> c = null;
    AttributeValueRefSetMemberList list =
        contentService.getAttributeValueRefSetMembersForDescription("89332015",
            terminology, version, authToken);
    for (AttributeValueRefSetMember<?> a : list.getObjects()) {
      if (a.getTerminologyId().equals(testId)) {
        c = a;
      }
    }
    if (c == null)
      fail("Could not retrieve attribute value ref set member");

    // test all attribute value ref set members modified over all time
    results =
        historyService.findAttributeValueRefSetMembersModifiedSinceDate(
            terminology, "19700101", pfs, authToken);
    assertTrue(results.getTotalCount() == 1994);

    // test all attribute value ref set members modified after lower bound date
    results =
        historyService.findAttributeValueRefSetMembersModifiedSinceDate(
            terminology, "20080131", pfs, authToken);
    assertTrue(results.getTotalCount() == 557);

    // set pfs to no max results -- find methods currently do not return total
    // count correctly
    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findAttributeValueRefSetMemberRevisions(c.getId()
            .toString(), "19700101", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 4);

    // test revisions method lower bound
    results =
        historyService.findAttributeValueRefSetMemberRevisions(c.getId()
            .toString(), "20050131", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 3);

    // test revisions method upper bound
    results =
        historyService.findAttributeValueRefSetMemberRevisions(c.getId()
            .toString(), "19700731", "20050131", pfs, authToken);
    assertTrue(results.getTotalCount() == 2);

    // test retrieve release revision at specific release time
    // - time should match
    c =
        historyService.findAttributeValueRefSetMemberReleaseRevision(c.getId()
            .toString(), "20050131", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20050131"));
  }

  /**
   * Test complex map ref set methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory009() throws Exception {

    objectNames.remove("ComplexMapRefSetMember");

    // The test id for this component
    testId = "055c30ae-b018-5b82-bd3d-74ff9451de15";

    ComplexMapRefSetMemberList results;

    // get the component
    ComplexMapRefSetMember c = null;
    ComplexMapRefSetMemberList list =
        contentService.getComplexMapRefSetMembersForConcept("297249002",
            terminology, version, authToken);
    for (ComplexMapRefSetMember a : list.getObjects()) {
      if (a.getTerminologyId().equals(testId))
        c = a;
    }
    if (c == null)
      fail("Could not retrieve complex map ref set member");

    // test all complex map ref set members modified over all time
    results =
        historyService.findComplexMapRefSetMembersModifiedSinceDate(
            terminology, "19700101", pfs, authToken);
    assertTrue(results.getTotalCount() == 8731);

    // test all complex map ref set members modified after lower bound date
    results =
        historyService.findComplexMapRefSetMembersModifiedSinceDate(
            terminology, "20080131", pfs, authToken);
    assertTrue(results.getTotalCount() == 5021);

    // set pfs to no max results -- find methods currently do not return total
    // count correctly
    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findComplexMapRefSetMemberRevisions(
            c.getId().toString(), "19700101", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 5);

    // test revisions method lower bound
    results =
        historyService.findComplexMapRefSetMemberRevisions(
            c.getId().toString(), "20060731", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 3);

    // test revisions method upper bound
    results =
        historyService.findComplexMapRefSetMemberRevisions(
            c.getId().toString(), "19700731", "20060731", pfs, authToken);
    assertTrue(results.getTotalCount() == 3);

    // test retrieve release revision at specific release time
    // - time should match
    c =
        historyService.findComplexMapRefSetMemberReleaseRevision(c.getId()
            .toString(), "20060731", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20060731"));
  }

  /**
   * Test description type ref set methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory010() throws Exception {

    objectNames.remove("DescriptionTypeRefSetMember");

    // The test id for this component
    testId = "807f775b-1d66-5069-b58e-a37ace985dcf";

    DescriptionTypeRefSetMemberList results;

    // get the component
    DescriptionTypeRefSetMember c = null;
    DescriptionTypeRefSetMemberList list =
        contentService.getDescriptionTypeRefSetMembersForConcept(
            "900000000000550004", terminology, version, authToken);
    for (DescriptionTypeRefSetMember a : list.getObjects()) {
      if (a.getTerminologyId().equals(testId))
        c = a;
    }
    if (c == null)
      fail("Could not retrieve description type ref set member");

    // test all description type ref set members modified over all time
    results =
        historyService.findDescriptionTypeRefSetMembersModifiedSinceDate(
            terminology, "19700101", pfs, authToken);
    assertTrue(results.getTotalCount() == 3);

    // test all description type ref set members modified after lower bound date
    results =
        historyService.findDescriptionTypeRefSetMembersModifiedSinceDate(
            terminology, "20080131", pfs, authToken);
    assertTrue(results.getTotalCount() == 1);

    // set pfs to no max results -- find methods currently do not return total
    // count correctly
    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findDescriptionTypeRefSetMemberRevisions(c.getId()
            .toString(), "19700101", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 2);

    // test revisions method lower bound
    results =
        historyService.findDescriptionTypeRefSetMemberRevisions(c.getId()
            .toString(), "20140131", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 1);

    // test revisions method upper bound
    results =
        historyService.findDescriptionTypeRefSetMemberRevisions(c.getId()
            .toString(), "19700731", "20140130", pfs, authToken);
    assertTrue(results.getTotalCount() == 1);

    // test retrieve release revision at specific release time
    // - time should match
    c =
        historyService.findDescriptionTypeRefSetMemberReleaseRevision(c.getId()
            .toString(), "20140131", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20140131"));
  }

  /**
   * Test module dependency ref set methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory011() throws Exception {

    objectNames.remove("ModuleDependencyRefSetMember");

    // The test id for this component
    testId = "1244116f-fdb5-5645-afcc-5281288409da";

    ModuleDependencyRefSetMemberList results;

    // get the component
    ModuleDependencyRefSetMember c = null;
    ModuleDependencyRefSetMemberList list =
        contentService.getModuleDependencyRefSetMembersForModule(
            "900000000000207008", terminology, version, authToken);
    for (ModuleDependencyRefSetMember a : list.getObjects()) {
      if (a.getTerminologyId().equals(testId))
        c = a;
    }
    if (c == null)
      fail("Could not retrieve module dependency ref set member");

    // test all module dependency ref set members modified over all time
    results =
        historyService.findModuleDependencyRefSetMembersModifiedSinceDate(
            terminology, "19700101", pfs, authToken);
    assertTrue(results.getTotalCount() == 3);

    // test all module dependency ref set members modified after lower bound
    // date
    results =
        historyService.findModuleDependencyRefSetMembersModifiedSinceDate(
            terminology, "20080131", pfs, authToken);
    assertTrue(results.getTotalCount() == 3);

    // set pfs to no max results -- find methods currently do not return total
    // count correctly
    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findModuleDependencyRefSetMemberRevisions(c.getId()
            .toString(), "19700101", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 26);

    // test revisions method lower bound
    results =
        historyService.findModuleDependencyRefSetMemberRevisions(c.getId()
            .toString(), "20140131", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 2);

    // test revisions method upper bound
    results =
        historyService.findModuleDependencyRefSetMemberRevisions(c.getId()
            .toString(), "19700731", "20140131", pfs, authToken);
    assertTrue(results.getTotalCount() == 25);

    // test retrieve release revision at specific release time
    // - time should match
    c =
        historyService.findModuleDependencyRefSetMemberReleaseRevision(c
            .getId().toString(), "20140131", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20140131"));
  }

  /**
   * Test refset descriptor ref set methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory012() throws Exception {

    objectNames.remove("RefsetDescriptorRefSetMember");

    // The test id for this component
    testId = "576ed8c3-1227-5489-b782-760a3b729b94";

    RefsetDescriptorRefSetMemberList results;

    // get the component
    RefsetDescriptorRefSetMember c = null;
    RefsetDescriptorRefSetMemberList list =
        contentService.getRefsetDescriptorRefSetMembers("447563008",
            terminology, version, authToken);
    for (RefsetDescriptorRefSetMember a : list.getObjects()) {
      if (a.getTerminologyId().equals(testId))
        c = a;
    }
    if (c == null)
      fail("Could not retrieve refset descriptor ref set member");

    // test all refset descriptor ref set members modified over all time
    results =
        historyService.findRefsetDescriptorRefSetMembersModifiedSinceDate(
            terminology, "19700101", pfs, authToken);
    assertTrue(results.getTotalCount() == 68);

    // test all refset descriptor ref set members modified after lower bound
    // date
    results =
        historyService.findRefsetDescriptorRefSetMembersModifiedSinceDate(
            terminology, "20080131", pfs, authToken);
    assertTrue(results.getTotalCount() == 22);

    // set pfs to no max results -- find methods currently do not return total
    // count correctly
    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findRefsetDescriptorRefSetMemberRevisions(c.getId()
            .toString(), "19700101", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 1);

    // test revisions method lower bound
    results =
        historyService.findRefsetDescriptorRefSetMemberRevisions(c.getId()
            .toString(), "20020131", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 1);

    // test revisions method upper bound
    results =
        historyService.findRefsetDescriptorRefSetMemberRevisions(c.getId()
            .toString(), "19700731", "20020131", pfs, authToken);
    assertTrue(results.getTotalCount() == 1);

    // test retrieve release revision at specific release time
    // - time should match
    c =
        historyService.findRefsetDescriptorRefSetMemberReleaseRevision(c
            .getId().toString(), "20020131", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20020131"));
  }

  /**
   * Test simple map ref set member methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory013() throws Exception {

    objectNames.remove("SimpleMapRefSetMember");

    // The test id for this component
    testId = "f8dbedb7-12a7-5e33-bbc8-3d1252c77820";

    SimpleMapRefSetMemberList results;

    // get the component
    SimpleMapRefSetMember c = null;
    SimpleMapRefSetMemberList list =
        contentService.getSimpleMapRefSetMembersForConcept("244476009",
            terminology, version, authToken);
    for (SimpleMapRefSetMember a : list.getObjects()) {
      if (a.getTerminologyId().equals(testId))
        c = a;
    }
    if (c == null)
      fail("Could not retrieve complex map ref set member");

    // test all simple map ref set members modified over all time
    results =
        historyService.findSimpleMapRefSetMembersModifiedSinceDate(terminology,
            "19700101", pfs, authToken);
    assertTrue(results.getTotalCount() == 22060);

    // test all simple map ref set members modified after lower bound date
    results =
        historyService.findSimpleMapRefSetMembersModifiedSinceDate(terminology,
            "20080131", pfs, authToken);
    assertTrue(results.getTotalCount() == 1956);

    // set pfs to no max results -- find methods currently do not return total
    // count correctly
    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findSimpleMapRefSetMemberRevisions(c.getId().toString(),
            "19700101", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 5);

    // test revisions method lower bound
    results =
        historyService.findSimpleMapRefSetMemberRevisions(c.getId().toString(),
            "20050131", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 3);

    // test revisions method upper bound
    results =
        historyService.findSimpleMapRefSetMemberRevisions(c.getId().toString(),
            "19700731", "20050131", pfs, authToken);
    assertTrue(results.getTotalCount() == 3);

    // test retrieve release revision at specific release time
    // - time should match
    c =
        historyService.findSimpleMapRefSetMemberReleaseRevision(c.getId()
            .toString(), "20050131", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20050131"));

  }

  /**
   * Test simple ref set member methods
   * @throws Exception
   */
  @Test
  public void testNormalUseRestHistory014() throws Exception {

    objectNames.remove("SimpleRefSetMember");

    // The test id for this component
    testId = "c0a26c19-e051-5cfa-86c5-a625ca44e690";

    SimpleRefSetMemberList results;

    // get the component
    SimpleRefSetMember c = null;
    SimpleRefSetMemberList list =
        contentService.getSimpleRefSetMembersForConcept("333536009",
            terminology, version, authToken);
    for (SimpleRefSetMember a : list.getObjects()) {
      if (a.getTerminologyId().equals(testId))
        c = a;
    }
    if (c == null)
      fail("Could not retrieve simple ref set member");

    // test all simple ref set members modified over all time
    results =
        historyService.findSimpleRefSetMembersModifiedSinceDate(terminology,
            "19700101", pfs, authToken);
    assertTrue(results.getTotalCount() == 35);

    // test all simple ref set members modified after lower bound date
    results =
        historyService.findSimpleRefSetMembersModifiedSinceDate(terminology,
            "20080131", pfs, authToken);
    assertTrue(results.getTotalCount() == 14);

    // set pfs to no max results -- find methods currently do not return total
    // count correctly
    pfs.setMaxResults(-1);

    // test revisions method -- range: all time
    results =
        historyService.findSimpleRefSetMemberRevisions(c.getId().toString(),
            "19700101", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 4);

    // test revisions method lower bound
    results =
        historyService.findSimpleRefSetMemberRevisions(c.getId().toString(),
            "20060131", currentDate, pfs, authToken);
    assertTrue(results.getTotalCount() == 3);

    // test revisions method upper bound
    results =
        historyService.findSimpleRefSetMemberRevisions(c.getId().toString(),
            "19700731", "20060131", pfs, authToken);
    assertTrue(results.getTotalCount() == 2);

    // test retrieve release revision at specific release time
    // - time should match
    c =
        historyService.findSimpleRefSetMemberReleaseRevision(c.getId()
            .toString(), "20060131", authToken);
    assertTrue(dtFormat.format(c.getEffectiveTime()).equals("20060131"));

  }

  /**
   * Teardown.
   *
   * @throws Exception the exception
   */
  @Override
  @After
  public void teardown() throws Exception {

    // NOTE: When contents of test 002 are enabled
    // this teardown class must remove release info
    // objects created by testing addReleaseInfo
    // and startEditingCycle
    ReleaseInfo releaseInfo =
        historyService.getReleaseInfo(terminology, currentDate, authToken);
    if (releaseInfo != null) {
      historyService.removeReleaseInfo(releaseInfo.getId(), authToken);
    }

    // logout
    securityService.logout(authToken);

  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<class xmlns="http://xml.phpdox.net/src" full="cymapgt\core\application\spreadsheet\SpreadsheetProcessor\PHPExcelWrapper\PHPExcelHFCodes" namespace="cymapgt\core\application\spreadsheet\SpreadsheetProcessor\PHPExcelWrapper" name="PHPExcelHFCodes" abstract="false" final="false" start="14" end="45">
  <file path="/home/rhossis/NetBeansProjects/cymapgt/core/application/spreadsheet/src/SpreadsheetProcessor/PHPExcelWrapper" file="PHPExcelHFCodes.php" realpath="/home/rhossis/NetBeansProjects/cymapgt/core/application/spreadsheet/src/SpreadsheetProcessor/PHPExcelWrapper/PHPExcelHFCodes.php" size="1847" time="2014-10-01T07:56:09+03:00" unixtime="1412139369" sha1="67ad48dfca1b512f780fe1fb69873a6b71c45db0" relative="SpreadsheetProcessor/PHPExcelWrapper/PHPExcelHFCodes.php"/>
  <docblock>
    <description compact="PHPExcelHFCodes This enables use of OpenXML standards for header codes. These can be used when declaring inline formatting on a worksheets Header/Footer"/>
    <category value="CYMAPGTReporting"/>
    <package value="core.application.spreadsheet.SpreadsheetProcessor"/>
    <copyright value="Copyright (c) 2012 CYMAP-GT"/>
  </docblock>
  <constant name="HFCODE_LEFTSECTION" value="'&L'"/>
  <constant name="HFCODE_CURRENTPAGE" value="'&P'"/>
  <constant name="HFCODE_TOTALPAGES" value="'&N'"/>
  <constant name="HFCODE_FONTSIZE" value="'&font size'"/>
  <constant name="HFCODE_FONTCOLOR" value="'&K'"/>
  <constant name="HFCODE_STRIKETHROUGH" value="'&S'"/>
  <constant name="HFCODE_SUPERSCRIPT" value="'&X'"/>
  <constant name="HFCODE_SUBSCRIPT" value="'&Y'"/>
  <constant name="HFCODE_CENTERSECTION" value="'&C'"/>
  <constant name="HFCODE_DATE" value="'&D'"/>
  <constant name="HFCODE_TIME" value="'&T'"/>
  <constant name="HFCODE_PICTUREASBACKGROUND" value="'&G'"/>
  <constant name="HFCODE_TEXTSINGLEUNDERLINE" value="'&U'"/>
  <constant name="HFCODE_DOUBLEUNDERLINE" value="'&E'"/>
  <constant name="HFCODE_RIGHTSECTION" value="'&R'"/>
  <constant name="HFCODE_FILEPATH" value="'&Z'"/>
  <constant name="HFCODE_FILENAME" value="'&F'"/>
  <constant name="HFCODE_SHEETTABNAME" value="'&A'"/>
  <constant name="HFCODE_ADDTOPAGENO" value="'&+'"/>
  <constant name="HFCODE_SUBTRACTFROMPAGENO" value="'&-'"/>
  <constant name="HFCODE_FONTNAMEANDTYPE" value="'&"font name,font type"'"/>
  <constant name="HFCODE_BOLDFONTSTYLEA" value="'&"-,Bold"'"/>
  <constant name="HFCODE_BOLDFONTSTYLEB" value="'&B'"/>
  <constant name="HFCODE_REGULARFONTSTYLE" value="'&"-,Regular"'"/>
  <constant name="HFCODE_ITALICFONTSTYLEA" value="'&"-,Italic"'"/>
  <constant name="HFCODE_ITALICFONTSTYLEB" value="'&I'"/>
  <constant name="HFCODE_BOLDITALICFONTSTYLE" value="'&"-,Bold Italic"'"/>
  <constant name="HFCODE_OUTLINESTYLE" value="'&0'"/>
  <constant name="HFCODE_SHADOWSTYLE" value="'&H'"/>
</class>

redpajama_set_name: RedPajamaGithub


text:
///////////////////////////////////////////////////////////////////////////////
// Name:        wx/bitmap.h
// Purpose:     wxBitmap class interface
// Author:      Vaclav Slavik
// Modified by:
// Created:     22.04.01
// RCS-ID:      $Id$
// Copyright:   (c) wxWidgets team
// Licence:     wxWindows licence
///////////////////////////////////////////////////////////////////////////////

#ifndef _WX_BITMAP_H_BASE_
#define _WX_BITMAP_H_BASE_

// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------

#include "wx/string.h"
#include "wx/gdicmn.h"  // for wxBitmapType
#include "wx/colour.h"
#include "wx/image.h"

class WXDLLIMPEXP_FWD_CORE wxBitmap;
class WXDLLIMPEXP_FWD_CORE wxBitmapHandler;
class WXDLLIMPEXP_FWD_CORE wxIcon;
class WXDLLIMPEXP_FWD_CORE wxMask;
class WXDLLIMPEXP_FWD_CORE wxPalette;

// ----------------------------------------------------------------------------
// wxVariant support
// ----------------------------------------------------------------------------

#if wxUSE_VARIANT
#include "wx/variant.h"
DECLARE_VARIANT_OBJECT_EXPORTED(wxBitmap,WXDLLIMPEXP_CORE)
#endif

// ----------------------------------------------------------------------------
// wxMask represents the transparent area of the bitmap
// ----------------------------------------------------------------------------

// TODO: all implementation of wxMask, except the generic one,
//       do not derive from wxMaskBase,,, they should
class WXDLLIMPEXP_CORE wxMaskBase : public wxObject
{
public:
    // create the mask from bitmap pixels of the given colour
    bool Create(const wxBitmap& bitmap, const wxColour& colour);

#if wxUSE_PALETTE
    // create the mask from bitmap pixels with the given palette index
    bool Create(const wxBitmap& bitmap, int paletteIndex);
#endif // wxUSE_PALETTE

    // create the mask from the given mono bitmap
    bool Create(const wxBitmap& bitmap);

protected:
    // this function is called from Create() to free the existing mask data
    virtual void FreeData() = 0;

    // these functions must be overridden to implement the corresponding public
    // Create() methods, they shouldn't call FreeData() as it's already called
    // by the public wrappers
    virtual bool InitFromColour(const wxBitmap& bitmap,
                                const wxColour& colour) = 0;
    virtual bool InitFromMonoBitmap(const wxBitmap& bitmap) = 0;
};

#if defined(__WXDFB__) || \
    defined(__WXMAC__) || \
    defined(__WXGTK__) || \
    defined(__WXCOCOA__) || \
    defined(__WXMOTIF__) || \
    defined(__WXX11__)
    #define wxUSE_BITMAP_BASE 1
#else
    #define wxUSE_BITMAP_BASE 0
#endif

// a more readable way to tell
#define wxBITMAP_SCREEN_DEPTH       (-1)

// All ports except wxMSW and wxOS2 use wxBitmapHandler and wxBitmapBase as
// base class for wxBitmapHandler; wxMSW and wxOS2 use wxGDIImageHandler as
// base class since it allows some code reuse there.
#if wxUSE_BITMAP_BASE

// ----------------------------------------------------------------------------
// wxBitmapHandler: class which knows how to create/load/save bitmaps in
// different formats
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_CORE wxBitmapHandler : public wxObject
{
public:
    wxBitmapHandler() { m_type = wxBITMAP_TYPE_INVALID; }
    virtual ~wxBitmapHandler() { }

    // NOTE: the following functions should be pure virtuals, but they aren't
    //       because otherwise almost all ports would have to implement
    //       them as "return false"...

    virtual bool Create(wxBitmap *WXUNUSED(bitmap), const void* WXUNUSED(data),
                         wxBitmapType WXUNUSED(type), int WXUNUSED(width), int WXUNUSED(height),
                         int WXUNUSED(depth) = 1)
        { return false; }

    virtual bool LoadFile(wxBitmap *WXUNUSED(bitmap), const wxString& WXUNUSED(name),
                           wxBitmapType WXUNUSED(type), int WXUNUSED(desiredWidth),
                           int WXUNUSED(desiredHeight))
        { return false; }

    virtual bool SaveFile(const wxBitmap *WXUNUSED(bitmap), const wxString& WXUNUSED(name),
                           wxBitmapType WXUNUSED(type), const wxPalette *WXUNUSED(palette) = NULL) const
        { return false; }

    void SetName(const wxString& name)      { m_name = name; }
    void SetExtension(const wxString& ext)  { m_extension = ext; }
    void SetType(wxBitmapType type)         { m_type = type; }
    const wxString& GetName() const         { return m_name; }
    const wxString& GetExtension() const    { return m_extension; }
    wxBitmapType GetType() const            { return m_type; }

private:
    wxString      m_name;
    wxString      m_extension;
    wxBitmapType  m_type;

    DECLARE_ABSTRACT_CLASS(wxBitmapHandler)
};

// ----------------------------------------------------------------------------
// wxBitmap: class which represents platform-dependent bitmap (unlike wxImage)
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_CORE wxBitmapBase : public wxGDIObject
{
public:
    /*
    Derived class must implement these:

    wxBitmap();
    wxBitmap(const wxBitmap& bmp);
    wxBitmap(const char bits[], int width, int height, int depth = 1);
    wxBitmap(int width, int height, int depth = wxBITMAP_SCREEN_DEPTH);
    wxBitmap(const wxSize& sz, int depth = wxBITMAP_SCREEN_DEPTH);
    wxBitmap(const char* const* bits);
    wxBitmap(const wxString &filename, wxBitmapType type = wxBITMAP_TYPE_XPM);
    wxBitmap(const wxImage& image, int depth = wxBITMAP_SCREEN_DEPTH);

    static void InitStandardHandlers();
    */

    virtual bool Create(int width, int height, int depth = wxBITMAP_SCREEN_DEPTH) = 0;
    virtual bool Create(const wxSize& sz, int depth = wxBITMAP_SCREEN_DEPTH) = 0;

    virtual int GetHeight() const = 0;
    virtual int GetWidth() const = 0;
    virtual int GetDepth() const = 0;

    wxSize GetSize() const
        { return wxSize(GetWidth(), GetHeight()); }

#if wxUSE_IMAGE
    virtual wxImage ConvertToImage() const = 0;

    // Convert to disabled (dimmed) bitmap.
    wxBitmap ConvertToDisabled(unsigned char brightness = 255) const;
#endif // wxUSE_IMAGE

    virtual wxMask *GetMask() const = 0;
    virtual void SetMask(wxMask *mask) = 0;

    virtual wxBitmap GetSubBitmap(const wxRect& rect) const = 0;

    virtual bool SaveFile(const wxString &name, wxBitmapType type,
                          const wxPalette *palette = NULL) const = 0;
    virtual bool LoadFile(const wxString &name, wxBitmapType type) = 0;

    /*
       If raw bitmap access is supported (see wx/rawbmp.h), the following
       methods should be implemented:

       virtual bool GetRawData(wxRawBitmapData *data) = 0;
       virtual void UngetRawData(wxRawBitmapData *data) = 0;
     */

#if wxUSE_PALETTE
    virtual wxPalette *GetPalette() const = 0;
    virtual void SetPalette(const wxPalette& palette) = 0;
#endif // wxUSE_PALETTE

    // copies the contents and mask of the given (colour) icon to the bitmap
    virtual bool CopyFromIcon(const wxIcon& icon) = 0;

    // implementation:
    virtual void SetHeight(int height) = 0;
    virtual void SetWidth(int width) = 0;
    virtual void SetDepth(int depth) = 0;

    // Format handling
    static inline wxList& GetHandlers() { return sm_handlers; }
    static void AddHandler(wxBitmapHandler *handler);
    static void InsertHandler(wxBitmapHandler *handler);
    static bool RemoveHandler(const wxString& name);
    static wxBitmapHandler *FindHandler(const wxString& name);
    static wxBitmapHandler *FindHandler(const wxString& extension, wxBitmapType bitmapType);
    static wxBitmapHandler *FindHandler(wxBitmapType bitmapType);

    //static void InitStandardHandlers();
    //  (wxBitmap must implement this one)

    static void CleanUpHandlers();

    // this method is only used by the generic implementation of wxMask
    // currently but could be useful elsewhere in the future: it can be
    // overridden to quantize the colour to correspond to bitmap colour depth
    // if necessary; default implementation simply returns the colour as is
    virtual wxColour QuantizeColour(const wxColour& colour) const
    {
        return colour;
    }

protected:
    static wxList sm_handlers;

    DECLARE_ABSTRACT_CLASS(wxBitmapBase)
};

#endif // wxUSE_BITMAP_BASE

// the wxBITMAP_DEFAULT_TYPE constant defines the default argument value
// for wxBitmap's ctor and wxBitmap::LoadFile() functions.
#if defined(__WXMSW__)
    #define wxBITMAP_DEFAULT_TYPE    wxBITMAP_TYPE_BMP_RESOURCE
    #include "wx/msw/bitmap.h"
#elif defined(__WXMOTIF__)
    #define wxBITMAP_DEFAULT_TYPE    wxBITMAP_TYPE_XPM
    #include "wx/x11/bitmap.h"
#elif defined(__WXGTK20__)
    #ifdef __WINDOWS__
        #define wxBITMAP_DEFAULT_TYPE    wxBITMAP_TYPE_BMP_RESOURCE
    #else
        #define wxBITMAP_DEFAULT_TYPE    wxBITMAP_TYPE_XPM
    #endif
    #include "wx/gtk/bitmap.h"
#elif defined(__WXGTK__)
    #define wxBITMAP_DEFAULT_TYPE    wxBITMAP_TYPE_XPM
    #include "wx/gtk1/bitmap.h"
#elif defined(__WXX11__)
    #define wxBITMAP_DEFAULT_TYPE    wxBITMAP_TYPE_XPM
    #include "wx/x11/bitmap.h"
#elif defined(__WXDFB__)
    #define wxBITMAP_DEFAULT_TYPE    wxBITMAP_TYPE_BMP_RESOURCE
    #include "wx/dfb/bitmap.h"
#elif defined(__WXMAC__)
    #define wxBITMAP_DEFAULT_TYPE    wxBITMAP_TYPE_PICT_RESOURCE
    #include "wx/osx/bitmap.h"
#elif defined(__WXCOCOA__)
    #define wxBITMAP_DEFAULT_TYPE    wxBITMAP_TYPE_BMP_RESOURCE
    #include "wx/cocoa/bitmap.h"
#elif defined(__WXPM__)
    #define wxBITMAP_DEFAULT_TYPE    wxBITMAP_TYPE_BMP_RESOURCE
    #include "wx/os2/bitmap.h"
#endif

#if wxUSE_IMAGE
inline
wxBitmap
#if wxUSE_BITMAP_BASE
wxBitmapBase::
#else
wxBitmap::
#endif
ConvertToDisabled(unsigned char brightness) const
{
    return ConvertToImage().ConvertToDisabled(brightness);
}
#endif // wxUSE_IMAGE

// we must include generic mask.h after wxBitmap definition
#if defined(__WXDFB__)
    #define wxUSE_GENERIC_MASK 1
#else
    #define wxUSE_GENERIC_MASK 0
#endif

#if wxUSE_GENERIC_MASK
    #include "wx/generic/mask.h"
#endif

#endif // _WX_BITMAP_H_BASE_


text:
When you write code to parse, evaluate, or otherwise handle untrustworthy inputs
from the Internet — which is almost everything we do in a web browser! — we like
to follow a simple rule to make sure it's safe enough to do so. The Rule Of 2
is: Pick no more than 2 of

  * untrustworthy inputs;
  * unsafe implementation language; and
  * high privilege.

![alt text](rule-of-2-drawing.png "Venn diagram showing you should always use
a safe language, a sandbox, or not be processing untrustworthy inputs in the first
place.")

(drawing source
[here](https://docs.google.com/drawings/d/12WoPI7-E5NAINHUZqEPGn38aZBYBxq20BgVBjZIvgCQ/edit?usp=sharing))

## Why?

When code that handles untrustworthy inputs at high privilege has bugs, the
resulting vulnerabilities are typically of Critical or High severity. (See our
[Severity Guidelines](severity-guidelines.md).) We'd love to reduce the severity
of such bugs by reducing the amount of damage they can do (lowering their
privilege), avoiding the various types of memory corruption bugs (using a safe
language), or reducing the likelihood that the input is malicious (asserting the
trustworthiness of the source).

For the purposes of this document, our main concern is reducing (and hopefully,
ultimately eliminating) bugs that arise due to _memory unsafety_. [A recent
study by Matt Miller from Microsoft
Security](https://github.com/Microsoft/MSRC-Security-Research/blob/master/presentations/2019_02_BlueHatIL/2019_01%20-%20BlueHatIL%20-%20Trends%2C%20challenge%2C%20and%20shifts%20in%20software%20vulnerability%20mitigation.pdf)
states that "~70% of the vulnerabilities addressed through a security update
each year continue to be memory safety issues". A trip through Chromium's bug
tracker will show many, many vulnerabilities whose root cause is memory
unsafety. (As of March 2019, only about 5 of 130 [public Critical-severity
bugs](https://bugs.chromium.org/p/chromium/issues/list?can=1&q=Type%3DBug-Security+Security_Severity%3DCritical+-status%3AWontFix+-status%3ADuplicate&sort=&groupby=&colspec=ID+Pri+M+Stars+ReleaseBlock+Component+Status+Owner+Summary+OS+Modified&x=m&y=releaseblock&mode=&cells=ids&num=)
are not obviously due to memory corruption.)

Security engineers in general, very much including Chrome Security Team, would
like to advance the state of engineering to where memory safety issues are much
more rare. Then, we could focus more attention on the application-semantic
vulnerabilities. 😊 That would be a big improvement.

## What?

Some definitions are in order.

### Untrustworthy Inputs

_Untrustworthy inputs_ are inputs that

  * have non-trivial grammars; and/or
  * come from untrustworthy sources.

If there were an input type so simple that it were straightforward to write a
memory-safe handler for it, we wouldn't need to worry much about where it came
from **for the purposes of memory safety**, because we'd be sure we could handle
it. We would still need to treat the input as untrustworthy after
parsing, of course.

Unfortunately, it is very rare to find a grammar trivial enough that we can
trust ourselves to parse it successfully or fail safely. (But see
[Normalization](#Normalization) for a potential example.) Therefore, we do need
to concern ourselves with the provenance of such inputs.

Any arbitrary peer on the Internet is an untrustworthy source, unless we get
some evidence of its trustworthiness (which includes at least [a strong
assertion of the source's
identity](#verifying-the-trustworthiness-of-a-source)). When we can know with
certainty that an input is coming from the same source as the application itself
(e.g. Google in the case of Chrome, or Mozilla in the case of Firefox), and that
the transport is integrity-protected (such as with HTTPS), then it can be
acceptable to parse even complex inputs from that source. It's still ideal,
where feasible, to reduce our degree of trust in the source — such as by parsing
the input in a sandbox.

### Unsafe Implementation Languages

_Unsafe implementation languages_ are languages that lack [memory
safety](https://en.wikipedia.org/wiki/Memory_safety), including at least C, C++,
and assembly language. Memory-safe languages include Go, Rust, Python, Java,
JavaScript, Kotlin, and Swift. (Note that the safe subsets of these languages
are safe by design, but of course implementation quality is a different story.)

### High Privilege

_High privilege_ is a relative term. The very highest-privilege programs are the
computer's firmware, the bootloader, the kernel, any hypervisor or virtual
machine monitor, and so on. Below that are processes that run as an OS-level
account representing a person; this includes the Chrome browser process. We
consider such processes to have high privilege. (After all, they can do anything
the person can do, with any and all of the person's valuable data and accounts.)

Processes with slightly reduced privilege include (as of March 2019) the GPU
process and (hopefully soon) the network process. These are still pretty
high-privilege processes. We are always looking for ways to reduce their
privilege without breaking them.

Low-privilege processes include sandboxed utility processes and renderer
processes with [Site
Isolation](https://www.chromium.org/Home/chromium-security/site-isolation) (very
good) or [origin
isolation](https://cloud.google.com/docs/chrome-enterprise/policies/?policy=IsolateOrigins)
(even better).

## Solutions To This Puzzle

Chrome Security Team will generally not approve landing a CL or new feature
that involves all 3 of untrustworthy inputs, unsafe language, and high
privilege. To solve this problem, you need to get rid of at least 1 of those 3
things. Here are some ways to do that.

### Privilege Reduction

Also known as [_sandboxing_](https://cs.chromium.org/chromium/src/sandbox/),
privilege reduction means running the code in a process that has had some or
many of its privileges revoked.

When appropriate, try to handle the inputs in a renderer process that is Site
Isolated to the same site as the inputs come from. Take care to validate the
parsed (processed) inputs in the browser, since only the browser can trust
itself to validate and act on the meaning of an object.

Equivalently, you can launch a sandboxed utility process to handle the data, and
return a well-formed response back to the caller in an IPC message. See [Safe
Browsing's ZIP
analyzer](https://cs.chromium.org/chromium/src/chrome/common/safe_browsing/zip_analyzer.h)
for an example.

### Verifying The Trustworthiness Of A Source

If you can be sure that the input comes from a trustworthy source, it can be OK
to parse/evaluate it at high privilege in an unsafe language. A "trustworthy
source" means that Chromium can cryptographically prove that the data comes
from a business entity that you can or do trust (e.g.
for Chrome, an [Alphabet](https://abc.xyz) company).

Such cryptographic proof can potentially be obtained by:

  * Component Updater;
  * The variations framework (on some platforms; see [1078056](https://crbug.com/1078056)
    for Android and iOS limitations)
  * Pinned TLS (see below).

Pinned TLS needs to meet all these criteria to be effective:

  * communication happens via validly-authenticated TLS, HTTPS, or QUIC;
  * the peer's keys are [pinned in Chrome](https://cs.chromium.org/chromium/src/net/http/transport_security_state_static.json?sq=package:chromium&g=0); and
  * pinning is active on all platforms where the feature will launch.

At present pinning is not enabled for all Chrome platforms. On other platforms,
pinning may be disabled or rendered ineffective by enterprise security products.
It is generally much better to use the Component Updater.

One common pattern is to deliver a cryptographic hash of some content via such
a trustworthy channel, but deliver the content itself via an untrustworthy
channel. So long as the hash is properly verified, that's fine.

### Normalization {#normalization}

You can 'defang' a potentially-malicious input by transforming it into a
_normal_ or _minimal_ form, usually by first transforming it into a format with
a simpler grammar. We say that all data, file, and wire formats are defined by a
_grammar_, even if that grammar is implicit or only partially-specified (as is
so often the case). A file format with a particularly simple grammar is
[Farbfeld](https://tools.suckless.org/farbfeld/). (The grammar is represented in
the table at the top.)

It's rare to find such a simple grammar for input formats, however.

For example, consider the PNG image format, which is complex and whose [C
implementation has suffered from memory corruption bugs in the
past](https://www.cvedetails.com/vulnerability-list/vendor_id-7294/Libpng.html).
An attacker could craft a malicious PNG to trigger such a bug. But if you
transform the image into a format that doesn't have PNG's complexity (in a
low-privilege process, of course), the malicious nature of the PNG 'should' be
eliminated and then safe for parsing at a higher privilege level. Even if the
attacker manages to compromise the low-privilege process with a malicious PNG,
the high-privilege process will only parse the compromised process' output with
a simple, plausibly-safe parser. If that parse is successful, the
higher-privilege process can then optionally further transform it into a
normalized, minimal form (such as to save space). Otherwise, the parse can fail
safely, without memory corruption.

The trick of this technique lies in finding a sufficiently-trivial grammar, and
committing to its limitations.

Another good approach is to

  1. define a new Mojo message type for the information you want;
  2. extract that information from a complex input object in a sandboxed
     process; and then
  3. send the result to a higher-privileged process in a Mojo message using the
     new message type.

That way, the higher-privileged process need only process objects adhering to a
well-defined, generally low-complexity grammar. This is a big part of why [we
like for Mojo messages to use structured types](mojo.md#Use-structured-types).

For example, it should be safe enough to convert a PNG to an `SkBitmap` in a
sandboxed process, and then send the `SkBitmap` to a higher-privileged process
via IPC. Although there may be bugs in the IPC message deserialization code
and/or in Skia's `SkBitmap` handling code, we consider this safe enough for a
few reasons:

  * we must accept the risk of bugs in Mojo deserialization; but thankfully
  * Mojo deserialization is very amenable to fuzzing; and
  * it's a big improvement to scope bugs to smaller areas, like IPC
    deserialization functions and very simple classes like `SkBitmap` and
    `SkPixmap`.

Ultimately this process results in parsing significantly simpler grammars. (PNG
→ Mojo + `SkBitmap` in this case.)

> (We have to accept the risk of memory safety bugs in Mojo deserialization
> because C++'s high performance is crucial in such a throughput- and
> latency-sensitive area. If we could change this code to be both in a safer
> language and still have such high performance, that'd be ideal. But that's
> unlikely to happen soon.)

### Safe Languages

Where possible, it's great to use a memory-safe language. Of the currently
approved set of implementation languages in Chromium, the most likely candidates
are Java (on Android only) and JavaScript or WebAssembly (although we don't
currently use them in high-privilege processes like the browser). One can
imagine Swift on iOS or Kotlin on Android, too, although they are not currently
used in Chromium. (Some of us on Security Team aspire to get more of Chromium in
safer languages, but that's a long-term, heavy lift.)

For an example of image processing, we have the pure-Java class
[BaseGifImage](https://cs.chromium.org/chromium/src/third_party/gif_player/src/jp/tomorrowkey/android/gifplayer/BaseGifImage.java?rcl=27febd503d1bab047d73df26db83184fff8d6620&l=27).
On Android, where we can use Java and also face a particularly high cost for
creating new processes (necessary for sandboxing), using Java to decode tricky
formats can be a great approach. We do a similar thing with the pure-Java
[JsonSanitizer](https://cs.chromium.org/chromium/src/services/data_decoder/public/cpp/android/java/src/org/chromium/services/data_decoder/JsonSanitizer.java),
to 'vet' incoming JSON in a memory-safe way before passing the input to the C++
JSON implementation.

## Existing Code That Violates The Rule

We still have a lot of code that violates this rule. For example, until very
recently, all of the network stack was in the browser process, and its whole job
is to parse complex and untrustworthy inputs (TLS, QUIC, HTTP, DNS, X.509, and
more). This dangerous combination is why bugs in that area of code are often of
Critical severity:

  * [OOB Write in `QuicStreamSequencerBuffer::OnStreamData`](https://bugs.chromium.org/p/chromium/issues/detail?id=778505)
  * [Stack Buffer Overflow in `QuicClientPromisedInfo::OnPromiseHeaders`](https://bugs.chromium.org/p/chromium/issues/detail?id=777728)

We now have the network stack in its own dedicated process, and have begun the
process of reducing that process' privilege. ([macOS
bug](https://bugs.chromium.org/p/chromium/issues/detail?id=915910), [Windows
bug](https://bugs.chromium.org/p/chromium/issues/detail?id=841001))


text:
package list;

import version.Version;
import java.util.Collection;
import java.util.ArrayList;
import java.io.File;

public class ListFile {
  static {
    Version.register("list");
  }

  public static Collection list(File dir) {
    Collection files = new ArrayList();

    return list(dir, files);
  }

  private static Collection list(File file, Collection files) {
    if (file.isDirectory()) {
      File[] f = file.listFiles();
      for (int i=0; i<f.length; i++) {
        list(f[i], files);
      }
    } else {
      files.add(file);
    }
    return files;
  }
}


text:
@interface VRTNodeContainerShadowView : VRTShadowView

@end


text:
<?php
/**
 * This file is part of the Uri package.
 *
 * @author Daniel Schröder <daniel.schroeder@gravitymedia.de>
 */

namespace GravityMedia\Uri;

/**
 * Scheme registry class.
 *
 * @package GravityMedia\Uri
 */
class SchemeRegistry
{
    /**
     * The schemes.
     *
     * @var array
     */
    protected static $schemes = [
        'http' => 80,
        'https' => 443,
    ];

    /**
     * Register scheme.
     *
     * @param string     $scheme
     * @param int|string $port
     *
     * @throws \InvalidArgumentException
     */
    public static function registerScheme($scheme, $port)
    {
        if (!is_string($scheme)) {
            throw new \InvalidArgumentException('Invalid scheme argument');
        }

        if (!is_numeric($port)) {
            throw new \InvalidArgumentException('Invalid port argument');
        }

        static::$schemes[strtolower($scheme)] = (int)$port;
    }

    /**
     * Register schemes.
     *
     * @param array $schemes
     *
     * @throws \InvalidArgumentException
     */
    public static function registerSchemes(array $schemes)
    {
        foreach ($schemes as $scheme => $port) {
            static::registerScheme($scheme, $port);
        }
    }

    /**
     * Return whether or not the scheme is registered.
     *
     * @param string $scheme
     *
     * @return bool
     * @throws \InvalidArgumentException
     */
    public static function isSchemeRegistered($scheme)
    {
        if (!is_string($scheme)) {
            throw new \InvalidArgumentException('Invalid scheme argument');
        }

        return isset(static::$schemes[strtolower($scheme)]);
    }

    /**
     * Return whether or not the port is the standard port of the scheme.
     *
     * @param string     $scheme
     * @param int|string $port
     *
     * @return bool
     * @throws \InvalidArgumentException
     */
    public static function isStandardPort($scheme, $port)
    {
        if (!static::isSchemeRegistered($scheme)) {
            throw new \InvalidArgumentException('Scheme is not registered');
        }

        if (!is_numeric($port)) {
            return false;
        }

        return (int)$port === static::$schemes[strtolower($scheme)];
    }
}


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

<title>I-Index</title>
<meta name="date" content="2016-05-01">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D F G H I L M N P R S T U W X Y

I

icon - Variable in class ModelSubsystem.MapObject

increaseBomb() - Method in class ModelSubsystem.Player

increaseRange() - Method in class ModelSubsystem.Player

initializeButtons() - Method in class UserInterfaceSubsystem.LoadGamePanel

isBombControllable() - Method in class ModelSubsystem.Player

isDestroyable() - Method in class ModelSubsystem.MapObject

isDone() - Method in class ControllerSubsystem.GameEngine

checks if the map is done for the current level

isDone() - Method in class ModelSubsystem.GameMap

isPaused() - Method in class ControllerSubsystem.GameEngine

A B C D F G H I L M N P R S T U W X Y

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<!DOCTYPE html>

   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
   <meta name="description" content="Bootstrap Admin App + jQuery">
   <meta name="keywords" content="app, responsive, jquery, bootstrap, dashboard, admin">
   <title>Angle - Bootstrap Admin Template</title>

   <link rel="stylesheet" href="../vendor/fontawesome/css/font-awesome.min.css">

   <link rel="stylesheet" href="../vendor/simple-line-icons/css/simple-line-icons.css">

   <link rel="stylesheet" href="../vendor/animate.css/animate.min.css">

   <link rel="stylesheet" href="../vendor/whirl/dist/whirl.css">

   <link rel="stylesheet" href="css/bootstrap.css" id="bscss">

   <link rel="stylesheet" href="css/app.css" id="maincss">

11

New followers

                                          1 new follower

New e-mails

                                          You have 10 new emails

Pending Tasks

                                          11 pending task

                                 More notifications
                                 14

            <form role="search" action="search.html" class="navbar-form">

                  <input type="text" placeholder="Type and hit enter ..." class="form-control">

               <button type="submit" class="hidden btn btn-default">Submit</button>
            </form>

                              Hello, Mike
                              Designer

                     Main Navigation

3

                        Dashboard

Dashboard

                              Dashboard v1

                              Dashboard v2

                              Dashboard v3

30

                        Widgets

                        Layouts

Layouts

                              Horizontal

                     Components

                        Elements

Elements

                              Buttons

                              Notifications

                              Carousel

                              Spinners

                              Animations

                              Dropdown

                              Nestable

                              Sortable

                              Panels

                              Portlets

                              Grid

                              Grid Masonry

                              Typography

+400

                              Font Icons

+100

                              Weather Icons

                              Colors

                        Forms

Forms

                              Standard

                              Extended

                              Validation

                              Wizard

                              Upload

                              xEditable

                        Charts

Charts

                              Flot

                              Radial

                              Chart JS

                              Rickshaw

                              MorrisJS

                              Chartist

                        Tables

Tables

                              Standard

                              Extended

                              DataTables

                              jqGrid

                        Maps

Maps

                              Google Maps

                              Vector Maps

                     More

                        Pages

Pages

                              Login

                              Sign up

                              Recover Password

                              Lock

                              Starter Template

                              404

new

                        Extras

Extras

new

                              Blog

Blog

                                    List

                                    Post

                                    Articles

                                    Article View

new

                              eCommerce

eCommerce

10

                                    Orders

                                    Order View

                                    Products

                                    Product View

new

                              Forum

Forum

                                    Categories

                                    Topics

                                    Discussion

                              Mailbox

                              Timeline

                              Calendar

                              Invoice

                              Search

                              Todo List

                              Profile

                        Multilevel

Multilevel

                              Level 1

Level 1

                                    Level1 Item

                                    Level 2

Level 2

                                          Level 3

Level 3

                                                Level3 Item

                        Documentation

Settings

Themes

                                    <input type="radio" name="setting-theme" checked="checked">

                                    <input type="radio" name="setting-theme">

                                    <input type="radio" name="setting-theme">

                                    <input type="radio" name="setting-theme">

                                    <input type="radio" name="setting-theme">

                                    <input type="radio" name="setting-theme">

                                    <input type="radio" name="setting-theme">

                                    <input type="radio" name="setting-theme">

Layout

Fixed

                                 <input id="chk-fixed" type="checkbox" data-toggle-state="layout-fixed">

Boxed

                                 <input id="chk-boxed" type="checkbox" data-toggle-state="layout-boxed">

RTL

                                 <input id="chk-rtl" type="checkbox">

Aside

Collapsed

                                 <input id="chk-collapsed" type="checkbox" data-toggle-state="aside-collapsed">

Float

                                 <input id="chk-float" type="checkbox" data-toggle-state="aside-float">

Hover

                                 <input id="chk-hover" type="checkbox" data-toggle-state="aside-hover">

Connections

                           ONLINE

                                    Juan Sims

                                    Designeer

                                    Maureen Jenkins

                                    Designeer

                                    Billie Dunn

                                    Designeer

                                    Tomothy Roberts

                                    Designer

                           OFFLINE

                                    Lawrence Robinson

                                    Developer

                                    Tyrone Owens

                                    Designer

                                 Load more..

                           Tasks completion

                              80% Complete

                           Upload quota

                              40% Complete

MailBox

                        <button type="button" data-toggle="collapse" data-target=".mb-boxes" class="btn btn-sm btn-default mb-toggle-button pull-right dropdown-toggle">

                        </button>

                           Compose

                                    MAILBOXES

                                       42

                                       Inbox

                                       10

                                       Starred

                                       0

                                       Sent

                                       5

                                       Draft

                                       0

                                       Trash

                                    LABELS

                                       Red

                                       Pink

                                       Blue

                                       Yellow

                        <button type="button" class="btn btn-default btn-sm">

                        </button>
                        <button type="button" class="btn btn-default btn-sm">

                        </button>
                        <button type="button" class="btn btn-default btn-sm">

                        </button>

                        <button type="button" class="btn btn-default btn-sm">

                        </button>
                        <button type="button" class="btn btn-default btn-sm">

                        </button>

                                          <input type="checkbox">

10 minutes ago

Admin web application

Evelyn Holmes

Fusce gravida, diam ac adipiscing pretium, sem nibh bibendum diam, non consequat quam metus non nunc

                                          <input type="checkbox">

1 day ago

Admin theme based on Bootstrap and AngularJS

Allison Grant

Nunc eget lacinia felis. Pellentesque sollicitudin sollicitudin erat, in imperdiet tortor fringil

                                          <input type="checkbox">

2 days ago

Nested route mailbox application

Daryl Carlson

Nulla
                                          facilisi. Sed sit amet sem vel purus pulvinar venenatis. Class aptent taciti

                                          <input type="checkbox">

3 days ago

Angular with lazy load components

George Clark

Integer sit amet vulputate mauris. Proin purus nisl, tempor ut tempor at, ornare vel mauris. Ut ac l

                                          <input type="checkbox">

4 days ago

Translation ready and RTL support!

Bonnie Bowman

Integer sit amet vulputate mauris. Proin purus nisl, tempor ut tempor at, ornare vel mauris. Ut ac l

                                          <input type="checkbox">

5 days ago

Don't forget to check latest updates!

Warren Watts

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In at conseq

                                          <input type="checkbox">

6 days ago

We have to meet someday

Elijah Ward

Nunc hendrerit, neque ullamcorper eleifend ornare, arcu est bibendum ipsum, id malesuada sem justo v

                                          <input type="checkbox">

7 days ago

New issue found

Colleen Payne

Integer sit amet vulputate mauris. Proin purus nisl, tempor ut tempor at, ornare vel mauris. Ut ac l

                                          <input type="checkbox">

8 days ago

Issue #5478 awaiting reply

Rose Fox

Sed eu felis nulla. Nunc malesuada sapien at risus eleifend ut lacinia sem pretium.

                                          <input type="checkbox">

9 days ago

Check Angle for your next startup project

Jenny Knight

Morbi varius sem quis purus suscipit tempus. Integer fermentum accumsan metus, id sagittis ipsum mol

         © 2015 - Angle


text:
package JS_datasource_obj;

use warnings;
use strict;
use Data::Dumper;
use Date::Manip;
use JSON;
use version;
use Toolkit_helpers qw (logger);

# constructor
# parameters
# - dlpxObject - connection to DE
# - debug - debug flag (debug on if defined)

sub new {
    my $classname  = shift;
    my $dlpxObject = shift;
    my $template = shift;
    my $container = shift;
    my $debug = shift;
    logger($debug, "Entering JS_datasource_obj::constructor",1);

    my %jsdatasource;
    my $self = {
        _jsdatasource => \%jsdatasource,
        _dlpxObject => $dlpxObject,
        _debug => $debug
    };

    bless($self,$classname);

    $self->loadJSDataSourceList($template, $container, $debug);
    return $self;
}

# Procedure getJSDataSourceByName
# parameters:
# - name
# Return template reference for particular name

sub getJSDataSourceByName {
    my $self = shift;
    my $name = shift;
    logger($self->{_debug}, "Entering JS_datasource_obj::getJSDataSourceByName",1);
    my $ret;

    #print Dumper $$config;

    for my $dsitem ( sort ( keys %{$self->{_jsdatasource}} ) ) {

        if ( $self->getName($dsitem) eq $name) {
            $ret = $dsitem;
        }
    }

    return $ret;
}

# Procedure getJSDataSourceByContainer
# parameters:
# - conref
# Return data source reference for particular container

sub getJSDataSourceByContainer {
    my $self = shift;
    my $conref = shift;
    logger($self->{_debug}, "Entering JS_datasource_obj::getJSDataSourceByContainer",1);
    my @retarray;

    #print Dumper $$config;

    for my $dsitem ( sort ( keys %{$self->{_jsdatasource}} ) ) {

        if ( $self->getJSDataLayout($dsitem) eq $conref) {
            push(@retarray, $dsitem);
        }
    }

    return \@retarray;
}

# Procedure getJSDataSource
# parameters:
# - reference
# Return template hash for specific template reference

sub getJSDataSource {
    my $self = shift;
    my $reference = shift;

    logger($self->{_debug}, "Entering JS_datasource_obj::getJSDataSource",1);

    my $jsdatasource = $self->{_jsdatasource};
    return $jsdatasource->{$reference};
}

# Procedure getJSDataSourceList
# parameters:
# Return JS datasource list

sub getJSDataSourceList {
    my $self = shift;

    logger($self->{_debug}, "Entering JS_datasource_obj::getJSDataSourceList",1);

    my @arrret = sort (keys %{$self->{_jsdatasource}} );

    return \@arrret;
}

# Procedure getName
# parameters:
# - reference
# Return JS template name for specific template reference

sub getName {
    my $self = shift;
    my $reference = shift;

    logger($self->{_debug}, "Entering JS_datasource_obj::getName",1);

    my $jsdatasource = $self->{_jsdatasource};
    return $jsdatasource->{$reference}->{name};
}

# Procedure getPriority
# parameters:
# - reference
# Return JS source priority for specific data source reference

sub getPriority {
    my $self = shift;
    my $reference = shift;

    logger($self->{_debug}, "Entering JS_datasource_obj::getPriority",1);

    my $jsdatasource = $self->{_jsdatasource};
    return $jsdatasource->{$reference}->{priority};
}

# Procedure getJSTemplate
# parameters:
# - reference
# Return JS template for specific Data Source reference

sub getJSTemplate {
    my $self = shift;
    my $reference = shift;

    logger($self->{_debug}, "Entering JS_datasource_obj::getJSTemplate",1);

    my $jsdatasource = $self->{_jsdatasource};
    return $jsdatasource->{$reference}->{dataLayout};
}

# Procedure getJSDBContainer
# parameters:
# - reference
# Return JS DB container for specific Data Source reference

sub getJSDBContainer {
    my $self = shift;
    my $reference = shift;

    logger($self->{_debug}, "Entering JS_datasource_obj::getJSDBContainer",1);

    my $jsdatasource = $self->{_jsdatasource};
    return $jsdatasource->{$reference}->{container};
}

# Procedure getJSDataLayout
# parameters:
# - reference
# Return JS datasource container

sub getJSDataLayout {
    my $self = shift;
    my $reference = shift;

    logger($self->{_debug}, "Entering JS_datasource_obj::getJSDataLayout",1);

    my $jsdatasource = $self->{_jsdatasource};
    return $jsdatasource->{$reference}->{dataLayout};
}

# Procedure getProperties
# parameters:
# - reference
# Return JS template properties hash for specific template reference

sub getProperties {
    my $self = shift;
    my $reference = shift;

    logger($self->{_debug}, "Entering JS_datasource_obj::getProperties",1);

    my $jsdatasource = $self->{_jsdatasource};
    return $jsdatasource->{$reference}->{properties};
}

# Procedure checkTime
# parameters:
# - reference
# Return array of datasource times for specific datasource reference and time

sub checkTime {
    my $self = shift;
    my $reference = shift;
    my $time = shift;
    my $noformat = shift;

    logger($self->{_debug}, "Entering JS_datasource_obj::checkTime",1);

    my %checktime_hash;
    if (version->parse($self->{_dlpxObject}->getApi()) < version->parse(1.8.0)) {
      %checktime_hash = (
          "type" => "JSSourceDataTimestampParameters",
          "dataLayout" => $reference,
          "time" => $time
        );
    } else {
      %checktime_hash = (
          "type" => "JSSourceDataTimestampParameters",
          "branch" => $reference,
          "time" => $time
        );
    }

    my $json_data = to_json(\%checktime_hash, {pretty=>1});

    my $operation = "resources/json/delphix/jetstream/datasource/dataTimestamps";

    my ($result, $result_fmt) = $self->{_dlpxObject}->postJSONData($operation, $json_data);

    if ( defined($result->{status}) && ($result->{status} eq 'OK' )) {
        my @source_time;
        my $detz = $self->{_dlpxObject}->getTimezone();
        for my $t ( @{$result->{result} } ) {
          if (defined($noformat)) {
            my %source_hash = (
              'name' => $t->{name},
              'timestamp' => $t->{timestamp},
              'dsref' => $t->{source}
            );
            push(@source_time, \%source_hash);
          } else {
            $t->{timestamp} =~ s/\....Z//;
            my $time = Toolkit_helpers::convert_from_utc($t->{timestamp}, $detz, 1);
            my %source_hash = (
              'name' => $t->{name},
              'dsref' => $t->{source},
              'timestamp' => $time
            );
            push(@source_time, \%source_hash);
          }
        }

        #return $result->{result};
        return \@source_time;
    } else {
        return undef;
    }
}

# Procedure checkTime
# parameters:
# - reference
# Return array of datasource times for specific datasource reference and time

sub checkTimeDelta {
    my $self = shift;
    my $reference = shift;
    my $time = shift;
    my $diff = shift;

    logger($self->{_debug}, "Entering JS_datasource_obj::checkTime",1);

    my %checktime_hash = (
        "type" => "JSSourceDataTimestampParameters",
        "dataLayout" => $reference,
        "time" => $time
    );

    my $ret = 0;

    my $json_data = to_json(\%checktime_hash, {pretty=>1});

    my $operation = "resources/json/delphix/jetstream/datasource/dataTimestamps";

    my ($result, $result_fmt) = $self->{_dlpxObject}->postJSONData($operation, $json_data);

    if ( defined($result->{status}) && ($result->{status} eq 'OK' )) {

        my @source_time;
        my $tz = new Date::Manip::TZ;
        my $detz = $self->{_dlpxObject}->getTimezone();
        my %source_hash ;
        for my $t ( @{$result->{result} } ) {

            # print Dumper $t->{timestamp};
            # print Dumper "DELTA";
            my $time_epoch = UnixDate($time,'%s');
            my $realtime_epoch = UnixDate($t->{timestamp},'%s');
            # print Dumper $time_epoch;
            # print Dumper $realtime_epoch;
            my $delta = $time_epoch - $realtime_epoch + 0;
            # print Dumper $delta;
            # print Dumper $diff;
            # print Dumper ($delta >= $diff);
            if ($delta  >= $diff) {
                $ret = $ret + 1;
            }
        }
    }

    return $ret;

}

# Procedure loadJSDataSourceList
# parameters: none
# Load a list of template objects from Delphix Engine

sub loadJSDataSourceList
{
    my $self = shift;
    my $template = shift;
    my $container = shift;
    logger($self->{_debug}, "Entering JS_datasource_obj::loadJSDataSourceList",1);

    my $operation = "resources/json/delphix/jetstream/datasource?";

    if (defined($template)) {
        $operation = $operation . "dataLayout=" . $template . "&";
    }

    if (defined($container)) {
        $operation = $operation . "container=" . $container . "&";
    }

    my ($result, $result_fmt) = $self->{_dlpxObject}->getJSONResult($operation);
    if (defined($result->{status}) && ($result->{status} eq 'OK')) {
        my @res = @{$result->{result}};
        my $jsdatasource = $self->{_jsdatasource};

        for my $dsitem (@res) {
            $jsdatasource->{$dsitem->{reference}} = $dsitem;
        }
    }
}

1;


text:
[CmdletBinding()]
param(
    [PSCredential] $Credential,
    [Parameter(Mandatory=$False, HelpMessage='Tenant ID (This is a GUID which represents the "Directory ID" of the AzureAD tenant into which you want to create the apps')]
    [string] $tenantId,
    [Parameter(Mandatory=$False, HelpMessage='Azure environment to use while running the script (it defaults to AzureCloud)')]
    [string] $azureEnvironmentName
)

#Requires -Modules AzureAD -RunAsAdministrator

if ($null -eq (Get-Module -ListAvailable -Name "AzureAD")) {
    Install-Module "AzureAD" -Scope CurrentUser
}
Import-Module AzureAD
$ErrorActionPreference = "Stop"

Function Cleanup
{
    if (!$azureEnvironmentName)
    {
        $azureEnvironmentName = "AzureCloud"
    }

    <#
    .Description
    This function removes the Azure AD applications for the sample. These applications were created by the Configure.ps1 script
    #>

    # $tenantId is the Active Directory Tenant. This is a GUID which represents the "Directory ID" of the AzureAD tenant
    # into which you want to create the apps. Look it up in the Azure portal in the "Properties" of the Azure AD.

    # Login to Azure PowerShell (interactive if credentials are not already provided:
    # you'll need to sign-in with creds enabling your to create apps in the tenant)
    if (!$Credential -and $TenantId)
    {
        $creds = Connect-AzureAD -TenantId $tenantId -AzureEnvironmentName $azureEnvironmentName
    }
    else
    {
        if (!$TenantId)
        {
            $creds = Connect-AzureAD -Credential $Credential -AzureEnvironmentName $azureEnvironmentName
        }
        else
        {
            $creds = Connect-AzureAD -TenantId $tenantId -Credential $Credential -AzureEnvironmentName $azureEnvironmentName
        }
    }

    if (!$tenantId)
    {
        $tenantId = $creds.Tenant.Id
    }
    $tenant = Get-AzureADTenantDetail
    $tenantName =  ($tenant.VerifiedDomains | Where-Object { $_._Default -eq $True }).Name

    # Removes the applications
    Write-Host "Cleaning-up applications from tenant '$tenantName'"

    Write-Host "Removing 'service' (TodoListService-ManualJwt) if needed"
    try
    {
        Get-AzureADApplication -Filter "DisplayName eq 'TodoListService-ManualJwt'"  | ForEach-Object {Remove-AzureADApplication -ObjectId $_.ObjectId }
    }
    catch
    {
	    Write-Host "Unable to remove the 'TodoListService-ManualJwt' . Try deleting manually." -ForegroundColor White -BackgroundColor Red
    }
    $apps = Get-AzureADApplication -Filter "DisplayName eq 'TodoListService-ManualJwt'"
    if ($apps)
    {
        Remove-AzureADApplication -ObjectId $apps.ObjectId
    }

    foreach ($app in $apps)
    {
        Remove-AzureADApplication -ObjectId $app.ObjectId
        Write-Host "Removed TodoListService-ManualJwt.."
    }
    # also remove service principals of this app
    try
    {
        Get-AzureADServicePrincipal -filter "DisplayName eq 'TodoListService-ManualJwt'" | ForEach-Object {Remove-AzureADServicePrincipal -ObjectId $_.Id -Confirm:$false}
    }
    catch
    {
	    Write-Host "Unable to remove ServicePrincipal 'TodoListService-ManualJwt' . Try deleting manually from Enterprise applications." -ForegroundColor White -BackgroundColor Red
    }
    Write-Host "Removing 'client' (TodoListClient-ManualJwt) if needed"
    try
    {
        Get-AzureADApplication -Filter "DisplayName eq 'TodoListClient-ManualJwt'"  | ForEach-Object {Remove-AzureADApplication -ObjectId $_.ObjectId }
    }
    catch
    {
	    Write-Host "Unable to remove the 'TodoListClient-ManualJwt' . Try deleting manually." -ForegroundColor White -BackgroundColor Red
    }
    $apps = Get-AzureADApplication -Filter "DisplayName eq 'TodoListClient-ManualJwt'"
    if ($apps)
    {
        Remove-AzureADApplication -ObjectId $apps.ObjectId
    }

    foreach ($app in $apps)
    {
        Remove-AzureADApplication -ObjectId $app.ObjectId
        Write-Host "Removed TodoListClient-ManualJwt.."
    }
    # also remove service principals of this app
    try
    {
        Get-AzureADServicePrincipal -filter "DisplayName eq 'TodoListClient-ManualJwt'" | ForEach-Object {Remove-AzureADServicePrincipal -ObjectId $_.Id -Confirm:$false}
    }
    catch
    {
	    Write-Host "Unable to remove ServicePrincipal 'TodoListClient-ManualJwt' . Try deleting manually from Enterprise applications." -ForegroundColor White -BackgroundColor Red
    }
}

Cleanup -Credential $Credential -tenantId $TenantId


text:
Flux::DynamicFunction::DynamicFunction()
{
}

Flux::DynamicFunction::DynamicFunction(std::string _name)//  : Flux::FunctionHead(_name)
{
}

Flux::DynamicFunction::~DynamicFunction()
{
}


text:
Link
https://github.com/mikepenz/MaterialDrawer


text:
<?php
/**
 * Utility functions
 */
function add_filters($tags, $function) {
  foreach($tags as $tag) {
    add_filter($tag, $function);
  }
}

function is_element_empty($element) {
  $element = trim($element);
  return empty($element) ? false : true;
}

/**
* Compare url against relative url. Returns boolean.
*/
function roots_url_compare($url, $rel) {
$url = trailingslashit($url);
$rel = trailingslashit($rel);
if ((strcasecmp($url, $rel) === 0) || roots_root_relative_url($url) == $rel) {
return true;
} else {
return false;
}
}


text:
package org.sfm.csv.impl.cellreader.joda;

import org.sfm.csv.CellValueReader;
import org.sfm.csv.CsvColumnDefinition;
import org.sfm.map.column.joda.JodaHelper;
import org.sfm.map.impl.JodaTimeClasses;
import org.sfm.reflect.TypeHelper;

import java.lang.reflect.Type;

public class JodaTimeCellValueReaderHelper {

    public static CellValueReader<?> getReader(Type type, CsvColumnDefinition columnDefinition) {
        Class<?> clazz = TypeHelper.toClass(type);

        if (JodaTimeClasses.isJodaDateTime(clazz)) {
            return new JodaDateTimeCellValueReader(JodaHelper.getDateTimeFormatter(columnDefinition));
        }
        if (JodaTimeClasses.isJodaLocalDate(clazz)) {
            return new JodaLocalDateCellValueReader(JodaHelper.getDateTimeFormatter(columnDefinition));
        }
        if (JodaTimeClasses.isJodaLocalDateTime(clazz)) {
            return new JodaLocalDateTimeCellValueReader(JodaHelper.getDateTimeFormatter(columnDefinition));
        }
        if (JodaTimeClasses.isJodaLocalTime(clazz)) {
            return new JodaLocalTimeCellValueReader(JodaHelper.getDateTimeFormatter(columnDefinition));
        }

        return null;
    }
}


text:
GREEN='\033[0;32m'
NC='\033[0m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
LIGHTRED='\033[1;31m'
WHITE='\033[1;37m'
clear
echo -e "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n* ${WHITE}welcome to ${GREEN}fugitive${WHITE} installer${NC} *\n*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*"
echo -e "\n press any key when ready \n"
if [ -f ".ready" ];
  then
while true; do
    read -e -n1 -p "Looks like you already ran this setup program. Run again? (y/n): " yn
    case $yn in
        [Yy]* ) break;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
done

fi

for (( i=5; i>0; i--)); do
    printf "\rHit any key to start, or starting automatically in $i seconds...\n"
    read -s -n 1 -t 1 key
    if [ $? -eq 0 ]
    then
        was_key_pressed="true"
        break
    fi
done
echo -e "\n$LIGHTRED[$YELLOW*$LIGHTRED]$WHITE CHECKING OS: $LIGHTRED[$YELLOW*$LIGHTRED]$NC\n"
sleep 1
echo "looks like you are running..."
sleep 1
OS="`uname`"
case $OS in
  'Linux')
    OS='Linux'
    alias ls='ls --color=auto'
    ;;
  'FreeBSD')
    OS='FreeBSD'
    alias ls='ls -G'
    ;;
  'WindowsNT')
    OS='Windows'
    echo "Use a different OS, Windows sucks. Sorry, not sorry."
    exit 1
    ;;
  'Darwin')
    OS='OSX'
    ;;
  'SunOS')
    OS='Solaris'
    ;;
  'AIX') ;;
  *) ;;
esac
echo -e "$CYAN$OS$NC";
echo -e "\n$LIGHTRED[$YELLOW*$LIGHTRED]$WHITE CHECKING FOR PHP 7+ $LIGHTRED[$YELLOW*$LIGHTRED]$NC\n";
sleep 1
#echo "checking for php 7+";

pyv="$(php -V 2>&1)";
pyv="${pyv:7:1}";
if (( $pyv < 7)); then
    echo "no php 7+ installed, attempting install now";
    if $OS == 'OSX'; then
    echo "install php here: https://www.python.org/ftp/python/3.6.2/python-3.6.2-macosx10.6.pkg"
    echo "then run again"
    exit 1
    else echo "install PHP 7+ and run this again";
    exit 1
    fi
else echo "PHP 7+ IS HERE, continuing...";

fi

# check for nginx
echo -e "\n$LIGHTRED[$YELLOW*$LIGHTRED]$WHITE CHECKING FOR NGINX $LIGHTRED[$YELLOW*$LIGHTRED]$NC\n";
if ! which nginx > /dev/null 2>&1; then
    echo "Nginx not installed, attempting install now..."
    if $OS == 'Linux'
        if ! uname -a | grep "Ubuntu" > /dev/null 2>&1; then
            "We don't support your linux flavor, install nginx and rerun."
        else
            echo "Installing nginx via apt-get"
            sudo apt-get install nginx
            "NGINX installed, attempting to move files to sites-available..."
            sudo cp config/example.vhost /etc/nginx/sites-available/fugitive
            sudo ln -s /etc/nginx-sites-available/fugitive /etc/nginx/sites-enabled/
        fi
    fi
else
    "Found NGINX, attempting to move files to sites-available..."
    sudo cp config/example.vhost /etc/nginx/sites-available/fugitive
    sudo ln -s /etc/nginx-sites-available/fugitive /etc/nginx/sites-enabled/
fi
echo "you need to edit your nginx sites-available/fugitive file to match your hostname and other info"