text:
package fr.adrienbrault.idea.symfony2plugin.action.ui;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.psi.PsiFile;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.table.TableView;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ListTableModel;
import com.jetbrains.php.lang.psi.elements.*;
import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons;
import fr.adrienbrault.idea.symfony2plugin.Symfony2InterfacesUtil;
import fr.adrienbrault.idea.symfony2plugin.action.generator.naming.DefaultServiceNameStrategy;
import fr.adrienbrault.idea.symfony2plugin.action.generator.naming.JavascriptServiceNameStrategy;
import fr.adrienbrault.idea.symfony2plugin.action.generator.naming.ServiceNameStrategyInterface;
import fr.adrienbrault.idea.symfony2plugin.action.generator.naming.ServiceNameStrategyParameter;
import fr.adrienbrault.idea.symfony2plugin.dic.ContainerService;
import fr.adrienbrault.idea.symfony2plugin.stubs.ContainerCollectionResolver;
import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.psi.YAMLFile;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.*;
import java.util.List;

public class SymfonyCreateService extends JDialog {

    private JPanel panel1;
    private JPanel content;
    private JTextField textFieldClassName;
    private JPanel tableViewPanel;
    private JTextArea textAreaOutput;
    private JButton generateButton;
    private JButton buttonCopy;
    private JButton closeButton;

    private JRadioButton radioButtonOutXml;
    private JRadioButton radioButtonOutYaml;
    private JTextField textFieldServiceName;
    private JButton buttonSettings;
    private JButton buttonInsert;

    private TableView<MethodParameter.MethodModelParameter> tableView;
    private ListTableModel<MethodParameter.MethodModelParameter> modelList;

    private Map<String, ContainerService> serviceClass;
    private Set<String> serviceSetComplete;

    private Project project;
    private String className;

    @Nullable
    private PsiFile psiFile;

    public SymfonyCreateService(Project project, String className) {
        this(project, (PsiFile) null);
        this.className = className;
    }

    public SymfonyCreateService(Project project, @Nullable PsiFile psiFile) {
        this.project = project;
        this.psiFile = psiFile;
    }

    private static ServiceNameStrategyInterface[] NAME_STRATEGIES = new ServiceNameStrategyInterface[] {
        new JavascriptServiceNameStrategy(),
        new DefaultServiceNameStrategy(),
    };

    public void init() {

        setContentPane(panel1);
        setModal(true);

        this.modelList = new ListTableModel<MethodParameter.MethodModelParameter>(
            new IconColumn(),
            new NamespaceColumn(),
            new ParameterIndexColumn(),
            new ServiceColumn(),
            new IsServiceColumn()
        );

        // default is xml
        radioButtonOutXml.setSelected(true);
        if(this.psiFile instanceof YAMLFile) {
            radioButtonOutYaml.setSelected(true);
        }

        this.tableView = new TableView<MethodParameter.MethodModelParameter>();
        this.tableView.setModelAndUpdateColumns(this.modelList);

        tableViewPanel.add(ToolbarDecorator.createDecorator(this.tableView)
            .disableAddAction()
            .disableDownAction()
            .disableRemoveAction()
            .disableUpDownActions()
            .createPanel()
        );

        this.serviceClass = ContainerCollectionResolver.getServices(project);

        this.serviceSetComplete = new TreeSet<String>();
        serviceSetComplete.add("");
        serviceSetComplete.addAll(this.serviceClass.keySet());

        //update();

        this.modelList.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                generateServiceDefinition();
            }

        });

        this.generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                update();
            }
        });

        this.closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setEnabled(false);
                dispose();
            }
        });

        this.buttonCopy.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(StringUtils.isBlank(textAreaOutput.getText())) {
                    return;
                }

                StringSelection stringSelection = new StringSelection(textAreaOutput.getText());
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard ();
                clipboard.setContents(stringSelection, null);
            }
        });

        this.buttonSettings.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SymfonyJavascriptServiceNameForm.create(SymfonyCreateService.this, project, textFieldClassName.getText());
            }
        });

        if(this.className != null) {
            this.textFieldClassName.setText(this.className);
            update();
        } else {
            try {
                String data = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
                if(data != null && data.length() <= 255 && data.matches("[_A-Za-z0-9\\\\]+")) {
                    this.textFieldClassName.setText(data);
                    update();
                }
            } catch (UnsupportedFlavorException ignored) {
            } catch (IOException ignored) {
            }
        }

        radioButtonOutXml.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                generateServiceDefinition();
            }
        });

        radioButtonOutYaml.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                generateServiceDefinition();
            }
        });

        textFieldServiceName.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                generateServiceDefinition();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                generateServiceDefinition();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                generateServiceDefinition();
            }
        });

        // @TODO: support yaml
        if(this.psiFile instanceof XmlFile) {
            this.buttonInsert.setEnabled(false);
            this.buttonInsert.setVisible(false);

            /*
            not working npe: !?
            this.buttonInsert.requestFocusInWindow();
            this.getRootPane().setDefaultButton(buttonInsert);

            this.buttonInsert.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if(psiFile instanceof XmlFile) {
                        insertXmlServiceTag();
                    }
                }
            });
            */
        } else {
            this.buttonInsert.setEnabled(false);
            this.buttonInsert.setVisible(false);
        }

    }

    private void insertXmlServiceTag() {

        ApplicationManager.getApplication().runWriteAction(new Runnable() {
            @Override
            public void run() {

                final XmlTag rootTag = ((XmlFile) SymfonyCreateService.this.psiFile).getRootTag();
                if(rootTag == null) {
                    return;
                }

                XmlTag services = rootTag.findFirstSubTag("services");
                XmlElementFactory instance = XmlElementFactory.getInstance(SymfonyCreateService.this.project);
                if(services == null) {
                    services = rootTag.addSubTag(instance.createTagFromText("<services/>", rootTag.getLanguage()), false);
                }

                XmlTag tag = instance.createTagFromText(textAreaOutput.getText().replace("\r\n", "\n").replace("\n", " "), services.getLanguage());
                //XmlTag tag = instance.createTagFromText("<service id=\"test\"></service>", services.getLanguage());
                services.addSubTag(tag, false);
            }

        });
    }

    private void generateServiceDefinition() {

        String className = textFieldClassName.getText();
        if(StringUtils.isBlank(className)) {
            return;
        }

        if(className.startsWith("\\")) {
            className = className.substring(1);
        }

        // after cleanup class is empty
        if(StringUtils.isBlank(className)) {
            return;
        }

        ServiceBuilder.OutputType outputType = ServiceBuilder.OutputType.XML;
        if(radioButtonOutYaml.isSelected()) {
            outputType = ServiceBuilder.OutputType.Yaml;
        }

        textAreaOutput.setText(new ServiceBuilder(this.modelList.getItems(), this.project).build(
            outputType,
            className,
            textFieldServiceName.getText()
        ));
    }

    private void update() {
        ApplicationManager.getApplication().runReadAction(new Thread(new Runnable() {
            @Override
            public void run() {
                updateTask();
            }
        }));
    }

    private void updateTask() {

        String className = textFieldClassName.getText();
        if(className.startsWith("\\")) {
            className = className.substring(1);
        }

        if(className.length() == 0) {
            return;
        }

        textFieldServiceName.setText(generateServiceName(className));

        PhpClass phpClass = PhpElementsUtil.getClass(project, className);
        if(phpClass == null) {
            JOptionPane.showMessageDialog(null, String.format("invalid %s class", className));
            return;
        }

        List<MethodParameter.MethodModelParameter> modelParameters = new ArrayList<MethodParameter.MethodModelParameter>();

        for(Method method: phpClass.getMethods()) {
            if(method.getModifier().isPublic()) {
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Set<String> possibleServices = getPossibleServices(parameters[i]);
                    if(possibleServices.size() > 0) {
                        modelParameters.add(new MethodParameter.MethodModelParameter(method, parameters[i], i, possibleServices, getServiceName(possibleServices)));
                    } else {
                        modelParameters.add(new MethodParameter.MethodModelParameter(method, parameters[i], i, serviceSetComplete));
                    }

                }
            }

            method.getName();
        }

        Collections.sort(modelParameters, new Comparator<MethodParameter.MethodModelParameter>() {
            @Override
            public int compare(MethodParameter.MethodModelParameter o1, MethodParameter.MethodModelParameter o2) {
                int i = o1.getName().compareTo(o2.getName());
                if (i != 0) {
                    return i;
                }

                return Integer.valueOf(o1.getIndex()).compareTo(o2.getIndex());
            }
        });

        while(this.modelList.getRowCount() > 0) {
            this.modelList.removeRow(0);
        }

        this.modelList.addRows(modelParameters);
        generateServiceDefinition();
    }

    @Nullable
    private String getServiceName(Set<String> services) {
        if(services.size() == 0) {
            return null;
        }

        // we have a weight sorted Set, so first one
        return services.iterator().next();
    }

    @Override
    protected void dialogInit() {
        super.dialogInit();
    }

    public void setClassName(String className) {
        this.className = className;
    }

    private class IsServiceColumn extends ColumnInfo<MethodParameter.MethodModelParameter, Boolean> {

        public IsServiceColumn() {
            super("Act");
        }

        @Nullable
        @Override
        public Boolean valueOf(MethodParameter.MethodModelParameter modelParameter) {
            return modelParameter.isPossibleService();
        }

        public void setValue(MethodParameter.MethodModelParameter modelParameter, Boolean value){
            modelParameter.setPossibleService(value);
            tableView.getListTableModel().fireTableDataChanged();
        }

        public Class getColumnClass() {
            return Boolean.class;
        }

        public boolean isCellEditable(MethodParameter.MethodModelParameter modelParameter) {
            return true;
        }

        @Override
        public int getWidth(JTable table) {
            return 36;
        }

    }

    private class ServiceColumn extends ColumnInfo<MethodParameter.MethodModelParameter, String> {

        public ServiceColumn() {
            super("Service");
        }

        @Nullable
        @Override
        public String valueOf(MethodParameter.MethodModelParameter modelParameter) {
            return modelParameter.getCurrentService();
        }

        public void setValue(MethodParameter.MethodModelParameter modelParameter, String value){
            modelParameter.setCurrentService(value);
            tableView.getListTableModel().fireTableDataChanged();
        }

        @Override
        public boolean isCellEditable(MethodParameter.MethodModelParameter modelParameter) {
            return true;
        }

        @Nullable
        @Override
        public TableCellEditor getEditor(MethodParameter.MethodModelParameter modelParameter) {

            Set<String> sorted = modelParameter.getPossibleServices();
            ComboBox comboBox = new ComboBox(sorted.toArray(new String[sorted.size()] ), 200);
            comboBox.setEditable(true);

            return new DefaultCellEditor(comboBox);
        }
    }

    private class NamespaceColumn extends ColumnInfo<MethodParameter.MethodModelParameter, String> {

        public NamespaceColumn() {
            super("Method");
        }

        @Nullable
        @Override
        public String valueOf(MethodParameter.MethodModelParameter modelParameter) {
            return modelParameter.getName();
        }
    }

    private class IconColumn extends ColumnInfo<MethodParameter.MethodModelParameter, Icon> {
        public IconColumn() {
            super("");
        }

        @Nullable
        @Override
        public Icon valueOf(MethodParameter.MethodModelParameter modelParameter) {
            return modelParameter.getMethod().getIcon();
        }

        public java.lang.Class getColumnClass() {
            return ImageIcon.class;
        }

        @Override
        public int getWidth(JTable table) {
            return 32;
        }

    }

    private class ParameterIndexColumn extends ColumnInfo<MethodParameter.MethodModelParameter, String> {

        public ParameterIndexColumn() {
            super("Parameter");
        }

        @Nullable
        @Override
        public String valueOf(MethodParameter.MethodModelParameter modelParameter) {
            return modelParameter.getParameter().getName();
        }
    }

    private Set<String> getPossibleServices(Parameter parameter) {

        Set<String> possibleServices = new LinkedHashSet<String>();
        List<ContainerService> matchedContainer = new ArrayList<ContainerService>();

        PhpPsiElement phpPsiElement = parameter.getFirstPsiChild();
        if(!(phpPsiElement instanceof ClassReference)) {
            return possibleServices;
        }

        String type = ((ClassReference) phpPsiElement).getFQN();
        if(type != null) {
            PhpClass typeClass = PhpElementsUtil.getClassInterface(project, type);
            if(typeClass != null) {
                for(Map.Entry<String, ContainerService> entry: serviceClass.entrySet()) {
                    if(entry.getValue().getClassName() != null) {
                        PhpClass serviceClass = PhpElementsUtil.getClassInterface(project, entry.getValue().getClassName());
                        if(serviceClass != null) {
                            if(new Symfony2InterfacesUtil().isInstanceOf(serviceClass, typeClass)) {
                                matchedContainer.add(entry.getValue());
                            }
                        }
                    }

                }
            }
        }

        if(matchedContainer.size() > 0) {

            // weak service have lower priority
            Collections.sort(matchedContainer, new ContainerServicePriorityWeakComparator());

            // lower priority of services like "doctrine.orm.default_entity_manager"
            Collections.sort(matchedContainer, new ContainerServicePriorityNameComparator());

            for(ContainerService containerService: matchedContainer) {
                possibleServices.add(containerService.getName());
            }

        }

        return possibleServices;
    }

    public static class ContainerServicePriorityNameComparator implements Comparator<ContainerService> {

        private static String[] LOWER_PRIORITY = new String[] { "debug", "default", "abstract"};

        @Override
        public int compare(ContainerService o1, ContainerService o2) {

            if(this.isLowerPriority(o1.getName()) && this.isLowerPriority(o2.getName())) {
                return 0;
            }

            if(this.isLowerPriority(o1.getName())) {
                return 1;
            }

            return -1;
        }

        private boolean isLowerPriority(String name) {

            for(String lowerName: LOWER_PRIORITY) {
                if(name.contains(lowerName)) {
                    return true;
                }
            }

            return false;
        }

    }

    public static class ContainerServicePriorityWeakComparator implements Comparator<ContainerService> {
        @Override
        public int compare(ContainerService o1, ContainerService o2) {

            if(o1.isWeak() == o2.isWeak()) {
                return 0;
            }

            return (o1.isWeak() ? 1 : -1);
        }
    }

    @NotNull
    private String generateServiceName(@NotNull String className) {

        // normalize
        if(className.startsWith("\\")) {
            className = className.substring(1);
        }

        ServiceNameStrategyParameter parameter = new ServiceNameStrategyParameter(project, className);
        for (ServiceNameStrategyInterface nameStrategy : NAME_STRATEGIES) {
            String serviceName = nameStrategy.getServiceName(parameter);
            if(serviceName != null && StringUtils.isNotBlank(serviceName)) {
                return serviceName;
            }
        }

        return className.toLowerCase().replace("\\", "_");
    }

    private static SymfonyCreateService prepare(@NotNull SymfonyCreateService service) {

        service.init();
        service.setTitle("Symfony: Service Generator");
        service.setIconImage(Symfony2Icons.getImage(Symfony2Icons.SYMFONY));
        service.pack();

        service.setMinimumSize(new Dimension(550, 250));
        service.setLocationRelativeTo(null);
        service.setVisible(true);

        return service;
    }

    public static SymfonyCreateService create(@NotNull Project project, @NotNull PsiFile psiFile) {
        return prepare(new SymfonyCreateService(project, psiFile));
    }

    public static SymfonyCreateService create(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull PhpClass phpClass) {

        SymfonyCreateService symfonyCreateService = new SymfonyCreateService(project, psiFile);
        String presentableFQN = phpClass.getPresentableFQN();
        if(presentableFQN != null) {
            symfonyCreateService.setClassName(presentableFQN);
        }

        return prepare(symfonyCreateService);
    }

}


text:
using System;
using System.Collections.Generic;

namespace SistemaAguaPotable.Core.Model
{
    public partial class mora
    {
        public string cliente { get; set; }
        public System.DateTime inicioPeridoNoCancelado { get; set; }
        public System.DateTime finPeriodoNoCancelado { get; set; }
        public decimal saldoPendiente { get; set; }
        public virtual cliente cliente1 { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace webdriver {

DocumentHost::DocumentHost(HWND hwnd, HWND executor_handle) {
  LOG(TRACE) << "Entering DocumentHost::DocumentHost";

  // NOTE: COM should be initialized on this thread, so we
  // could use CoCreateGuid() and StringFromGUID2() instead.
  UUID guid;
  RPC_WSTR guid_string = NULL;
  RPC_STATUS status = ::UuidCreate(&guid);
  if (status != RPC_S_OK) {
    // If we encounter an error, not bloody much we can do about it.
    // Just log it and continue.
    LOG(WARN) << "UuidCreate returned a status other then RPC_S_OK: " << status;
  }
  status = ::UuidToString(&guid, &guid_string);
  if (status != RPC_S_OK) {
    // If we encounter an error, not bloody much we can do about it.
    // Just log it and continue.
    LOG(WARN) << "UuidToString returned a status other then RPC_S_OK: " << status;
  }

  // RPC_WSTR is currently typedef'd in RpcDce.h (pulled in by rpc.h)
  // as unsigned short*. It needs to be typedef'd as wchar_t*
  wchar_t* cast_guid_string = reinterpret_cast<wchar_t*>(guid_string);
  this->browser_id_ = StringUtilities::ToString(cast_guid_string);

  ::RpcStringFree(&guid_string);

  this->window_handle_ = hwnd;
  this->executor_handle_ = executor_handle;
  this->is_closing_ = false;
  this->wait_required_ = false;
  this->focused_frame_window_ = NULL;
}

DocumentHost::~DocumentHost(void) {
}

std::string DocumentHost::GetCurrentUrl() {
  LOG(TRACE) << "Entering DocumentHost::GetCurrentUrl";

  CComPtr<IHTMLDocument2> doc;
  this->GetDocument(&doc);
  if (!doc) {
    LOG(WARN) << "Unable to get document object, DocumentHost::GetDocument returned NULL. "
              << "Attempting to get URL from IWebBrowser2 object";
    return this->GetBrowserUrl();
  }

  CComBSTR url;
  HRESULT hr = doc->get_URL(&url);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Unable to get current URL, call to IHTMLDocument2::get_URL failed";
    return "";
  }

  std::wstring converted_url = url;
  std::string current_url = StringUtilities::ToString(converted_url);
  return current_url;
}

std::string DocumentHost::GetPageSource() {
  LOG(TRACE) << "Entering DocumentHost::GetPageSource";

  CComPtr<IHTMLDocument2> doc;
  this->GetDocument(&doc);
  if (!doc) {
    LOG(WARN) << "Unable to get document object, DocumentHost::GetDocument did not return a valid IHTMLDocument2 pointer";
    return "";
  }

  CComPtr<IHTMLDocument3> doc3;
  HRESULT hr = doc->QueryInterface<IHTMLDocument3>(&doc3);
  if (FAILED(hr) || !doc3) {
    LOG(WARN) << "Unable to get document object, QueryInterface to IHTMLDocument3 failed";
    return "";
  }

  CComPtr<IHTMLElement> document_element;
  hr = doc3->get_documentElement(&document_element);
  if (FAILED(hr) || !document_element) {
    LOGHR(WARN, hr) << "Unable to get document element from page, call to IHTMLDocument3::get_documentElement failed";
    return "";
  }

  CComBSTR html;
  hr = document_element->get_outerHTML(&html);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Have document element but cannot read source, call to IHTMLElement::get_outerHTML failed";
    return "";
  }

  std::wstring converted_html = html;
  std::string page_source = StringUtilities::ToString(converted_html);
  return page_source;
}

int DocumentHost::SetFocusedFrameByElement(IHTMLElement* frame_element) {
  LOG(TRACE) << "Entering DocumentHost::SetFocusedFrameByElement";

  HRESULT hr = S_OK;
  if (!frame_element) {
    this->focused_frame_window_ = NULL;
    return WD_SUCCESS;
  }

  CComPtr<IHTMLFrameBase2> frame_base;
  frame_element->QueryInterface<IHTMLFrameBase2>(&frame_base);
  if (!frame_base) {
    LOG(WARN) << "IHTMLElement is not a FRAME or IFRAME element";
    return ENOSUCHFRAME;
  }

  CComPtr<IHTMLWindow2> interim_result;
  hr = frame_base->get_contentWindow(&interim_result);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Cannot get contentWindow from IHTMLFrameBase2, call to IHTMLFrameBase2::get_contentWindow failed";
    return ENOSUCHFRAME;
  }

  this->focused_frame_window_ = interim_result;
  return WD_SUCCESS;
}

int DocumentHost::SetFocusedFrameByName(const std::string& frame_name) {
  LOG(TRACE) << "Entering DocumentHost::SetFocusedFrameByName";
  CComVariant frame_identifier =  StringUtilities::ToWString(frame_name).c_str();
  return this->SetFocusedFrameByIdentifier(frame_identifier);
}

int DocumentHost::SetFocusedFrameByIndex(const int frame_index) {
  LOG(TRACE) << "Entering DocumentHost::SetFocusedFrameByIndex";
  CComVariant frame_identifier;
  frame_identifier.vt = VT_I4;
  frame_identifier.lVal = frame_index;
  return this->SetFocusedFrameByIdentifier(frame_identifier);
}

void DocumentHost::SetFocusedFrameToParent() {
  LOG(TRACE) << "Entering DocumentHost::SetFocusedFrameToParent";
  // Three possible outcomes.
  // Outcome 1: Already at top-level browsing context. No-op.
  if (this->focused_frame_window_ != NULL) {
    CComPtr<IHTMLWindow2> parent_window;
    HRESULT hr = this->focused_frame_window_->get_parent(&parent_window);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "IHTMLWindow2::get_parent call failed.";
    }
    CComPtr<IHTMLWindow2> top_window;
    hr = this->focused_frame_window_->get_top(&top_window);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "IHTMLWindow2::get_top call failed.";
    }
    if (top_window.IsEqualObject(parent_window)) {
      // Outcome 2: Focus is on a frame one level deep, making the
      // parent the top-level browsing context. Set focused frame
      // pointer to NULL.
      this->focused_frame_window_ = NULL;
    } else {
      // Outcome 3: Focus is on a frame more than one level deep.
      // Set focused frame pointer to parent frame.
      this->focused_frame_window_ = parent_window;
    }
  }
}

int DocumentHost::SetFocusedFrameByIdentifier(VARIANT frame_identifier) {
  LOG(TRACE) << "Entering DocumentHost::SetFocusedFrameByIdentifier";

  CComPtr<IHTMLDocument2> doc;
  this->GetDocument(&doc);

  CComPtr<IHTMLFramesCollection2> frames;
  HRESULT hr = doc->get_frames(&frames);

  if (!frames) {
    LOG(WARN) << "No frames in document are set, IHTMLDocument2::get_frames returned NULL";
    return ENOSUCHFRAME;
  }

  long length = 0;
  frames->get_length(&length);
  if (!length) {
    LOG(WARN) << "No frames in document are found IHTMLFramesCollection2::get_length returned 0";
    return ENOSUCHFRAME;
  }

  // Find the frame
  CComVariant frame_holder;
  hr = frames->item(&frame_identifier, &frame_holder);

  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Error retrieving frame holder, call to IHTMLFramesCollection2::item failed";
    return ENOSUCHFRAME;
  }

  CComPtr<IHTMLWindow2> interim_result;
  frame_holder.pdispVal->QueryInterface<IHTMLWindow2>(&interim_result);
  if (!interim_result) {
    LOG(WARN) << "Error retrieving frame, IDispatch cannot be cast to IHTMLWindow2";
    return ENOSUCHFRAME;
  }

  this->focused_frame_window_ = interim_result;
  return WD_SUCCESS;
}

void DocumentHost::GetCookies(std::map<std::string, std::string>* cookies) {
  LOG(TRACE) << "Entering DocumentHost::GetCookies";

  CComPtr<IHTMLDocument2> doc;
  this->GetDocument(&doc);

  if (!doc) {
    LOG(WARN) << "Unable to get document";
    return;
  }

  CComBSTR cookie_bstr;
  HRESULT hr = doc->get_cookie(&cookie_bstr);
  if (!cookie_bstr) {
    LOG(WARN) << "Unable to get cookie str, call to IHTMLDocument2::get_cookie failed";
    cookie_bstr = L"";
  }

  std::wstring cookie_string = cookie_bstr;
  while (cookie_string.size() > 0) {
    size_t cookie_delimiter_pos = cookie_string.find(L"; ");
    std::wstring cookie = cookie_string.substr(0, cookie_delimiter_pos);
    if (cookie_delimiter_pos == std::wstring::npos) {
      cookie_string = L"";
    } else {
      cookie_string = cookie_string.substr(cookie_delimiter_pos + 2);
    }
    size_t cookie_separator_pos(cookie.find_first_of(L"="));
    std::string cookie_name(StringUtilities::ToString(cookie.substr(0, cookie_separator_pos)));
    std::string cookie_value(StringUtilities::ToString(cookie.substr(cookie_separator_pos + 1)));
    cookies->insert(std::pair<std::string, std::string>(cookie_name, cookie_value));
  }
}

int DocumentHost::AddCookie(const std::string& cookie) {
  LOG(TRACE) << "Entering DocumentHost::AddCookie";

  CComBSTR cookie_bstr = StringUtilities::ToWString(cookie.c_str()).c_str();

  CComPtr<IHTMLDocument2> doc;
  this->GetDocument(&doc);

  if (!doc) {
    LOG(WARN) << "Unable to get document";
    return EUNHANDLEDERROR;
  }

  if (!this->IsHtmlPage(doc)) {
    LOG(WARN) << "Unable to add cookie, document does not appear to be an HTML page";
    return ENOSUCHDOCUMENT;
  }

  HRESULT hr = doc->put_cookie(cookie_bstr);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Unable to put cookie to document, call to IHTMLDocument2::put_cookie failed";
    return EUNHANDLEDERROR;
  }

  return WD_SUCCESS;
}

int DocumentHost::DeleteCookie(const std::string& cookie_name) {
  LOG(TRACE) << "Entering DocumentHost::DeleteCookie";

  // Construct the delete cookie script
  std::wstring script_source;
  for (int i = 0; DELETECOOKIES[i]; i++) {
    script_source += DELETECOOKIES[i];
  }

  CComPtr<IHTMLDocument2> doc;
  this->GetDocument(&doc);
  Script script_wrapper(doc, script_source, 1);
  script_wrapper.AddArgument(cookie_name);
  int status_code = script_wrapper.Execute();
  return status_code;
}

void DocumentHost::PostQuitMessage() {
  LOG(TRACE) << "Entering DocumentHost::PostQuitMessage";

  this->set_is_closing(true);

  LPSTR message_payload = new CHAR[this->browser_id_.size() + 1];
  strcpy_s(message_payload, this->browser_id_.size() + 1, this->browser_id_.c_str());
  ::PostMessage(this->executor_handle(),
                WD_BROWSER_QUIT,
                NULL,
                reinterpret_cast<LPARAM>(message_payload));
}

bool DocumentHost::IsHtmlPage(IHTMLDocument2* doc) {
  LOG(TRACE) << "Entering DocumentHost::IsHtmlPage";

  CComBSTR type;
  HRESULT hr = doc->get_mimeType(&type);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Unable to get mime type for document, call to IHTMLDocument2::get_mimeType failed";
    return false;
  }

  // Call once to get the required buffer size, then again to fill
  // the buffer.
  DWORD mime_type_name_buffer_size = 0;
  hr = ::AssocQueryString(0,
                          ASSOCSTR_FRIENDLYDOCNAME,
                          L".htm",
                          NULL,
                          NULL,
                          &mime_type_name_buffer_size);

  std::vector<wchar_t> mime_type_name_buffer(mime_type_name_buffer_size);
  hr = ::AssocQueryString(0,
                          ASSOCSTR_FRIENDLYDOCNAME,
                          L".htm",
                          NULL,
                          &mime_type_name_buffer[0],
                          &mime_type_name_buffer_size);

  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Call to AssocQueryString failed in getting friendly name of .htm documents";
    return false;
  }

  std::wstring mime_type_name = &mime_type_name_buffer[0];
  std::wstring type_string = type;
  if (type_string == mime_type_name) {
    return true;
  }

  // If the user set Firefox as a default browser at any point, the MIME type
  // appears to be "sticky". This isn't elegant, but it appears to alleviate
  // the worst symptoms. Tested by using both Safari and Opera as the default
  // browser, even after setting IE as the default after Firefox (so the chain
  // of defaults looks like (IE -> Firefox -> IE -> Opera)

  if (L"Firefox HTML Document" == mime_type_name) {
    LOG(INFO) << "It looks like Firefox was once the default browser. "
              << "Guessing the page type from mime type alone";
    return true;
  }

  return false;
}

HWND DocumentHost::FindContentWindowHandle(HWND top_level_window_handle) {
  LOG(TRACE) << "Entering DocumentHost::FindContentWindowHandle";

  ProcessWindowInfo process_window_info;
  process_window_info.pBrowser = NULL;
  process_window_info.hwndBrowser = NULL;
  DWORD process_id;
  ::GetWindowThreadProcessId(top_level_window_handle, &process_id);
  process_window_info.dwProcessId = process_id;

  ::EnumChildWindows(top_level_window_handle,
                     &BrowserFactory::FindChildWindowForProcess,
                     reinterpret_cast<LPARAM>(&process_window_info));
  return process_window_info.hwndBrowser;
}

int DocumentHost::GetDocumentMode(IHTMLDocument2* doc) {
  LOG(TRACE) << "Entering DocumentHost::GetDocumentMode";
  CComPtr<IHTMLDocument6> mode_doc;
  doc->QueryInterface<IHTMLDocument6>(&mode_doc);
  if (!mode_doc) {
    LOG(DEBUG) << "QueryInterface for IHTMLDocument6 fails, so document mode must be 7 or less.";
    return 5;
  }
  CComVariant mode;
  HRESULT hr = mode_doc->get_documentMode(&mode);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "get_documentMode failed.";
    return 5;
  }
  int document_mode = static_cast<int>(mode.fltVal);
  return document_mode;
}

bool DocumentHost::IsStandardsMode(IHTMLDocument2* doc) {
  LOG(TRACE) << "Entering DocumentHost::IsStandardsMode";
  CComPtr<IHTMLDocument5> compatibility_mode_doc;
  doc->QueryInterface<IHTMLDocument5>(&compatibility_mode_doc);
  if (!compatibility_mode_doc) {
    LOG(WARN) << "Unable to cast document to IHTMLDocument5. IE6 or greater is required.";
    return false;
  }

  CComBSTR compatibility_mode;
  HRESULT hr = compatibility_mode_doc->get_compatMode(&compatibility_mode);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Failed calling get_compatMode.";
    return false;
  }
  // Compatibility mode should be "BackCompat" for quirks mode, and
  // "CSS1Compat" for standards mode. Check for "BackCompat" because
  // that's less likely to change.
  return compatibility_mode != L"BackCompat";
}

bool DocumentHost::GetDocumentDimensions(IHTMLDocument2* doc, LocationInfo* info) {
  LOG(TRACE) << "Entering DocumentHost::GetDocumentDimensions";
  CComVariant document_height;
  CComVariant document_width;

  // In non-standards-compliant mode, the BODY element represents the canvas.
  // In standards-compliant mode, the HTML element represents the canvas.
  CComPtr<IHTMLElement> canvas_element;
  if (!IsStandardsMode(doc)) {
    doc->get_body(&canvas_element);
    if (!canvas_element) {
      LOG(WARN) << "Unable to get canvas element from document in compatibility mode";
      return false;
    }
  } else {
    CComPtr<IHTMLDocument3> document_element_doc;
    doc->QueryInterface<IHTMLDocument3>(&document_element_doc);
    if (!document_element_doc) {
      LOG(WARN) << "Unable to get IHTMLDocument3 handle from document.";
      return false;
    }

    // The root node should be the HTML element.
    document_element_doc->get_documentElement(&canvas_element);
    if (!canvas_element) {
      LOG(WARN) << "Could not retrieve document element.";
      return false;
    }

    CComPtr<IHTMLHtmlElement> html_element;
    canvas_element->QueryInterface<IHTMLHtmlElement>(&html_element);
    if (!html_element) {
      LOG(WARN) << "Document element is not the HTML element.";
      return false;
    }
  }

  canvas_element->getAttribute(CComBSTR("scrollHeight"), 0, &document_height);
  canvas_element->getAttribute(CComBSTR("scrollWidth"), 0, &document_width);
  info->height = document_height.lVal;
  info->width = document_width.lVal;
  return true;
}

} // namespace webdriver


text:
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require("firebase-functions");
// The Firebase Admin SDK to access the Firebase Realtime Database.
const fb = require("firebase-admin");
const dummyOWScheduleEvent = {
    beginAt: '2018-08-22T21:00:00Z',
    game: 'Overwatch',
    league: {
        imageUrl: 'https://cdn.pandascore.co/images/league/image/289/lcs-g63ljv52.png',
        name: 'OWL',
        season: 'Season 2',
        year: 2018
    },
    status: 'not_started',
    teams: [
        {
            abbreviatedName: 'NYXE',
            id: 169,
            imageUrl: 'https://cdn.pandascore.co/images/team/image/113/echo-fox-ejngzoa3.png',
            name: 'New York Excel'
        },
        {
            abbreviatedName: 'LON',
            id: 53,
            imageUrl: 'https://cdn.pandascore.co/images/team/image/390/team-liquid-3g983dra.png',
            name: 'London Spitfire'
        }
    ]
};
const dummyLOLScheduleEvent = {
    beginAt: 1539080640000,
    foreignId: "100783238194455272",
    game: "League of Legends",
    league: {
        imageUrl: "https://lolstatic-a.akamaihd.net/esports-assets/production/league/worlds-3om032jn.png",
        name: "World Championship",
        roundName: "Day 2",
        season: "2018",
        year: "championship"
    },
    matchType: {
        iteration: "TBD",
        type: "TBD"
    },
    status: "UNRESOLVED",
    teams: [
        {
            acronym: "KBM",
            id: 66,
            imageUrl: "https://lolstatic-a.akamaihd.net/esports-assets/production/team/kabum-orange-egig9edp.png",
            name: "KaBuM! e-Sports"
        },
        {
            acronym: "C9",
            id: 18,
            imageUrl: "https://lolstatic-a.akamaihd.net/esports-assets/production/team/cloud9-gnd9b0gn.png",
            name: "Cloud9",
        }
    ]
};
exports.addDummyOWScheduleEvent = functions.https.onRequest((req, res) => {
    try {
        return fb
            .database()
            .ref('/esportsMatches/overwatch')
            .push(dummyOWScheduleEvent)
            .then((snapshot) => {
            // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
            return res.redirect(303, snapshot.ref.toString());
        });
    }
    catch (err) {
        console.log('Error: ' + err);
        return res.status(500).send(err);
    }
    ;
});
exports.addDummyLOLScheduleEvent = functions.https.onRequest((req, res) => __awaiter(this, void 0, void 0, function* () {
    try {
        // Push the new message into the Realtime Database using the Firebase Admin SDK.
        const newEventKey = fb
            .database()
            .ref()
            .child('/esportsMatches/leagueOfLegends')
            .push()
            .key;
        yield fb
            .database()
            .ref(`/esportsMatches/leagueOfLegends/${newEventKey}`)
            .set(dummyLOLScheduleEvent);
        return res.redirect(303, 'Success');
    }
    catch (error) {
        console.log('Error: ' + error);
        return res.status(500).send(error);
    }
    ;
}));
exports.addMessage = functions.https.onRequest((req, res) => {
    const original = req.query.text;
    return res.redirect(303, original);
});
//# sourceMappingURL=testing.js.map


text:
class GURL;
class CefBrowserImpl;

// Associated with browser-initated navigations to hold tracking data.
class BrowserExtraData : public WebKit::WebDataSource::ExtraData {
 public:
  explicit BrowserExtraData(int32 pending_page_id)
      : pending_page_id(pending_page_id),
        request_committed(false) {
  }

  // Contains the page_id for this navigation or -1 if there is none yet.
  int32 pending_page_id;

  // True if we have already processed the "DidCommitLoad" event for this
  // request.  Used by session history.
  bool request_committed;
};

// Stores one back/forward navigation state for the test shell.
class BrowserNavigationEntry {
 public:
  BrowserNavigationEntry();
  BrowserNavigationEntry(int page_id,
                      const GURL& url,
                      const CefString& title,
                      const CefString& target_frame,
                      const CefString& method,
                      const WebKit::WebHTTPBody& upload,
                      const CefRequest::HeaderMap& headers);
  ~BrowserNavigationEntry();

  // Set / Get the URI
  void SetURL(const GURL& url) { url_ = url; }
  const GURL& GetURL() const { return url_; }

  // Set / Get the title
  void SetTitle(const CefString& a_title) { title_ = a_title; }
  const CefString& GetTitle() const { return title_; }

  // Set / Get opaque state.
  // WARNING: This state is saved to the database and used to restore previous
  // states. If you use write a custom TabContents and provide your own
  // state make sure you have the ability to modify the format in the future
  // while being able to deal with older versions.
  void SetContentState(const std::string& state);
  const std::string& GetContentState() const { return state_; }

  // Get the page id corresponding to the tab's state.
  void SetPageID(int page_id) { page_id_ = page_id; }
  int32 GetPageID() const { return page_id_; }

  const CefString& GetTargetFrame() const { return target_frame_; }

  const CefString& GetMethod() const { return method_; }
  const WebKit::WebHTTPBody& GetUploadData() const { return upload_; }
  const CefRequest::HeaderMap& GetHeaders() const { return headers_; }

 private:
  // Describes the current page that the tab represents. This is not relevant
  // for all tab contents types.
  int32 page_id_;

  GURL url_;
  CefString title_;
  std::string state_;
  CefString method_;
  WebKit::WebHTTPBody upload_;
  CefRequest::HeaderMap headers_;

  CefString target_frame_;

  DISALLOW_COPY_AND_ASSIGN(BrowserNavigationEntry);
};

// Browser's NavigationController.  The goal is to be as close to the Chrome
// version as possible.
class BrowserNavigationController {
 public:
  explicit BrowserNavigationController(CefBrowserImpl* browser);
  ~BrowserNavigationController();

  void Reset();

  // Causes the controller to reload the current (or pending) entry.
  void Reload(bool ignoreCache);

  // Causes the controller to go to the specified offset from current.  Does
  // nothing if out of bounds.
  void GoToOffset(int offset);

  // Causes the controller to go to the specified index.
  void GoToIndex(int index);

  // Causes the controller to load the specified entry.  The controller
  // assumes ownership of the entry.
  // NOTE: Do not pass an entry that the controller already owns!
  void LoadEntry(BrowserNavigationEntry* entry);

  // Returns the last committed entry, which may be null if there are no
  // committed entries.
  BrowserNavigationEntry* GetLastCommittedEntry() const;

  // Returns the number of entries in the NavigationControllerBase, excluding
  // the pending entry if there is one.
  int GetEntryCount() const {
    return static_cast<int>(entries_.size());
  }

  // Returns the active entry, which is the pending entry if a navigation is in
  // progress or the last committed entry otherwise.  NOTE: This can be NULL!!
  //
  // If you are trying to get the current state of the NavigationControllerBase,
  // this is the method you will typically want to call.
  BrowserNavigationEntry* GetActiveEntry() const;

  // Returns the index from which we would go back/forward or reload.  This is
  // the last_committed_entry_index_ if pending_entry_index_ is -1.  Otherwise,
  // it is the pending_entry_index_.
  int GetCurrentEntryIndex() const;

  // Returns the entry at the specified index.  Returns NULL if out of
  // bounds.
  BrowserNavigationEntry* GetEntryAtIndex(int index) const;

  // Return the entry with the corresponding type and page_id, or NULL if
  // not found.
  BrowserNavigationEntry* GetEntryWithPageID(int32 page_id) const;

  // Returns the index of the last committed entry.
  int GetLastCommittedEntryIndex() const {
    return last_committed_entry_index_;
  }

  // Returns true if there are no entries before the last committed entry.
  bool IsAtStart() const {
    return (GetLastCommittedEntryIndex() == 0);
  }

  // Returns true if there are no entries after the last committed entry.
  bool IsAtEnd() const {
    return (GetLastCommittedEntryIndex() == GetEntryCount()-1);
  }

  // Used to inform us of a navigation being committed for a tab. We will take
  // ownership of the entry. Any entry located forward to the current entry will
  // be deleted. The new entry becomes the current entry.
  void DidNavigateToEntry(BrowserNavigationEntry* entry);

  // Used to inform us to discard its pending entry.
  void DiscardPendingEntry();

 private:
  // Inserts an entry after the current position, removing all entries after it.
  // The new entry will become the active one.
  void InsertEntry(BrowserNavigationEntry* entry);

  int GetMaxPageID() const { return max_page_id_; }
  void NavigateToPendingEntry(bool reload, bool ignoreCache);

  // Return the index of the entry with the corresponding type and page_id,
  // or -1 if not found.
  int GetEntryIndexWithPageID(int32 page_id) const;

  // Updates the max page ID with that of the given entry, if is larger.
  void UpdateMaxPageID();

  // List of NavigationEntry for this tab
  typedef ScopedVector<BrowserNavigationEntry> NavigationEntryList;
  NavigationEntryList entries_;

  // An entry we haven't gotten a response for yet.  This will be discarded
  // when we navigate again.  It's used only so we know what the currently
  // displayed tab is.
  BrowserNavigationEntry* pending_entry_;

  // currently visible entry
  int last_committed_entry_index_;

  // index of pending entry if it is in entries_, or -1 if pending_entry_ is a
  // new entry (created by LoadURL).
  int pending_entry_index_;

  CefBrowserImpl* browser_;
  int max_page_id_;

  DISALLOW_EVIL_CONSTRUCTORS(BrowserNavigationController);
};

#endif  // CEF_LIBCEF_BROWSER_NAVIGATION_CONTROLLER_H_


text:
import { makeLogger, arrayify, mapObject } from './utils'
const { debug } = makeLogger('connect')

import instance from './instance'

/**
 * Higher-order function that creates a function that will execute `func` on all
 * `instances` with the given arguments.
 *
 * @param  {Function} func
 * @param  {Object|Array} instances
 * @return {Array}
 */
const execAll = (func, instances) => (...args) => {
  const mappingFn = (obj) => obj && obj[func] && obj[func](...args)

  if (Array.isArray(instances)) return instances.map(mappingFn)
  else return mapObject(instances, mappingFn)
}

/**
 * Enhance instances container with `on`, `send` and `dispatch` functions
 *
 * @param {Object|Array} instances
 * @return {Object|Array}
 */
const enhanceInstances = (instances) => {
  // enhance `instances` container
  instances.on = execAll('on', instances)
  instances.send = execAll('send', instances)
  instances.dispatch = execAll('dispatch', instances)
  instances.filter = (fn) => enhanceInstances(Array.from(instances).filter(fn))
  instances.map = (fn) => enhanceInstances(Array.from(instances).map(fn))
  instances.reduce = (fn) => enhanceInstances(Array.from(instances).reduce(fn))
  return instances
}

/**
 * Create an instance container, which allows handling multiple networks on
 * various protocols.
 *
 * You can pass:
 *  - a single config object (will return an array with a single instance)
 *  - an array of config objects (will return an array with instances)
 *  - an object of config objects (will return an object of instances)
 *
 * @param  {Object|Array} rawConfig
 * @return {Object|Array}
 */
export default function connect (rawConfig) {
  debug('connect(' + JSON.stringify(rawConfig) + ')')

  let instances
  if (Array.isArray(rawConfig)) { // array of configs
    instances = rawConfig.map(instance)
  } else if (rawConfig.hasOwnProperty('protocol')) { // single config
    instances = arrayify(instance(rawConfig))
  } else { // object of configs
    instances = mapObject(rawConfig, instance)
  }

  if (
    (Array.isArray(instances) && instances.length === 0) ||
    (Object.keys(instances).length === 0)
  ) throw new Error('no config/s defined')

  return enhanceInstances(instances)
}


text:
<?php

class Abstract_Mapper
{

    protected $_dbTable;

    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_User');
        }
        return $this->_dbTable;
    }

    public function save($row)
    {
        if (null === ($id = $row->get('id'))) {
            unset($row['id']);
            $this->getDbTable()->insert($row);
        } else {
            $this->getDbTable()->update($row, array('id = ?' => $id));
        }
    }

    public function saveInRow($params)
    {
        $task = $this->_dbTable;
        $row  = $task->createRow($params);
        return $row->save();
    }

    public function find($id)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
    }

    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();

        return $resultSet;
    }

    public function now()
    {
        return date('Y-m-d H:i:s');
    }

    public function updateInRow($id, $idName, $params)
    {
        $table = $this->_dbTable;

        $where = " $idName = $id ";
        $row   = $table->fetchRow($where);
        $row->setFromArray($params);
        $row->save();
    }
}


text:
require 'rails_helper'

RSpec.describe Series, :type => :model do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
module ShouldCompile where

data R a = R {
    field1 :: a -- | comment for field2
  , field2 :: a
  , field3 :: a -- ^ comment for field3
  , {-| comment for field4 -} field4 :: a
}


text:
@implementation BlankPage_8

+ (id)scene
{
	CCScene *scene = [CCScene node];
	BlankPage_8 *layer = [BlankPage_8 node];
	[scene addChild: layer];
	return scene;
}

-(void) paintloader {
    [[ForegroundSingleton sharedInstance] showPaintPageForPage:8];
}

-(id) init
{
    CCLOG(@"Blank");

	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init] )) {
        [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(paintloader) userInfo:nil repeats:NO];
    }
	return self;
}

- (void) dealloc {
    CCLOG(@"BlankPage dealloc");
    NSLog(@"rc: %d", [BlankPage_8 retainCount]);

	[super dealloc];

    // [[CCTextureCache sharedTextureCache] removeUnusedTextures];
    // [[CCDirector sharedDirector] purgeCachedData];

}
@end


text:
package com.ansorgit.plugins.bash.lang.psi.stubs.elements;

import com.ansorgit.plugins.bash.file.BashFileType;
import com.ansorgit.plugins.bash.lang.psi.api.BashFile;
import com.ansorgit.plugins.bash.lang.psi.stubs.api.BashFileStub;
import com.ansorgit.plugins.bash.lang.psi.stubs.impl.BashFileStubImpl;
import com.ansorgit.plugins.bash.lang.psi.stubs.index.BashIndexVersion;
import com.ansorgit.plugins.bash.lang.psi.stubs.index.BashScriptNameIndex;
import com.intellij.psi.PsiFile;
import com.intellij.psi.StubBuilder;
import com.intellij.psi.stubs.*;
import com.intellij.psi.tree.IStubFileElementType;
import com.intellij.util.io.StringRef;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

public class BashStubFileElementType extends IStubFileElementType<BashFileStub> {

    public BashStubFileElementType() {
        super(BashFileType.BASH_LANGUAGE);
    }

    @Override
    public StubBuilder getBuilder() {
        return new DefaultStubBuilder() {
            @NotNull
            @Override
            protected StubElement createStubForFile(@NotNull PsiFile file) {
                if (file instanceof BashFile) {
                    return new BashFileStubImpl((BashFile) file);
                }

                return super.createStubForFile(file);
            }
        };
    }

    @Override
    public int getStubVersion() {
        return super.getStubVersion() + BashIndexVersion.CACHES_VERSION;
    }

    @NotNull
    public String getExternalId() {
        return "bash.FILE";
    }

    @Override
    public void indexStub(@NotNull PsiFileStub stub, @NotNull IndexSink sink) {
        super.indexStub(stub, sink);
        assert stub instanceof BashFileStub;

        //fixme write full canonical path
        //fixme get rid of double indexing
        String name = ((BashFileStub) stub).getName().toString();
        sink.occurrence(BashScriptNameIndex.KEY, name);
        //sink.occurrence(BashFullScriptPathIndex.KEY);
    }

    @Override
    public void serialize(@NotNull final BashFileStub stub, @NotNull final StubOutputStream dataStream) throws IOException {
        dataStream.writeName(stub.getName().toString());
    }

    @NotNull
    @Override
    public BashFileStub deserialize(@NotNull final StubInputStream dataStream, final StubElement parentStub) throws IOException {
        StringRef name = dataStream.readName();

        return new BashFileStubImpl(null, name);
    }
}


text:
RSpec.describe RuboCop::Cop::Style::MethodDefParentheses, :config do
  context 'require_parentheses' do
    let(:cop_config) { { 'EnforcedStyle' => 'require_parentheses' } }

    it 'reports an offense for def with parameters but no parens' do
      expect_offense(<<~RUBY)
        def func a, b
                 ^^^^ Use def with parentheses when there are parameters.
        end
      RUBY

      expect_correction(<<~RUBY)
        def func(a, b)
        end
      RUBY
    end

    it 'reports an offense for correct + opposite' do
      expect_offense(<<~RUBY)
        def func(a, b)
        end
        def func a, b
                 ^^^^ Use def with parentheses when there are parameters.
        end
      RUBY

      expect_correction(<<~RUBY)
        def func(a, b)
        end
        def func(a, b)
        end
      RUBY
    end

    it 'reports an offense for class def with parameters but no parens' do
      expect_offense(<<~RUBY)
        def Test.func a, b
                      ^^^^ Use def with parentheses when there are parameters.
        end
      RUBY

      expect_correction(<<~RUBY)
        def Test.func(a, b)
        end
      RUBY
    end

    it 'accepts def with no args and no parens' do
      expect_no_offenses(<<~RUBY)
        def func
        end
      RUBY
    end

    it 'auto-adds required parens for a defs' do
      expect_offense(<<~RUBY)
        def self.test param; end
                      ^^^^^ Use def with parentheses when there are parameters.
      RUBY

      expect_correction(<<~RUBY)
        def self.test(param); end
      RUBY
    end

    it 'auto-adds required parens for a defs after a passing method' do
      expect_offense(<<~RUBY)
        def self.fine; end

        def self.test param; end
                      ^^^^^ Use def with parentheses when there are parameters.

        def self.test2 param; end
                       ^^^^^ Use def with parentheses when there are parameters.
      RUBY

      expect_correction(<<~RUBY)
        def self.fine; end

        def self.test(param); end

        def self.test2(param); end
      RUBY
    end

    it 'auto-adds required parens to argument lists on multiple lines' do
      expect_offense(<<~RUBY)
        def test one,
                 ^^^^ Use def with parentheses when there are parameters.
        two
        end
      RUBY

      expect_correction(<<~RUBY)
        def test(one,
        two)
        end
      RUBY
    end
  end

  shared_examples 'no parentheses' do
    # common to require_no_parentheses and
    # require_no_parentheses_except_multiline
    it 'reports an offense for def with parameters with parens' do
      expect_offense(<<~RUBY)
        def func(a, b)
                ^^^^^^ Use def without parentheses.
        end
      RUBY

      expect_correction(<<~RUBY)
        def func a, b
        end
      RUBY
    end

    it 'accepts a def with parameters but no parens' do
      expect_no_offenses(<<~RUBY)
        def func a, b
        end
      RUBY
    end

    it 'reports an offense for opposite + correct' do
      expect_offense(<<~RUBY)
        def func(a, b)
                ^^^^^^ Use def without parentheses.
        end
        def func a, b
        end
      RUBY

      expect_correction(<<~RUBY)
        def func a, b
        end
        def func a, b
        end
      RUBY
    end

    it 'reports an offense for class def with parameters with parens' do
      expect_offense(<<~RUBY)
        def Test.func(a, b)
                     ^^^^^^ Use def without parentheses.
        end
      RUBY

      expect_correction(<<~RUBY)
        def Test.func a, b
        end
      RUBY
    end

    it 'accepts a class def with parameters with parens' do
      expect_no_offenses(<<~RUBY)
        def Test.func a, b
        end
      RUBY
    end

    it 'reports an offense for def with no args and parens' do
      expect_offense(<<~RUBY)
        def func()
                ^^ Use def without parentheses.
        end
      RUBY

      expect_correction(<<~RUBY)
        def func#{trailing_whitespace}
        end
      RUBY
    end

    it 'accepts def with no args and no parens' do
      expect_no_offenses(<<~RUBY)
        def func
        end
      RUBY
    end

    it 'auto-removes the parens for defs' do
      expect_offense(<<~RUBY)
        def self.test(param); end
                     ^^^^^^^ Use def without parentheses.
      RUBY
      expect_correction(<<~RUBY)
        def self.test param; end
      RUBY
    end
  end

  context 'require_no_parentheses' do
    let(:cop_config) { { 'EnforcedStyle' => 'require_no_parentheses' } }

    it_behaves_like 'no parentheses'
  end

  context 'require_no_parentheses_except_multiline' do
    let(:cop_config) do
      { 'EnforcedStyle' => 'require_no_parentheses_except_multiline' }
    end

    context 'when args are all on a single line' do
      it_behaves_like 'no parentheses'
    end

    context 'when args span multiple lines' do
      it 'auto-adds required parens to argument lists on multiple lines' do
        expect_offense(<<~RUBY)
          def test one,
                   ^^^^ Use def with parentheses when there are parameters.
          two
          end
        RUBY

        expect_correction(<<~RUBY)
          def test(one,
          two)
          end
        RUBY
      end

      it 'reports an offense for correct + opposite' do
        expect_offense(<<~RUBY)
          def func(a,
                   b)
          end
          def func a,
                   ^^ Use def with parentheses when there are parameters.
                   b
          end
        RUBY

        expect_correction(<<~RUBY)
          def func(a,
                   b)
          end
          def func(a,
                   b)
          end
        RUBY
      end
    end
  end
end


text:
layout: data_model
title: CustomObjectType
this_version: 1.1
---

  Heads up! These docs are for STIX 1.1, which is not the latest version (1.2). View the latest!

CustomObjectTypeCustom Object Schema

The CustomObjectType is intended to characterize objects that are not described by other defined CybOX Object schemas. Objects of this type have no pre-defined properties but instead all properties are provided by the author using the inherited Custom_Properties field.

      <form id="nav-version">
        <select>

            <option value="1.2" >STIX 1.2</option>

            <option value="1.1.1" >STIX 1.1.1</option>

            <option value="1.1" selected="selected">STIX 1.1</option>

            <option value="1.0.1" >STIX 1.0.1</option>

            <option value="1.0" >STIX 1.0</option>

        </select>
      </form>

Fields

      Field Name
      Type
      Description

      @object_referenceoptional

          QName

The object_reference field specifies a unique ID reference to an Object defined elsewhere. This construct allows for the re-use of the defined Properties of one Object within another, without the need to embed the full Object in the location from which it is being referenced. Thus, this ID reference is intended to resolve to the Properties of the Object that it points to.

      Custom_Properties0..1

          CustomPropertiesType

The Custom_Properties construct is optional and enables the specification of a set of custom Object Properties that may not be defined in existing Properties schemas.

      @custom_nameoptional

          QName

The custom_name field specifies a name for this for this type of Custom Object. The custom_name field should use the same namespace as used in the Object and Observable id fields for this author. Two Objects should only have the same custom_name value if they are written by the same author (i.e., their namespace is the same) and they are characterizing the same type of Object. Note that this does not necessarily mean that two such Object instances will both have identical properties in every case.

      Description0..1

          string

A description of the intent of this Custom object.


text:
const {it, fit, ffit, fffit, beforeEach, afterEach} = require('./helpers/async-spec-helpers') // eslint-disable-line no-unused-vars

describe('About', () => {
  let workspaceElement

  beforeEach(async () => {
    let storage = {}

    spyOn(window.localStorage, 'setItem').andCallFake((key, value) => {
      storage[key] = value
    })
    spyOn(window.localStorage, 'getItem').andCallFake((key) => {
      return storage[key]
    })

    workspaceElement = atom.views.getView(atom.workspace)
    await atom.packages.activatePackage('about')
  })

  it('deserializes correctly', () => {
    let deserializedAboutView = atom.deserializers.deserialize({
      deserializer: 'AboutView',
      uri: 'atom://about'
    })

    expect(deserializedAboutView).toBeTruthy()
  })

  describe('when the about:about-atom command is triggered', () => {
    it('shows the About Atom view', async () => {
      // Attaching the workspaceElement to the DOM is required to allow the
      // `toBeVisible()` matchers to work. Anything testing visibility or focus
      // requires that the workspaceElement is on the DOM. Tests that attach the
      // workspaceElement to the DOM are generally slower than those off DOM.
      jasmine.attachToDOM(workspaceElement)

      expect(workspaceElement.querySelector('.about')).not.toExist()
      await atom.workspace.open('atom://about')

      let aboutElement = workspaceElement.querySelector('.about')
      expect(aboutElement).toBeVisible()
    })
  })

  describe('when the Atom version number is clicked', () => {
    it('copies the version number to the clipboard', async () => {
      await atom.workspace.open('atom://about')

      let aboutElement = workspaceElement.querySelector('.about')
      let versionContainer = aboutElement.querySelector('.atom')
      versionContainer.click()
      expect(atom.clipboard.read()).toBe(atom.getVersion())
    })
  })

  describe('when the show more link is clicked', () => {
    it('expands to show additional version numbers', async () => {
      await atom.workspace.open('atom://about')
      jasmine.attachToDOM(workspaceElement)

      let aboutElement = workspaceElement.querySelector('.about')
      let showMoreElement = aboutElement.querySelector('.show-more-expand')
      let moreInfoElement = workspaceElement.querySelector('.show-more')
      showMoreElement.click()
      expect(moreInfoElement).toBeVisible()
    })
  })

  describe('when the Electron version number is clicked', () => {
    it('copies the version number to the clipboard', async () => {
      await atom.workspace.open('atom://about')

      let aboutElement = workspaceElement.querySelector('.about')
      let versionContainer = aboutElement.querySelector('.electron')
      versionContainer.click()
      expect(atom.clipboard.read()).toBe(process.versions.electron)
    })
  })

  describe('when the Chrome version number is clicked', () => {
    it('copies the version number to the clipboard', async () => {
      await atom.workspace.open('atom://about')

      let aboutElement = workspaceElement.querySelector('.about')
      let versionContainer = aboutElement.querySelector('.chrome')
      versionContainer.click()
      expect(atom.clipboard.read()).toBe(process.versions.chrome)
    })
  })

  describe('when the Node version number is clicked', () => {
    it('copies the version number to the clipboard', async () => {
      await atom.workspace.open('atom://about')

      let aboutElement = workspaceElement.querySelector('.about')
      let versionContainer = aboutElement.querySelector('.node')
      versionContainer.click()
      expect(atom.clipboard.read()).toBe(process.version)
    })
  })
})


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

<TITLE>
Uses of Package object.actor
</TITLE>

<META NAME="date" CONTENT="2012-07-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
object.actor

Packages that use object.actor

gui

io

object.actor

object.location

object.thing

Classes in object.actor used by gui

Actor

          Questa è la superclasse attore, o personaggio giocante.

HumanPlayer

          Questa è la classe per il giocatore umano, il cui codice di default, se omesso, è "HUMAN".

Classes in object.actor used by io

Actor

          Questa è la superclasse attore, o personaggio giocante.

Classes in object.actor used by object.actor

Actor

          Questa è la superclasse attore, o personaggio giocante.

Event

          Questa è la classe di costruzione e gestione degli Eventi.

Event.EventType

          L'enum EventType può essere del tipo:

 Locazione
 Interazione
 Possesso
 Domanda

Event.Predicate

          L'enum predicate può essere del tipo:

 Da
 Posside
 Si trova in
 Esce da
 Domanda
 Parla

Classes in object.actor used by object.location

Actor

          Questa è la superclasse attore, o personaggio giocante.

Event

          Questa è la classe di costruzione e gestione degli Eventi.

Classes in object.actor used by object.thing

Actor

          Questa è la superclasse attore, o personaggio giocante.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
<?php

/**
* Router class
*/
final class Router {
	private $registry;
	private $pre_action = array();
	private $error;

	/**
	 * Constructor
	 *
	 * @param	object	$route
 	*/
	public function __construct($registry) {
		$this->registry = $registry;
	}

	/**
	 *
	 *
	 * @param	object	$pre_action
 	*/
	public function addPreAction(Action $pre_action) {
		$this->pre_action[] = $pre_action;
	}

	/**
	 *
	 *
	 * @param	object	$action
	 * @param	object	$error
 	*/
	public function dispatch(Action $action, Action $error) {
		$this->error = $error;

		foreach ($this->pre_action as $pre_action) {
			$result = $this->execute($pre_action);

			if ($result instanceof Action) {
				$action = $result;

				break;
			}
		}

		while ($action instanceof Action) {
			$action = $this->execute($action);
		}
	}

	/**
	 *
	 *
	 * @param	object	$action
	 * @return	object
 	*/
	private function execute(Action $action) {
		$result = $action->execute($this->registry);

		if ($result instanceof Action) {
			return $result;
		}

		if ($result instanceof Exception) {
			$action = $this->error;

			$this->error = null;

			return $action;
		}
	}
}


text:
import * as instantiate_benchmark from './instantiate_benchmark';
import * as instantiate_directive_benchmark from './instantiate_directive_benchmark';
import * as instantiate_benchmark_codegen from './instantiate_benchmark_codegen';

import {benchmark, benchmarkStep} from 'benchpress/benchpress';

export function main() {
  benchmark(`ElementInjector.instantiate + instantiateDirectives`, function() {
    benchmarkStep('run', instantiate_benchmark.run);
  });

  benchmark(`ElementInjector.instantiateDirectives`, function() {
    benchmarkStep('run', instantiate_directive_benchmark.run);
  });

  benchmark(`ElementInjector.instantiate + instantiateDirectives (codegen)`, function() {
    benchmarkStep('run', instantiate_benchmark_codegen.run);
  });
}


text:
package org.apache.arrow.vector.complex.writer;

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

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.SchemaChangeCallBack;
import org.apache.arrow.vector.complex.ListVector;
import org.apache.arrow.vector.complex.MapVector;
import org.apache.arrow.vector.complex.NullableMapVector;
import org.apache.arrow.vector.complex.UnionVector;
import org.apache.arrow.vector.complex.impl.ComplexWriterImpl;
import org.apache.arrow.vector.complex.impl.SingleMapReaderImpl;
import org.apache.arrow.vector.complex.impl.UnionListReader;
import org.apache.arrow.vector.complex.impl.UnionListWriter;
import org.apache.arrow.vector.complex.impl.UnionReader;
import org.apache.arrow.vector.complex.impl.UnionWriter;
import org.apache.arrow.vector.complex.reader.BaseReader.MapReader;
import org.apache.arrow.vector.complex.reader.FieldReader;
import org.apache.arrow.vector.complex.writer.BaseWriter.ComplexWriter;
import org.apache.arrow.vector.complex.writer.BaseWriter.ListWriter;
import org.apache.arrow.vector.complex.writer.BaseWriter.MapWriter;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.ArrowType.ArrowTypeID;
import org.apache.arrow.vector.types.pojo.ArrowType.Int;
import org.apache.arrow.vector.types.pojo.ArrowType.Union;
import org.apache.arrow.vector.types.pojo.ArrowType.Utf8;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.util.CallBack;
import org.apache.arrow.vector.util.JsonStringArrayList;
import org.apache.arrow.vector.util.JsonStringHashMap;
import org.apache.arrow.vector.util.Text;
import org.apache.arrow.vector.util.TransferPair;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Assert;
import org.junit.Test;

import io.netty.buffer.ArrowBuf;

public class TestComplexWriter {

  private static final BufferAllocator allocator = new RootAllocator(Integer.MAX_VALUE);

  private static final int COUNT = 100;

  @Test
  public void simpleNestedTypes() {
    MapVector parent = populateMapVector(null);
    MapReader rootReader = new SingleMapReaderImpl(parent).reader("root");
    for (int i = 0; i < COUNT; i++) {
      rootReader.setPosition(i);
      Assert.assertEquals(i, rootReader.reader("int").readInteger().intValue());
      Assert.assertEquals(i, rootReader.reader("bigInt").readLong().longValue());
    }

    parent.close();
  }

  @Test
  public void transferPairSchemaChange() {
    SchemaChangeCallBack callBack1 = new SchemaChangeCallBack();
    SchemaChangeCallBack callBack2 = new SchemaChangeCallBack();
    MapVector parent = populateMapVector(callBack1);

    TransferPair tp = parent.getTransferPair("newVector", allocator, callBack2);

    ComplexWriter writer = new ComplexWriterImpl("newWriter", parent);
    MapWriter rootWriter = writer.rootAsMap();
    IntWriter intWriter = rootWriter.integer("newInt");
    intWriter.writeInt(1);
    writer.setValueCount(1);

    assertTrue(callBack1.getSchemaChangedAndReset());
    // The second vector should not have registered a schema change
    assertFalse(callBack1.getSchemaChangedAndReset());
  }

  private MapVector populateMapVector(CallBack callBack) {
    MapVector parent = new MapVector("parent", allocator, callBack);
    ComplexWriter writer = new ComplexWriterImpl("root", parent);
    MapWriter rootWriter = writer.rootAsMap();
    IntWriter intWriter = rootWriter.integer("int");
    BigIntWriter bigIntWriter = rootWriter.bigInt("bigInt");
    for (int i = 0; i < COUNT; i++) {
      rootWriter.start();
      intWriter.writeInt(i);
      bigIntWriter.writeBigInt(i);
      rootWriter.end();
    }
    writer.setValueCount(COUNT);
    return parent;
  }

  @Test
  public void nullableMap() {
    try (MapVector mapVector = new MapVector("parent", allocator, null)) {
      ComplexWriter writer = new ComplexWriterImpl("root", mapVector);
      MapWriter rootWriter = writer.rootAsMap();
      for (int i = 0; i < COUNT; i++) {
        rootWriter.start();
        if (i % 2 == 0) {
          MapWriter mapWriter = rootWriter.map("map");
          mapWriter.setPosition(i);
          mapWriter.start();
          mapWriter.bigInt("nested").writeBigInt(i);
          mapWriter.end();
        }
        rootWriter.end();
      }
      writer.setValueCount(COUNT);
      checkNullableMap(mapVector);
    }
  }

  /**
   * This test is similar to {@link #nullableMap()} ()} but we get the inner map writer once at the beginning
   */
  @Test
  public void nullableMap2() {
    try (MapVector mapVector = new MapVector("parent", allocator, null)) {
      ComplexWriter writer = new ComplexWriterImpl("root", mapVector);
      MapWriter rootWriter = writer.rootAsMap();
      MapWriter mapWriter = rootWriter.map("map");

      for (int i = 0; i < COUNT; i++) {
        rootWriter.start();
        if (i % 2 == 0) {
          mapWriter.setPosition(i);
          mapWriter.start();
          mapWriter.bigInt("nested").writeBigInt(i);
          mapWriter.end();
        }
        rootWriter.end();
      }
      writer.setValueCount(COUNT);
      checkNullableMap(mapVector);
    }
  }

  private void checkNullableMap(MapVector mapVector) {
    MapReader rootReader = new SingleMapReaderImpl(mapVector).reader("root");
    for (int i = 0; i < COUNT; i++) {
      rootReader.setPosition(i);
      assertTrue("index is set: " + i, rootReader.isSet());
      FieldReader map = rootReader.reader("map");
      if (i % 2 == 0) {
        assertTrue("index is set: " + i, map.isSet());
        assertNotNull("index is set: " + i, map.readObject());
        assertEquals(i, map.reader("nested").readLong().longValue());
      } else {
        assertFalse("index is not set: " + i, map.isSet());
        assertNull("index is not set: " + i, map.readObject());
      }
    }
  }

  @Test
  public void testList() {
    MapVector parent = new MapVector("parent", allocator, null);
    ComplexWriter writer = new ComplexWriterImpl("root", parent);
    MapWriter rootWriter = writer.rootAsMap();

    rootWriter.start();
    rootWriter.bigInt("int").writeBigInt(0);
    rootWriter.list("list").startList();
    rootWriter.list("list").bigInt().writeBigInt(0);
    rootWriter.list("list").endList();
    rootWriter.end();

    rootWriter.start();
    rootWriter.bigInt("int").writeBigInt(1);
    rootWriter.end();

    writer.setValueCount(2);

    MapReader rootReader = new SingleMapReaderImpl(parent).reader("root");

    rootReader.setPosition(0);
    assertTrue("row 0 list is not set", rootReader.reader("list").isSet());
    assertEquals(Long.valueOf(0), rootReader.reader("list").reader().readLong());

    rootReader.setPosition(1);
    assertFalse("row 1 list is set", rootReader.reader("list").isSet());
  }

  @Test
  public void listScalarType() {
    ListVector listVector = new ListVector("list", allocator, null, null);
    listVector.allocateNew();
    UnionListWriter listWriter = new UnionListWriter(listVector);
    for (int i = 0; i < COUNT; i++) {
      listWriter.startList();
      for (int j = 0; j < i % 7; j++) {
        listWriter.writeInt(j);
      }
      listWriter.endList();
    }
    listWriter.setValueCount(COUNT);
    UnionListReader listReader = new UnionListReader(listVector);
    for (int i = 0; i < COUNT; i++) {
      listReader.setPosition(i);
      for (int j = 0; j < i % 7; j++) {
        listReader.next();
        assertEquals(j, listReader.reader().readInteger().intValue());
      }
    }
  }

  @Test
  public void listScalarTypeNullable() {
    ListVector listVector = new ListVector("list", allocator, null, null);
    listVector.allocateNew();
    UnionListWriter listWriter = new UnionListWriter(listVector);
    for (int i = 0; i < COUNT; i++) {
      if (i % 2 == 0) {
        listWriter.setPosition(i);
        listWriter.startList();
        for (int j = 0; j < i % 7; j++) {
          listWriter.writeInt(j);
        }
        listWriter.endList();
      }
    }
    listWriter.setValueCount(COUNT);
    UnionListReader listReader = new UnionListReader(listVector);
    for (int i = 0; i < COUNT; i++) {
      listReader.setPosition(i);
      if (i % 2 == 0) {
        assertTrue("index is set: " + i, listReader.isSet());
        assertEquals("correct length at: " + i, i % 7, ((List<?>)listReader.readObject()).size());
      } else {
        assertFalse("index is not set: " + i, listReader.isSet());
        assertNull("index is not set: " + i, listReader.readObject());
      }
    }
  }

  @Test
  public void listMapType() {
    ListVector listVector = new ListVector("list", allocator, null, null);
    listVector.allocateNew();
    UnionListWriter listWriter = new UnionListWriter(listVector);
    MapWriter mapWriter = listWriter.map();
    for (int i = 0; i < COUNT; i++) {
      listWriter.startList();
      for (int j = 0; j < i % 7; j++) {
        mapWriter.start();
        mapWriter.integer("int").writeInt(j);
        mapWriter.bigInt("bigInt").writeBigInt(j);
        mapWriter.end();
      }
      listWriter.endList();
    }
    listWriter.setValueCount(COUNT);
    UnionListReader listReader = new UnionListReader(listVector);
    for (int i = 0; i < COUNT; i++) {
      listReader.setPosition(i);
      for (int j = 0; j < i % 7; j++) {
        listReader.next();
        Assert.assertEquals("record: " + i, j, listReader.reader().reader("int").readInteger().intValue());
        Assert.assertEquals(j, listReader.reader().reader("bigInt").readLong().longValue());
      }
    }
  }

  @Test
  public void listListType() {
    try (ListVector listVector = new ListVector("list", allocator, null, null)) {
      listVector.allocateNew();
      UnionListWriter listWriter = new UnionListWriter(listVector);
      for (int i = 0; i < COUNT; i++) {
        listWriter.startList();
        for (int j = 0; j < i % 7; j++) {
          ListWriter innerListWriter = listWriter.list();
          innerListWriter.startList();
          for (int k = 0; k < i % 13; k++) {
            innerListWriter.integer().writeInt(k);
          }
          innerListWriter.endList();
        }
        listWriter.endList();
      }
      listWriter.setValueCount(COUNT);
      checkListOfLists(listVector);
    }
  }

  /**
   * This test is similar to {@link #listListType()} but we get the inner list writer once at the beginning
   */
  @Test
  public void listListType2() {
    try (ListVector listVector = new ListVector("list", allocator, null, null)) {
      listVector.allocateNew();
      UnionListWriter listWriter = new UnionListWriter(listVector);
      ListWriter innerListWriter = listWriter.list();

      for (int i = 0; i < COUNT; i++) {
        listWriter.startList();
        for (int j = 0; j < i % 7; j++) {
          innerListWriter.startList();
          for (int k = 0; k < i % 13; k++) {
            innerListWriter.integer().writeInt(k);
          }
          innerListWriter.endList();
        }
        listWriter.endList();
      }
      listWriter.setValueCount(COUNT);
      checkListOfLists(listVector);
    }
  }

  private void checkListOfLists(final ListVector listVector) {
    UnionListReader listReader = new UnionListReader(listVector);
    for (int i = 0; i < COUNT; i++) {
      listReader.setPosition(i);
      for (int j = 0; j < i % 7; j++) {
        listReader.next();
        FieldReader innerListReader = listReader.reader();
        for (int k = 0; k < i % 13; k++) {
          innerListReader.next();
          Assert.assertEquals("record: " + i, k, innerListReader.reader().readInteger().intValue());
        }
      }
    }
  }

  @Test
  public void unionListListType() {
    try (ListVector listVector = new ListVector("list", allocator, null, null)) {
      listVector.allocateNew();
      UnionListWriter listWriter = new UnionListWriter(listVector);
      for (int i = 0; i < COUNT; i++) {
        listWriter.startList();
        for (int j = 0; j < i % 7; j++) {
          ListWriter innerListWriter = listWriter.list();
          innerListWriter.startList();
          for (int k = 0; k < i % 13; k++) {
            if (k % 2 == 0) {
              innerListWriter.integer().writeInt(k);
            } else {
              innerListWriter.bigInt().writeBigInt(k);
            }
          }
          innerListWriter.endList();
        }
        listWriter.endList();
      }
      listWriter.setValueCount(COUNT);
      checkUnionList(listVector);
    }
  }

  /**
   * This test is similar to {@link #unionListListType()} but we get the inner list writer once at the beginning
   */
  @Test
  public void unionListListType2() {
    try (ListVector listVector = new ListVector("list", allocator, null, null)) {
      listVector.allocateNew();
      UnionListWriter listWriter = new UnionListWriter(listVector);
      ListWriter innerListWriter = listWriter.list();

      for (int i = 0; i < COUNT; i++) {
        listWriter.startList();
        for (int j = 0; j < i % 7; j++) {
          innerListWriter.startList();
          for (int k = 0; k < i % 13; k++) {
            if (k % 2 == 0) {
              innerListWriter.integer().writeInt(k);
            } else {
              innerListWriter.bigInt().writeBigInt(k);
            }
          }
          innerListWriter.endList();
        }
        listWriter.endList();
      }
      listWriter.setValueCount(COUNT);
      checkUnionList(listVector);
    }
  }

  private void checkUnionList(ListVector listVector) {
    UnionListReader listReader = new UnionListReader(listVector);
    for (int i = 0; i < COUNT; i++) {
      listReader.setPosition(i);
      for (int j = 0; j < i % 7; j++) {
        listReader.next();
        FieldReader innerListReader = listReader.reader();
        for (int k = 0; k < i % 13; k++) {
          innerListReader.next();
          if (k % 2 == 0) {
            Assert.assertEquals("record: " + i, k, innerListReader.reader().readInteger().intValue());
          } else {
            Assert.assertEquals("record: " + i, k, innerListReader.reader().readLong().longValue());
          }
        }
      }
    }
  }

  @Test
  public void simpleUnion() {
    UnionVector vector = new UnionVector("union", allocator, null);
    UnionWriter unionWriter = new UnionWriter(vector);
    unionWriter.allocate();
    for (int i = 0; i < COUNT; i++) {
      unionWriter.setPosition(i);
      if (i % 2 == 0) {
        unionWriter.writeInt(i);
      } else {
        unionWriter.writeFloat4((float) i);
      }
    }
    vector.getMutator().setValueCount(COUNT);
    UnionReader unionReader = new UnionReader(vector);
    for (int i = 0; i < COUNT; i++) {
      unionReader.setPosition(i);
      if (i % 2 == 0) {
        Assert.assertEquals(i, i, unionReader.readInteger());
      } else {
        Assert.assertEquals((float) i, unionReader.readFloat(), 1e-12);
      }
    }
    vector.close();
  }

  @Test
  public void promotableWriter() {
    MapVector parent = new MapVector("parent", allocator, null);
    ComplexWriter writer = new ComplexWriterImpl("root", parent);
    MapWriter rootWriter = writer.rootAsMap();
    for (int i = 0; i < 100; i++) {
      BigIntWriter bigIntWriter = rootWriter.bigInt("a");
      bigIntWriter.setPosition(i);
      bigIntWriter.writeBigInt(i);
    }
    Field field = parent.getField().getChildren().get(0).getChildren().get(0);
    Assert.assertEquals("a", field.getName());
    Assert.assertEquals(Int.TYPE_TYPE, field.getType().getTypeID());
    Int intType = (Int) field.getType();

    Assert.assertEquals(64, intType.getBitWidth());
    Assert.assertTrue(intType.getIsSigned());
    for (int i = 100; i < 200; i++) {
      VarCharWriter varCharWriter = rootWriter.varChar("a");
      varCharWriter.setPosition(i);
      byte[] bytes = Integer.toString(i).getBytes();
      ArrowBuf tempBuf = allocator.buffer(bytes.length);
      tempBuf.setBytes(0, bytes);
      varCharWriter.writeVarChar(0, bytes.length, tempBuf);
    }
    field = parent.getField().getChildren().get(0).getChildren().get(0);
    Assert.assertEquals("a", field.getName());
    Assert.assertEquals(Union.TYPE_TYPE, field.getType().getTypeID());
    Assert.assertEquals(Int.TYPE_TYPE, field.getChildren().get(0).getType().getTypeID());
    Assert.assertEquals(Utf8.TYPE_TYPE, field.getChildren().get(1).getType().getTypeID());
    MapReader rootReader = new SingleMapReaderImpl(parent).reader("root");
    for (int i = 0; i < 100; i++) {
      rootReader.setPosition(i);
      FieldReader reader = rootReader.reader("a");
      Long value = reader.readLong();
      Assert.assertNotNull("index: " + i, value);
      Assert.assertEquals(i, value.intValue());
    }
    for (int i = 100; i < 200; i++) {
      rootReader.setPosition(i);
      FieldReader reader = rootReader.reader("a");
      Text value = reader.readText();
      Assert.assertEquals(Integer.toString(i), value.toString());
    }
  }

  /**
   * Even without writing to the writer, the union schema is created correctly
   */
  @Test
  public void promotableWriterSchema() {
    MapVector parent = new MapVector("parent", allocator, null);
    ComplexWriter writer = new ComplexWriterImpl("root", parent);
    MapWriter rootWriter = writer.rootAsMap();
    rootWriter.bigInt("a");
    rootWriter.varChar("a");

    Field field = parent.getField().getChildren().get(0).getChildren().get(0);
    Assert.assertEquals("a", field.getName());
    Assert.assertEquals(ArrowTypeID.Union, field.getType().getTypeID());

    Assert.assertEquals(ArrowTypeID.Int, field.getChildren().get(0).getType().getTypeID());
    Int intType = (Int) field.getChildren().get(0).getType();
    Assert.assertEquals(64, intType.getBitWidth());
    Assert.assertTrue(intType.getIsSigned());
    Assert.assertEquals(ArrowTypeID.Utf8, field.getChildren().get(1).getType().getTypeID());
  }

  private Set<String> getFieldNames(List<Field> fields) {
    Set<String> fieldNames = new HashSet<>();
    for (Field field: fields) {
      fieldNames.add(field.getName());
      if (!field.getChildren().isEmpty()) {
        for (String name: getFieldNames(field.getChildren())) {
          fieldNames.add(field.getName() + "::" + name);
        }
      }
    }
    return fieldNames;
  }

  @Test
  public void mapWriterMixedCaseFieldNames() {
    // test case-sensitive MapWriter
    MapVector parent = new MapVector("parent", allocator, null);
    ComplexWriter writer = new ComplexWriterImpl("rootCaseSensitive", parent, false, true);
    MapWriter rootWriterCaseSensitive = writer.rootAsMap();
    rootWriterCaseSensitive.bigInt("int_field");
    rootWriterCaseSensitive.bigInt("Int_Field");
    rootWriterCaseSensitive.float4("float_field");
    rootWriterCaseSensitive.float4("Float_Field");
    MapWriter mapFieldWriterCaseSensitive = rootWriterCaseSensitive.map("map_field");
    mapFieldWriterCaseSensitive.varChar("char_field");
    mapFieldWriterCaseSensitive.varChar("Char_Field");
    ListWriter listFieldWriterCaseSensitive = rootWriterCaseSensitive.list("list_field");
    MapWriter listMapFieldWriterCaseSensitive = listFieldWriterCaseSensitive.map();
    listMapFieldWriterCaseSensitive.bit("bit_field");
    listMapFieldWriterCaseSensitive.bit("Bit_Field");

    List<Field> fieldsCaseSensitive = parent.getField().getChildren().get(0).getChildren();
    Set<String> fieldNamesCaseSensitive = getFieldNames(fieldsCaseSensitive);
    Assert.assertEquals(11, fieldNamesCaseSensitive.size());
    Assert.assertTrue(fieldNamesCaseSensitive.contains("int_field"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("Int_Field"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("float_field"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("Float_Field"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("map_field"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("map_field::char_field"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("map_field::Char_Field"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("list_field"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("list_field::$data$"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("list_field::$data$::bit_field"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("list_field::$data$::Bit_Field"));

    // test case-insensitive MapWriter
    ComplexWriter writerCaseInsensitive = new ComplexWriterImpl("rootCaseInsensitive", parent, false, false);
    MapWriter rootWriterCaseInsensitive = writerCaseInsensitive.rootAsMap();

    rootWriterCaseInsensitive.bigInt("int_field");
    rootWriterCaseInsensitive.bigInt("Int_Field");
    rootWriterCaseInsensitive.float4("float_field");
    rootWriterCaseInsensitive.float4("Float_Field");
    MapWriter mapFieldWriterCaseInsensitive = rootWriterCaseInsensitive.map("map_field");
    mapFieldWriterCaseInsensitive.varChar("char_field");
    mapFieldWriterCaseInsensitive.varChar("Char_Field");
    ListWriter listFieldWriterCaseInsensitive = rootWriterCaseInsensitive.list("list_field");
    MapWriter listMapFieldWriterCaseInsensitive = listFieldWriterCaseInsensitive.map();
    listMapFieldWriterCaseInsensitive.bit("bit_field");
    listMapFieldWriterCaseInsensitive.bit("Bit_Field");

    List<Field> fieldsCaseInsensitive = parent.getField().getChildren().get(1).getChildren();
    Set<String> fieldNamesCaseInsensitive = getFieldNames(fieldsCaseInsensitive);
    Assert.assertEquals(7, fieldNamesCaseInsensitive.size());
    Assert.assertTrue(fieldNamesCaseInsensitive.contains("int_field"));
    Assert.assertTrue(fieldNamesCaseInsensitive.contains("float_field"));
    Assert.assertTrue(fieldNamesCaseInsensitive.contains("map_field"));
    Assert.assertTrue(fieldNamesCaseInsensitive.contains("map_field::char_field"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("list_field"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("list_field::$data$"));
    Assert.assertTrue(fieldNamesCaseSensitive.contains("list_field::$data$::bit_field"));
  }

  @Test
  public void timeStampWriters() throws Exception {
    // test values
    final long expectedNanos = 981173106123456789L;
    final long expectedMicros = 981173106123456L;
    final long expectedMillis = 981173106123L;
    final long expectedSecs = 981173106L;
    final DateTime expectedSecDateTime = new DateTime(2001, 2, 3, 4, 5, 6, 0).withZoneRetainFields(DateTimeZone.getDefault());
    final DateTime expectedMilliDateTime = new DateTime(2001, 2, 3, 4, 5, 6, 123).withZoneRetainFields(DateTimeZone.getDefault());
    final DateTime expectedMicroDateTime = expectedMilliDateTime;
    final DateTime expectedNanoDateTime = expectedMilliDateTime;

    // write
    MapVector parent = new MapVector("parent", allocator, null);
    ComplexWriter writer = new ComplexWriterImpl("root", parent);
    MapWriter rootWriter = writer.rootAsMap();

    TimeStampSecWriter timeStampSecWriter = rootWriter.timeStampSec("sec");
    timeStampSecWriter.setPosition(0);
    timeStampSecWriter.writeTimeStampSec(expectedSecs);

    TimeStampMilliWriter timeStampWriter = rootWriter.timeStampMilli("milli");
    timeStampWriter.setPosition(1);
    timeStampWriter.writeTimeStampMilli(expectedMillis);

    TimeStampMicroWriter timeStampMicroWriter = rootWriter.timeStampMicro("micro");
    timeStampMicroWriter.setPosition(2);
    timeStampMicroWriter.writeTimeStampMicro(expectedMicros);

    TimeStampNanoWriter timeStampNanoWriter = rootWriter.timeStampNano("nano");
    timeStampNanoWriter.setPosition(3);
    timeStampNanoWriter.writeTimeStampNano(expectedNanos);

    // schema
    Field secField = parent.getField().getChildren().get(0).getChildren().get(0);
    Assert.assertEquals("sec", secField.getName());
    Assert.assertEquals(ArrowType.Timestamp.TYPE_TYPE, secField.getType().getTypeID());

    Field milliField = parent.getField().getChildren().get(0).getChildren().get(1);
    Assert.assertEquals("milli", milliField.getName());
    Assert.assertEquals(ArrowType.Timestamp.TYPE_TYPE, milliField.getType().getTypeID());

    Field microField = parent.getField().getChildren().get(0).getChildren().get(2);
    Assert.assertEquals("micro", microField.getName());
    Assert.assertEquals(ArrowType.Timestamp.TYPE_TYPE, microField.getType().getTypeID());

    Field nanoField = parent.getField().getChildren().get(0).getChildren().get(3);
    Assert.assertEquals("nano", nanoField.getName());
    Assert.assertEquals(ArrowType.Timestamp.TYPE_TYPE, nanoField.getType().getTypeID());

    // read
    MapReader rootReader = new SingleMapReaderImpl(parent).reader("root");

    FieldReader secReader = rootReader.reader("sec");
    secReader.setPosition(0);
    DateTime secDateTime = secReader.readDateTime();
    Assert.assertEquals(expectedSecDateTime, secDateTime);
    long secLong = secReader.readLong();
    Assert.assertEquals(expectedSecs, secLong);

    FieldReader milliReader = rootReader.reader("milli");
    milliReader.setPosition(1);
    DateTime milliDateTime = milliReader.readDateTime();
    Assert.assertEquals(expectedMilliDateTime, milliDateTime);
    long milliLong = milliReader.readLong();
    Assert.assertEquals(expectedMillis, milliLong);

    FieldReader microReader = rootReader.reader("micro");
    microReader.setPosition(2);
    DateTime microDateTime = microReader.readDateTime();
    Assert.assertEquals(expectedMicroDateTime, microDateTime);
    long microLong = microReader.readLong();
    Assert.assertEquals(expectedMicros, microLong);

    FieldReader nanoReader = rootReader.reader("nano");
    nanoReader.setPosition(3);
    DateTime nanoDateTime = nanoReader.readDateTime();
    Assert.assertEquals(expectedNanoDateTime, nanoDateTime);
    long nanoLong = nanoReader.readLong();
    Assert.assertEquals(expectedNanos, nanoLong);
  }

  @Test
  public void complexCopierWithList() {
    MapVector parent = new MapVector("parent", allocator, null);
    ComplexWriter writer = new ComplexWriterImpl("root", parent);
    MapWriter rootWriter = writer.rootAsMap();
    ListWriter listWriter = rootWriter.list("list");
    MapWriter innerMapWriter = listWriter.map();
    IntWriter outerIntWriter = listWriter.integer();
    rootWriter.start();
    listWriter.startList();
    outerIntWriter.writeInt(1);
    outerIntWriter.writeInt(2);
    innerMapWriter.start();
    IntWriter intWriter = innerMapWriter.integer("a");
    intWriter.writeInt(1);
    innerMapWriter.end();
    innerMapWriter.start();
    intWriter = innerMapWriter.integer("a");
    intWriter.writeInt(2);
    innerMapWriter.end();
    listWriter.endList();
    rootWriter.end();
    writer.setValueCount(1);

    NullableMapVector mapVector = (NullableMapVector) parent.getChild("root");
    TransferPair tp = mapVector.getTransferPair(allocator);
    tp.splitAndTransfer(0, 1);
    MapVector toMapVector = (MapVector) tp.getTo();
    JsonStringHashMap<?,?> toMapValue = (JsonStringHashMap<?,?>) toMapVector.getAccessor().getObject(0);
    JsonStringArrayList<?> object = (JsonStringArrayList<?>) toMapValue.get("list");
    assertEquals(1, object.get(0));
    assertEquals(2, object.get(1));
    JsonStringHashMap<?,?> innerMap = (JsonStringHashMap<?,?>) object.get(2);
    assertEquals(1, innerMap.get("a"));
    innerMap = (JsonStringHashMap<?,?>) object.get(3);
    assertEquals(2, innerMap.get("a"));
  }
}