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

import com.android.tools.idea.templates.Parameter;
import com.android.tools.idea.templates.Template;
import com.android.tools.idea.templates.TemplateMetadata;
import com.android.utils.Pair;
import com.android.utils.XmlUtils;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Maps;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.ui.ColorPanel;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.JBColor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;

import static com.android.SdkConstants.ATTR_ID;
import static com.android.tools.idea.templates.Template.ATTR_DEFAULT;
import static com.android.tools.idea.templates.TemplateMetadata.*;

/**
 * TemplateWizardStep is the base class for step pages in Freemarker template-based wizards.
 *
 * Deprecated. Use {@link DynamicWizardStepWithHeaderAndDescription} instead.
 */
@Deprecated
public abstract class TemplateWizardStep extends ModuleWizardStep
  implements ActionListener, FocusListener, DocumentListener, ChangeListener, AndroidStudioWizardStep {
  private static final Logger LOG = Logger.getInstance("#" + TemplateWizardStep.class.getName());

  protected static final String LAST_USED_CLASS_PREFIX_KEY = "LAST_USED_CLASS_PREFIX";

  protected final TemplateWizardState myTemplateState;
  protected final BiMap<String, JComponent> myParamFields = HashBiMap.create();
  protected final Map<String, JLabel> myParamFieldLabels = Maps.newHashMap();
  protected final Map<JRadioButton, Pair<String, Object>> myRadioButtonValues = Maps.newHashMap();
  protected final Map<Parameter, ComboBoxItem> myComboBoxValues = Maps.newHashMap();
  protected final Project myProject;
  protected final Module myModule;
  private final Icon mySidePanelIcon;
  protected boolean myIgnoreUpdates = false;
  protected boolean myFirstUpdate = true;
  protected boolean myIsValid = true;
  protected boolean myVisible = true;
  protected final UpdateListener myUpdateListener;
  private final StringEvaluator myStringEvaluator = new StringEvaluator();

  // Ids for params that have been edited in this round of updating/validation
  protected Queue<String> myIdsWithNewValues = new ConcurrentLinkedQueue<String>();

  public interface UpdateListener {
    public void update();
  }

  public static final UpdateListener NONE = new UpdateListener() {
    @Override
    public void update() {}
  };

  public TemplateWizardStep(@NotNull TemplateWizardState state, @Nullable Project project, @Nullable Module module,
                            @Nullable Icon sidePanelIcon, @Nullable UpdateListener updateListener) {
    myTemplateState = state;
    myProject = project;
    myModule = module;
    mySidePanelIcon = sidePanelIcon;
    myUpdateListener = updateListener;
  }

  @Override
  public void _init() {
    super._init();
    update();
  }

  /** Override this to return a {@link JLabel} that holds the description of the UI element that has focus. */
  @NotNull protected abstract JLabel getDescription();

  /** Wraps the given string in <html> and </html> tags and sets it into the description label. */
  protected void setDescriptionHtml(@Nullable String s) {
    if (s == null) {
      s = "";
    }
    if (!s.startsWith("")) {
      s = "" + s + "";
      s.replaceAll("\n", "
");
    }
    JLabel label = getDescription();
    if (label != null) {
      label.setText(s);
      growLabelIfNecessary(label);
    }
  }

  /** Override this to return a {@link JLabel} that displays a validation error message. */
  @NotNull protected abstract JLabel getError();

  /** Wraps the given string in <html> and </html> tags and sets it into the error label. */
  public void setErrorHtml(@Nullable String s) {
    if (s == null) {
      s = "";
    }
    if (!s.startsWith("")) {
      s = "" + XmlUtils.toXmlTextValue(s) + "";
      s.replaceAll("\n", "
");
    }
    JLabel label = getError();
    if (label != null) {
      label.setText(s);
      growLabelIfNecessary(label);
    }
  }

  /**
   * Increases the given label's vertical size if necessary to accommodate the amount of text it currently displays. If you are using
   * IntelliJ's {@link GridLayoutManager}, then the minimum, maximum, and preferred sizes for the label component must be unspecified in
   * the layout, or the layout manager will use those and override the component-level sizes that this method adjusts.
   */
  protected void growLabelIfNecessary(JLabel label) {
    Dimension newSize = label.getMinimumSize();
    label.setPreferredSize(null);
    label.validate();
    Dimension pd = label.getPreferredSize();
    int currentWidth = label.getSize().width;
    int preferredHeight = 0;
    if (currentWidth != 0 && pd.width != 0 && pd.height != 0) {
      preferredHeight = pd.height * (int) ((float)pd.width / (float)currentWidth);
      if (currentWidth % pd.width != 0) {
        preferredHeight += pd.height;
      }
    }
    newSize.height = Math.max(newSize.height, preferredHeight);
    label.setMinimumSize(newSize);
    label.setPreferredSize(newSize);
    if (getComponent() != null) {
      getComponent().revalidate();
    }
  }

  /** Override this to provide help text for a parameter that does not have its own help text in the template. */
  @Nullable
  protected String getHelpText(@NotNull String param) {
    return null;
  }

  /** Returns true if the data in this wizard step is correct and the user is permitted to move to the next step. */
  @Override
  public boolean isValid() {
    return myIsValid;
  }

  public void setVisible(boolean visible) {
    myVisible = visible;
  }

  @Override
  public boolean isStepVisible() {
    return myVisible;
  }

  /**
   * Called by update to write the new values of the parameters being edited into the template model.
   */
  public void updateParams() {
    if (!myVisible) {
      return;
    }

    Template.convertApisToInt(myTemplateState.getParameters());

    Component focusedComponent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
    setDescriptionHtml("");
    setErrorHtml("");
    for (String paramName : myParamFields.keySet()) {
      if (myTemplateState.myHidden.contains(paramName)) {
        continue;
      }
      Parameter param = myTemplateState.hasTemplate() ? myTemplateState.getTemplateMetadata().getParameter(paramName) : null;
      Object oldValue = myTemplateState.get(paramName);
      JComponent component = myParamFields.get(paramName);
      if (component == focusedComponent || component.isAncestorOf(focusedComponent)) {
        String help = param != null && param.help != null && param.help.length() > 0 ? param.help : getHelpText(paramName);
        setDescriptionHtml(help);
      }
      Object newValue = getComponentValue(param, component);

      if (newValue != null && !newValue.equals(oldValue)) {
        myTemplateState.put(paramName, newValue);
        if (oldValue != null) {
          myTemplateState.myModified.add(paramName);
        }
        if (!myIdsWithNewValues.contains(paramName)) {
          myIdsWithNewValues.add(paramName);
        }
      }
    }
    for (Map.Entry<JRadioButton, Pair<String, Object>> entry : myRadioButtonValues.entrySet()) {
      if (entry.getKey().isSelected()) {
        Pair<String, Object> value = entry.getValue();
        myTemplateState.put(value.getFirst(), value.getSecond());
      }
    }
  }

  /**
   * Called by update() to write derived values to the template model.
   */
  protected void deriveValues() {
    TemplateMetadata metadata = myTemplateState.getTemplateMetadata();
    if (metadata == null) {
      return;
    }

    for (String changedParamId : myIdsWithNewValues) {
      for (String paramName : myParamFields.keySet()) {
        Parameter param = myTemplateState.hasTemplate() ? metadata.getParameter(paramName) : null;

        // If this parameter is null or doesn't have anything to update (both visibility and suggestion are null or empty), skip it.
        if (param == null ||
            ((param.suggest == null || param.suggest.isEmpty()) && (param.visibility == null || param.visibility.isEmpty()))) {
          continue;
        }

        // If this parameter has dynamic visibility, calculate it and process accordingly
        if (param.visibility != null && param.visibility.contains(changedParamId)) {
          updateVisibility(param);
        }

        // Don't process hidden fields
        if (myTemplateState.myHidden.contains(paramName)) {
          continue;
        }

        // If this parameter has a suggestion depending on the changed parameter, calculate it, record the new value
        // and add it for consideration so that things dependent on it can be updated
        if (param.suggest != null && param.suggest.contains(changedParamId)) {
          final String updated = myStringEvaluator.evaluate(param.suggest, myTemplateState.getParameters());
          if (updated != null && !updated.equals(myTemplateState.get(param.id))) {
            myIdsWithNewValues.add(param.id);

            updateDerivedValue(param.id, (JTextField)myParamFields.get(param.id), new Callable<String>() {
              @Override
              public String call() throws Exception {
                return updated;
              }
            });
          }
        }
      }
    }
  }

  protected void updateVisibility(Parameter param) {
    if (param.visibility != null && !param.visibility.isEmpty()) {
      boolean visible = myStringEvaluator.evaluateBooleanExpression(param.visibility, myTemplateState.getParameters(), true);
      if (visible) {
        myTemplateState.myHidden.remove(param.id);
        // Update the newly shown parameter if necessary
        if (param.suggest != null) {
          final String updated = myStringEvaluator.evaluate(param.suggest, myTemplateState.getParameters());
          if (updated != null && !updated.equals(myTemplateState.get(param.id))) {
            updateDerivedValue(param.id, (JTextField)myParamFields.get(param.id), new Callable<String>() {
              @Override
              public String call() throws Exception {
                return updated;
              }
            });
          }
        }
      }
      else {
        myTemplateState.myHidden.add(param.id);
      }
      myParamFields.get(param.id).setVisible(visible);
      if (myParamFieldLabels.containsKey(param.id)) {
        myParamFieldLabels.get(param.id).setVisible(visible);
      }
    }
  }

  @Override
  public boolean validate() {
    Template.convertApisToInt(myTemplateState.getParameters());
    if (!myVisible) {
      return true;
    }
    Integer minApi = (Integer)myTemplateState.get(ATTR_MIN_API_LEVEL);
    Integer buildApi = (Integer)myTemplateState.get(ATTR_BUILD_API);

    for (String paramName : myParamFields.keySet()) {
      if (myTemplateState.myHidden.contains(paramName)) {
        continue;
      }
      Parameter param = myTemplateState.hasTemplate() ? myTemplateState.getTemplateMetadata().getParameter(paramName) : null;
      if (param != null) {
        String error = param.validate(myProject, myModule, myTemplateState.getSourceProvider(),
                                      (String)myTemplateState.get(ATTR_PACKAGE_NAME), myTemplateState.get(paramName));
        if (error != null) {
          setErrorHtml(error);
          return false;
        }

        // Check to see that the selection's constraints are met if this is a combo box
        if (myComboBoxValues.containsKey(param)) {
          ComboBoxItem selectedItem = myComboBoxValues.get(param);

          if (selectedItem == null) {
            return false;
          }
          if (minApi != null && selectedItem.minApi > minApi) {
            setErrorHtml(String.format("The \"%s\" option for %s requires a minimum API level of %d", selectedItem.label, param.name,
                                       selectedItem.minApi));
            return false;
          }
          if (buildApi != null && selectedItem.minBuildApi > buildApi) {
            setErrorHtml(String.format("The \"%s\" option for %s requires a minimum API level of %d", selectedItem.label, param.name,
                                       selectedItem.minBuildApi));
            return false;
          }
        }
      }
    }

    return true;
  }

  public void refreshUiFromParameters() {
    if (myTemplateState.myTemplate == null) {
      return;
    }

    for (Parameter param : myTemplateState.myTemplate.getMetadata().getParameters()) {
      if (param.initial != null && !myTemplateState.myModified.contains(param.id)) {
        myTemplateState.myParameters.remove(param.id);
      }
    }
    myTemplateState.setParameterDefaults();
    Template.convertApisToInt(myTemplateState.getParameters());
    boolean oldIgnoreUpdates = myIgnoreUpdates;
    try {
      myIgnoreUpdates = true;
      for (String paramName : myParamFields.keySet()) {
        if (myTemplateState.myHidden.contains(paramName)) {
          continue;
        }
        JComponent component = myParamFields.get(paramName);
        Object value = myTemplateState.get(paramName);
        if (value == null) {
          continue;
        }
        if (component instanceof JCheckBox) {
          ((JCheckBox)component).setSelected(Boolean.parseBoolean(value.toString()));
        }
        else if (component instanceof JComboBox) {
          for (int i = 0; i < ((JComboBox)component).getItemCount(); i++) {
            if (((ComboBoxItem)((JComboBox)component).getItemAt(i)).id.equals(value)) {
              ((JComboBox)component).setSelectedIndex(i);
              break;
            }
          }
        }
        else if (component instanceof JTextField) {
          ((JTextField)component).setText(value.toString());
        } else if (component instanceof TextFieldWithBrowseButton) {
          ((TextFieldWithBrowseButton)component).setText(value.toString());
        } else if (component instanceof JSlider) {
          ((JSlider)component).setValue(Integer.parseInt(value.toString()));
        } else if (component instanceof JSpinner) {
          ((JSpinner)component).setValue(Integer.parseInt(value.toString()));
        } else if (component instanceof ColorPanel) {
          ((ColorPanel)component).setSelectedColor((Color)value);
        }
      }
    } finally {
      myIgnoreUpdates = oldIgnoreUpdates;
    }
  }

  /**
   * Retrieve a value from the given JComponent
   */
  @Nullable
  protected Object getComponentValue(Parameter param, JComponent component) {
    Object newValue = null;
    if (component instanceof JCheckBox) {
      newValue = ((JCheckBox)component).isSelected();
    }
    else if (component instanceof JComboBox) {
      ComboBoxItem selectedItem = (ComboBoxItem)((JComboBox)component).getSelectedItem();
      myComboBoxValues.put(param, selectedItem);

      if (selectedItem != null) {
        newValue = selectedItem.id;
      }
    }
    else if (component instanceof JTextField) {
      newValue = ((JTextField)component).getText();
    } else if (component instanceof TextFieldWithBrowseButton) {
      newValue = ((TextFieldWithBrowseButton)component).getText();
    } else if (component instanceof JSlider) {
      newValue = ((JSlider)component).getValue();
    } else if (component instanceof JSpinner) {
      newValue = ((JSpinner)component).getValue();
    } else if (component instanceof ColorPanel) {
      newValue = ((ColorPanel)component).getSelectedColor();
    }
    return newValue;
  }

  /**
   * Takes a {@link JComboBox} instance and a {@Parameter} that represents an enumerated type and
   * populates the combo box with all possible values of the enumerated type.
   */
  protected static void populateComboBox(@NotNull JComboBox comboBox, @NotNull Parameter parameter) {
    List<Element> options = parameter.getOptions();
    assert !options.isEmpty();
    for (int i = 0, n = options.size(); i < n; i++) {
      Element option = options.get(i);
      String optionId = option.getAttribute(ATTR_ID);
      assert optionId != null && !optionId.isEmpty() : ATTR_ID;
      NodeList childNodes = option.getChildNodes();
      assert childNodes.getLength() == 1 && childNodes.item(0).getNodeType() == Node.TEXT_NODE;
      String optionLabel = childNodes.item(0).getNodeValue().trim();

      int minSdk = 1;
      try { minSdk = Integer.parseInt(option.getAttribute(TemplateMetadata.ATTR_MIN_API)); } catch (Exception e) { }
      int minBuildApi = 1;
      try { minBuildApi = Integer.parseInt(option.getAttribute(TemplateMetadata.ATTR_MIN_BUILD_API)); } catch (Exception e) { }
      comboBox.addItem(new ComboBoxItem(optionId, optionLabel, minSdk, minBuildApi));
      String isDefault = option.getAttribute(ATTR_DEFAULT);
      if (isDefault != null && !isDefault.isEmpty() && Boolean.valueOf(isDefault)) {
        comboBox.setSelectedIndex(comboBox.getItemCount() - 1);
      }
    }
  }

  /**
   * Takes a {@link JComboBox} instance and a {@Enum} and
   * populates the combo box with all possible values of the enumerated type.
   */
  protected static <E extends Enum<E>> void populateComboBox(@NotNull JComboBox comboBox, @NotNull Class<E> enumClass) {
    for (Enum<E> e : enumClass.getEnumConstants()) {
      comboBox.addItem(new ComboBoxItem(e.name(), e.toString(), 1, 1));
    }
  }

  /**
   * Takes a {@link JComboBox} instance and an array and
   * populates the combo box with the values in the array.
   * Similar to the {@link DefaultComboBoxModel}, but uses our ComboBoxItem.
   */
  protected static void populateComboBox(@NotNull JComboBox comboBox, @NotNull Object[] array) {
    for (int i = 0; i < array.length; ++i) {
      comboBox.addItem(new ComboBoxItem(i, array[i].toString(), 1, 1));
    }
  }

  /**
   * Connects the given {@link JLabel} to the given parameter and sets a listener to pick up changes to visibility that need to
   * trigger UI updates.
   */
  protected void registerLabel(@NotNull String paramName, @NotNull JLabel label) {
    myParamFieldLabels.put(paramName, label);
  }

  /**
   * Connects the given {@link JCheckBox} to the given parameter and sets a listener to pick up changes that need to trigger validation
   * and UI updates.
   */
  protected void register(@NotNull String paramName, @NotNull JCheckBox checkBox) {
    myParamFields.put(paramName, (JComponent)checkBox);
    Object value = myTemplateState.get(paramName);
    if (value != null) {
      checkBox.setSelected(Boolean.parseBoolean(value.toString()));
    } else {
      myTemplateState.put(paramName, false);
    }
    checkBox.addFocusListener(this);
    checkBox.addActionListener(this);
  }

  /**
   * Connects the given {@link JComboBox} to the given parameter and sets a listener to pick up changes that need to trigger validation
   * and UI updates.
   */
  protected void register(@NotNull String paramName, @NotNull JComboBox comboBox) {
    myParamFields.put(paramName, comboBox);
    Object value = myTemplateState.get(paramName);
    if (value != null) {
      for (int i = 0; i < comboBox.getItemCount(); i++) {
        Object item = comboBox.getItemAt(i);
        if (!(item instanceof ComboBoxItem)) {
          continue;
        }
        if (((ComboBoxItem)item).id.equals(value)) {
          comboBox.setSelectedIndex(i);
          break;
        }
      }
    }
    comboBox.addFocusListener(this);
    comboBox.addActionListener(this);
  }

  /**
   * Connects the given {@link JTextField} to the given parameter and sets a listener to pick up changes that need to trigger validation
   * and UI updates.
   */
  protected void register(@NotNull String paramName, @NotNull JTextField textField) {
    String value = (String)myTemplateState.get(paramName);
    if (value != null) {
      textField.setText(value);
    } else {
      myTemplateState.put(paramName, "");
    }
    myParamFields.put(paramName, textField);
    textField.addFocusListener(this);
    textField.getDocument().addDocumentListener(this);
  }

  protected void register(@NotNull String paramName, @NotNull JRadioButton radioButton, @Nullable Object value) {
    Object currentValue = myTemplateState.get(paramName);
    radioButton.setSelected(currentValue != null && currentValue.equals(value));
    if (value != null) {
      myRadioButtonValues.put(radioButton, Pair.of(paramName, value));
    }
    radioButton.addFocusListener(this);
    radioButton.addActionListener(this);
  }

  protected void register(@NotNull String paramName, @NotNull JSlider paddingSlider) {
    Integer value = (Integer)myTemplateState.get(paramName);
    if (value != null) {
      paddingSlider.setValue(value);
    } else {
      myTemplateState.put(paramName, paddingSlider.getValue());
    }
    myParamFields.put(paramName, (JComponent)paddingSlider);
    paddingSlider.addFocusListener(this);
    paddingSlider.addChangeListener(this);
  }

  protected void register(@NotNull String paramName, @NotNull JSpinner spinner) {
    Integer value = (Integer)myTemplateState.get(paramName);
    if (value != null) {
      spinner.setValue(value);
    } else {
      myTemplateState.put(paramName, spinner.getValue());
    }
    myParamFields.put(paramName, (JComponent)spinner);
    spinner.addFocusListener(this);
    spinner.addChangeListener(this);
  }

  protected void register(@NotNull String paramName, @NotNull final TextFieldWithBrowseButton field) {
    String value = (String)myTemplateState.get(paramName);
    if (value != null) {
      field.setText(value);
    } else {
      myTemplateState.put(paramName, field.getText());
    }
    myParamFields.put(paramName, (JComponent)field);
    field.addFocusListener(this);
    field.getTextField().getDocument().addDocumentListener(this);
    field.getTextField().addFocusListener(this);
  }

  protected void register(@NotNull String paramName, @NotNull ColorPanel colorPanel) {
    Color value = (Color)myTemplateState.get(paramName);
    if (value != null) {
      colorPanel.setSelectedColor(value);
    } else {
      myTemplateState.put(paramName, colorPanel.getSelectedColor());
    }
    myParamFields.put(paramName, (JComponent)colorPanel);
    colorPanel.addFocusListener(this);
    colorPanel.addActionListener(this);
  }

  /** Revalidates the UI and asks the parent wizard to update its state to reflect changes. */
  protected void update() {
    if (myIgnoreUpdates) {
      return;
    }

    myIgnoreUpdates = true;

    // Create a list of parameters that have been modified this round
    myIdsWithNewValues = new ConcurrentLinkedQueue<String>();

    // First we load the updated values into our model
    updateParams();

    // The first time update() is called, refresh the "suggest" attrs by ensuring *all* parameters are set.
    if (myFirstUpdate) {
      myIdsWithNewValues = new ConcurrentLinkedQueue<String>(myTemplateState.getParameters().keySet());
    }

    // Then we calculate any values that we need to
    deriveValues();
    // Finally we make sure these new values are valid
    myIsValid = validate();
    if (myUpdateListener != null) {
      myUpdateListener.update();
    }

    myFirstUpdate = false;
    myIgnoreUpdates = false;
  }

  protected boolean updateDerivedValue(@NotNull String attrName, @NotNull JTextField textField, @NotNull Callable<String> valueDeriver) {
    boolean updated = false;
    try {
      myIgnoreUpdates = true;
      if (!myTemplateState.myModified.contains(attrName)) {
        String s = valueDeriver.call();
        if (s != null && !s.equals(myTemplateState.get(attrName))) {
          myTemplateState.put(attrName, s);
          textField.setText(s);
          myTemplateState.myModified.remove(attrName);
          updated = true;
        }
      }
    }
    catch (Exception e) {
    }
    finally {
      myIgnoreUpdates = false;
    }
    return updated;
  }

  @Override
  public JComponent getComponent() {
    return null;
  }

  @Override
  public Icon getIcon() {
    return mySidePanelIcon;
  }

  @Override
  public void updateDataModel() {
  }

  @Override
  public void actionPerformed(@NotNull ActionEvent actionEvent) {
    update();
  }

  @Override
  public void focusGained(@NotNull FocusEvent focusEvent) {
    update();
  }

  @Override
  public void focusLost(@NotNull FocusEvent focusEvent) {
    update();
  }

  @Override
  public void insertUpdate(@NotNull DocumentEvent documentEvent) {
    update();
  }

  @Override
  public void removeUpdate(@NotNull DocumentEvent documentEvent) {
    update();
  }

  @Override
  public void changedUpdate(@NotNull DocumentEvent documentEvent) {
    update();
  }

  @Override
  public void stateChanged(@NotNull ChangeEvent e) {
    update();
  }

  protected void hide(JComponent... components) {
    for (JComponent component : components) {
      component.setVisible(false);
    }
  }

  protected void show(JComponent... components) {
    for (JComponent component : components) {
      component.setVisible(true);
    }
  }
}


text:
<?php

namespace Genemu\Bundle\FormBundle\Form\JQuery\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;

/**
 * {@inheritdoc}
 *
 * @author Bilal Amarni <bilal.amarni@gmail.com>
 */
class ArrayToStringTransformer implements DataTransformerInterface
{
    /**
     * {@inheritdoc}
     */
    public function transform($array)
    {
        if (null === $array || !is_array($array)) {
            return '';
        }

        return implode(',', $array);
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($string)
    {
        if (is_array($string)) {
            return $string;
        }

        return explode(',', $string);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Cocur\Plum;

use Cocur\Plum\Reader\ReaderInterface;
use Cocur\Plum\Writer\WriterInterface;

/**
 * WorkflowConcatenator
 *
 * @package   Cocur\Plum
 * @author    Florian Eckerstorfer <florian@eckerstorfer.co>
 * @copyright 2014 Florian Eckerstorfer
 */
class WorkflowConcatenator implements ReaderInterface, WriterInterface
{
    /** @var mixed[] */
    private $data = [];

    /**
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->data);
    }

    /**
     * @return int
     */
    public function count()
    {
        return count($this->data);
    }

    /**
     * Write the given item.
     *
     * @param mixed $item
     *
     * @return void
     */
    public function writeItem($item)
    {
        $this->data[] = $item;
    }

    /**
     * Prepare the writer.
     *
     * @return void
     */
    public function prepare()
    {
    }

    /**
     * Finish the writer.
     *
     * @return void
     */
    public function finish()
    {
    }
}


text:
from emailer import Emailer

msg = [
'Hey __receiver__,',
'I\'m __sender_name__, a fellow Stanford student studying computer science. I\'m working on an intense class project where we interview professionals to find needs and problems in industries, and later build software solutions for free.',
'We\'re trying our best to learn more about different industries out there.',
'It\'d be great to hear about advice, your biggest pain points, and what\'s generally on your mind in regards to your industy. Maybe we can build something together!\n\nWould you have any time to chat on phone? Email is also great too!',
'Thanks so much,',
'__sender_name__'
]

subject = "Test Subject Line"

emailer = Emailer(email_body=msg, subject_line=subject, sender_name="Kevin", contacts_file = "test_contacts.csv", \
    path_to_driver="/Users/admin/Desktop/chromedriver", cc=["itotalpwnyou@gmail.com"])

emailer.custom_login()
emailer.send_emails()


text:
#ifndef XENIA_UI_GL_GL_CONTEXT_H_
#define XENIA_UI_GL_GL_CONTEXT_H_

#include <gflags/gflags.h>

#include <memory>

#include "xenia/ui/gl/blitter.h"
#include "xenia/ui/gl/gl.h"
#include "xenia/ui/graphics_context.h"

DECLARE_bool(thread_safe_gl);

// TODO(benvanik): hide Win32 stuff.
typedef struct HDC__* HDC;
typedef struct HGLRC__* HGLRC;

namespace xe {
namespace ui {
namespace gl {

class GLImmediateDrawer;
class GLProvider;

class GLContext : public GraphicsContext {
 public:
  ~GLContext() override;

  ImmediateDrawer* immediate_drawer() override;

  bool is_current() override;
  bool MakeCurrent() override;
  void ClearCurrent() override;
  bool WasLost() override;

  void BeginSwap() override;
  void EndSwap() override;

  std::unique_ptr<RawImage> Capture() override;

  Blitter* blitter() { return &blitter_; }

 private:
  friend class GLProvider;

  static std::unique_ptr<GLContext> Create(GraphicsProvider* provider,
                                           Window* target_window,
                                           GLContext* share_context = nullptr);
  static std::unique_ptr<GLContext> CreateOffscreen(GraphicsProvider* provider,
                                                    GLContext* parent_context);

 private:
  GLContext(GraphicsProvider* provider, Window* target_window);

  bool Initialize(GLContext* share_context);
  void AssertExtensionsPresent();

  void SetupDebugging();
  void DebugMessage(GLenum source, GLenum type, GLuint id, GLenum severity,
                    GLsizei length, const GLchar* message);
  static void GLAPIENTRY DebugMessageThunk(GLenum source, GLenum type,
                                           GLuint id, GLenum severity,
                                           GLsizei length,
                                           const GLchar* message,
                                           GLvoid* user_param);

  HDC dc_ = nullptr;
  HGLRC glrc_ = nullptr;

  std::unique_ptr<GLEWContext> glew_context_;
  std::unique_ptr<WGLEWContext> wglew_context_;

  Blitter blitter_;
  std::unique_ptr<GLImmediateDrawer> immediate_drawer_;

  bool context_lost_ = false;
  bool robust_access_supported_ = false;
};

}  // namespace gl
}  // namespace ui
}  // namespace xe

#endif  // XENIA_UI_GL_GL_CONTEXT_H_


text:
<?php

/**
 * Implements
 *
 * @author Marcus Nyeholt <marcus@silverstripe.com.au>
 *
 */
class QueuedCmisImporter extends QueuedExternalContentImporter
{
	public function __construct()
	{
		$this->contentTransforms['document'] = new CmisDocumentToFileTransformer();
		$this->contentTransforms['folder'] = new CmisFolderToFolderTransformer();
	}

	protected function getExternalType($item)
	{
		// see if it has a content url
		if (strtolower($item->BaseType) == 'document') {
			return 'document';
		}

		return 'folder';
	}
}

?>


text:
INFORMACIÓN PARA LOS TITULARES DE DERECHOS DE AUTOR

Si eres de los derechos de autor de cualquier material enlace (o enlaces) que está disponible en este sitio, y no quiere que se difunda esta información por parte de los usuarios sin su consentimiento, estaremos encantados de ayudarle mediante la eliminación de los enlaces apropiados.

Esto requiere que usted nos ha enviado una carta (en forma electrónica)
lo cual nos indica la siguiente información:

1. La prueba documental de sus derechos a material protegido por derechos de autor:

 - documento escaneado con el sello, o

 - correo electrónico de un funcionario de dominio de correo electrónico del propietario de la empresa, o

 - otra información de contacto que identifica a usted como el propietario del material.

2. El texto que desea lugar, acompañado por un extraíble información.

En ella se puede especificar dónde y bajo qué condiciones se puede obtener información, las referencias a las que se han eliminado, así como su información de contacto para que los usuarios puedan obtener toda la información necesaria con respecto a este material.

3. Enlaces directos a las páginas que contienen referencias a los datos que deben ser removidos.

Los enlaces deben ser vistas http://<?= $_SERVER['SERVER_NAME']?>/tXXXXX o algo similar.

Después de que en 48 horas, vamos a quitar interesante que los enlaces desde el sitio.

Nuestro correo electrónico: <a href="mailto:<?= $bb_cfg['abuse_email']; ?>" class="gen"><?= $bb_cfg['abuse_email']; ?>

ADVERTENCIA!

a) Nos reservamos el derecho a publicar en el sitio de cualquier información enviada a nosotros por correo electrónico <a href="mailto:<?= $bb_cfg['abuse_email']; ?>" class="gen"><?= $bb_cfg['abuse_email']; ?>

b) no Tenemos ningún control sobre las acciones de los usuarios que pueden ser re-publicar enlaces a la información, que es el objeto de su derecho de autor. Cualquier información en el foro, lugar de forma automática, sin ningún tipo de control desde cualquier trimestre alguno, lo que corresponde a los internacionales generalmente aceptados de la práctica de colocar la información en Internet. Sin embargo, en cualquier caso, vamos a considerar todas sus consultas respecto a la referencia a la información que viole sus derechos.

c) de Acuerdo a la Ley sobre derecho de Autor y Derechos Conexos, una referencia a los datos (información), por sí mismo, no está sujeto a la ley de derechos de autor (aunque puede violar el "Acuerdo sobre el uso del sitio web"). Por lo tanto, no es necesario enviar cartas con amenazas o exigencias, como no tener una verdadera razón.


text:
package com.laytonsmith.core.constructs;

import com.laytonsmith.annotations.typeof;
import com.laytonsmith.core.MethodScriptCompiler;
import com.laytonsmith.core.ParseTree;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.environments.GlobalEnv;
import com.laytonsmith.core.exceptions.CancelCommandException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.exceptions.FunctionReturnException;
import com.laytonsmith.core.exceptions.LoopManipulationException;
import com.laytonsmith.core.exceptions.ProgramFlowManipulationException;
import com.laytonsmith.core.functions.Exceptions;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A closure is just an anonymous procedure.
 *
 *
 */
@typeof("closure")
public class CClosure extends Construct {

    public static final long serialVersionUID = 1L;
    private ParseTree node;
    private final Environment env;
    private final String[] names;
    private final Construct[] defaults;
	private final CClassType[] types;
	private final CClassType returnType;

    public CClosure(ParseTree node, Environment env, CClassType returnType, String[] names, Construct[] defaults, CClassType[] types, Target t) {
        super(node != null ? node.toString() : "", ConstructType.CLOSURE, t);
        this.node = node;
		this.env = env;
        this.names = names;
        this.defaults = defaults;
		this.types = types;
		this.returnType = returnType;
    }

    @Override
    public String val() {
        StringBuilder b = new StringBuilder();
        condense(getNode(), b);
        return b.toString();
    }

    private void condense(ParseTree node, StringBuilder b) {
		if(node == null){
			return;
		}
        if (node.getData() instanceof CFunction) {
            b.append(( (CFunction) node.getData() ).val()).append("(");
            for (int i = 0; i < node.numberOfChildren(); i++) {
                condense(node.getChildAt(i), b);
                if (i != node.numberOfChildren() - 1 && !( (CFunction) node.getData() ).val().equals("__autoconcat__")) {
                    b.append(",");
                }
            }
            b.append(")");
        } else if (node.getData() instanceof CString) {
            CString data = (CString) node.getData();
            // Convert: \ -> \\ and ' -> \'
            b.append("'").append(data.val().replace("\\", "\\\\").replaceAll("\t", "\\\\t").replaceAll("\n", "\\\\n").replace("'", "\\'")).append("'");
		} else if(node.getData() instanceof IVariable){
			b.append(((IVariable)node.getData()).getName());
        } else {
            b.append(node.getData().val());
        }
    }

    public ParseTree getNode() {
        return node;
    }

    @Override
    public CClosure clone() throws CloneNotSupportedException {
        CClosure clone = (CClosure) super.clone();
        if (this.node != null) {
            clone.node = this.node.clone();
        }
        return clone;
    }

    /**
     * If meta code needs to affect this closure's environment, it can access it
     * with this function. Note that changing this will only affect future runs
     * of the closure, it will not affect the currently running closure, (if
     * any) due to the environment being cloned right before running.
     *
     * @return
     */
    public synchronized Environment getEnv() {
        return env;
    }

    /**
     * Executes the closure, giving it the supplied arguments. {@code values}
     * may be null, which means that no arguments are being sent.
	 *
	 * LoopManipulationExceptions will never bubble up past this point, because they are
	 * never allowed, so they are handled automatically, but
	 * other ProgramFlowManipulationExceptions will, . ConfigRuntimeExceptions will
	 * also bubble up past this, since an execution mechanism may need to do custom
	 * handling.
	 *
	 * A typical execution will include the following code:
	 * <pre>
	 * try {
	 *	closure.execute();
	 * } catch(ConfigRuntimeException e){
	 *	ConfigRuntimeException.HandleUncaughtException(e);
	 * } catch(ProgramFlowManipulationException e){
	 *	// Ignored
	 * }
     * </pre>
     * @param values The values to be passed to the closure
	 * @throws ConfigRuntimeException If any call inside the closure causes a CRE
	 * @throws ProgramFlowManipulationException If any ProgramFlowManipulationException is thrown
	 * (other than a LoopManipulationException) within the closure
	 * @throws FunctionReturnException If the closure has a return() call in it.
     */
    public void execute(Construct... values) throws ConfigRuntimeException, ProgramFlowManipulationException, FunctionReturnException, CancelCommandException {
		if(node == null){
			return;
		}
        try {
            Environment environment;
            synchronized (this) {
                environment = env.clone();
            }
            if (values != null) {
                for (int i = 0; i < names.length; i++) {
                    String name = names[i];
                    Construct value;
                    try {
                        value = values[i];
                    }
                    catch (Exception e) {
                        value = defaults[i].clone();
                    }
                    environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(types[i], name, value, getTarget()));
                }
            }
            CArray arguments = new CArray(node.getData().getTarget());
            if (values != null) {
                for (Construct value : values) {
                    arguments.push(value);
                }
            }
            environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(new CClassType("array", Target.UNKNOWN), "@arguments", arguments, node.getData().getTarget()));
            ParseTree newNode = new ParseTree(new CFunction("g", getTarget()), node.getFileOptions());
            List<ParseTree> children = new ArrayList<ParseTree>();
            children.add(node);
            newNode.setChildren(children);
            try {
                MethodScriptCompiler.execute(newNode, environment, null, environment.getEnv(GlobalEnv.class).GetScript());
            } catch (LoopManipulationException e){
				//This shouldn't ever happen.
				LoopManipulationException lme = ((LoopManipulationException)e);
				Target t = lme.getTarget();
				ConfigRuntimeException.HandleUncaughtException(ConfigRuntimeException.CreateUncatchableException("A " + lme.getName() + "() bubbled up to the top of"
						+ " a closure, which is unexpected behavior.", t), environment);
			} catch (FunctionReturnException ex){
				// Check the return type of the closure to see if it matches the defined type
				Construct ret = ex.getReturn();
				if(!InstanceofUtil.isInstanceof(ret, returnType)){
					throw new Exceptions.CastException("Expected closure to return a value of type " + returnType.val()
							 + " but a value of type " + ret.typeof() + " was returned instead", ret.getTarget());
				}
				// Now rethrow it
				throw ex;
			} catch (CancelCommandException e){
				// die()
			}
			// If we got here, then there was no return type. This is fine, but only for returnType void or auto.
			if(!(returnType.equals(CClassType.AUTO) || returnType.equals(CClassType.VOID))){
				throw new Exceptions.CastException("Expecting closure to return a value of type " + returnType.val() + ","
						+ " but no value was returned.", node.getTarget());
			}
        }
        catch (CloneNotSupportedException ex) {
            Logger.getLogger(CClosure.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public boolean isDynamic() {
        return false;
    }
}


text:
package com.justwayward.reader.ui.presenter;

import com.justwayward.reader.api.BookApi;
import com.justwayward.reader.base.RxPresenter;
import com.justwayward.reader.bean.BooksByTag;
import com.justwayward.reader.ui.contract.SearchByAuthorContract;
import com.justwayward.reader.utils.LogUtils;
import com.justwayward.reader.utils.RxUtil;
import com.justwayward.reader.utils.StringUtils;

import javax.inject.Inject;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;

/**
 * @author yuyh.
 * @date 2016/9/8.
 */
public class SearchByAuthorPresenter extends RxPresenter<SearchByAuthorContract.View> implements SearchByAuthorContract.Presenter {

    private BookApi bookApi;

    @Inject
    public SearchByAuthorPresenter(BookApi bookApi) {
        this.bookApi = bookApi;
    }

    @Override
    public void getSearchResultList(String author) {
        String key = StringUtils.creatAcacheKey("search-by-author", author);
        Observable<BooksByTag> fromNetWork = bookApi.searchBooksByAuthor(author)
                .compose(RxUtil.<BooksByTag>rxCacheListHelper(key));

        //依次检查disk、network
        Subscription rxSubscription = Observable.concat(RxUtil.rxCreateDiskObservable(key, BooksByTag.class), fromNetWork)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BooksByTag>() {
                    @Override
                    public void onNext(BooksByTag booksByTag) {
                        if (mView != null)
                            mView.showSearchResultList(booksByTag.books);
                    }

                    @Override
                    public void onCompleted() {
                        LogUtils.i("complete");
                        mView.complete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("getSearchResultList:" + e.toString());
                        if (mView != null)
                            mView.showError();
                    }
                });
        addSubscrebe(rxSubscription);
    }

}


text:
from weld import *
from weld.lazy import WeldLazy, weldfunc
from weld.types import *

def test_weldfunc_simple():
    @weldfunc
    def exp(a, b):
        return "exp({}, {})".format(a, b)

    result = exp("1", "2")(F64(), None)
    assert isinstance(result, WeldLazy)
    assert result.expression == "exp(1, 2)"

    result2 = exp("1", result)(F64(), None)
    assert isinstance(result, WeldLazy)
    assert result2.expression == "exp(1, {})".format(result.id)
    assert result2.num_dependencies == 1
    assert result in result2.children

def test_weldfunc_many_children():
    @weldfunc
    def exp(a, b):
        return "exp({}, {})".format(a, b)

    result = exp("1", "2")(F64(), None)
    result2 = exp("1", result)(F64(), None)
    result3 = exp(result2, result)(F64(), None)

    assert result in result3.children
    assert result2 in result3.children
    assert result3.num_dependencies == 2
    assert result3.expression == "exp({}, {})".format(result2.id, result.id)

def test_weldfunc_chain():
    @weldfunc
    def sqrt(a):
        return "sqrt({})".format(a)

    result = sqrt(1)(F64(), None)
    assert result.num_dependencies == 0
    assert result.expression == "sqrt(1)"

    chain_length = 10
    for i in range(chain_length):
        result = sqrt(result)(F64(), None)
    code = result.code
    # Make sure the final code has chain_length + 1 square roots.
    count = 0
    loc = code.find("sqrt")
    while loc > 0:
        count += 1
        code = code[loc + len("sqrt"):]
        loc = code.find("sqrt")
    assert count == chain_length + 1

def test_weldfunc_non_string_args():
    @weldfunc
    def exp(a, b, use_pow):
        operator = "pow" if use_pow else "exp"
        return "{}({}, {})".format(operator, a, b)

    result = exp("1", "2", True)(F64(), None)
    assert isinstance(result, WeldLazy)
    assert result.expression == "pow(1, 2)"

    result2 = exp("1", result, False)(F64(), None)
    assert isinstance(result, WeldLazy)
    assert result2.expression == "exp(1, {})".format(result.id)
    assert result2.num_dependencies == 1
    assert result in result2.children

def test_weldfunc_non_string_kwargs():
    @weldfunc
    def exp(a, b, use_pow=True):
        operator = "pow" if use_pow else "exp"
        return "{}({}, {})".format(operator, a, b)

    result = exp("1", "2")(F64(), None)
    assert isinstance(result, WeldLazy)
    assert result.expression == "pow(1, 2)"

    result2 = exp("1", result, use_pow=False)(F64(), None)
    assert isinstance(result, WeldLazy)
    assert result2.expression == "exp(1, {})".format(result.id)
    assert result2.num_dependencies == 1
    assert result in result2.children


text: - Implement basic function for annotation intercept.


text:
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.CSharp;

namespace AutoRest.Preview
{
    public static class TypeExtensions
    {

        public static string GetSimpleName(this Type type)
        {
            var compiler = new CSharpCodeProvider();
            var result = compiler.GetTypeOutput(new CodeTypeReference(type));
            result = Regex.Replace(result, @"[_A-Za-z0-9]+\.", "");
            result = Regex.Replace(result, @"Nullable<(.+?)>", @"$1?");
            return result;
        }

        public static string CreateSummary(this Type type, int indentLevel)
        {
            var sb = new StringBuilder();
            sb.Append("class ");
            sb.Append(type.Name);
            sb.AppendLine();
            sb.AppendLine("{");

            var props = type.GetProperties();
            var methods = type.GetMethods().Where(m => !m.IsSpecialName).ToArray();

            // properties
            if (props.Length > 0)
            {
                sb.Append(' ', indentLevel);
                sb.AppendLine("// properties");
                foreach (var member in props)
                {
                    sb.Append(' ', indentLevel);
                    sb.Append(member.PropertyType.GetSimpleName());
                    sb.Append(' ');
                    sb.Append(member.Name);
                    sb.AppendLine(";");
                }
            }

            if (methods.Length > 0 && props.Length > 0)
                sb.AppendLine();

            // methods
            if (methods.Length > 0)
            {
                sb.Append(' ', indentLevel);
                sb.AppendLine("// methods");
                foreach (var member in methods)
                {
                    sb.Append(' ', indentLevel);
                    sb.Append(member.ReturnType.GetSimpleName());
                    sb.Append(' ');
                    sb.Append(member.Name);
                    sb.Append('(');
                    sb.Append(string.Join(", ", member.GetParameters().Select(p => p.ParameterType.GetSimpleName() + " " + p.Name)));
                    sb.Append(')');
                    sb.AppendLine(";");
                }
            }

            sb.AppendLine("}");

            return sb.ToString();
        }
    }
}


text:
require 'mxx_ru/binary_unittest'

Mxx_ru::setup_target(
	Mxx_ru::Binary_unittest_target.new(
		"test/numeric_limits/prj.ut.rb",
		"test/numeric_limits/prj.rb" )
)


text:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';

import { Global } from '../../../services/global';
import { UserService } from '../../../services/user.service';
import { User } from '../../../models/user'

@Component({
  selector: 'app-edit-user',
  templateUrl: './edit-user.component.html',
  styleUrls: ['./edit-user.component.css'],
  providers: [UserService]
})
export class EditUserComponent implements OnInit {
  public user:User;
  constructor(
    private _route: ActivatedRoute,
    private _router: Router,
    private _userService: UserService
  ) {
    this.user = new User("", "", "", "", "");
  }

  ngOnInit() {
    this.getUser();
  }

  getUser() {
    this._route.params.forEach((params: Params) => {
      let id = params['userId'];
      this._userService.getUser(id).subscribe(
        res => {
          if(res.user) {
            this.user = res.user;
            this.user.password = '';
            console.log(this.user);
          } else {
            console.log(res.message);
          }
        }, err => {
          console.log(err);
        }
      );
    });
  }

  onSubmit() {
    this._userService.updateUser(this.user).subscribe(
      res => {
        console.log(res);
        this._router.navigate(['/admin-pannel', {outlets: {'admin-pannel': ['user']}}]);
      }, err => {
        console.log(err);
      }
    );
  }
}


text:
<?php

/**
 * Content.php
 *
 * @since 16/05/16
 * @author gseidel
 */

namespace Enhavo\Bundle\ContentBundle\Entity;

use Enhavo\Bundle\AppBundle\Model\RouteInterface;
use Enhavo\Bundle\AppBundle\Route\Routeable;
use Enhavo\Bundle\AppBundle\Route\Slugable;
use Enhavo\Bundle\ContentBundle\Content\Publishable;
use Enhavo\Bundle\ContentBundle\Content\PublishableTrait;
use Enhavo\Bundle\ContentBundle\Sitemap\SitemapInterface;
use Sylius\Component\Resource\Model\ResourceInterface;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;

abstract class Content implements Publishable, Routeable, Slugable, SitemapInterface, ResourceInterface
{
    use PublishableTrait;

    /**
     * @var \DateTime
     */
    protected $created;

    /**
     * @var \DateTime
     */
    protected $updated;

    /**
     * @var integer
     */
    protected $id;

    /**
     * @var string
     */
    protected $title;

    /**
     * @var string
     */
    protected $slug;

    /**
     * @var string
     */
    protected $metaDescription;

    /**
     * @var string
     */
    protected $pageTitle;

    /**
     * @var float
     */
    protected $priority;

    /**
     * @var string
     */
    protected $changeFrequency;

    /**
     * @var RouteInterface
     */
    protected $route;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Content
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param \DateTime $updated
     * @return Content
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Content
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

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

    /**
     * @param string $slug
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;
    }

    /**
     * Set meta_description
     *
     * @param string $metaDescription
     * @return Content
     */
    public function setMetaDescription($metaDescription)
    {
        $this->metaDescription = $metaDescription;

        return $this;
    }

    /**
     * Get meta_description
     *
     * @return string
     */
    public function getMetaDescription()
    {
        return $this->metaDescription;
    }

    /**
     * Set page_title
     *
     * @param string $pageTitle
     * @return Content
     */
    public function setPageTitle($pageTitle)
    {
        $this->pageTitle = $pageTitle;

        return $this;
    }

    /**
     * Get page_title
     *
     * @return string
     */
    public function getPageTitle()
    {
        return $this->pageTitle;
    }

    /**
     * Set priority
     *
     * @param float $priority
     * @return Content
     */
    public function setPriority($priority)
    {
        $this->priority = $priority;

        return $this;
    }

    /**
     * Get priority
     *
     * @return float
     */
    public function getPriority()
    {
        if($this->priority === null) {
            return '0.5';
        }
        return $this->priority;
    }

    /**
     * Set change_frequency
     *
     * @param string $changeFrequency
     * @return Content
     */
    public function setChangeFrequency($changeFrequency)
    {
        $this->changeFrequency = $changeFrequency;

        return $this;
    }

    /**
     * Get change_frequency
     *
     * @return string
     */
    public function getChangeFrequency()
    {
        if($this->changeFrequency === null) {
            return 'never';
        }
        return $this->changeFrequency;
    }

    /**
     * @return RouteInterface
     */
    public function getRoute()
    {
        return $this->route;
    }

    /**
     * @param RouteObjectInterface $route
     */
    public function setRoute(RouteObjectInterface $route)
    {
        $this->route = $route;
    }
}


text:
<?php

namespace CodeIgniter\Validation\StrictRules;

use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\URI;
use CodeIgniter\HTTP\UserAgent;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Validation\Exceptions\ValidationException;
use CodeIgniter\Validation\Validation;
use Config\App;
use Config\Services;
use Generator;
use Tests\Support\Validation\TestRules;

/**
 * @internal
 */
final class ValidationTest extends CIUnitTestCase
{
    private Validation $validation;
    private array $config = [
        'ruleSets' => [
            Rules::class,
            FormatRules::class,
            FileRules::class,
            CreditCardRules::class,
            TestRules::class,
        ],
        'groupA' => [
            'foo' => 'required|min_length[5]',
        ],
        'login' => [
            'username' => [
                'label'  => 'Username',
                'rules'  => 'required',
                'errors' => [
                    'required' => 'custom username required error msg.',
                ],
            ],
            'password' => [
                'label'  => 'Password',
                'rules'  => 'required',
                'errors' => [
                    'required' => 'custom password required error msg.',
                ],
            ],
        ],
        'groupA_errors' => [
            'foo' => [
                'min_length' => 'Shame, shame. Too short.',
            ],
        ],
        'groupX'    => 'Not an array, so not a real group',
        'templates' => [
            'list'   => 'CodeIgniter\Validation\Views\list',
            'single' => 'CodeIgniter\Validation\Views\single',
        ],
    ];

    protected function setUp(): void
    {
        parent::setUp();
        $this->validation = new Validation((object) $this->config, Services::renderer());
        $this->validation->reset();
    }

    public function testSetRulesStoresRules(): void
    {
        $rules = [
            'foo' => 'bar|baz',
            'bar' => 'baz|belch',
        ];
        $this->validation->setRules($rules);
        $this->assertSame($rules, $this->validation->getRules());
    }

    public function testRunReturnsFalseWithNothingToDo(): void
    {
        $this->validation->setRules([]);
        $this->assertFalse($this->validation->run([]));
    }

    public function testRunDoesTheBasics(): void
    {
        $data = ['foo' => 'notanumber'];
        $this->validation->setRules(['foo' => 'is_numeric']);
        $this->assertFalse($this->validation->run($data));
    }

    /**
     * @see https://github.com/codeigniter4/CodeIgniter4/issues/5368
     *
     * @dataProvider arrayDataProvider
     *
     * @param mixed $value
     */
    public function testCanValidatetArrayData($value, bool $expected): void
    {
        $this->validation->setRules(['arr' => 'is_array']);

        $data['arr'] = $value;
        $this->assertSame($expected, $this->validation->run($data));
    }

    public function arrayDataProvider(): Generator
    {
        yield 'list array' => [
            [1, 2, 3, 4, 5],
            true,   // false in Traditional Rule
        ];

        yield 'associative array' => [
            [
                'username' => 'admin001',
                'role'     => 'administrator',
                'usepass'  => 0,
            ],
            true,   // false in Traditional Rule
        ];

        yield 'int' => [
            0,
            false,
        ];

        yield 'string int' => [
            '0',
            false,
        ];

        yield 'bool' => [
            false,
            false,
        ];

        yield 'null' => [
            null,
            false,
        ];
    }

    /**
     * @see https://github.com/codeigniter4/CodeIgniter4/issues/5374
     *
     * @dataProvider isIntInvalidTypeDataProvider
     *
     * @param mixed $value
     */
    public function testIsIntWithInvalidTypeData($value, bool $expected): void
    {
        $this->validation->setRules(['foo' => 'is_int']);

        $data = ['foo' => $value];
        $this->assertSame($expected, $this->validation->run($data));
    }

    public function isIntInvalidTypeDataProvider(): Generator
    {
        yield 'array with int' => [
            [555],
            false,  // true in Traditional Rule
        ];

        yield 'empty array' => [
            [],
            false,
        ];

        yield 'bool true' => [
            true,
            false,
        ];

        yield 'bool false' => [
            false,
            false,
        ];

        yield 'null' => [
            null,
            false,
        ];
    }

    public function testRunReturnsLocalizedErrors(): void
    {
        $data = ['foo' => 'notanumber'];
        $this->validation->setRules(['foo' => 'is_numeric']);
        $this->assertFalse($this->validation->run($data));
        $this->assertSame('Validation.is_numeric', $this->validation->getError('foo'));
    }

    public function testRunWithCustomErrors(): void
    {
        $data = ['foo' => 'notanumber'];

        $messages = [
            'foo' => [
                'is_numeric' => 'Nope. Not a number.',
            ],
        ];

        $this->validation->setRules(['foo' => 'is_numeric'], $messages);
        $this->validation->run($data);
        $this->assertSame('Nope. Not a number.', $this->validation->getError('foo'));
    }

    public function testCheck(): void
    {
        $this->assertFalse($this->validation->check('notanumber', 'is_numeric'));
    }

    public function testCheckLocalizedError(): void
    {
        $this->assertFalse($this->validation->check('notanumber', 'is_numeric'));
        $this->assertSame('Validation.is_numeric', $this->validation->getError());
    }

    public function testCheckCustomError(): void
    {
        $this->validation->check('notanumber', 'is_numeric', [
            'is_numeric' => 'Nope. Not a number.',
        ]);
        $this->assertSame('Nope. Not a number.', $this->validation->getError());
    }

    public function testGetErrors(): void
    {
        $data = ['foo' => 'notanumber'];
        $this->validation->setRules(['foo' => 'is_numeric']);
        $this->validation->run($data);
        $this->assertSame(['foo' => 'Validation.is_numeric'], $this->validation->getErrors());
    }

    public function testGetErrorsWhenNone(): void
    {
        $data = ['foo' => 123];
        $this->validation->setRules(['foo' => 'is_numeric']);
        $this->validation->run($data);
        $this->assertSame([], $this->validation->getErrors());
    }

    public function testSetErrors(): void
    {
        $this->validation->setRules(['foo' => 'is_numeric']);
        $this->validation->setError('foo', 'Nadda');
        $this->assertSame(['foo' => 'Nadda'], $this->validation->getErrors());
    }

    public function testRulesReturnErrors(): void
    {
        $this->validation->setRules(['foo' => 'customError']);
        $this->validation->run(['foo' => 'bar']);
        $this->assertSame(['foo' => 'My lovely error'], $this->validation->getErrors());
    }

    public function testGroupsReadFromConfig(): void
    {
        $data = ['foo' => 'bar'];
        $this->assertFalse($this->validation->run($data, 'groupA'));
        $this->assertSame('Shame, shame. Too short.', $this->validation->getError('foo'));
    }

    public function testGroupsReadFromConfigValid(): void
    {
        $data = ['foo' => 'barsteps'];
        $this->assertTrue($this->validation->run($data, 'groupA'));
    }

    public function testGetRuleGroup(): void
    {
        $this->assertSame([
            'foo' => 'required|min_length[5]',
        ], $this->validation->getRuleGroup('groupA'));
    }

    public function testGetRuleGroupException(): void
    {
        $this->expectException(ValidationException::class);
        $this->validation->getRuleGroup('groupZ');
    }

    public function testSetRuleGroup(): void
    {
        $this->validation->setRuleGroup('groupA');
        $this->assertSame([
            'foo' => 'required|min_length[5]',
        ], $this->validation->getRules());
    }

    public function testSetRuleGroupException(): void
    {
        $this->expectException(ValidationException::class);
        $this->validation->setRuleGroup('groupZ');
    }

    public function testSetRuleGroupWithCustomErrorMessage(): void
    {
        $this->validation->reset();
        $this->validation->setRuleGroup('login');
        $this->validation->run(['username' => 'codeigniter']);
        $this->assertSame([
            'password' => 'custom password required error msg.',
        ], $this->validation->getErrors());
    }

    public function testRunGroupWithCustomErrorMessage(): void
    {
        $this->validation->reset();
        $this->validation->run([
            'username' => 'codeigniter',
        ], 'login');

        $this->assertSame([
            'password' => 'custom password required error msg.',
        ], $this->validation->getErrors());
    }

    /**
     * @dataProvider rulesSetupProvider
     *
     * @param string|string[] $rules
     * @param string          $expected
     */
    public function testRulesSetup($rules, $expected, array $errors = [])
    {
        $data = ['foo' => ''];
        $this->validation->setRules(['foo' => $rules], $errors);
        $this->validation->run($data);
        $this->assertSame($expected, $this->validation->getError('foo'));
    }

    public function rulesSetupProvider(): Generator
    {
        yield from [
            [
                'min_length[10]',
                'The foo field must be at least 10 characters in length.',
            ],
            [
                'min_length[10]',
                'The foo field is very short.',
                ['foo' => ['min_length' => 'The {field} field is very short.']],
            ],
            [
                ['min_length[10]'],
                'The foo field must be at least 10 characters in length.',
            ],
            [
                ['min_length[10]'],
                'The foo field is very short.',
                ['foo' => ['min_length' => 'The {field} field is very short.']],
            ],
            [
                ['rules' => 'min_length[10]'],
                'The foo field must be at least 10 characters in length.',
            ],
            [
                [
                    'label' => 'Foo Bar',
                    'rules' => 'min_length[10]',
                ],
                'The Foo Bar field must be at least 10 characters in length.',
            ],
            [
                [
                    'label' => 'Foo Bar',
                    'rules' => 'min_length[10]',
                ],
                'The Foo Bar field is very short.',
                ['foo' => ['min_length' => 'The {field} field is very short.']],
            ],
            [
                [
                    'label'  => 'Foo Bar',
                    'rules'  => 'min_length[10]',
                    'errors' => ['min_length' => 'The {field} field is very short.'],
                ],
                'The Foo Bar field is very short.',
            ],
        ];
    }

    public function testSetRulesRemovesErrorsArray(): void
    {
        $rules = [
            'foo' => [
                'label'  => 'Foo Bar',
                'rules'  => 'min_length[10]',
                'errors' => [
                    'min_length' => 'The {field} field is very short.',
                ],
            ],
        ];

        $this->validation->setRules($rules, []);
        $this->validation->run(['foo' => 'abc']);
        $this->assertSame('The Foo Bar field is very short.', $this->validation->getError('foo'));
    }

    public function testInvalidRule(): void
    {
        $this->expectException(ValidationException::class);

        $rules = [
            'foo' => 'bar|baz',
            'bar' => 'baz|belch',
        ];
        $this->validation->setRules($rules);

        $data = ['foo' => ''];
        $this->validation->run($data);
    }

    public function testRawInput(): void
    {
        $rawstring = 'username=admin001&role=administrator&usepass=0';

        $data = [
            'username' => 'admin001',
            'role'     => 'administrator',
            'usepass'  => 0,
        ];

        $config          = new App();
        $config->baseURL = 'http://example.com/';

        $request = new IncomingRequest($config, new URI(), $rawstring, new UserAgent());
        $this->validation->withRequest($request->withMethod('patch'))->run($data);
        $this->assertSame([], $this->validation->getErrors());
    }

    public function testJsonInput(): void
    {
        $data = [
            'username' => 'admin001',
            'role'     => 'administrator',
            'usepass'  => 0,
        ];
        $json = json_encode($data);

        $_SERVER['CONTENT_TYPE'] = 'application/json';

        $config          = new App();
        $config->baseURL = 'http://example.com/';

        $request = new IncomingRequest($config, new URI(), $json, new UserAgent());

        $rules = [
            'role' => 'required|min_length[5]',
        ];
        $validated = $this->validation
            ->withRequest($request->withMethod('patch'))
            ->setRules($rules)
            ->run();

        $this->assertTrue($validated);
        $this->assertSame([], $this->validation->getErrors());

        unset($_SERVER['CONTENT_TYPE']);
    }

    public function testHasRule(): void
    {
        $this->validation->setRuleGroup('groupA');
        $this->assertTrue($this->validation->hasRule('foo'));
    }

    public function testNotARealGroup(): void
    {
        $this->expectException(ValidationException::class);
        $this->validation->setRuleGroup('groupX');
        $this->validation->getRuleGroup('groupX');
    }

    public function testBadTemplate(): void
    {
        $this->expectException(ValidationException::class);
        $this->validation->listErrors('obviouslyBadTemplate');
    }

    public function testShowNonError(): void
    {
        $this->validation->setRules(['foo' => 'is_numeric']);
        $this->validation->setError('foo', 'Nadda');
        $this->assertSame('', $this->validation->showError('bogus'));
    }

    public function testShowBadTemplate(): void
    {
        $this->expectException(ValidationException::class);
        $this->validation->setRules(['foo' => 'is_numeric']);
        $this->validation->setError('foo', 'Nadda');
        $this->assertSame('We should never get here', $this->validation->showError('foo', 'bogus_template'));
    }

    public function testNoRuleSetsSetup(): void
    {
        $this->expectException(ValidationException::class);

        $this->config['ruleSets'] = null;
        $this->validation         = new Validation((object) $this->config, Services::renderer());
        $this->validation->reset();
        $this->validation->run(['foo' => '']);
    }

    public function testNotCustomRuleGroup(): void
    {
        $this->expectException(ValidationException::class);
        $data = ['foo' => ''];
        $this->validation->run($data, 'GeorgeRules');
    }

    public function testNotRealCustomRule(): void
    {
        $this->expectException(ValidationException::class);
        $data = ['foo' => ''];
        $this->validation->run($data, 'groupX');
    }

    public function testHasError(): void
    {
        $data = [
            'foo' => 'notanumber',
            'bar' => [
                ['baz' => 'string'],
                ['baz' => ''],
            ],
        ];

        $this->validation->setRules([
            'foo'       => 'is_numeric',
            'bar.*.baz' => 'required',
        ]);

        $this->validation->run($data);
        $this->assertTrue($this->validation->hasError('foo'));
        $this->assertTrue($this->validation->hasError('bar.*.baz'));
        $this->assertFalse($this->validation->hasError('bar.0.baz'));
        $this->assertTrue($this->validation->hasError('bar.1.baz'));
    }

    public function testSplitRulesTrue(): void
    {
        $this->validation->setRules([
            'phone' => 'required|regex_match[/^(01[2689]|09)[0-9]{8}$/]|numeric',
        ]);
        $this->assertTrue($this->validation->run(['phone' => '0987654321']));
    }

    public function testSplitRulesFalse(): void
    {
        $this->validation->setRules([
            'phone' => 'required|regex_match[/^(01[2689]|09)[0-9]{8}$/]|numeric',
        ]);
        $this->assertFalse($this->validation->run(['phone' => '09876543214']));
    }

    /**
     * @see https://github.com/codeigniter4/CodeIgniter4/issues/1201
     */
    public function testSplitNotRegex(): void
    {
        $method = $this->getPrivateMethodInvoker($this->validation, 'splitRules');
        $result = $method('uploaded[avatar]|max_size[avatar,1024]');
        $this->assertSame('uploaded[avatar]', $result[0]);
    }

    public function testSplitRegex(): void
    {
        $method = $this->getPrivateMethodInvoker($this->validation, 'splitRules');
        $result = $method('required|regex_match[/^[0-9]{4}[\-\.\[\/][0-9]{2}[\-\.\[\/][0-9]{2}/]|max_length[10]');
        $this->assertSame('regex_match[/^[0-9]{4}[\-\.\[\/][0-9]{2}[\-\.\[\/][0-9]{2}/]', $result[1]);
    }

    public function testTagReplacement(): void
    {
        $data = ['Username' => 'Pizza'];
        $this->validation->setRules(
            ['Username' => 'min_length[6]'],
            ['Username' => [
                'min_length' => 'Supplied value ({value}) for {field} must have at least {param} characters.',
            ]]
        );
        $this->validation->run($data);
        $errors = $this->validation->getErrors();

        if (! isset($errors['Username'])) {
            $this->fail('Unable to find "Username"');
        }

        $expected = 'Supplied value (Pizza) for Username must have at least 6 characters.';
        $this->assertSame($expected, $errors['Username']);
    }

    public function testRulesForObjectField(): void
    {
        $this->validation->setRules([
            'configuration' => 'required|check_object_rule',
        ]);

        $data = (object) ['configuration' => (object) ['first' => 1, 'second' => 2]];
        $this->validation->run((array) $data);
        $this->assertSame([], $this->validation->getErrors());

        $this->validation->reset();
        $this->validation->setRules([
            'configuration' => 'required|check_object_rule',
        ]);

        $data = (object) ['configuration' => (object) ['first1' => 1, 'second' => 2]];
        $this->validation->run((array) $data);

        $this->assertSame([
            'configuration' => 'Validation.check_object_rule',
        ], $this->validation->getErrors());
    }

    /**
     * @dataProvider arrayFieldDataProvider
     */
    public function testRulesForArrayField(array $body, array $rules, array $results)
    {
        $config          = new App();
        $config->baseURL = 'http://example.com/';

        $request = new IncomingRequest($config, new URI(), http_build_query($body), new UserAgent());

        $this->validation->setRules($rules);
        $this->validation->withRequest($request->withMethod('post'))->run($body);
        $this->assertSame($results, $this->validation->getErrors());
    }

    public function arrayFieldDataProvider(): Generator
    {
        yield from [
            'all_rules_should_pass' => [
                'body' => [
                    'foo' => [
                        'a',
                        'b',
                        'c',
                    ],
                ],
                'rules' => [
                    'foo.0' => 'required|alpha|max_length[2]',
                    'foo.1' => 'required|alpha|max_length[2]',
                    'foo.2' => 'required|alpha|max_length[2]',
                ],
                'results' => [],
            ],
            'first_field_will_return_required_error' => [
                'body' => [
                    'foo' => [
                        '',
                        'b',
                        'c',
                    ],
                ],
                'rules' => [
                    'foo.0' => 'required|alpha|max_length[2]',
                    'foo.1' => 'required|alpha|max_length[2]',
                    'foo.2' => 'required|alpha|max_length[2]',
                ],
                'results' => [
                    'foo.0' => 'The foo.0 field is required.',
                ],
            ],
            'first_and second_field_will_return_required_and_min_length_error' => [
                'body' => [
                    'foo' => [
                        '',
                        'b',
                        'c',
                    ],
                ],
                'rules' => [
                    'foo.0' => 'required|alpha|max_length[2]',
                    'foo.1' => 'required|alpha|min_length[2]|max_length[4]',
                    'foo.2' => 'required|alpha|max_length[2]',
                ],
                'results' => [
                    'foo.0' => 'The foo.0 field is required.',
                    'foo.1' => 'The foo.1 field must be at least 2 characters in length.',
                ],
            ],
        ];
    }

    public function testRulesForSingleRuleWithAsteriskWillReturnNoError(): void
    {
        $config          = new App();
        $config->baseURL = 'http://example.com/';

        $_REQUEST = [
            'id_user' => [
                1,
                3,
            ],
            'name_user' => [
                'abc123',
                'xyz098',
            ],
        ];

        $request = new IncomingRequest($config, new URI(), 'php://input', new UserAgent());

        $this->validation->setRules([
            'id_user.*'   => 'numeric',
            'name_user.*' => 'alpha_numeric',
        ]);

        $this->validation->withRequest($request->withMethod('post'))->run();
        $this->assertSame([], $this->validation->getErrors());
    }

    public function testRulesForSingleRuleWithAsteriskWillReturnError(): void
    {
        $config          = new App();
        $config->baseURL = 'http://example.com/';

        $_REQUEST = [
            'id_user' => [
                '1dfd',
                3,
            ],
            'name_user' => [
                123,
                'alpha',
                'xyz098',
            ],
            'contacts' => [
                'friends' => [
                    ['name' => ''],
                    ['name' => 'John'],
                ],
            ],
        ];

        $request = new IncomingRequest($config, new URI(), 'php://input', new UserAgent());

        $this->validation->setRules([
            'id_user.*'       => 'numeric',
            'name_user.*'     => 'alpha',
            'contacts.*.name' => 'required',
        ]);

        $this->validation->withRequest($request->withMethod('post'))->run();
        $this->assertSame([
            'id_user.0'               => 'The id_user.* field must contain only numbers.',
            'name_user.0'             => 'The name_user.* field may only contain alphabetical characters.',
            'name_user.2'             => 'The name_user.* field may only contain alphabetical characters.',
            'contacts.friends.0.name' => 'The contacts.*.name field is required.',
        ], $this->validation->getErrors());

        $this->assertSame(
            "The name_user.* field may only contain alphabetical characters.\n"
            . 'The name_user.* field may only contain alphabetical characters.',
            $this->validation->getError('name_user.*')
        );
        $this->assertSame(
            'The contacts.*.name field is required.',
            $this->validation->getError('contacts.*.name')
        );
    }

    public function testRulesForSingleRuleWithSingleValue(): void
    {
        $config          = new App();
        $config->baseURL = 'http://example.com/';

        $_REQUEST = [
            'id_user' => 'gh',
        ];

        $request = new IncomingRequest($config, new URI(), 'php://input', new UserAgent());

        $this->validation->setRules([
            'id_user' => 'numeric',
        ]);

        $this->validation->withRequest($request->withMethod('post'))->run();
        $this->assertSame([
            'id_user' => 'The id_user field must contain only numbers.',
        ], $this->validation->getErrors());
    }

    public function testTranslatedLabel(): void
    {
        $rules = [
            'foo' => [
                'label' => 'Foo.bar',
                'rules' => 'min_length[10]',
            ],
        ];

        $this->validation->setRules($rules, []);
        $this->validation->run(['foo' => 'abc']);
        $this->assertSame('The Foo Bar Translated field must be at least 10 characters in length.', $this->validation->getError('foo'));
    }

    public function testTranslatedLabelIsMissing(): void
    {
        $rules = [
            'foo' => [
                'label' => 'Foo.bar.is.missing',
                'rules' => 'min_length[10]',
            ],
        ];

        $this->validation->setRules($rules, []);
        $this->validation->run(['foo' => 'abc']);
        $this->assertSame('The Foo.bar.is.missing field must be at least 10 characters in length.', $this->validation->getError('foo'));
    }

    public function testTranslatedLabelWithCustomErrorMessage(): void
    {
        $rules = [
            'foo' => [
                'label'  => 'Foo.bar',
                'rules'  => 'min_length[10]',
                'errors' => [
                    'min_length' => 'Foo.bar.min_length1',
                ],
            ],
        ];

        $this->validation->setRules($rules, []);
        $this->validation->run(['foo' => 'abc']);
        $this->assertSame('The Foo Bar Translated field is very short.', $this->validation->getError('foo'));
    }

    public function testTranslatedLabelTagReplacement(): void
    {
        $data = ['Username' => 'Pizza'];

        $this->validation->setRules(
            ['Username' => [
                'label' => 'Foo.bar',
                'rules' => 'min_length[6]',
            ]],
            ['Username' => [
                'min_length' => 'Foo.bar.min_length2',
            ]]
        );

        $this->validation->run($data);
        $errors = $this->validation->getErrors();

        if (! isset($errors['Username'])) {
            $this->fail('Unable to find "Username"');
        }

        $expected = 'Supplied value (Pizza) for Foo Bar Translated must have at least 6 characters.';
        $this->assertSame($expected, $errors['Username']);
    }

    /**
     * @dataProvider dotNotationForIfExistProvider
     *
     * @see https://github.com/codeigniter4/CodeIgniter4/issues/4521
     */
    public function testDotNotationOnIfExistRule(bool $expected, array $rules, array $data): void
    {
        $actual = $this->validation->setRules($rules)->run($data);
        $this->assertSame($expected, $actual);
    }

    public function dotNotationForIfExistProvider(): Generator
    {
        yield 'dot-on-end-fail' => [
            false,
            ['status.*' => 'if_exist|in_list[status_1,status_2]'],
            ['status'   => ['bad-status']],
        ];

        yield 'dot-on-end-pass' => [
            true,
            ['status.*' => 'if_exist|in_list[status_1,status_2]'],
            ['status'   => ['status_1']],
        ];

        yield 'dot-on-middle-fail' => [
            false,
            ['fizz.*.baz' => 'if_exist|numeric'],
            [
                'fizz' => [
                    'bar' => ['baz' => 'yes'],
                ],
            ],
        ];

        yield 'dot-on-middle-pass' => [
            true,
            ['fizz.*.baz' => 'if_exist|numeric'],
            [
                'fizz' => [
                    'bar' => ['baz' => 30],
                ],
            ],
        ];

        yield 'dot-multiple-fail' => [
            false,
            ['fizz.*.bar.*' => 'if_exist|numeric'],
            ['fizz' => [
                'bos' => [
                    'bar' => [
                        'bub' => 'noo',
                    ],
                ],
            ]],
        ];

        yield 'dot-multiple-pass' => [
            true,
            ['fizz.*.bar.*' => 'if_exist|numeric'],
            ['fizz' => [
                'bos' => [
                    'bar' => [
                        'bub' => 5,
                    ],
                ],
            ]],
        ];
    }

    /**
     * @dataProvider validationArrayDataCaseProvider
     *
     * @see https://github.com/codeigniter4/CodeIgniter4/issues/4510
     */
    public function testValidationOfArrayData(bool $expected, array $rules, array $data): void
    {
        $actual = $this->validation->setRules($rules)->run($data);
        $this->assertSame($expected, $actual);
    }

    public function validationArrayDataCaseProvider(): iterable
    {
        yield 'fail-empty-string' => [
            false,
            ['bar.*.foo' => 'required'],
            ['bar' => [
                ['foo' => 'baz'],
                ['foo' => ''],
            ]],
        ];

        yield 'pass-nonempty-string' => [
            true,
            ['bar.*.foo' => 'required'],
            ['bar' => [
                ['foo' => 'baz'],
                ['foo' => 'boz'],
            ]],
        ];

        yield 'fail-empty-array' => [
            false,
            ['bar.*.foo' => 'required'],
            ['bar' => [
                ['foo' => 'baz'],
                ['foo' => []],
            ]],
        ];

        yield 'pass-nonempty-array' => [
            true,
            ['bar.*.foo' => 'required'],
            ['bar' => [
                ['foo' => 'baz'],
                ['foo' => ['boz']],
            ]],
        ];
    }

    /**
     * @dataProvider provideStringRulesCases
     *
     * @see https://github.com/codeigniter4/CodeIgniter4/issues/4929
     */
    public function testSplittingOfComplexStringRules(string $input, array $expected): void
    {
        $splitter = $this->getPrivateMethodInvoker($this->validation, 'splitRules');
        $this->assertSame($expected, $splitter($input));
    }

    public function provideStringRulesCases(): iterable
    {
        yield [
            'required',
            ['required'],
        ];

        yield [
            'required|numeric',
            ['required', 'numeric'],
        ];

        yield [
            'required|max_length[500]|hex',
            ['required', 'max_length[500]', 'hex'],
        ];

        yield [
            'required|numeric|regex_match[/[a-zA-Z]+/]',
            ['required', 'numeric', 'regex_match[/[a-zA-Z]+/]'],
        ];

        yield [
            'required|max_length[500]|regex_match[/^;"\'{}\[\]^<>=/]',
            ['required', 'max_length[500]', 'regex_match[/^;"\'{}\[\]^<>=/]'],
        ];

        yield [
            'regex_match[/^;"\'{}\[\]^<>=/]|regex_match[/[^a-z0-9.\|_]+/]',
            ['regex_match[/^;"\'{}\[\]^<>=/]', 'regex_match[/[^a-z0-9.\|_]+/]'],
        ];

        yield [
            'required|regex_match[/^(01[2689]|09)[0-9]{8}$/]|numeric',
            ['required', 'regex_match[/^(01[2689]|09)[0-9]{8}$/]', 'numeric'],
        ];

        yield [
            'required|regex_match[/^[0-9]{4}[\-\.\[\/][0-9]{2}[\-\.\[\/][0-9]{2}/]|max_length[10]',
            ['required', 'regex_match[/^[0-9]{4}[\-\.\[\/][0-9]{2}[\-\.\[\/][0-9]{2}/]', 'max_length[10]'],
        ];

        yield [
            'required|regex_match[/^(01|2689|09)[0-9]{8}$/]|numeric',
            ['required', 'regex_match[/^(01|2689|09)[0-9]{8}$/]', 'numeric'],
        ];
    }
}


text:
package com.yeyu.dearinformaton.adapter.PagerAdapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import com.yeyu.dearinformaton.fragment.PhotoDetailFragment;

import java.util.List;

/**
 * Created by gaoyehua on 2016/9/9.
 */
public class PhotoPagerAdapter extends FragmentStatePagerAdapter {
    private List<PhotoDetailFragment> mFragmentList;

    public PhotoPagerAdapter(FragmentManager fm, List<PhotoDetailFragment> fragmentList) {
        super(fm);
        mFragmentList = fragmentList;
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }
}


text:
'use strict';

//Clients service used to communicate Clients REST endpoints
angular.module('clients').factory('Clients', ['$resource',
	function($resource) {
		return $resource('clients/:clientId', { clientId: '@_id'
		}, {
			update: {
				method: 'PUT'
			}
		});
	}
]);


text:
CREATE TABLE `operacion` (
`id`  int(11) NOT NULL AUTO_INCREMENT ,
`agente_emisor_id`  int(11) NOT NULL ,
`agente_tenedor_id`  int(11) NOT NULL ,
`banco_id`  int(11) NOT NULL ,
`nro_cheque`  int(15) NOT NULL ,
`importe`  decimal(15,4) NOT NULL ,
`fecha_venc`  date NULL DEFAULT NULL ,
`nro_dias`  int(5) NULL DEFAULT NULL ,
`tasa_mensual`  decimal(5,4) NULL DEFAULT NULL ,
`interes`  decimal(15,4) NULL DEFAULT NULL ,
`impuesto_cheque`  decimal(15,4) NULL DEFAULT NULL ,
`gastos`  decimal(15,4) NULL DEFAULT NULL ,
`compra`  decimal(15,4) NULL DEFAULT NULL ,
`comision_valor`  decimal(15,4) NULL DEFAULT NULL ,
`comision_total`  decimal(15,4) NULL DEFAULT NULL ,
`subtotal`  decimal(15,4) NULL DEFAULT NULL COMMENT 'Total Sin descuentos' ,
`iva`  decimal(15,4) NULL DEFAULT NULL ,
`sellado`  decimal(15,4) NULL DEFAULT NULL ,
`neto`  decimal(15,4) NULL DEFAULT NULL ,
`inversor_id`  int(11) NOT NULL ,
`obveservacion`  text CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL ,
`estado`  int(1) NULL DEFAULT 0 ,
`created`  datetime NULL DEFAULT NULL ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=latin1 COLLATE=latin1_swedish_ci
AUTO_INCREMENT=1
ROW_FORMAT=COMPACT
;