text:
package org.apache.pluto.container.om.portlet.impl.jsr362;

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

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.xml.namespace.QName;

import org.apache.pluto.container.om.portlet.ContainerRuntimeOption;
import org.apache.pluto.container.om.portlet.CustomPortletMode;
import org.apache.pluto.container.om.portlet.CustomWindowState;
import org.apache.pluto.container.om.portlet.EventDefinition;
import org.apache.pluto.container.om.portlet.Filter;
import org.apache.pluto.container.om.portlet.FilterMapping;
import org.apache.pluto.container.om.portlet.Listener;
import org.apache.pluto.container.om.portlet.PortletApplicationDefinition;
import org.apache.pluto.container.om.portlet.PublicRenderParameter;
import org.apache.pluto.container.om.portlet.SecurityConstraint;
import org.apache.pluto.container.om.portlet.UserAttribute;
import org.apache.pluto.container.om.portlet.impl.ConfigurationHolder;
import org.apache.pluto.container.om.portlet.impl.ContainerRuntimeOptionImpl;
import org.apache.pluto.container.om.portlet.impl.CustomPortletModeImpl;
import org.apache.pluto.container.om.portlet.impl.CustomWindowStateImpl;
import org.apache.pluto.container.om.portlet.impl.EventDefinitionImpl;
import org.apache.pluto.container.om.portlet.impl.FilterImpl;
import org.apache.pluto.container.om.portlet.impl.FilterMappingImpl;
import org.apache.pluto.container.om.portlet.impl.ListenerImpl;
import org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl;
import org.apache.pluto.container.om.portlet.impl.PublicRenderParameterImpl;
import org.apache.pluto.container.om.portlet.impl.SecurityConstraintImpl;
import org.apache.pluto.container.om.portlet.impl.UserAttributeImpl;
import org.apache.pluto.container.om.portlet.impl.UserDataConstraintImpl;
import org.apache.pluto.container.om.portlet.impl.fixtures.TestPortletAppAnnotatedClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * Junit test cases for mer of portlet app definition from annotation
 * with that from the portlet.xml file.
 *
 * @author Scott Nicklous
 *
 */
public class MergePortletAppTest {

   private static final Class<?> TEST_ANNOTATED_CLASS = TestPortletAppAnnotatedClass.class;
   private static final String  WEBDDPKG         = "org/apache/pluto/container/om/portlet/";
   private static final String  WEBDD31          = "webApp31simple.xml";

   private static final String XML_FILE =
         "org/apache/pluto/container/om/portlet/portlet362Merge.xml";

   private static PortletApplicationDefinition pad;
   private static ConfigurationHolder cfp;

   // class under test; cloned new for each test
   private  PortletApplicationDefinition cut;

   /**
    * @throws java.lang.Exception
    */
   @BeforeClass
   public static void setUpBeforeClass() throws Exception {

      InputStream in = MergePortletAppTest.class
            .getClassLoader().getResourceAsStream(XML_FILE);

      Set<Class<?>> classes = new HashSet<Class<?>>();
      classes.add(TEST_ANNOTATED_CLASS);
      cfp = new ConfigurationHolder();
      try {
         // portlet XML must be processed after annotations
         cfp.processConfigAnnotations(classes);
         cfp.processPortletDD(in);
         pad = cfp.getPad();
      } catch (Exception e) {
         e.printStackTrace();
         throw e;
      }
   }

   @Before
   public void setUpBefore() throws Exception {
      cut = new PortletApplicationDefinitionImpl(pad);
   }

   /**
    * Bundle from XML overrides bundle from annotation
    */
   @Test
   public void testGetSetResourceBundle() {
      String val = cut.getResourceBundle();
      String txt = "com.ibm.portal.ResourceBundle";
      assertNotNull(val);
      assertEquals("org.apache.pluto.container.om.portlet.GoodBundle", val);
      cut.setResourceBundle(txt);
      val = cut.getResourceBundle();
      assertNotNull(val);
      assertEquals(txt, val);
   }

   /**
    * Namespace from XML overrrides namespace from annotation
    */
   @Test
   public void testGetSetDefaultNamespace() {
      String val = cut.getDefaultNamespace();
      String txt = "https://www.ibm.com/";
      assertNotNull(val);
      assertEquals("https://www.some.org/", val);
      cut.setDefaultNamespace(txt);
      val = cut.getDefaultNamespace();
      assertNotNull(val);
      assertEquals(txt, val);
   }

   /**
    * Total event defs is uniion of annotation event defs & xml event defs
    */
   @Test
   public void testGetEventDefinitions() {
      List<EventDefinition> list = cut.getEventDefinitions();
      assertNotNull(list);
      assertEquals(3, list.size());
      QName qn = new QName("https://www.some.org/", "another-event");
      EventDefinition evt = new EventDefinitionImpl(qn);
      assertTrue(list.contains(evt));
   }

   /**
    * Total event defs is uniion of annotation event defs & xml event defs
    */
   @Test
   public void testGetEventDefinition() {
      QName qn = new QName("https://www.some.org/", "another-event");
      EventDefinition item = cut.getEventDefinition(qn);
      assertNotNull(item);
      qn = new QName("https://www.some.org/", "supported-event");
      item = cut.getEventDefinition(qn);
      assertNotNull(item);
      qn = new QName("http://test.com", "supported-event");
      item = cut.getEventDefinition(qn);
      assertNotNull(item);
   }

   /**
    * Total event defs is uniion of annotation event defs & xml event defs
    */
   @Test
   public void testAddEventDefinition() {
      QName qn = new QName("https://www.ibm.com/", "some-other-event");
      EventDefinition ed = new EventDefinitionImpl(qn);
      cut.addEventDefinition(ed);

      List<EventDefinition> list = cut.getEventDefinitions();
      assertNotNull(list);
      assertEquals(4, list.size());
      EventDefinition evt = new EventDefinitionImpl(qn);
      assertTrue(list.contains(evt));
   }

   /**
    * Total event defs is uniion of annotation event defs & xml event defs
    */
   @Test
   public void testAddDupEventDefinition() {
      QName qn = new QName("https://www.some.org/", "different-event");
      EventDefinition ed = new EventDefinitionImpl(qn);
      cut.addEventDefinition(ed);

      List<EventDefinition> list = cut.getEventDefinitions();
      assertNotNull(list);
      assertEquals(4, list.size());
      boolean ok = false;
      for (EventDefinition item : list) {
         if (item.getQName().equals(qn)) {
            ok = true;
         }
      }
      assertTrue(ok);
   }

   /**
    * Total prps are union of annotation prps & xml prps
    */
   @Test
   public void testGetPublicRenderParameter() {
      assertNotNull(cut.getPublicRenderParameter("color"));
      assertNotNull(cut.getPublicRenderParameter("imgName"));
      assertNotNull(cut.getPublicRenderParameter("link"));
      List<PublicRenderParameter> prps = cut.getPublicRenderParameters();
      assertNotNull(prps);
      assertEquals(3, prps.size());
   }

   private boolean isPrpPresent(String prpid, List<PublicRenderParameter> prps) {
      for (PublicRenderParameter prp : prps) {
         if (prp.getIdentifier().equals(prpid)) {
            return true;
         }
      }
      return false;
   }

   /**
    * Total prps are union of annotation prps & xml prps
    */
   @Test
   public void testGetPublicRenderParameters() {
      String prpid = "imgName";
      List<PublicRenderParameter> prps = cut.getPublicRenderParameters();
      assertNotNull(prps);
      assertEquals(3, prps.size());
      assertTrue(isPrpPresent(prpid, prps));
   }

   /**
    * Total prps are union of annotation prps & xml prps
    */
   @Test
   public void testAddPublicRenderParameter() {
      String prpid = "newprp";
      QName qn = new QName("https://www.ibm.com/", "some-other-prp");
      PublicRenderParameter prp = new PublicRenderParameterImpl(qn, prpid);
      cut.addPublicRenderParameter(prp);

      List<PublicRenderParameter> prps = cut.getPublicRenderParameters();
      assertNotNull(prps);
      assertEquals(4, prps.size());
      assertTrue(isPrpPresent(prpid, prps));
   }

   /**
    * Total prps are union of annotation prps & xml prps
    */
   @Test
   public void testAddDupPublicRenderParameter() {
      String prpid = "color";
      QName qn = new QName("https://www.some.org/", "color");
      PublicRenderParameter prp = new PublicRenderParameterImpl(qn, prpid);
      cut.addPublicRenderParameter(prp);

      List<PublicRenderParameter> prps = cut.getPublicRenderParameters();
      assertNotNull(prps);
      assertEquals(3, prps.size());
      assertTrue(isPrpPresent(prpid, prps));
   }

   /**
    * Union of annotation modes & XML modes
    */
   @Test
   public void testGetCustomPortletMode() {
      assertNotNull(cut.getCustomPortletMode("portlet-mode"));
      assertNotNull(cut.getCustomPortletMode("admin"));
      assertNotNull(cut.getCustomPortletMode("aMode"));
   }

   private boolean isPMPresent(String pm, List<CustomPortletMode> list) {
      for (CustomPortletMode mode : list) {
         if (mode.getPortletMode().equals(pm)) {
            return true;
         }
      }
      return false;
   }

   /**
    * Total portlet modes is union of annotation modes & XML modes
    */
   @Test
   public void testGetCustomPortletModes() {
      String newItem = "portlet-mode";
      List<CustomPortletMode> list = cut.getCustomPortletModes();
      assertNotNull(list);
      assertEquals(3, list.size());
      assertTrue(isPMPresent(newItem, list));
   }

   /**
    * Total portlet modes is union of annotation modes & XML modes
    */
   @Test
   public void testAddCustomPortletMode() {
      String newItem = "newMode";
      CustomPortletMode prp = new CustomPortletModeImpl(newItem);
      cut.addCustomPortletMode(prp);

      List<CustomPortletMode> list = cut.getCustomPortletModes();
      assertNotNull(list);
      assertEquals(4, list.size());
      assertTrue(isPMPresent(newItem, list));
   }

   /**
    * Total portlet modes is union of annotation modes & XML modes
    */
   @Test
   public void testAddDuplicateCustomPortletMode() {
      String newItem = "portlet-mode";
      CustomPortletMode prp = new CustomPortletModeImpl(newItem);
      cut.addCustomPortletMode(prp);

      List<CustomPortletMode> list = cut.getCustomPortletModes();
      assertNotNull(list);
      assertEquals(3, list.size());
      assertTrue(isPMPresent(newItem, list));
   }

   private boolean isWSPresent(String ws, List<CustomWindowState> list) {
      for (CustomWindowState cws : list) {
         if (cws.getWindowState().equals(ws)) {
            return true;
         }
      }
      return false;
   }

   /**
    * Total custom window states is union of annotation states & XML states
    */
   @Test
   public void testGetCustomWindowState() {
      assertNotNull(cut.getCustomWindowState("window-state"));
      assertNotNull(cut.getCustomWindowState("half_page"));
      assertNotNull(cut.getCustomWindowState("quarter_page"));
   }

   /**
    * Total custom window states is union of annotation states & XML states
    */
   @Test
   public void testGetCustomWindowStates() {
      String newItem = "window-state";
      List<CustomWindowState> list = cut.getCustomWindowStates();
      assertNotNull(list);
      assertEquals(3, list.size());
      assertTrue(isWSPresent(newItem, list));
   }

   /**
    * Total custom window states is union of annotation states & XML states
    */
   @Test
   public void testAddCustomWindowState() {
      String newItem = "newState";
      CustomWindowState prp = new CustomWindowStateImpl(newItem);
      cut.addCustomWindowState(prp);

      List<CustomWindowState> list = cut.getCustomWindowStates();
      assertNotNull(list);
      assertEquals(4, list.size());
      assertTrue(isWSPresent(newItem, list));
   }

   /**
    * Total custom window states is union of annotation states & XML states
    */
   @Test
   public void testAddDupCustomWindowState() {
      String newItem = "window-state";
      CustomWindowState prp = new CustomWindowStateImpl(newItem);
      cut.addCustomWindowState(prp);

      List<CustomWindowState> list = cut.getCustomWindowStates();
      assertNotNull(list);
      assertEquals(3, list.size());
      assertTrue(isWSPresent(newItem, list));
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#getUserAttribute(java.lang.String)}.
    */
   @Test
   public void testGetUserAttribute() {
      assertNotNull(cut.getUserAttribute("user.name.given"));
      assertNotNull(cut.getUserAttribute("user.name.family"));
      assertNotNull(cut.getUserAttribute("dogs.name"));
      assertNotNull(cut.getUserAttribute("user.home-info.online.email"));
      assertNotNull(cut.getUserAttribute("user.business-info.postal.organization"));
   }

   private boolean isUAPresent(String ua, List<UserAttribute> list) {
      for (UserAttribute item : list) {
         if (item.getName().equals(ua)) {
            return true;
         }
      }
      return false;
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#getUserAttributes()}.
    */
   @Test
   public void testGetUserAttributes() {
      String newItem = "user.name.family";
      List<UserAttribute> list = cut.getUserAttributes();
      assertNotNull(list);
      assertEquals(5, list.size());
      assertTrue(isUAPresent(newItem, list));
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addUserAttribute(org.apache.pluto.container.om.portlet.UserAttribute)}.
    */
   @Test
   public void testAddUserAttribute() {
      String newItem = "newAttr";
      UserAttribute prp = new UserAttributeImpl(newItem);
      cut.addUserAttribute(prp);

      List<UserAttribute> list = cut.getUserAttributes();
      assertNotNull(list);
      assertEquals(6, list.size());
      assertTrue(isUAPresent(newItem, list));
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addUserAttribute(org.apache.pluto.container.om.portlet.UserAttribute)}.
    */
   @Test
   public void testAddDupUserAttribute() {
      String newItem = "user.name.family";
      UserAttribute prp = new UserAttributeImpl(newItem);
      cut.addUserAttribute(prp);

      List<UserAttribute> list = cut.getUserAttributes();
      assertNotNull(list);
      assertEquals(5, list.size());
      assertTrue(isUAPresent(newItem, list));
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#getFilter(java.lang.String)}.
    */
   @Test
   public void testGetFilter() {
      String newItem = "filter-name";
      String filterClass = "org.apache.pluto.container.om.portlet.impl.fixtures.TestFilter";
      Filter item = cut.getFilter(newItem);
      assertNotNull(item);
      Filter filter = cut.getFilters().get(0);
      assertEquals(filterClass,
            filter.getFilterClass());
      assertEquals("description", filter.getDescription(new Locale("de")).getText());
      assertEquals("display-name", filter.getDisplayName(new Locale("de")).getText());
      assertEquals("lifecycle", filter.getLifecycles().get(0));
      assertEquals("value", filter.getInitParam("name").getParamValue());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#getFilters()}.
    */
   @Test
   public void testGetFilters() {
      String newItem = "filter-name";
      List<Filter> list = cut.getFilters();
      assertNotNull(list);
      assertEquals(1, list.size());
      assertEquals(newItem, list.get(0).getFilterName());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addFilter(org.apache.pluto.container.om.portlet.Filter)}.
    */
   @Test
   public void testAddFilter() {
      String newItem = "newFilter";
      String filterClass = "org.apache.pluto.container.om.portlet.impl.fixtures.TestFilter";
      Filter fil = new FilterImpl(newItem);
      fil.setFilterClass(filterClass);
      cut.addFilter(fil);

      List<Filter> list = cut.getFilters();
      assertNotNull(list);
      assertEquals(2, list.size());
      assertEquals(newItem, list.get(1).getFilterName());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addFilter(org.apache.pluto.container.om.portlet.Filter)}.
    */
   @Test
   public void testRemoveFilter() {
      // existing filter def is removed if filter class is null (= not set)
      String newItem = "filter-name";
      Filter fil = new FilterImpl(newItem);
      assertNotNull(cut.getFilter(newItem));
      cut.addFilter(fil);

      List<Filter> list = cut.getFilters();
      assertNotNull(list);
      assertEquals(0, list.size());
      assertEquals(null, cut.getFilter(newItem));
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addFilter(org.apache.pluto.container.om.portlet.Filter)}.
    */
   @Test
   public void testAddDupFilter() {
      String newItem = "filter-name";
      String filterClass = "org.apache.pluto.container.om.portlet.impl.fixtures.TestFilter";
      Filter fil = new FilterImpl(newItem);
      fil.setFilterClass(filterClass);
      cut.addFilter(fil);

      List<Filter> list = cut.getFilters();
      assertNotNull(list);
      assertEquals(1, list.size());
      assertEquals(newItem, list.get(0).getFilterName());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#getFilterMapping(java.lang.String)}.
    */
   @Test
   public void testGetFilterMapping() {
      String newItem = "filter-name";
      FilterMapping item = cut.getFilterMapping(newItem);
      assertNotNull(item);
      assertEquals(1, item.getPortletNames().size());
      assertEquals("AnnotatedPortlet", item.getPortletNames().get(0));
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#getFilterMappings()}.
    */
   @Test
   public void testGetFilterMappings() {
      String newItem = "filter-name";
      List<FilterMapping> list = cut.getFilterMappings();
      assertNotNull(list);
      assertEquals(1, list.size());
      assertEquals(newItem, list.get(0).getFilterName());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addFilterMapping(org.apache.pluto.container.om.portlet.FilterMapping)}.
    */
   @Test
   public void testAddFilterMapping() {
      String newItem = "newFilter";
      String portletName = "portlet362";
      FilterMapping fm = new FilterMappingImpl(newItem);
      fm.addPortletName(portletName);
      cut.addFilterMapping(fm);

      List<FilterMapping> list = cut.getFilterMappings();
      assertNotNull(list);
      assertEquals(2, list.size());
      assertEquals(newItem, list.get(1).getFilterName());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addFilterMapping(org.apache.pluto.container.om.portlet.FilterMapping)}.
    */
   @Test
   public void testRemoveFilterMapping() {
      String newItem = "filter-name";
      FilterMapping fm = new FilterMappingImpl(newItem);
      assertNotNull(cut.getFilterMapping(newItem));
      cut.addFilterMapping(fm);

      List<FilterMapping> list = cut.getFilterMappings();
      assertNotNull(list);
      assertEquals(0, list.size());
      assertEquals(null, cut.getFilterMapping(newItem));
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addFilterMapping(org.apache.pluto.container.om.portlet.FilterMapping)}.
    */
   @Test
   public void testAddDupFilterMapping() {
      String newItem = "filter-name";
      String portletName = "portlet362";
      FilterMapping fm = new FilterMappingImpl(newItem);
      fm.addPortletName(portletName);
      cut.addFilterMapping(fm);

      List<FilterMapping> list = cut.getFilterMappings();
      assertNotNull(list);
      assertEquals(1, list.size());
      assertEquals(newItem, list.get(0).getFilterName());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#getContainerRuntimeOption(java.lang.String)}.
    */
   @Test
   public void testGetContainerRuntimeOption() {
      assertNotNull(cut.getContainerRuntimeOption("javax.portlet.renderHeaders"));
      assertNotNull(cut.getContainerRuntimeOption("Runtime-Option-Portlet-App"));
      assertNotNull(cut.getContainerRuntimeOption("runtime.option"));
   }

   private boolean isRTOPresent(String rt, List<ContainerRuntimeOption> list) {
      for (ContainerRuntimeOption item : list) {
         if (item.getName().equals(rt)) {
            return true;
         }
      }
      return false;
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#getContainerRuntimeOptions()}.
    */
   @Test
   public void testGetContainerRuntimeOptions() {
      String newItem = "Runtime-Option-Portlet-App";
      List<ContainerRuntimeOption> list = cut.getContainerRuntimeOptions();
      assertNotNull(list);
      assertEquals(3, list.size());
      assertTrue(isRTOPresent(newItem, list));
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addContainerRuntimeOption(org.apache.pluto.container.om.portlet.ContainerRuntimeOption)}.
    */
   @Test
   public void testAddContainerRuntimeOption() {
      String newItem = "newRTO";
      String[] newvals = {"v1", "v2"};
      ContainerRuntimeOption item = new ContainerRuntimeOptionImpl(newItem, Arrays.asList(newvals));
      cut.addContainerRuntimeOption(item);

      List<ContainerRuntimeOption> list = cut.getContainerRuntimeOptions();
      assertNotNull(list);
      assertEquals(4, list.size());
      assertTrue(isRTOPresent(newItem, list));
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addContainerRuntimeOption(org.apache.pluto.container.om.portlet.ContainerRuntimeOption)}.
    */
   @Test
   public void testAddDupContainerRuntimeOption() {
      String newItem = "Runtime-Option-Portlet-App";
      String[] newvals = {"v1", "v2"};
      ContainerRuntimeOption item = new ContainerRuntimeOptionImpl(newItem, Arrays.asList(newvals));
      cut.addContainerRuntimeOption(item);

      List<ContainerRuntimeOption> list = cut.getContainerRuntimeOptions();
      assertNotNull(list);
      assertEquals(3, list.size());
      assertTrue(isRTOPresent(newItem, list));
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#getListeners()}.
    */
   @Test
   public void testGetListeners() {
      List<Listener> list = cut.getListeners();
      assertNotNull(list);
      assertEquals(1, list.size());
      assertEquals("org.apache.pluto.container.om.portlet.impl.fixtures.TestListener", list.get(0).getListenerClass());
      assertEquals("test listener", list.get(0).getListenerName());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addListener(org.apache.pluto.container.om.portlet.Listener)}.
    */
   @Test
   public void testAddListener() {
      String clsName = "org.apache.pluto.container.om.portlet.impl.fixtures.DifferentListener";
      String lisName = "Different Listener";
      Listener newitem = new ListenerImpl(clsName);
      newitem.setListenerName(lisName);

      cut.addListener(newitem);

      List<Listener> list = cut.getListeners();
      assertNotNull(list);
      assertEquals(2, list.size());
      assertEquals(clsName, list.get(1).getListenerClass());
      assertEquals(lisName, list.get(1).getListenerName());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addListener(org.apache.pluto.container.om.portlet.Listener)}.
    */
   @Test
   public void testAddDupListener() {
      String clsName = "org.apache.pluto.container.om.portlet.impl.fixtures.TestListener";
      String lisName = "test listener";
      Listener newitem = new ListenerImpl(clsName);
      newitem.setListenerName(lisName);

      cut.addListener(newitem);

      List<Listener> list = cut.getListeners();
      assertNotNull(list);
      assertEquals(1, list.size());
      assertEquals(clsName, list.get(0).getListenerClass());
      assertEquals(lisName, list.get(0).getListenerName());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addSecurityConstraint(org.apache.pluto.container.om.portlet.SecurityConstraint)}.
    */
   @Test
   public void testAddSecurityConstraint() {
      SecurityConstraint seco = new SecurityConstraintImpl(new UserDataConstraintImpl("CONFIDENTIAL"));
      cut.addSecurityConstraint(seco);

      List<SecurityConstraint> list = cut.getSecurityConstraints();
      assertNotNull(list);
      assertEquals(1, list.size());
      assertEquals("CONFIDENTIAL", list.get(0).getUserDataConstraint().getTransportGuarantee());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addSecurityConstraint(org.apache.pluto.container.om.portlet.SecurityConstraint)}.
    */
   @Test
   public void testAddDupSecurityConstraint() {
      SecurityConstraint seco = new SecurityConstraintImpl(new UserDataConstraintImpl("NONE"));
      cut.addSecurityConstraint(seco);

      List<SecurityConstraint> list = cut.getSecurityConstraints();
      assertNotNull(list);
      assertEquals(1, list.size());
      assertEquals("NONE", list.get(0).getUserDataConstraint().getTransportGuarantee());
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#getLocaleEncodingMappings()}.
    * @throws Exception
    */
   @Test
   public void testGetLocaleEncodingMappings() throws Exception {
      String file = WEBDDPKG + WEBDD31;
      InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);

      try {
         cfp.processWebDD(in);
         pad = cfp.getPad();
      } catch (Exception e) {
         e.printStackTrace();
         throw e;
      }

      Map<Locale, String> localemap = pad.getLocaleEncodingMappings();
      assertEquals(2, localemap.size());
      ArrayList<Locale> testlocs = new ArrayList<Locale>(Arrays.asList(new Locale[]{
            Locale.forLanguageTag("de"), Locale.forLanguageTag("ja") }));
      String[] testencs = {"UTF-8", "Shift_JIS"};
      for (Locale loc : localemap.keySet()) {
         assertTrue(testlocs.contains(loc));
         int ind = testlocs.indexOf(loc);
         assertEquals(testencs[ind], localemap.get(loc));
      }
   }

   /**
    * Test method for {@link org.apache.pluto.container.om.portlet.impl.PortletApplicationDefinitionImpl#addLocaleEncodingMapping(java.util.Locale, java.lang.String)}.
    */
   @Test
   public void testAddLocaleEncodingMapping() {
      ArrayList<Locale> testlocs = new ArrayList<Locale>(Arrays.asList(new Locale[]{
            Locale.forLanguageTag("de"), Locale.forLanguageTag("ja") }));
      String[] testencs = {"UTF-8", "Shift_JIS"};
      for (Locale loc : testlocs) {
         int ind = testlocs.indexOf(loc);
         cut.addLocaleEncodingMapping(loc, testencs[ind]);
      }

      Map<Locale, String> localemap = cut.getLocaleEncodingMappings();
      assertEquals(2, localemap.size());
      for (Locale loc : localemap.keySet()) {
         assertTrue(testlocs.contains(loc));
         int ind = testlocs.indexOf(loc);
         assertEquals(testencs[ind], localemap.get(loc));
      }
   }

   /**
    * Make sure validate() throws no exceptions
    */
   @Test
   public void testValidate() {
         cfp.validate();
   }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="arrayService">
        <item>@string/str_levelOfService_Amazing</item>
        <item>@string/str_levelOfService_excellent</item>
        <item>@string/str_levelOfService_average</item>
        <item>@string/str_levelOfService_poor</item>
        <item>@string/str_levelOfService_Unacceptable</item>
    </string-array>
</resources>

redpajama_set_name: RedPajamaGithub


text:
/* eslint-disable complexity */
/* eslint-disable max-nested-callbacks,no-nested-ternary */
import React, {
  ComponentProps,
  ForwardedRef,
  forwardRef,
  useCallback,
  useMemo,
  useRef,
  useState,
} from 'react'
import {isValidationErrorMarker, isValidationMarker, Reference, SchemaType} from '@sanity/types'
import {
  EllipsisVerticalIcon,
  LaunchIcon as OpenInNewTabIcon,
  SyncIcon as ReplaceIcon,
  TrashIcon,
  CopyIcon as DuplicateIcon,
} from '@sanity/icons'
import {concat, Observable, of} from 'rxjs'
import {catchError, distinctUntilChanged, filter, map, scan, switchMap, tap} from 'rxjs/operators'
import {
  Badge,
  Box,
  Button,
  Card,
  CardTone,
  Flex,
  Inline,
  Menu,
  MenuButton,
  MenuDivider,
  MenuItem,
  Stack,
  Text,
  Tooltip,
  useForwardedRef,
  useToast,
} from '@sanity/ui'
import {
  FormField,
  FormFieldValidationStatus,
  IntentLink,
  PreviewCard,
} from '@sanity/base/components'
import {FieldPresence, GlobalPresence} from '@sanity/base/presence'
import {getPublishedId} from '@sanity/base/_internal'
import {useObservableCallback} from 'react-rx'
import {uuid} from '@sanity/uuid'
import {useId} from '@reach/auto-id'
import styled from 'styled-components'

import PatchEvent, {set, setIfMissing, unset} from '../../PatchEvent'
import {EMPTY_ARRAY} from '../../utils/empty'
import {useDidUpdate} from '../../hooks/useDidUpdate'

import {isNonNullable} from '../../utils/isNonNullable'
import {AlertStrip} from '../../AlertStrip'
import {RowWrapper} from '../arrays/ArrayOfObjectsInput/item/components/RowWrapper'
import {DragHandle} from '../arrays/common/DragHandle'
import {InsertEvent} from '../arrays/ArrayOfObjectsInput/types'
import randomKey from '../arrays/common/randomKey'
import {InsertMenu} from '../arrays/ArrayOfObjectsInput/InsertMenu'
import {useOnClickOutside} from '../../hooks/useOnClickOutside'
import {BaseInputProps, CreateOption, SearchState} from './types'
import {OptionPreview} from './OptionPreview'
import {useReferenceInfo} from './useReferenceInfo'
import {PreviewReferenceValue} from './PreviewReferenceValue'
import {CreateButton} from './CreateButton'
import {ReferenceAutocomplete} from './ReferenceAutocomplete'
import {AutocompleteContainer} from './AutocompleteContainer'

const StyledPreviewCard = styled(PreviewCard)`
  /* this is a hack to avoid layout jumps while previews are loading
  there's probably better ways of solving this */
  min-height: 36px;
`

const INITIAL_SEARCH_STATE: SearchState = {
  hits: [],
  isLoading: false,
}

export interface Props extends BaseInputProps {
  value: OptionalRef
  isSortable: boolean
  insertableTypes?: SchemaType[]
  onInsert?: (event: InsertEvent) => void
}

const NO_FILTER = () => true

const dragHandle = <DragHandle paddingX={1} paddingY={3} />

type PartialPick<T, K extends keyof T> = Omit<T, K> &
  {
    [P in K]?: T[K]
  }

type OptionalRef = PartialPick<Reference, '_ref'>

function valueHasRef<T extends {_ref?: string}>(value: T): value is T & {_ref: string} {
  return typeof value._ref === 'string'
}

export const ArrayItemReferenceInput = forwardRef(function ReferenceInput(
  props: Props,
  forwardedRef: ForwardedRef<HTMLInputElement>
) {
  const {
    type,
    value,
    markers,
    readOnly,
    liveEdit,
    onSearch,
    onChange,
    insertableTypes,
    focusPath = EMPTY_ARRAY,
    onFocus,
    presence,
    createOptions,
    isSortable,
    level,
    onBlur,
    onInsert,
    selectedState,
    editReferenceLinkComponent: EditReferenceLink,
    onEditReference,
    getReferenceInfo,
  } = props

  const [searchState, setSearchState] = useState<SearchState>(INITIAL_SEARCH_STATE)

  const handleCreateNew = (option: CreateOption) => {
    const id = uuid()

    const patches = [
      setIfMissing({}),
      set(type.name, ['_type']),
      set(id, ['_ref']),
      set(true, ['_weak']),
      set({type: option.type, weak: type.weak, template: option.template}, [
        '_strengthenOnPublish',
      ]),
    ]

    onChange(PatchEvent.from(patches))

    onEditReference({id, type: option.type, template: option.template})
    onFocus?.([])
  }

  const handleDuplicate = useCallback(() => {
    onInsert?.({
      item: {...value, _key: randomKey()},
      position: 'after',
      path: [{_key: value._key}],
      edit: false,
    })
  }, [onInsert, value])

  const handleInsert = useCallback(
    (pos: 'before' | 'after') => {
      onInsert?.({
        item: {_type: type.name, _key: randomKey()},
        position: pos,
        path: [{_key: value._key}],
      })
    },
    [onInsert, type.name, value._key]
  )

  const handleChange = useCallback(
    (id: string) => {
      if (!id) {
        onChange(PatchEvent.from(unset()))
        onFocus?.([])
        return
      }

      const hit = searchState.hits.find((h) => h.id === id)

      if (!hit) {
        throw new Error('Selected an item that wasnt part of the result set')
      }
      // if there's no published version of this document, set the reference to weak

      const patches = [
        setIfMissing({}),
        set(type.name, ['_type']),
        set(getPublishedId(id), ['_ref']),
        hit.published && !type.weak ? unset(['_weak']) : set(true, ['_weak']),
        hit.published
          ? unset(['_strengthenOnPublish'])
          : set({type: hit?.type, weak: type.weak}, ['_strengthenOnPublish']),
      ].filter(isNonNullable)

      onChange(PatchEvent.from(patches))
      onFocus?.([])
    },
    [searchState.hits, type.name, type.weak, onChange, onFocus]
  )

  const handleClear = useCallback(() => {
    onChange(PatchEvent.from(unset()))
  }, [onChange])

  const handlePreviewKeyPress = useCallback(
    (event) => {
      if (event.key !== 'Enter' && event.key !== 'Space') {
        // enable "search for reference"-mode
        onFocus?.(['_ref'])
      }
    },
    [onFocus]
  )

  const handleCancelEdit = useCallback(() => {
    if (!value?._ref) {
      onChange(PatchEvent.from(unset()))
    }
    onFocus?.([])
  }, [onChange, onFocus, value?._ref])

  const handleAutocompleteKeyDown = useCallback(
    (event) => {
      // escape
      if (event.keyCode === 27) {
        handleCancelEdit()
      }
    },
    [handleCancelEdit]
  )

  const getReferenceInfoMemo = useCallback((id) => getReferenceInfo(id, type), [
    getReferenceInfo,
    type,
  ])

  const loadableReferenceInfo = useReferenceInfo(value?._ref, getReferenceInfoMemo)

  const refTypeName = loadableReferenceInfo.result?.type || value?._strengthenOnPublish?.type

  const refType = refTypeName ? type.to.find((toType) => toType.name === refTypeName) : undefined

  // --- focus handling
  const hasFocusAtRef = focusPath.length === 1 && (focusPath[0] === '_ref' || focusPath[0] === '$')
  const focusElementRef = useForwardedRef(forwardedRef)
  useDidUpdate({hasFocusAt: hasFocusAtRef, ref: value?._ref}, (prev, current) => {
    const refUpdated = prev.ref !== current.ref
    const focusAtUpdated = prev.hasFocusAt !== current.hasFocusAt

    if ((focusAtUpdated || refUpdated) && current.hasFocusAt) {
      // if search mode changed and we're having focus always ensure the
      // ref element gets focus
      focusElementRef.current?.focus()
    }
  })
  const weakIs = value?._weak ? 'weak' : 'strong'
  const weakShouldBe = type.weak === true ? 'weak' : 'strong'

  const hasRef = valueHasRef(value)
  // If the reference value is marked with _strengthenOnPublish,
  // we allow weak references if the reference points to a document that has a draft but not a published
  // In all other cases we should display a "weak mismatch" warning
  const weakWarningOverride =
    hasRef && !loadableReferenceInfo.isLoading && value?._strengthenOnPublish

  const handleFixStrengthMismatch = useCallback(() => {
    onChange(PatchEvent.from(type.weak === true ? set(true, ['_weak']) : unset(['_weak'])))
  }, [onChange, type])

  const referenceExists = hasRef && loadableReferenceInfo.result?.preview?.published?._id

  const handleRemoveStrengthenOnPublish = useCallback(() => {
    onChange(
      PatchEvent.from([
        type.weak === true ? set(true, ['_weak']) : unset(['_weak']),
        unset(['_strengthenOnPublish']),
      ])
    )
  }, [onChange, type])

  const {push} = useToast()

  const validation = useMemo(() => markers.filter(isValidationMarker), [markers])
  const errors = useMemo(() => validation.filter(isValidationErrorMarker), [validation])

  const pressed = selectedState === 'pressed'
  const selected = selectedState === 'selected'
  const handleFocus = useCallback(
    (event) => {
      if (onFocus && event.currentTarget === focusElementRef.current) {
        onFocus([])
      }
    },
    [onFocus, focusElementRef]
  )

  const handleAutocompleteFocus = useCallback(
    (event) => {
      if (onFocus && event.currentTarget === focusElementRef.current) {
        onFocus(['_ref'])
      }
    },
    [onFocus, focusElementRef]
  )

  const handleQueryChange = useObservableCallback((inputValue$: Observable<string | null>) => {
    return inputValue$.pipe(
      filter(isNonNullable),
      distinctUntilChanged(),
      switchMap((searchString) =>
        concat(
          of({isLoading: true}),
          onSearch(searchString).pipe(
            map((hits) => ({hits, isLoading: false, searchString})),
            catchError((error) => {
              push({
                title: 'Reference search failed',
                description: error.message,
                status: 'error',
                id: `reference-search-fail-${inputId}`,
              })
              console.error(error)
              return of({hits: []})
            })
          )
        )
      ),
      scan(
        (prevState, nextState): SearchState => ({...prevState, ...nextState}),
        INITIAL_SEARCH_STATE
      ),
      tap(setSearchState)
    )
  }, [])

  const handleAutocompleteOpenButtonClick = useCallback(() => {
    handleQueryChange('')
  }, [handleQueryChange])

  const showWeakRefMismatch =
    !loadableReferenceInfo.isLoading && hasRef && weakIs !== weakShouldBe && !weakWarningOverride

  const inputId = useId()

  const handleCreateButtonKeyDown = useCallback(
    (e) => {
      if (e.key === 'Escape') {
        focusElementRef.current?.focus()
      }
    },
    [focusElementRef]
  )

  const renderOption = useCallback(
    (option) => {
      const id = option.hit.draft?._id || option.hit.published?._id

      return (
        <PreviewCard as="button" type="button" radius={2}>
          <Box paddingX={3} paddingY={1}>
            <OptionPreview getReferenceInfo={getReferenceInfoMemo} id={id} type={type} />
          </Box>
        </PreviewCard>
      )
    },
    [type, getReferenceInfoMemo]
  )

  const OpenLink = useMemo(
    () =>
      // eslint-disable-next-line @typescript-eslint/no-shadow
      forwardRef(function OpenLink(
        restProps: ComponentProps<typeof IntentLink>,
        _ref: ForwardedRef<HTMLAnchorElement>
      ) {
        const template = (value?._strengthenOnPublish || {}).template
        return (
          <IntentLink
            {...restProps}
            intent="edit"
            params={[
              {id: value?._ref, type: refType?.name, template: template?.id},
              {params: template?.params},
            ]}
            target="_blank"
            rel="noopener noreferrer"
            ref={_ref}
          />
        )
      }),
    [refType?.name, value?._ref, value?._strengthenOnPublish]
  )

  const preview =
    loadableReferenceInfo.result?.preview.draft || loadableReferenceInfo.result?.preview.published

  const isEditing = hasFocusAtRef

  // --- click outside handling
  const clickOutsideBoundaryRef = useRef<HTMLDivElement>()
  const autocompletePortalRef = useRef<HTMLDivElement>()
  const createButtonMenuPortalRef = useRef<HTMLDivElement>()
  useOnClickOutside(
    [clickOutsideBoundaryRef, autocompletePortalRef, createButtonMenuPortalRef],
    () => {
      if (isEditing) {
        handleCancelEdit()
      }
    }
  )

  const autocompletePopoverReferenceElementRef = useRef()

  return (
    <RowWrapper
      radius={2}
      padding={1}
      tone={
        (isEditing
          ? ' default'
          : readOnly
          ? 'transparent'
          : loadableReferenceInfo.error || errors.length > 0
          ? 'critical'
          : showWeakRefMismatch
          ? 'caution'
          : 'default') as CardTone
      }
    >
      <Flex align="center">
        {!isEditing && isSortable && !readOnly && (
          <Card className="dragHandle" tone="inherit" marginRight={1}>
            {dragHandle}
          </Card>
        )}

        {isEditing ? (
          <Box flex={1} padding={1} ref={clickOutsideBoundaryRef}>
            <FormField
              __unstable_markers={markers}
              __unstable_presence={presence}
              __unstable_changeIndicator={false}
              inputId={inputId}
              title={type.title}
              level={level}
              description={type.description}
            >
              <AutocompleteContainer ref={autocompletePopoverReferenceElementRef}>
                <ReferenceAutocomplete
                  data-testid="autocomplete"
                  loading={searchState.isLoading}
                  portalRef={autocompletePortalRef}
                  ref={focusElementRef}
                  id={inputId || ''}
                  options={searchState.hits.map((hit) => ({
                    value: hit.id,
                    hit: hit,
                  }))}
                  onFocus={handleAutocompleteFocus}
                  onBlur={onBlur}
                  radius={1}
                  placeholder="Type to search"
                  onKeyDown={handleAutocompleteKeyDown}
                  readOnly={readOnly}
                  disabled={loadableReferenceInfo.isLoading}
                  onQueryChange={handleQueryChange}
                  searchString={searchState.searchString}
                  onChange={handleChange}
                  referenceElement={autocompletePopoverReferenceElementRef.current}
                  filterOption={NO_FILTER}
                  renderOption={renderOption}
                  openButton={{onClick: handleAutocompleteOpenButtonClick}}
                />
                {!readOnly && createOptions.length > 0 && (
                  <CreateButton
                    menuRef={createButtonMenuPortalRef}
                    id={`${inputId}-selectTypeMenuButton`}
                    createOptions={createOptions}
                    onCreate={handleCreateNew}
                    onKeyDown={handleCreateButtonKeyDown}
                  />
                )}
              </AutocompleteContainer>
            </FormField>
          </Box>
        ) : (
          <Box flex={1}>
            <Flex align="center">
              {hasRef ? (

              ) : (
                <Card
                  flex={1}
                  padding={3}
                  marginRight={1}
                  radius={2}
                  tone="inherit"
                  as="button"
                  __unstable_focusRing
                  tabIndex={0}
                  onClick={() => onFocus?.(['_ref'])}
                  ref={focusElementRef}
                >
                  <Box marginY={1}>
                    <Text muted>Empty reference</Text>
                  </Box>
                </Card>
              )}
              <Inline marginLeft={!readOnly && presence.length > 0 ? 2 : undefined}>
                {!readOnly && presence.length > 0 && (
                  <Box marginLeft={1}>
                    <FieldPresence presence={presence} maxAvatars={1} />
                  </Box>
                )}
                {validation.length > 0 && (
                  <Box marginLeft={1} paddingX={1} paddingY={3}>
                    <FormFieldValidationStatus __unstable_markers={validation} />
                  </Box>
                )}
                {!value._key && (
                  <Box marginLeft={1}>
                    <Tooltip
                      content={
                        <Box padding={2}>
                          <Text muted size={1}>
                            This item is missing the required _key property.
                          </Text>
                        </Box>
                      }
                      placement="top"
                    >
                      <Badge mode="outline" tone="caution">
                        Missing key
                      </Badge>
                    </Tooltip>
                  </Box>
                )}
              </Inline>
            </Flex>
          </Box>
        )}
        {!isEditing && (
          <Box marginLeft={1}>
            <MenuButton
              button={<Button paddingY={3} paddingX={2} mode="bleed" icon={EllipsisVerticalIcon} />}
              id={`${inputId}-menuButton`}
              menu={
                <Menu>
                  {!readOnly && (
                    <>
                      <MenuItem
                        text="Remove"
                        tone="critical"
                        icon={TrashIcon}
                        onClick={handleClear}
                      />
                      <MenuItem
                        text="Replace"
                        icon={ReplaceIcon}
                        onClick={() => {
                          onFocus?.(['_ref'])
                        }}
                      />
                      <MenuItem text="Duplicate" icon={DuplicateIcon} onClick={handleDuplicate} />
                      <InsertMenu onInsert={handleInsert} types={insertableTypes} />
                    </>
                  )}
                  {!readOnly && hasRef && <MenuDivider />}
                  {hasRef && (
                    <MenuItem
                      as={OpenLink}
                      data-as="a"
                      text="Open in new tab"
                      icon={OpenInNewTabIcon}
                    />
                  )}
                </Menu>
              }
              placement="right"
              popover={{portal: true, tone: 'default'}}
            />
          </Box>
        )}
      </Flex>
      {liveEdit && referenceExists && value._strengthenOnPublish && (
        <AlertStrip
          padding={1}
          title={type.weak ? 'Finalize reference' : 'Convert to strong reference'}
          status="info"
          data-testid="alert-reference-published"
        >
          <Stack space={3}>
            <Text as="p" muted size={1}>
              {loadableReferenceInfo.result.preview.published.title} is published
              and this reference should now be{' '}
              {type.weak ? <>finalized</> : <>converted to a strong reference</>}.
            </Text>
            <Button
              onClick={handleRemoveStrengthenOnPublish}
              text={<>Convert to strong reference</>}
              tone="positive"
            />
          </Stack>
        </AlertStrip>
      )}
      {showWeakRefMismatch && (
        <AlertStrip
          padding={1}
          title="Reference strength mismatch"
          status="warning"
          data-testid="alert-reference-strength-mismatch"
        >
          <Stack space={3}>
            <Text as="p" muted size={1}>
              This reference is {weakIs}, but according to the current schema it should be{' '}
              {weakShouldBe}.
            </Text>

            <Text as="p" muted size={1}>
              {type.weak ? (
                <>
                  It will not be possible to delete the "{preview?.title}"-document without first
                  removing this reference.
                </>
              ) : (
                <>
                  This makes it possible to delete the "{preview?.title}"-document without first
                  deleting this reference, leaving this field referencing a nonexisting document.
                </>
              )}
            </Text>
            <Button
              onClick={handleFixStrengthMismatch}
              text={<>Convert to {weakShouldBe} reference</>}
              tone="caution"
            />
          </Stack>
        </AlertStrip>
      )}
      {loadableReferenceInfo.error && (
        <AlertStrip
          padding={1}
          title="Unable to load reference metadata"
          status="warning"
          data-testid="alert-reference-info-failed"
        >
          <Stack space={3}>
            <Text as="p" muted size={1}>
              Error: {loadableReferenceInfo.error.message}
            </Text>
            <Button onClick={loadableReferenceInfo.retry!} text={<>Retry</>} tone="primary" />
          </Stack>
        </AlertStrip>
      )}
    </RowWrapper>
  )
})


text:
/**
 *
 * @file libscp_v1c.h
 * @brief libscp version 1 client api declarations
 * @author Simone Fedele
 *
 */

#ifndef LIBSCP_V1C_H
#define LIBSCP_V1C_H

#include "libscp.h"

/* client API */
/* 001 */
enum SCP_CLIENT_STATES_E scp_v1c_connect(struct SCP_CONNECTION* c, struct SCP_SESSION* s);

/* 004 */
enum SCP_CLIENT_STATES_E scp_v1c_resend_credentials(struct SCP_CONNECTION* c, struct SCP_SESSION* s);

/* 021 */
enum SCP_CLIENT_STATES_E scp_v1c_pwd_change(struct SCP_CONNECTION* c, char* newpass);

/* 022 */
enum SCP_CLIENT_STATES_E scp_v1c_pwd_change_cancel(struct SCP_CONNECTION* c);

/* 041 */
enum SCP_CLIENT_STATES_E scp_v1c_get_session_list(struct SCP_CONNECTION* c, int* scount, struct SCP_DISCONNECTED_SESSION** s);

/* 043 */
enum SCP_CLIENT_STATES_E scp_v1c_select_session(struct SCP_CONNECTION* c, struct SCP_SESSION* s, SCP_SID sid);

/* 044 */
enum SCP_CLIENT_STATES_E scp_v1c_select_session_cancel(struct SCP_CONNECTION* c);

#endif


text:
package org.zaproxy.zap.extension.globalexcludeurl;

import org.zaproxy.zap.utils.Enableable;

/** TODO The GlobalExcludeURL functionality is currently alpha and subject to change.  */
class GlobalExcludeURLParamToken extends Enableable {

    private String regex;
    private String description;

    public GlobalExcludeURLParamToken() {
        this("", "", false);
    }

    public GlobalExcludeURLParamToken(String regex) {
        this(regex, "", false);
    }

    public GlobalExcludeURLParamToken(String regex, boolean enabled) {
        this(regex, "", false);
    }

    public GlobalExcludeURLParamToken(String regex, String description, boolean enabled) {
        super(enabled);

        this.regex = regex;
        this.description = description;
    }

    public GlobalExcludeURLParamToken(GlobalExcludeURLParamToken token) {
        this(token.regex, token.description, token.isEnabled());
    }

    public String getRegex() {
        return regex;
    }

    public void setRegex(String regex) {
        this.regex = regex;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public int hashCode() {
        return 31 * super.hashCode() + ((regex == null) ? 0 : regex.hashCode());
    }

    @Override
    /** If the regexs are equal, then the objects are equal; description is not compared. */
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!super.equals(obj)) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        GlobalExcludeURLParamToken other = (GlobalExcludeURLParamToken) obj;
        if (regex == null) {
            if (other.regex != null) {
                return false;
            }
        } else if (!regex.equals(other.regex)) {
            return false;
        }
        return true;
    }
}


text:
public class Parent
{
	public Parent () { }
	private Collide Collide;
}

public class Child : Parent
{
	public class Nested
	{
		public readonly Collide Test;

		public Nested ()
		{
			Test = Collide.Die;
		}
	}
}

public class Collide
{
	public Collide (int a)
	{
		this.A = a;
	}

	public readonly int A;
	public static readonly Collide Die = new Collide (5);

	public static int Main ()
	{
		Child.Nested nested = new Child.Nested ();
		if (nested.Test.A != 5)
			return 1;
		return 0;
	}
}


text:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

use yii\captcha\Captcha;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */

$this->title = 'Sign In';

$fieldOptions1 = [
    'options' => ['class' => 'form-group has-feedback'],
    'inputTemplate' => "{input}"
];

$fieldOptions2 = [
    'options' => ['class' => 'form-group has-feedback'],
    'inputTemplate' => "{input}"
];
?>
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Ling's CMS Login</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">

        <link rel="stylesheet" href="../css/reset.css">
        <link rel="stylesheet" href="../css/supersized.css">
        <link rel="stylesheet" href="../css/style.css">

Login

            <?php $form = ActiveForm::begin(['id' => 'login-form', 'enableClientValidation' => false]); ?>

            <?= $form
                ->field($model, 'username', $fieldOptions1)
                ->label(false)
                ->error(false)
                ->textInput(['placeholder' => $model->getAttributeLabel('username')]) ?>

            <?= $form
                ->field($model, 'password', $fieldOptions2)
                ->label(false)
                ->error(false)
                ->passwordInput(['placeholder' => $model->getAttributeLabel('password')]) ?>

                    <?= Html::submitButton('Sign in', ['class' => 'btn btn-primary btn-block btn-flat', 'id' => 'submit']) ?>

            <?php ActiveForm::end(); ?>

<?=Html::encode($motto['english'])?>

<?=Html::encode($motto['chinese'])?>

消息

确定


text:
Kevin Greene - @SurrealAnalysis

kevingreene.github.io/functional-programming-talk/

### Motivation

In my experience, OOP can lead to programs that are:

* Hard to reason about
* Hard to make concurrent
* Prone to state based bugs
* Prone to being incredibly large


text:
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"net/http"
	"net/url"
)

func ssoRedirectHandler(w http.ResponseWriter, r *http.Request) {
	commenterToken := r.FormValue("commenterToken")
	domain := r.Header.Get("Referer")

	if commenterToken == "" {
		fmt.Fprintf(w, "Error: %s\n", errorMissingField.Error())
		return
	}

	domain = domainStrip(domain)
	if domain == "" {
		fmt.Fprintf(w, "Error: No Referer header found in request\n")
		return
	}

	_, err := commenterGetByCommenterToken(commenterToken)
	if err != nil && err != errorNoSuchToken {
		fmt.Fprintf(w, "Error: %s\n", err.Error())
		return
	}

	d, err := domainGet(domain)
	if err != nil {
		fmt.Fprintf(w, "Error: %s\n", errorNoSuchDomain.Error())
		return
	}

	if !d.SsoProvider {
		fmt.Fprintf(w, "Error: SSO not configured for %s\n", domain)
		return
	}

	if d.SsoSecret == "" || d.SsoUrl == "" {
		fmt.Fprintf(w, "Error: %s\n", errorMissingConfig.Error())
		return
	}

	key, err := hex.DecodeString(d.SsoSecret)
	if err != nil {
		logger.Errorf("cannot decode SSO secret as hex: %v", err)
		fmt.Fprintf(w, "Error: %s\n", err.Error())
		return
	}

	token, err := ssoTokenNew(domain, commenterToken)
	if err != nil {
		fmt.Fprintf(w, "Error: %s\n", err.Error())
		return
	}

	tokenBytes, err := hex.DecodeString(token)
	if err != nil {
		logger.Errorf("cannot decode hex token: %v", err)
		fmt.Fprintf(w, "Error: %s\n", errorInternal.Error())
		return
	}

	h := hmac.New(sha256.New, key)
	h.Write(tokenBytes)
	signature := hex.EncodeToString(h.Sum(nil))

	u, err := url.Parse(d.SsoUrl)
	if err != nil {
		// this should really not be happening; we're checking if the
		// passed URL is valid at domain update
		logger.Errorf("cannot parse URL: %v", err)
		fmt.Fprintf(w, "Error: %s\n", errorInternal.Error())
		return
	}

	q := u.Query()
	q.Set("token", token)
	q.Set("hmac", signature)
	u.RawQuery = q.Encode()

	http.Redirect(w, r, u.String(), http.StatusFound)
}


text:
@interface Login_ViewController : UIViewController
@property (unsafe_unretained, nonatomic) IBOutlet UITextField *UserName;
@property (unsafe_unretained, nonatomic) IBOutlet UITextField *Password;
@property (unsafe_unretained, nonatomic) IBOutlet UIButton *btn_login;
@property (nonatomic, retain) IBOutlet UIView *mrView;

@end


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

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;

import java.util.List;

import org.flowable.cmmn.api.runtime.CaseInstance;
import org.flowable.cmmn.api.runtime.PlanItemDefinitionType;
import org.flowable.cmmn.api.runtime.PlanItemInstance;
import org.flowable.cmmn.api.runtime.PlanItemInstanceState;
import org.flowable.cmmn.api.runtime.UserEventListenerInstance;
import org.flowable.cmmn.engine.test.CmmnDeployment;
import org.flowable.cmmn.engine.test.FlowableCmmnTestCase;
import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.impl.util.CollectionUtil;
import org.flowable.task.api.Task;
import org.junit.Test;

/**
 * @author Joram Barrez
 */
public class RequiredRuleTest extends FlowableCmmnTestCase {

    @Test
    @CmmnDeployment
    public void testOneRequiredHumanTask() {

        // The required task is made active, the non-required not.
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
                .caseDefinitionKey("testOneRequiredHumanTask")
                .variable("required", true)
                .start();

        List<PlanItemInstance> planItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery()
                .caseInstanceId(caseInstance.getId()).orderByName().asc().list();
        assertThat(planItemInstances)
                .extracting(PlanItemInstance::getName, PlanItemInstance::getState)
                .containsExactly(
                        tuple("Non-required task", PlanItemInstanceState.AVAILABLE),
                        tuple("Required task", PlanItemInstanceState.ACTIVE)
                );

        Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
        assertThat(task.getName()).isEqualTo("Required task");

        // Completing the task should autocomplete the plan model, as the plan model is autoComplete enabled
        cmmnTaskService.complete(task.getId());
        assertCaseInstanceEnded(caseInstance);

        // Both required and non-required task are made active.
        caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
                .caseDefinitionKey("testOneRequiredHumanTask")
                .variable("required", true)
                .variable("nonRequired", true)
                .start();

        planItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery()
                .caseInstanceId(caseInstance.getId()).orderByName().asc().list();
        assertThat(planItemInstances)
                .extracting(PlanItemInstance::getName, PlanItemInstance::getState)
                .containsExactly(
                        tuple("Non-required task", PlanItemInstanceState.ACTIVE),
                        tuple("Required task", PlanItemInstanceState.ACTIVE)
                );

        List<Task> tasks = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).orderByTaskName().asc().list();
        assertThat(planItemInstances)
                .extracting(PlanItemInstance::getName)
                .containsExactly("Non-required task", "Required task");

        // Completing the required task should not autocomplete the plan model
        cmmnTaskService.complete(tasks.get(1).getId());
        assertCaseInstanceNotEnded(caseInstance);

        cmmnTaskService.complete(tasks.get(0).getId());
        assertCaseInstanceEnded(caseInstance);
    }

    @Test
    @CmmnDeployment
    public void testOneRequiredHumanTaskInStage() {

        // The required task is made active, the non-required not.
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
                .caseDefinitionKey("testOneRequiredHumanTaskInStage")
                .variable("required", true)
                .start();

        List<PlanItemInstance> planItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery()
                .caseInstanceId(caseInstance.getId()).orderByName().asc().list();
        assertThat(planItemInstances)
                .extracting(PlanItemInstance::getName, PlanItemInstance::getState)
                .containsExactly(
                        tuple("Non-required task", PlanItemInstanceState.AVAILABLE),
                        tuple("Other task", PlanItemInstanceState.ACTIVE),
                        tuple("Required task", PlanItemInstanceState.ACTIVE),
                        tuple("The Stage", PlanItemInstanceState.ACTIVE)
                );

        Task task = cmmnTaskService.createTaskQuery().taskName("Required task").singleResult();
        assertThat(task.getName()).isEqualTo("Required task");

        // Completing the task should autocomplete the stage
        cmmnTaskService.complete(task.getId());
        assertCaseInstanceNotEnded(caseInstance);
        planItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).list();
        assertThat(cmmnRuntimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).count()).isEqualTo(1);

        cmmnTaskService.complete(cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult().getId());
        assertCaseInstanceEnded(caseInstance);

        // Both required and non-required task are made active.
        caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
                .caseDefinitionKey("testOneRequiredHumanTaskInStage")
                .variable("required", true)
                .variable("nonRequired", true)
                .start();

        planItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery()
                .caseInstanceId(caseInstance.getId()).orderByName().asc().list();
        assertThat(planItemInstances)
                .extracting(PlanItemInstance::getName, PlanItemInstance::getState)
                .containsExactly(
                        tuple("Non-required task", PlanItemInstanceState.ACTIVE),
                        tuple("Other task", PlanItemInstanceState.ACTIVE),
                        tuple("Required task", PlanItemInstanceState.ACTIVE),
                        tuple("The Stage", PlanItemInstanceState.ACTIVE)
                );

        Task otherTask = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).taskName("Other task").singleResult();
        cmmnTaskService.complete(otherTask.getId());

        List<Task> tasks = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).orderByTaskName().asc().list();
        assertThat(tasks)
                .extracting(Task::getName)
                .containsExactly("Non-required task", "Required task");

        cmmnTaskService.complete(tasks.get(1).getId());
        assertCaseInstanceNotEnded(caseInstance);

        cmmnTaskService.complete(tasks.get(0).getId());
        assertCaseInstanceEnded(caseInstance);
    }

    @Test
    @CmmnDeployment
    public void testNonAutoCompleteStageManualCompleteable() {
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
                .caseDefinitionKey("testNonAutoCompleteStageManualCompleteable")
                .variable("required", true)
                .start();

        PlanItemInstance stagePlanItemInstance = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.STAGE)
                .singleResult();
        assertThat(stagePlanItemInstance.getState()).isEqualTo(PlanItemInstanceState.ACTIVE);
        assertThat(stagePlanItemInstance.isCompletable()).isFalse();

        // Completing the one task should mark the stage as completeable
        Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
        assertThat(task.getName()).isEqualTo("Required task");
        cmmnTaskService.complete(task.getId());

        stagePlanItemInstance = cmmnRuntimeService.createPlanItemInstanceQuery().planItemInstanceId(stagePlanItemInstance.getId()).singleResult();
        assertThat(stagePlanItemInstance.getState()).isEqualTo(PlanItemInstanceState.ACTIVE);
        assertThat(stagePlanItemInstance.isCompletable()).isTrue();
        assertThat(cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count()).isZero();

        // Making the other task active, should disable the completeable flag again
        cmmnRuntimeService.setVariables(caseInstance.getId(), CollectionUtil.singletonMap("nonRequired", true));
        assertThat(cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count()).isEqualTo(1);

        stagePlanItemInstance = cmmnRuntimeService.createPlanItemInstanceQuery().planItemInstanceId(stagePlanItemInstance.getId()).singleResult();
        assertThat(stagePlanItemInstance.getState()).isEqualTo(PlanItemInstanceState.ACTIVE);
        assertThat(stagePlanItemInstance.isCompletable()).isFalse();
    }

    @Test
    @CmmnDeployment
    public void testCompleteStageManually() {
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
                .caseDefinitionKey("testNonAutoCompleteStageManualCompleteable")
                .variable("required", true)
                .start();

        final PlanItemInstance stagePlanItemInstance1 = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.STAGE)
                .singleResult();
        assertThat(stagePlanItemInstance1.getState()).isEqualTo(PlanItemInstanceState.ACTIVE);
        assertThat(stagePlanItemInstance1.isCompletable()).isFalse();

        assertThatThrownBy(() -> cmmnRuntimeService.completeStagePlanItemInstance(stagePlanItemInstance1.getId()))
                .isInstanceOf(FlowableIllegalArgumentException.class)
                .hasMessage("Can only complete a stage plan item instance that is marked as completable (there might still be active plan item instance).");

        // Completing the one task should mark the stage as completeable
        Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
        assertThat(task.getName()).isEqualTo("Required task");
        cmmnTaskService.complete(task.getId());

        PlanItemInstance stagePlanItemInstance2 = cmmnRuntimeService.createPlanItemInstanceQuery().planItemInstanceId(stagePlanItemInstance1.getId())
                .singleResult();
        assertThat(stagePlanItemInstance2.getState()).isEqualTo(PlanItemInstanceState.ACTIVE);
        assertThat(stagePlanItemInstance2.isCompletable()).isTrue();
        assertThat(cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count()).isZero();

        assertThat(cmmnRuntimeService.createPlanItemInstanceQuery().planItemInstanceCompletable().singleResult()).isNotNull();
        cmmnRuntimeService.completeStagePlanItemInstance(stagePlanItemInstance2.getId());
        assertCaseInstanceEnded(caseInstance);
    }

    @Test
    @CmmnDeployment
    public void testCompleteCaseInstanceManually() {
        CaseInstance caseInstance1 = cmmnRuntimeService.createCaseInstanceBuilder()
                .caseDefinitionKey("testCompleteCaseInstanceManually")
                .variable("required", true)
                .start();

        assertThat(caseInstance1.isCompletable()).isFalse();
        assertThat(cmmnRuntimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance1.getId()).planItemInstanceStateActive().count()).isEqualTo(2);
        assertThat(cmmnRuntimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance1.getId()).planItemInstanceStateAvailable().count())
                .isEqualTo(1);

        List<Task> tasks = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance1.getId()).orderByTaskName().asc().list();
        assertThat(tasks)
                .extracting(Task::getName)
                .containsExactly("Other task", "Required task");

        // Case should not be completeable
        assertThatThrownBy(() -> cmmnRuntimeService.completeCaseInstance(caseInstance1.getId()))
                .isInstanceOf(FlowableIllegalArgumentException.class)
                .hasMessage("Can only complete a case instance which is marked as completeable. Check if there are active plan item instances.");

        // Completing both tasks should not auto complete the case, as the plan model is not auto complete
        for (Task task : tasks) {
            cmmnTaskService.complete(task.getId());
        }

        CaseInstance caseInstance2 = cmmnRuntimeService.createCaseInstanceQuery().caseInstanceId(caseInstance1.getId()).singleResult();
        assertThat(caseInstance2.isCompletable()).isTrue();
        cmmnRuntimeService.completeCaseInstance(caseInstance2.getId());
        assertCaseInstanceEnded(caseInstance2);
    }

    @Test
    @CmmnDeployment
    public void testComplexCase() {
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
                .caseDefinitionKey("myCase")
                .variable("dRequired", false)
                .variable("enableSubStage", true)
                .start();

        Task taskA = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
        assertThat(taskA).isNotNull();
        cmmnTaskService.complete(taskA.getId());

        List<Task> tasks = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).orderByTaskName().asc().list();
        assertThat(tasks)
                .extracting(Task::getName)
                .containsExactly("D");

        // D is required. So completing D will auto complete the stage
        cmmnTaskService.complete(tasks.get(0).getId());
        assertThat(cmmnRuntimeService.createMilestoneInstanceQuery().milestoneInstanceCaseInstanceId(caseInstance.getId()).count())
                .isEqualTo(2); // M1 is never reached. M2 and M3 are

        tasks = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).orderByTaskName().asc().list();
        assertThat(tasks)
                .extracting(Task::getName)
                .containsExactly("G");

        // G is the only required task. Completing it should complete the stage and case instance
        cmmnTaskService.complete(tasks.get(0).getId());
        assertCaseInstanceEnded(caseInstance);
    }

    @Test
    @CmmnDeployment
    public void testComplexCase02() {

        // Same as testComplexCase, but now B and E are manually enabled

        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
                .caseDefinitionKey("myCase")
                .variable("dRequired", false)
                .variable("enableSubStage", false)
                .variable("booleanVar", true)
                .variable("subStageRequired", false)
                .start();

        Task taskA = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
        assertThat(taskA).isNotNull();
        cmmnTaskService.complete(taskA.getId());

        PlanItemInstance planItemInstanceB = cmmnRuntimeService.createPlanItemInstanceQuery().planItemInstanceName("B").singleResult();
        assertThat(planItemInstanceB.getState()).isEqualTo(PlanItemInstanceState.ENABLED);
        cmmnRuntimeService.startPlanItemInstance(planItemInstanceB.getId());

        List<Task> tasks = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).orderByTaskName().asc().list();
        assertThat(tasks)
                .extracting(Task::getName)
                .containsExactly("B", "D");

        // D is required. But B is still active
        cmmnTaskService.complete(tasks.get(1).getId());
        assertThat(cmmnRuntimeService.createMilestoneInstanceQuery().milestoneInstanceCaseInstanceId(caseInstance.getId()).count()).isZero();
        cmmnTaskService.complete(tasks.get(0).getId());
        assertThat(cmmnRuntimeService.createMilestoneInstanceQuery().milestoneInstanceCaseInstanceId(caseInstance.getId()).count()).isEqualTo(1);

        tasks = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).orderByTaskName().asc().list();
        assertThat(tasks)
                .extracting(Task::getName)
                .containsExactly("C");

        // There are no active tasks in the second stage (as the nested stage is not active and not required).
        // Stage should autocomplete immediately after task completion
        cmmnTaskService.complete(tasks.get(0).getId());
        assertCaseInstanceEnded(caseInstance);
    }

    @Test
    @CmmnDeployment
    public void repetitiveStageWithRequiredItem() {
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
                .caseDefinitionKey("repetitionWithRequired")
                .start();

        // start human task and complete it
        UserEventListenerInstance userEventListenerInstance = cmmnRuntimeService.createUserEventListenerInstanceQuery()
                .caseInstanceId(caseInstance.getId())
                .name("Start from outside")
                .singleResult();
        cmmnRuntimeService.completeUserEventListenerInstance(userEventListenerInstance.getId());

        Task task = cmmnTaskService.createTaskQuery()
                .caseInstanceId(caseInstance.getId())
                .singleResult();
        assertThat(task).isNotNull();
        cmmnTaskService.complete(task.getId()); // runs in an infinitive loop in case required is not stage scoped

        // terminate instance since there is no other way to end it
        cmmnRuntimeService.terminateCaseInstance(caseInstance.getId());
    }

}


text:
module.exports = {
  presets: ["@babel/preset-env"],
  plugins: ["@babel/plugin-proposal-class-properties"],
};


text:
namespace BurningEngine
{
    Entity::Entity()
        : m_components(Entity::GetComponentId)
        , m_componentEventHandlerRoot( std::make_shared<ComponentEventHandlerComposite>() )
    {
    }

    int Entity::GetId()
    {
        return m_id;
    }

    void Entity::AddComponent( std::shared_ptr<Component> spComp )
    {
        // Add Component
        m_components.push_back(spComp);
        // Register for Event
        m_componentEventHandlerRoot->Composite()->Subscribe(spComp.get());
    }

    void Entity::RemoveComponent( int id )
    {
        // Unsubscribe for Event
        m_componentEventHandlerRoot->Composite()->Unsubscribe(m_components.GetItem(id).get());
        // Remove Component
        m_components.RemoveItem(id);
    }

    void Entity::Clear()
    {
        std::vector<int> ids;
        std::transform(m_components.begin(), m_components.end(), ids.begin(), GetComponentId);
        for( int id : ids )
            RemoveComponent(id);
    }

    int Entity::GetComponentId( std::shared_ptr<Component>& spComp )
    {
        BE_ASSERT(spComp != nullptr);
        return spComp->GetId();
    }

} // namespace BurningEngine


text:
using System.Net.Configuration;

public abstract class Animal
{
    private string name;
    private int age;
    private bool cleansingStatus;
    private bool isCastradet;

    protected Animal(string name, int age)
    {
        this.name = name;
        this.age = age;
        this.cleansingStatus = false;
        this.isCastradet = false;
    }

    public bool IsCastrated { get; set; }

    public string Name
    {
        get { return this.name; }
    }

    public bool CleansingStatus
    {
        get { return this.cleansingStatus; }
        set { this.cleansingStatus = value; }
    }
}


text:
<?php

/**
 * PullRequestState.php
 *
 * @author Dennis de Greef <github@link0.net>
 */
namespace LonelyPullRequests\Domain;

use Assert\Assertion as Ensure;

/**
 * Class PullRequestState models all the state a pull request can be in
 *
 * @package LonelyPullRequests\Domain
 */
final class PullRequestState
{
    /**
     * @const string
     */
    const STATE_OPEN = 'open';

    /**
     * @const string
     */
    const STATE_CLOSED = 'closed';

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

    /**
     * @param string $state
     */
    private function __construct($state)
    {
        Ensure::string($state, 'Pull request state is not of type string');
        Ensure::inArray($state, [
            self::STATE_OPEN,
            self::STATE_CLOSED,
        ], 'Unknown pull request state');

        $this->state = $state;
    }

    /**
     * @param string $pullRequestState
     *
     * @return PullRequestState
     */
    public static function fromString($pullRequestState)
    {
        return new self($pullRequestState);
    }

    /**
     * @return string
     */
    public function toString()
    {
        return $this->state;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->toString();
    }

    /**
     * This method compares a given state with the current
     *
     * @param string $pullRequestState
     *
     * @return bool
     */
    public function equals($pullRequestState)
    {
        return self::fromString($pullRequestState)->toString() === $this->toString();
    }
}


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

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var fruitList = new List<string>();

            fruitList.Add("Apple");
            fruitList.Add("orange");
            fruitList.Add("fi1g");

            foreach (var item in fruitList)
            {
                Console.WriteLine(item);
            }

            fruitList.Sort();

            foreach (var item in fruitList)
            {
                Console.WriteLine(item);
            }

            listpass(fruitList);
        }

        static void listpass(List<string> items)
        {
            string figReport = items.Contains("fig", StringComparer.OrdinalIgnoreCase) ?
                "yes there is some figs" :
                "No figs there";
            Console.WriteLine(figReport);

        }
    }
}


text:
package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/evalphobia/adventofcode/lib"
)

func main() {
	lib.ParseFlag()
	value := lib.GetValue()
	if value == "" {
		log.Fatal("cannot get value")
	}

	switch {
	case lib.GetPart() == 2:
		runPart2(value)
	default:
		runPart1(value)
	}
}

func runPart1(value string) {
	result := solvePart1(value)
	fmt.Printf("Answer: %d\n", result)
}

func solvePart1(val string) int {
	up := strings.Count(val, "(")
	down := strings.Count(val, ")")
	return up - down
}

func runPart2(value string) {
	result := solvePart2(value)
	fmt.Printf("Answer: %d\n", result)
}

func solvePart2(val string) int {
	floor := 0
	for i, v := range val {
		floor += getUpOrDown(string(v))
		if floor < 0 {
			return i + 1
		}
	}
	log.Fatalf("does not reach basement")
	return 0
}

func getUpOrDown(v string) int {
	switch v {
	case "(":
		return 1
	case ")":
		return -1
	}
	log.Fatalf("cannot parse value: %s", v)
	return 0
}


text:
import {Component, Input, EventEmitter, Output, SimpleChanges, OnChanges} from '@angular/core';
import {ISearchFilterDef, ISearchFilterDefType} from '../../../../app.interfaces';
import {I18NService} from '../../../../modules/i18n/services/i18n.service';
import {isFilterDef, isSearchDef} from '../../../../model/filters';

@Component({
	moduleId: __filename,
	selector: 'select-search-button',
	templateUrl: 'select-search-button.component.html',
	styleUrls: ['select-search-button.component.scss']
})
export class SelectSearchButtonComponent implements OnChanges {
	@Input()
	filters_all: Array<ISearchFilterDef>;
	@Input()
	filters_active: Array<ISearchFilterDef>;
	@Output()
	selectChange = new EventEmitter();
	showDialog = false;
	title: string;
	groups: Array<{
		name: string;
		filters: Array<{ active: boolean; isSearch: boolean; isFilter: boolean, filter: ISearchFilterDef, type: ISearchFilterDefType }>;
	}> = [];

	constructor(public i18n: I18NService) {
		this.title = i18n.get('Add Search Fields');
	}

	update(filter, isSearch): void {
		this.selectChange.emit({value: {isSearch: isSearch, filter: filter}});
	}

	public ngOnChanges(changes: SimpleChanges): void {
		if (!this.filters_all || !this.filters_active) {
			return;
		}
		let groups = {};
		this.filters_all.forEach(f => {
			let groupname = this.i18n.translateVariable(f.group || '_');
			groups[groupname] = groups[groupname] || {name: groupname, filters: []};
			groups[groupname].filters.push({
				active: this.filters_active.indexOf(f) >= 0,
				isSearch: isSearchDef(f),
				isFilter: isFilterDef(f),
				filter: f,
				type: ISearchFilterDefType[f.type]
			});
		});
		this.groups = Object.keys(groups).sort().map(key => groups[key]);
	}

}


text:
package lsp.models;

import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Created by admin on 28.10.2016.
 */
public class FoodTest {
    /**
     * var.
     */
    private static final int CARROT_EXPIRE = -2;
    /**
     * var.
     */
    private static final double CARROT_QUALITY = 0.5;
    /**
     * var.
     */
    private static final int PASTED_DAYS = 2;
    /**
     * var.
     */
    private static final int YEAR = 116;
    /**
     * var.
     */
    private static final int MONTH = 9;
    /**
     * var.
     */
    private static final int DAY_ONE = 26;
    /**
     * var.
     */
    private static final int DAY_TWO = 28;
    /**
     * test.
     * @throws Exception the exception
     */
        @Test
        public void whenWeDoAmortizeWeCanSeeQualityOfProduct() throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        Date one = calendar.getTime();
        calendar.add(Calendar.DAY_OF_YEAR, CARROT_EXPIRE);
        Date two = calendar.getTime();
        Food food = new Carrot("carrot", two, one);

        food.amortize();
        double checked = CARROT_QUALITY;
        double result = food.getDeprecation();

        assertThat(checked, is(result));
    }

    /**
     * test.
     * @throws Exception the exception
     */
    @Test
    public void whenWePastedDaysWeCountDays() throws Exception {
       Food food = new Carrot("carrot", new Date(YEAR, MONTH, DAY_ONE), new Date(YEAR, MONTH, DAY_TWO));
       double checked = PASTED_DAYS;
       double result = food.pastedDays(food.getExpaireDate(), food.getCreateDate());

       assertThat(checked, is(result));
    }
}


text:
package com.asakusafw.spark.runtime
package util

import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner

import com.asakusafw.spark.runtime.util.Iterators._

@RunWith(classOf[JUnitRunner])
class IteratorsSpecTest extends IteratorsSpec

class IteratorsSpec extends FlatSpec {

  behavior of Iterators.getClass.getSimpleName

  it should "groupByKey" in {
    val iter = Iterator((1, 10), (1, 11), (2, 20), (2, 21), (2, 22), (3, 30))

    val grouped = iter.groupByKey()

    assert(grouped.hasNext)
    val (key1, group1) = grouped.next()
    assert(key1 === 1)
    assert(group1.hasNext)
    assert(group1.next() === 10)
    assert(group1.next() === 11)
    assert(!group1.hasNext)

    assert(grouped.hasNext)
    val (key2, group2) = grouped.next()
    assert(key2 === 2)
    assert(group2.hasNext)
    assert(group2.next() === 20)

    // group2 has some more elements.
    assert(group2.hasNext)

    assert(grouped.hasNext)
    val (key3, group3) = grouped.next()
    assert(key3 === 3)
    assert(group3.hasNext)
    assert(group3.next() === 30)
    assert(!group3.hasNext)

    // the remains of group2 were dropped by `grouped.next()`.
    assert(!group2.hasNext)

    assert(!grouped.hasNext)
  }

  it should "sortmerge" in {
    val left = Iterator((1, 10), (1, 11), (2, 20), (4, 40))
    val right = Iterator((1, 12), (2, 21), (3, 30), (4, 41))

    assert(left.sortmerge(right).toSeq === Seq(
      (1, 10), (1, 11), (1, 12), (2, 20), (2, 21), (3, 30), (4, 40), (4, 41)))
  }
}


text:
package com.aerolitec.SMXL.ui.fragment;

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.aerolitec.SMXL.R;
import com.aerolitec.SMXL.model.GarmentType;
import com.aerolitec.SMXL.model.User;
import com.aerolitec.SMXL.tools.Constants;
import com.aerolitec.SMXL.tools.manager.UserManager;
import com.aerolitec.SMXL.ui.SMXL;
import com.aerolitec.SMXL.ui.adapter.TypeGarmentAdapter;

import java.util.ArrayList;

public class QuickSizeSelectGarmentFragment extends Fragment {

    private QuickSizeFragment quickSizeFragment;

    private GridView gvGarmentTypes;
    private User user;

    public QuickSizeSelectGarmentFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user = UserManager.get().getUser();
        quickSizeFragment = (QuickSizeFragment)getParentFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_quicksize_select_garment, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        gvGarmentTypes = (GridView) view.findViewById(R.id.gridViewGarmentTypes);
    }

    @Override
    public void onResume() {
        if(user == null)
        {
            user = UserManager.get().getUser();
        }
        fillGridView(gvGarmentTypes, getAllGarmentTypes());
        super.onResume();
    }

    private void fillGridView(GridView lv, ArrayList<GarmentType> garmentItems){
        lv.setAdapter(new TypeGarmentAdapter(getActivity(), R.layout.item_garment_with_icon, garmentItems));
        lv.setChoiceMode(GridView.CHOICE_MODE_SINGLE);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GarmentType selectedGarmentType = (GarmentType) parent.getItemAtPosition(position);
                String missingMeasure = checkValidMeasure(selectedGarmentType);
                //TODO Temporaire pour tester
                missingMeasure="";
                if (missingMeasure.isEmpty()) {
                    quickSizeFragment.setSelectedGarmentType(selectedGarmentType);
                    quickSizeFragment.getChildFragmentManager().beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.containerQuickSizeFragment, new QuickSizeSelectBrandFragment(), "brand")
                            .commit();
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setMessage(getString(R.string.message_enter_measures) +"\n" +missingMeasure)
                            .setTitle(R.string.missingMeasures).setNeutralButton(R.string.ok, null);

                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
            }
        });
    }

    private ArrayList<GarmentType> getAllGarmentTypes(){
        ArrayList<GarmentType> result = SMXL.getGarmentTypeDBManager().getAllGarmentTypesBySexOrderByPosition(user.getSexe());
        //TODO A changer
        switch (user.getSexe()){
            case 1 :
                result.remove(12);
                break;
            default:
                result.remove(14);
                break;
        }
        return result;
    }

    private String checkValidMeasure(GarmentType garmentType){
        int topBottomShoe = SMXL.getGarmentTypeDBManager().getOrderByCategoryGarment(garmentType);
        switch (topBottomShoe){
            case 1 :
                if(user.getChest()==0.0) {
                    return getString(R.string.libChest);
                }
                break;
            case 2 :
                if(user.getHips() == 0.0 || user.getWaist() == 0.0) {
                    if (user.getHips() == 0.0 && user.getWaist() == 0.0) {
                        return getString(R.string.libHips) + "\n" + getString(R.string.libWaist);
                    } else if (user.getHips() == 0.0){
                        return getString(R.string.libHips);
                    } else {
                        return getString(R.string.libWaist);
                    }
                }
                break;
            case 3 :
                if(user.getFeet() <= 0.0 ) {
                    return getString(R.string.libFeet);
                }
                break;
            default:
                break;
        }
        if(garmentType.getType().equalsIgnoreCase("CHEMISE")){
            if(user.getCollar()==0.0) {
                return getString(R.string.libCollar);
            }
        }
        return "";
    }

}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2015 Couchbase, Inc
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * This file defines the memory allocation hooks used on platforms
 * where we don't have a supported memory alloctor for memory tracking
 */

#include "config.h"

#include "alloc_hooks_dummy.h"

#include <memcached/extension_loggers.h>

void DummyAllocHooks::initialize() {
    get_stderr_logger()->log(EXTENSION_LOG_NOTICE, NULL,
                             "This version of Couchbase is built without "
                             "allocator hooks for accurate memory tracking");
}

bool DummyAllocHooks::add_new_hook(void (* hook)(const void* ptr, size_t size)) {
    return false;
}

bool DummyAllocHooks::remove_new_hook(void (* hook)(const void* ptr, size_t size)) {
    return false;
}

bool DummyAllocHooks::add_delete_hook(void (* hook)(const void* ptr)) {
    return false;
}

bool DummyAllocHooks::remove_delete_hook(void (* hook)(const void* ptr)) {
    return false;
}

int DummyAllocHooks::get_extra_stats_size() {
    return 0;
}

void DummyAllocHooks::get_allocator_stats(allocator_stats* stats) {
}

size_t DummyAllocHooks::get_allocation_size(const void* ptr) {
    return 0;
}

void DummyAllocHooks::get_detailed_stats(char* buffer, int size) {
    // empty
}

void DummyAllocHooks::release_free_memory() {
    // empty
}

bool DummyAllocHooks::enable_thread_cache(bool enable) {
    return true;
}

bool DummyAllocHooks::get_allocator_property(const char* name, size_t* value) {
    return false;
}

int DummyAllocHooks::set_allocator_property(const char* name,
                                            void* newp,
                                            size_t newlen) {
    return 1;
}


text:
@implementation MDrawFatArrow

-(BOOL)hitTest:(CGPoint)point
{
    return CGPointInRect(point, self.frame);
}

-(void)draw:(CGContextRef)ctx
{
    CGFloat length = CGPointDistance(_startPoint, _endPoint);
    CGSize dSize = CGPointOffset(_startPoint, _endPoint);

    // Draw an arrow at the horizontal line and then rotate it.
    // Here are the horizontal points.
    CGPoint p1 = CGPointZero;
    CGPoint p2 = CGPointMake(p1.x + length * 0.6, p1.y + length * 0.4);
    CGPoint p3 = CGPointMake(p1.x + length * 0.6, p1.y + length * 0.15);
    CGPoint p4 = CGPointMake(p1.x + length, p1.y + length * 0.15);
    CGPoint p5 = CGPointMake(p1.x + length, p1.y - length * 0.15);
    CGPoint p6 = CGPointMake(p1.x + length * 0.6, p1.y - length * 0.15);
    CGPoint p7 = CGPointMake(p1.x + length * 0.6, p1.y - length * 0.4);

    CGContextSaveGState(ctx);

    CGContextSetStrokeColorWithColor(ctx, self.color.CGColor);
    CGContextSetFillColorWithColor(ctx, self.color.CGColor);
    CGContextSetLineWidth(ctx, self.lineWidth);

    CGContextBeginPath(ctx);

    CGContextTranslateCTM(ctx, _startPoint.x,_startPoint.y);
    CGContextRotateCTM(ctx, atan2f(dSize.height,dSize.width));

    CGContextMoveToPoint(ctx, p1.x, p1.y);
    CGContextAddLineToPoint(ctx, p2.x, p2.y);
    CGContextAddLineToPoint(ctx, p3.x, p3.y);
    CGContextAddLineToPoint(ctx, p4.x, p4.y);
    CGContextAddLineToPoint(ctx, p5.x, p5.y);
    CGContextAddLineToPoint(ctx, p6.x, p6.y);
    CGContextAddLineToPoint(ctx, p7.x, p7.y);
    CGContextClosePath(ctx);

    CGContextFillPath(ctx);
    CGContextStrokePath(ctx);

    CGContextRestoreGState(ctx);

    if (self.selected)
    {
        CGContextSaveGState(ctx);
        CGContextSetStrokeColorWithColor(ctx, self.color.CGColor);
        CGContextSetFillColorWithColor(ctx, self.color.CGColor);

        [self drawHandle:ctx atPoint:_startPoint];
        [self drawHandle:ctx atPoint:_endPoint];

        CGContextRestoreGState(ctx);
    }

}

@end


text:
package org.carrot2.util;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * Base class for tests involving {@link BufferedImage}s.
 */
public class BufferedImageTestBase
{
    protected BufferedImage image(String fileName) throws IOException
    {
        return ImageIO.read(BufferedImageTestBase.class.getResourceAsStream("/images/"
            + fileName));
    }
}