text:
from __future__ import unicode_literals

import json
from werkzeug.exceptions import BadRequest

class ResourceNotFoundException(BadRequest):
    def __init__(self, message):
        super(ResourceNotFoundException, self).__init__()
        self.description = json.dumps({
            "message": message,
            '__type': 'ResourceNotFoundException',
        })

class ValidationException(BadRequest):
    def __init__(self, message):
        super(ValidationException, self).__init__()
        self.description = json.dumps({
            "message": message,
            '__type': 'ResourceNotFoundException',
        })

redpajama_set_name: RedPajamaGithub


text:
set -xe

# https://github.com/vadesecure/test-automation-framework/blob/66c29c58cdc219c9fe9bd702a7d1784c34b913ce/.travis.yml
export CHROMEDRIVER_VERSION=`curl -s http://chromedriver.storage.googleapis.com/LATEST_RELEASE`
curl -L -O "http://chromedriver.storage.googleapis.com/${CHROMEDRIVER_VERSION}/chromedriver_linux64.zip"
unzip chromedriver_linux64.zip
chmod +x chromedriver

# https://github.com/SeleniumHQ/docker-selenium/issues/87
export DBUS_SESSION_BUS_ADDRESS=/dev/null

#export CHROME_BIN=chromium-browser

PATH=$PATH:$PWD py.test -s \
 --driver "Chrome" \
 --capability browserName "${BROWSER_NAME}" \
 --capability version "${VERSION}" \
 --base-url http://127.0.0.1:8080/${CONSOLE} --verify-base-url --console ${CONSOLE}


text:
.btn-circular {
	font-size: 12px;
	border-radius: 26px!important;
	padding: 7px;
	border-color: #7AC29A!important;
	color: #7AC29A!important;
	box-sizing: border-box;
	border-width: 2px!important;
	background-color: transparent!important;
	font-weight: 500;
	opacity: 1;
	filter: alpha(opacity=100);
	line-height: 1.5;
	display: inline-block;
	margin-bottom: 0px;

	text-align: center;
	white-space: nowrap;
	vertical-align: middle;
	-ms-touch-action: manipulation;
	touch-action: manipulation;
	cursor: pointer;
	-webkit-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
	border: 1px solid transparent;
	background-image: none;

	-webkit-transition: all 150ms linear;
	-moz-transition: all 150ms linear;
	-o-transition: all 150ms linear;
	-ms-transition: all 150ms linear;
	transition: all 150ms linear;

	list-style: none;
}

.btn-circular:hover, .btn-circular:focus, .btn-circular:active {
    background-color: #7ac29a;
    color: rgba(255, 255, 255, 0.7);
    border-color: #7AC29A;
}


text:
/**
 * @author Yong.Teng
 */
package com.buession.geoip.model;


text:
using Android.App;
using Android.Content.Res;
using Android.Views;

using Java.Util;

namespace DotNetRu.Droid.Helpers
{
    public static class LocaleUtils
    {

        private static Locale currentLocale;
        public static void SetLocale(Locale locale)
        {
            currentLocale = locale;
            if (currentLocale != null)
            {
                Locale.Default = currentLocale;
            }
        }

        public static void UpdateConfig(ContextThemeWrapper wrapper)
        {
            if (currentLocale != null)
            {
                using Configuration configuration = new Configuration {Locale = currentLocale};
                wrapper?.ApplyOverrideConfiguration(configuration);
            }
        }

        public static void UpdateConfig(Application app, Configuration configuration)
        {
            if (currentLocale != null)
            {
                //Wrapping the configuration to avoid Activity endless loop
                using Configuration config = new Configuration(configuration) {Locale = currentLocale};
                Resources res = app?.BaseContext.Resources;
                if (res?.DisplayMetrics != null)
                {
                    res.UpdateConfiguration(config, res.DisplayMetrics);
                }
            }
        }
    }
}


text:
package org.fightteam.leeln.rpc.client;

import com.google.protobuf.*;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import org.fightteam.leeln.proto.RpcProto;

/**
 * RPC通道
 *
 * @author oyach
 * @since 0.0.1
 */
public class ClientRpcChannel implements RpcChannel {

    private ClientServer clientServer;

    public ClientRpcChannel(ClientServer clientServer) {
        this.clientServer = clientServer;
    }

    @Override
    public void callMethod(Descriptors.MethodDescriptor method, RpcController controller, Message request, Message responsePrototype, RpcCallback<Message> done) {

        RpcProto.RpcRequest rpcRequest = RpcProto.RpcRequest.getDefaultInstance().toBuilder()
                .setRequestMessage(request.toByteString()).setId(1)
                .setMethodName(method.getFullName())
                .setIsBlockingService(false).build();

        final Message responseMsg = responsePrototype;

        final RpcCallback<Message> callback = done;

        final RpcController rpcController = controller;

        ChannelFuture channelFuture = clientServer.getChannelFuture();

        channelFuture.channel().pipeline().addLast(new RpcClientHandler() {
            @Override
            protected void channelRead0(ChannelHandlerContext ctx, RpcProto.RpcResponse msg) throws Exception {
                if (msg.getErrorCode() == null) {
                    callback.run(responseMsg.toBuilder().mergeFrom(msg.getResponseMessage()).build());
                } else {
                    rpcController.setFailed(msg.getErrorMessage());
                    callback.run(responseMsg.toBuilder().getDefaultInstanceForType());

                   // rpcController.notifyOnCancel(callback);
                }
            }
        }).writeAndFlush(rpcRequest).awaitUninterruptibly();

    }
}


text:
using System;
using System.Data;
using System.Windows.Forms;
using DevExpress.Data;
using DevExpress.Utils;
using DevExpress.XtraVerticalGrid.Rows;
using SharpMap.Data;
using bv.winclient.Core;
using eidss.gis.Properties;

namespace eidss.gis.Tools.ToolForms
{
    public partial class InfoForm : BvForm
    {
        public InfoForm()
        {
            InitializeComponent();
        }

        private FeatureDataRow m_Feature;

        private DataTable m_StatTable;

        public bool IsAVR { get; set; }

        public bool IsSystem { get; set; }

        public DataTable StatTable
        {
            get { return m_StatTable; }
            set
            {
                if (m_StatTable!=null) featureGrid.Rows.Clear();
                m_StatTable = value;

                if (m_StatTable==null) return;
                if (m_StatTable.Columns.Count==0) return;
                if (m_StatTable.Rows == null) return;

                if (m_StatTable.Columns.Contains("strRegion"))
                {
                    if (!m_StatTable.Columns.Contains("strSettlement"))
                    {
                        // Region name
                        var columnReg = m_StatTable.Columns["strRegion"];
                        if (m_StatTable.Rows[0][columnReg.ColumnName] != null)
                        {
                            var val_reg = m_StatTable.Rows[0][columnReg.ColumnName];

                            var row_reg = new EditorRow(Resources.InfoForm_StatTable_Region) { Name = Resources.InfoForm_StatTable_Region, Enabled = true };

                            row_reg.Properties.Caption = Resources.InfoForm_StatTable_Region;
                            row_reg.Properties.RowEdit = persistentRepos.Items[0];
                            row_reg.Properties.Format.FormatType = FormatType.None;
                            row_reg.Properties.UnboundType = UnboundColumnType.String;

                            featureGrid.Rows.Add(row_reg);
                            featureGrid.SetCellValue(row_reg, 0, val_reg);
                        }

                        // Rayon name
                        var columnDistr = m_StatTable.Columns["strRayon"];
                        if (m_StatTable.Rows[0][columnDistr.ColumnName] != null)
                        {
                            var val_distr = m_StatTable.Rows[0][columnDistr.ColumnName];

                            var row_distr = new EditorRow(Resources.InfoForm_StatTable_Rayon) { Name = Resources.InfoForm_StatTable_Rayon, Enabled = true };

                            row_distr.Properties.Caption = Resources.InfoForm_StatTable_Rayon;
                            row_distr.Properties.RowEdit = persistentRepos.Items[0];
                            row_distr.Properties.Format.FormatType = FormatType.None;
                            row_distr.Properties.UnboundType = UnboundColumnType.String;

                            featureGrid.Rows.Add(row_distr);
                            featureGrid.SetCellValue(row_distr, 0, val_distr);
                        }
                    }
                    else
                    {
                        // Settlement name
                        var columnStt = m_StatTable.Columns["strSettlement"];
                        if (m_StatTable.Rows[0][columnStt.ColumnName] != null)
                        {
                            var val_stt = m_StatTable.Rows[0][columnStt.ColumnName];

                            var row_stt = new EditorRow(Resources.InfoForm_StatTable_Settlement) { Name = Resources.InfoForm_StatTable_Settlement, Enabled = true };

                            row_stt.Properties.Caption = Resources.InfoForm_StatTable_Settlement;
                            row_stt.Properties.RowEdit = persistentRepos.Items[0];
                            row_stt.Properties.Format.FormatType = FormatType.None;
                            row_stt.Properties.UnboundType = UnboundColumnType.String;

                            featureGrid.Rows.Add(row_stt);
                            featureGrid.SetCellValue(row_stt, 0, val_stt);
                        }

                        // Rayon name
                        var columnDistr1 = m_StatTable.Columns["strRayon"];
                        if (m_StatTable.Rows[0][columnDistr1.ColumnName] != null)
                        {
                            var val_distr1 = m_StatTable.Rows[0][columnDistr1.ColumnName];

                            var row_distr1 = new EditorRow(Resources.InfoForm_StatTable_Rayon) { Name = Resources.InfoForm_StatTable_Rayon, Enabled = true };

                            row_distr1.Properties.Caption = Resources.InfoForm_StatTable_Rayon;
                            row_distr1.Properties.RowEdit = persistentRepos.Items[0];
                            row_distr1.Properties.Format.FormatType = FormatType.None;
                            row_distr1.Properties.UnboundType = UnboundColumnType.String;

                            featureGrid.Rows.Add(row_distr1);
                            featureGrid.SetCellValue(row_distr1, 0, val_distr1);
                        }

                        // Region name
                        var columnReg1 = m_StatTable.Columns["strRegion"];
                        if (m_StatTable.Rows[0][columnReg1.ColumnName] != null)
                        {
                            var val_reg1 = m_StatTable.Rows[0][columnReg1.ColumnName];

                            var row_reg1 = new EditorRow(Resources.InfoForm_StatTable_Region) { Name = Resources.InfoForm_StatTable_Region, Enabled = true };

                            row_reg1.Properties.Caption = Resources.InfoForm_StatTable_Region;
                            row_reg1.Properties.RowEdit = persistentRepos.Items[0];
                            row_reg1.Properties.Format.FormatType = FormatType.None;
                            row_reg1.Properties.UnboundType = UnboundColumnType.String;

                            featureGrid.Rows.Add(row_reg1);
                            featureGrid.SetCellValue(row_reg1, 0, val_reg1);
                        }
                    }
                }
                else
                {
                    // Region name
                    var columnName = m_StatTable.Columns["strName"];
                    if (m_StatTable.Rows[0][columnName.ColumnName] != null)
                    {
                        var val_name = m_StatTable.Rows[0][columnName.ColumnName];

                        var row_name = new EditorRow(Resources.InfoForm_StatTable_Region) {Name = Resources.InfoForm_StatTable_Region, Enabled = true};

                        row_name.Properties.Caption = Resources.InfoForm_StatTable_Region;
                        row_name.Properties.RowEdit = persistentRepos.Items[0];
                        row_name.Properties.Format.FormatType = FormatType.None;
                        row_name.Properties.UnboundType = UnboundColumnType.String;

                        featureGrid.Rows.Add(row_name);
                        featureGrid.SetCellValue(row_name, 0, val_name);
                    }
                }

                if (!m_StatTable.Columns.Contains("strSettlement"))
                {
                    // Area
                    var columnArea = m_StatTable.Columns["varArea"];
                    if (m_StatTable.Rows[0][columnArea.ColumnName] != null)
                    {
                        var val_area = m_StatTable.Rows[0][columnArea.ColumnName];

                        var row_area = new EditorRow(Resources.InfoForm_StatTable_Area) {Name = Resources.InfoForm_StatTable_Area, Enabled = true};

                        row_area.Properties.Caption = Resources.InfoForm_StatTable_Area;
                        row_area.Properties.RowEdit = persistentRepos.Items[0];
                        row_area.Properties.Format.FormatType = FormatType.None;
                        row_area.Properties.UnboundType = UnboundColumnType.String;

                        featureGrid.Rows.Add(row_area);
                        featureGrid.SetCellValue(row_area, 0, val_area);
                    }

                    // Population
                    var columnPopulation = m_StatTable.Columns["varPopulation"];
                    if (m_StatTable.Rows[0][columnPopulation.ColumnName] != null)
                    {
                        var val_population = m_StatTable.Rows[0][columnPopulation.ColumnName];

                        var row_population = new EditorRow(Resources.InfoForm_StatTable_Human_population)
                                                 {Name = Resources.InfoForm_StatTable_Human_population, Enabled = true};

                        row_population.Properties.Caption = Resources.InfoForm_StatTable_Human_population;
                        row_population.Properties.RowEdit = persistentRepos.Items[0];
                        row_population.Properties.Format.FormatType = FormatType.None;
                        row_population.Properties.UnboundType = UnboundColumnType.String;

                        featureGrid.Rows.Add(row_population);
                        featureGrid.SetCellValue(row_population, 0, val_population);
                    }

                    // Population density
                    var columnPopDens = m_StatTable.Columns["varPopDens"];
                    if (m_StatTable.Rows[0][columnPopDens.ColumnName] != null)
                    {
                        var val_popdens = m_StatTable.Rows[0][columnPopDens.ColumnName];

                        var row_popdens = new EditorRow(Resources.InfoForm_StatTable_PopulationDens)
                                              {Name = Resources.InfoForm_StatTable_PopulationDens, Enabled = true};

                        row_popdens.Properties.Caption = Resources.InfoForm_StatTable_PopulationDens;
                        row_popdens.Properties.RowEdit = persistentRepos.Items[0];
                        row_popdens.Properties.Format.FormatType = FormatType.None;
                        row_popdens.Properties.UnboundType = UnboundColumnType.String;

                        featureGrid.Rows.Add(row_popdens);
                        featureGrid.SetCellValue(row_popdens, 0, val_popdens);
                    }
                }

            }
        }

        public FeatureDataRow Feature
        {
            get { return m_Feature; }
            set
            {
                if (m_Feature!=null) featureGrid.Rows.Clear();

                m_Feature = value;

                if (m_Feature == null) return;
                if (m_Feature.Table == null) return;
                if (m_Feature.Table.Columns.Count == 0) return;
                if (m_Feature.Table.Rows == null) return;
                if (m_Feature.Table.Rows.Count == 0) return;

                for (var i=0; i<m_Feature.Table.Columns.Count; i++)
                {
                    DataColumn column = m_Feature.Table.Columns[i];
                    if (m_Feature.Table.Rows[0][column.ColumnName]==null) continue;

                    if (IsAVR && i < m_Feature.Table.Columns.Count-6) continue;

                    var val = m_Feature.Table.Rows[0][column.ColumnName];

                    if (val==null) continue;

                    if (column.ColumnName == "info")
                    {
                        val = val.ToString().TrimStart('\r');
                        val = val.ToString().Trim('\n');
                        val = val.ToString().TrimEnd('\r');
                        val = val.ToString().Replace("\r\n", Environment.NewLine);
                    }

                    if (val.ToString().Trim()==string.Empty) continue;

                    var row = new EditorRow(column.ColumnName) {Name = column.ColumnName, Enabled = true};

                    row.Properties.Caption = column.ColumnName;
                    row.Properties.RowEdit = persistentRepos.Items[0];
                    row.Properties.Format.FormatType = FormatType.None;
                    row.Properties.UnboundType = UnboundColumnType.String;

                    featureGrid.Rows.Add(row);
                    featureGrid.SetCellValue(row, i, val);
                }
            }
        }

        private void InfoForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            Hide();
        }
    }
}


text:
<?xml version="1.0"?>
<!DOCTYPE import-control PUBLIC "-//Checkstyle//DTD ImportControl Configuration 1.4//EN" "https://checkstyle.org/dtds/import_control_1_4.dtd">
<import-control pkg="org|com" strategyOnMismatch="allowed" regex="true">
    <!--Use JUnit5 annotations.-->
    <allow class="org.junit.runner.RunWith"/>
    <allow pkg="org.junit.platform"/>
    <allow pkg="org.junit.jupiter"/>

    <disallow pkg="org.junit" exact-match="true"/>
    <disallow pkg="org.jetbrains.annotations" exact-match="true"/>
    <disallow pkg="org.junit.Assert"/>
    <disallow pkg="org.hamcrest"/>
    <disallow pkg="org\.junit\.(runners?|experimental\.categories)" regex="true" />

    <subpackage name="apereo.cas.util.junit">
        <allow pkg="org.junit" exact-match="true"/>
        <allow pkg="org\.junit\.runners?" regex="true"/>
    </subpackage>
</import-control>


text:
import PropTypes from 'prop-types'
import React, { Component } from 'react'

import SocialLogin from '../../src/index'

const ButtonFC = ({ children, triggerLogin, triggerLogout, ...props } = props)=>{

    const style = {
      background: '#eee',
      border: '1px solid black',
      borderRadius: '3px',
      backgroundColor:'orange',
      display: 'inline-block',
      margin: '5px',
      padding: '10px 20px'
    }

    return (
      <div onClick={triggerLogin} style={style} {...props}>
        { children }
      </div>
    )

}

export default SocialLogin(ButtonFC)


text:
package org.optaplanner.workbench.screens.domaineditor.client.widgets.planner;

import java.util.stream.Collectors;
import javax.inject.Inject;

import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import org.kie.workbench.common.screens.datamodeller.client.util.DataModelerUtils;
import org.kie.workbench.common.services.datamodeller.core.DataModel;
import org.kie.workbench.common.services.datamodeller.core.DataObject;
import org.kie.workbench.common.services.datamodeller.core.ObjectProperty;
import org.optaplanner.workbench.screens.domaineditor.model.ObjectPropertyPath;
import org.optaplanner.workbench.screens.domaineditor.model.ObjectPropertyPathImpl;

public class DataObjectFieldPickerItem implements DataObjectFieldPickerItemView.Presenter,
                                                  IsWidget {

    private DataObjectFieldPickerItemView view;

    private DataModel dataModel;

    private ObjectPropertyPath objectPropertyPath = new ObjectPropertyPathImpl();

    private DataObject rootDataObject;
    private DataObjectFieldPicker picker;

    @Inject
    public DataObjectFieldPickerItem(DataObjectFieldPickerItemView view) {
        this.view = view;
        view.setPresenter(this);
    }

    public void init(DataModel dataModel,
                     DataObject rootDataObject,
                     DataObjectFieldPicker picker) {
        this.dataModel = dataModel;
        this.rootDataObject = rootDataObject;
        this.picker = picker;
        initSelectFieldDropdownOptions(rootDataObject);
        view.addRootItem(rootDataObject);
        view.setOrderSelectDescendingValue(false);
    }

    private void initSelectFieldDropdownOptions(DataObject dataObject) {
        view.initSelectFieldDropdownOptions(dataObject.getProperties().stream().filter(p -> DataModelerUtils.isManagedProperty(p)).collect(Collectors.toList()));
    }

    @Override
    public void onFieldAdded(ObjectProperty objectProperty,
                             boolean notify) {
        objectPropertyPath.appendObjectProperty(objectProperty);
        view.addFieldItem(objectProperty);
        if (objectProperty.isBaseType() || objectProperty.isPrimitiveType()) {
            view.displaySelectFieldButton(false);
        } else {
            DataObject dataObject = dataModel.getDataObject(objectProperty.getClassName());
            initSelectFieldDropdownOptions(dataObject);
            view.displaySelectFieldButton(true);
        }
        if (notify) {
            picker.objectPropertyPathChanged(false);
        }
    }

    @Override
    public void onFieldRemoved(ObjectProperty objectProperty) {
        for (int i = objectPropertyPath.getObjectPropertyPath().size() - 1; i >= 0; i--) {
            ObjectProperty currentObjectProperty = objectPropertyPath.getObjectPropertyPath().get(i);
            objectPropertyPath.getObjectPropertyPath().remove(i);
            view.removeLastFieldItem();
            if (currentObjectProperty.equals(objectProperty)) {
                break;
            }
        }
        DataObject dataObject;
        if (objectPropertyPath.getObjectPropertyPath().isEmpty()) {
            dataObject = rootDataObject;
        } else {
            ObjectProperty parentObjectProperty = objectPropertyPath.getObjectPropertyPath().get(objectPropertyPath.getObjectPropertyPath().size() - 1);
            dataObject = dataModel.getDataObject(parentObjectProperty.getClassName());
        }
        initSelectFieldDropdownOptions(dataObject);
        view.displaySelectFieldButton(true);
        picker.objectPropertyPathChanged(true);
    }

    @Override
    public void onRootLabelRemoved() {
        picker.onFieldPickerItemRemoved(this);
    }

    @Override
    public void onMoveFieldItemUp() {
        picker.onMoveFieldPickerItemUp(this);
    }

    @Override
    public void onMoveFieldItemDown() {
        picker.onMoveFieldPickerItemDown(this);
    }

    @Override
    public void onOrderSelectValueChange(boolean descending,
                                         boolean notify) {
        view.setOrderSelectDescendingValue(descending);
        objectPropertyPath.setDescending(descending);
        if (notify) {
            picker.objectPropertyPathChanged(false);
        }
    }

    @Override
    public void setFieldPickerItemIndex(int index) {
        view.setFieldPickerItemIndex(index);
    }

    public ObjectPropertyPath getObjectPropertyPath() {
        return objectPropertyPath;
    }

    @Override
    public Widget asWidget() {
        return view.asWidget();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

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

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

    <com.viewpagerindicator.TitlePageIndicator
            android:id="@+id/indicator"
            android:padding="10dip"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:background="@color/light_gray"
            android:textColor="@color/light_blue"
            app:footerColor="@color/my_app_green"
            app:selectedBold="true"
            app:selectedColor="@color/red"
            />

    <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            />
</LinearLayout>


text:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="edu.cs4730.nearbyconnectiondemo.AdvertiseFragment">

    <Button
        android:id="@+id/start_advertise"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Start Advertising"/>

    <Button
        android:id="@+id/end_advertise"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Disconnect and Stop"/>

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/ad_output"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="Output:\n"
            android:textAppearance="?android:attr/textAppearanceMedium"/>
    </androidx.core.widget.NestedScrollView>
</LinearLayout>


text:
"""Formatter for the Keychain password database file."""

from plaso.lib import eventdata

class KeychainApplicationRecordFormatter(eventdata.ConditionalEventFormatter):
  """Formatter for keychain application record event."""

  DATA_TYPE = 'mac:keychain:application'

  FORMAT_STRING_PIECES = [
      u'Name: {entry_name}',
      u'Account: {account_name}']

  FORMAT_STRING_SHORT_PIECES = [u'{entry_name}']

  SOURCE_LONG = 'Keychain Application password'
  SOURCE_SHORT = 'LOG'

class KeychainInternetRecordFormatter(eventdata.ConditionalEventFormatter):
  """Formatter for keychain internet record event."""

  DATA_TYPE = 'mac:keychain:internet'

  FORMAT_STRING_PIECES = [
      u'Name: {entry_name}',
      u'Account: {account_name}',
      u'Where: {where}',
      u'Protocol: {protocol}',
      u'({type_protocol})']

  FORMAT_STRING_SHORT_PIECES = [u'{entry_name}']

  SOURCE_LONG = 'Keychain Internet password'
  SOURCE_SHORT = 'LOG'


text:
package com.opengamma.sesame.function;

import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringEscapeUtils;

import com.google.common.reflect.TypeToken;

/**
 * Helper methods for use when creating {@link ParameterType} instances and converting between arguments and strings.
 */
public final class ParameterUtils {

  private static final Pattern WHITESPACE = Pattern.compile("\\s");

  private ParameterUtils() {
  }

  /**
   * @param type a type
   * @return true if the type is a parameterized {@link Collection}, {@link List} or {@link Set}
   */
  public static boolean isCollection(Type type) {
    // we're only interested in parameterized types because we need to know the element type
    if (!(type instanceof ParameterizedType)) {
      return false;
    }
    Class<?> rawType = TypeToken.of(type).getRawType();
    return rawType == Collection.class || rawType == List.class || rawType == Set.class;
  }

  /**
   * @param type a type
   * @return true if the type is an array
   */
  public static boolean isArray(Type type) {
    return (type instanceof GenericArrayType) || ((type instanceof Class<?>) && ((Class<?>) type).isArray());
  }

  /**
   * @param type a type
   * @return true if they type is a parameterized map
   */
  public static boolean isMap(Type type) {
    // we're only interested in parameterized types because we need to know the key and value types
    if (!(type instanceof ParameterizedType)) {
      return false;
    }
    Class<?> rawType = TypeToken.of(type).getRawType();
    return rawType == Map.class;
  }

  /**
   * Returns the element type of an array or parameterized collection ({@link Collection}, {@link List} or {@link Set}).
   *
   * @param type the array or collection type
   * @return the type of the element in the collection or array
   * @throws IllegalArgumentException if the type isn't a collection or array or if the element can't be found (e.g.
   *   if the type doesn't have a type parameter)
   */
  public static Class<?> getElementType(Type type) {
    if (!isCollection(type) && !isArray(type)) {
      throw new IllegalArgumentException("Type must be a collection or array");
    }
    if (type instanceof GenericArrayType) {
      Type genericComponentType = ((GenericArrayType) type).getGenericComponentType();
      return TypeToken.of(genericComponentType).getRawType();
    }
    if ((type instanceof Class<?>) && ((Class<?>) type).isArray()) {
      return ((Class<?>) type).getComponentType();
    }
    if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;
      Type[] typeArguments = parameterizedType.getActualTypeArguments();

      // this shouldn't ever happen
      if (typeArguments.length != 1) {
        throw new IllegalArgumentException("Container must have one type argument " + type);
      }
      return TypeToken.of(typeArguments[0]).getRawType();
    }
    throw new IllegalArgumentException("Can't get element type for " + type);
  }

  /**
   * Returns the type of the keys in a generic map.
   *
   * @param type a map type
   * @return the type of the map's key
   * @throws IllegalArgumentException if the type isn't a map or the key type can't be found
   */
  public static Class<?> getKeyType(Type type) {
    return getMapTypeParameter(type, true);
  }

  /**
   * Returns the type of the values in a generic map.
   *
   * @param type a map type
   * @return the type of the map's key
   * @throws IllegalArgumentException if the type isn't a map or the value type can't be found
   */
  public static Class<?> getValueType(Type type) {
    return getMapTypeParameter(type, false);
  }

  /**
   * Returns a type parameter from a parameterized map type.
   *
   * @param type  the type, must be a parameterized {@code java.util.Map}.
   * @param keyType  true if the key type is required, false if the value type is required
   * @return  the key or value type parameter
   * @throws  IllegalArgumentException if the type isn't a map with two type parameters
   */
  private static Class<?> getMapTypeParameter(Type type, boolean keyType) {
    if (!isMap(type)) {
      throw new IllegalArgumentException("Type isn't a map. ");
    }
    ParameterizedType parameterizedType = (ParameterizedType) type;
    Type[] typeArguments = parameterizedType.getActualTypeArguments();

    if (typeArguments.length != 2) {
      throw new IllegalArgumentException("Expected 2 type arguments. ");
    }
    int argIndex = keyType ? 0 : 1;
    Type valueType = typeArguments[argIndex];
    return TypeToken.of(valueType).getRawType();

  }

  /**
   * Escapes the string and wraps it in quotes if it contains any whitespace.
   *
   * @param str a string
   * @return the escaped string, surrounded with quotes if it contains any whitespace
   */
  public static String escapeString(String str) {
    if (WHITESPACE.matcher(str).find()) {
      return "\"" + StringEscapeUtils.escapeJava(str) + "\"";
    } else {
      return StringEscapeUtils.escapeJava(str);
    }
  }
}


text:
package com.silentgo.core.build;

import java.lang.annotation.*;

/**
 * Project : silentgo
 * com.silentgo.core.build.annotation
 *
 * @author teddyzhu
 *

 *         Created by teddyzhu on 16/9/26.
 */
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Factory {
}


text:
<?php

namespace Cubiche\Domain\Web\Tests\Units;

use Cubiche\Domain\Model\Tests\Units\NativeValueObjectTestCase;
use Cubiche\Domain\Web\Port;

/**
 * PortTests class.
 *
 * Generated by TestGenerator on 2017-03-15 at 11:36:08.
 */
class PortTests extends NativeValueObjectTestCase
{
    /**
     * {@inheritdoc}
     */
    protected function randomNativeValue()
    {
        return rand(1, 10);
    }

    /**
     * {@inheritdoc}
     */
    protected function uniqueNativeValue()
    {
        return 20;
    }

    /**
     * {@inheritdoc}
     */
    protected function invalidNativeValue()
    {
        return 'text';
    }

    /**
     * {@inheritdoc}
     */
    protected function fromNative($value)
    {
        return Port::fromNative($value);
    }
}


text:
const EventEmitter = require("events");

module.exports =
class WebSocketWrapperBase extends EventEmitter
{
	constructor(webSocket, strURL)
	{
		super();

		this._webSocket = webSocket;
	}

	/**
	 * @returns {string|undefined}
	 */
	get url()
	{
		return this._webSocket.url;
	}

	/**
	 * @returns {Socket}
	 */
	get socket()
	{
		return this._webSocket.socket;
	}

	/**
	 * @returns {number}
	 */
	get readyState()
	{
		return this._webSocket.readyState;
	}

	/**
	 * @returns {string}
	 */
	get protocol()
	{
		return this._webSocket.protocol;
	}

	/**
	 * @returns {number}
	 */
	get protocolVersion()
	{
		return this._webSocket.protocolVersion;
	}

	/**
	 * @returns {number}
	 */
	static get CONNECTING()
	{
		return 0;
	}

	/**
	 * @returns {number}
	 */
	static get OPEN()
	{
		return 1;
	}

	/**
	 * @returns {number}
	 */
	static get CLOSING()
	{
		return 2;
	}

	/**
	 * @returns {number}
	 */
	static get CLOSED()
	{
		return 3;
	}

	/**
	 * @param {string} strEventName
	 * @param {Function} fnListener
	 */
	on(strEventName, fnListener)
	{
		return this._webSocket.on(strEventName, fnListener);
	}

	/**
	 * @param {string} strEventName
	 * @param {Function} fnListener
	 */
	superOn(strEventName, fnListener)
	{
		return super.on(strEventName, fnListener);
	}

	send(mxData, ...args)
	{
		return this._webSocket.send(mxData, ...args);
	}

	/**
	 * @param {number} nCode
	 * @param {string} strReason
	 */
	close(nCode, strReason)
	{
		return this._webSocket.close(nCode, strReason);
	}

	/**
	 *
	 */
	terminate()
	{
		return this._webSocket.terminate();
	}

	ping(...args)
	{
		return this._webSocket.ping(...args);
	}

	pong(...args)
	{
		return this._webSocket.pong(...args);
	}
};


text:
package com.aspose.imaging.api.imagingapi.examples.manipulate;

import android.content.Context;

import com.aspose.imaging.api.ImagingApi;
import com.aspose.imaging.api.imagingapi.R;
import com.aspose.imaging.api.imagingapi.examples.Configuration;
import com.aspose.imaging.api.imagingapi.examples.Utils;
import com.aspose.storage.api.StorageApi;
import java.io.File;
import java.io.IOException;

public class ResizeImageWithFormatChange {

    public static void execute(Context context) throws IOException {
    	//ExStart: ResizeImageWithFormatChange

        File inputFile = Utils.stream2file("sample5","jpg", context.getResources().openRawResource(R.raw.sample5));
        File outputFile = Utils.createTempFile("sample3","png");
        StorageApi storageApi = new StorageApi(Configuration.apiKey, Configuration.appSID, true);
        ImagingApi imagingApi = new ImagingApi(Configuration.apiKey, Configuration.appSID, true);

        Integer newWidth = 200;
        Integer newHeight = 200;
        String format = "png";
        String outPath = "";

        com.aspose.imaging.model.ResponseMessage apiResponse
                = imagingApi.PostChangeImageScale(
                        format,
                        newWidth,
                        newHeight,
                        outPath,
                        inputFile
                );

        Utils.copyInputStreamToFile(apiResponse.getInputStream(),outputFile);
      //ExEnd: ResizeImageWithFormatChange
    }
}


text:
package protorpc

import (
	"crypto/tls"
	"net"
	"time"
)

type Client struct {
	addr      string
	redial    time.Duration
	channel   *Channel
	tlsConfig *tls.Config
	handlers  map[string]Handler
	listener  clientListener
}

type clientListener struct {
	listener ChannelListener
	*Client
}

//if reDial is zero,no retry
func NewClient(svrAddr string, redialMillis int32, tlsCfg *tls.Config, listener ChannelListener) *Client {
	c := &Client{
		addr:      svrAddr,
		redial:    time.Duration(redialMillis) * time.Millisecond,
		tlsConfig: tlsCfg,
		handlers:  make(map[string]Handler),
	}
	c.listener.listener = listener
	c.listener.Client = c
	return c
}

//if connect success , return true
func (c *Client) Serve() bool {
	if c.channel != nil {
		c.channel.Close()
		<-time.After(100 * time.Millisecond)
	}
	c.channel = newChannel(c.handlers, &c.listener)
	return c.dialLoop()
}

func (c *Client) ServeBG() {
	if c.channel != nil {
		return
	}
	c.channel = newChannel(c.handlers, &c.listener)
	go c.dialLoop()
}

func (c *Client) Execute(req *Request, timeoutMills int) *Response {
	return c.channel.Execute(req, time.Duration(timeoutMills)*time.Millisecond)
}

func (c *Client) Notice(req *Request) (err error) {
	return c.channel.Notice(req)
}

func (c *Client) Handle(cmd string, h Handler) {
	if _, ok := c.handlers[cmd]; ok {
		panic("multi handler for command:" + cmd)
	}
	c.handlers[cmd] = h
}

func (c *Client) HandleFunc(cmd string, handler func(*Channel, *Request) *Response) {
	if _, ok := c.handlers[cmd]; ok {
		panic("multi handler for command:" + cmd)
	}
	c.handlers[cmd] = HandlerFunc(handler)
}

//if connect success , return true
func (c *Client) dialLoop() (succ bool) {
	var err error
	var conn net.Conn
	for {
		if c.tlsConfig != nil {
			conn, err = tls.Dial("tcp", c.addr, c.tlsConfig)
		} else {
			conn, err = net.Dial("tcp", c.addr)
		}
		if err == nil {
			break
		}
		Logger.Error("connect to server failed:", err)
		if c.redial == 0 {
			return
		}
		<-time.After(c.redial)
	}
	c.channel.serve(conn)
	succ = true
	return
}

func (c *Client) Close() {
	if c.channel != nil {
		c.channel.Close()
	}
}

func (c *clientListener) OnConnected(ch *Channel) {
	if c.listener != nil {
		c.listener.OnConnected(ch)
	}
}

func (c *clientListener) OnConnecting(ch *Channel) {
}

func (c *clientListener) OnDisconnect(ch *Channel) {
	if c.listener != nil {
		c.listener.OnDisconnect(ch)
	}
	if c.redial != 0 {
		go c.dialLoop()
	}
}

func (c *Client) IsValid() (ok bool) {
	if c.channel != nil {
		ok = c.channel.IsValid()
	}
	return
}


text:
package smarthouse.android;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import smarthouse.android.robosherlock.RoboSherlockActivity;
import smarthouse.android.utils.PairSerializable;
import smarthouse.ejb.service.Area;
import smarthouse.ejb.service.DriverIdentifier;
import smarthouse.ejb.service.Equipment;
import smarthouse.ejb.service.Home;
import smarthouse.ejb.service.Room;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;

public class SplashActivity extends RoboSherlockActivity implements Runnable {
	private static final String TAG = SplashActivity.class.getSimpleName();

	/*public static Home generateHome(){
		Random  r = new Random();
		DriverIdentifier drivId1 = new DriverIdentifier(
				"smarthouse.fmk.driver.impl.SimulatedLightLapeyreDriver",
				"BundleDrivers.jar");
		DriverIdentifier drivId2 = new DriverIdentifier(
				"smarthouse.fmk.driver.impl.SimulatedOvenBoschDriver",
				"BundleDrivers.jar");

			// Creation de la maison
			List<Area> areas = new ArrayList<Area>();
			for (int i = 0; i < 3; i++) {
				List<Room> rooms = new ArrayList<Room>();
				for (int j = 0; j < 3; j++) {
					List<Equipment> equipments = new ArrayList<Equipment>();
					int idEquipment = r.nextInt();
					equipments.add(new Equipment(drivId1, "lampe" + idEquipment, "id=LAMPE" + idEquipment));
					idEquipment = r.nextInt();
					equipments.add(new Equipment(drivId1, "lampe" + idEquipment, "id=LAMPE" + idEquipment));
					idEquipment = r.nextInt();
					equipments.add(new Equipment(drivId2, "Four" + idEquipment, "addr_ip=FOUR" + idEquipment));
					rooms.add(new Room(equipments, "room" + r.nextInt()));
				}
				areas.add(new Area("area" + r.nextInt(), rooms));
			}
			return new Home(areas, 1, "Home" + r.nextInt(), null);
	}*/

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			/*Mode test
			 *
			 * Intent intent = new Intent(SplashActivity.this, ZoneActivity.class);
			Home h = generateHome();
			intent.putExtra("home", generateHome());
			intent.putExtra("homeDesc", new PairSerializable<String, String>("wwwww", h.getName()));
			startActivity(intent);
			finish();*/

			Intent intent = new Intent(getApplicationContext(), AccueilActivity.class);
			startActivity(intent);
			finish();
		}
	};

	/**
	 * Création de l'activité d'ouverture de l'application Après une certaine
	 * attente --> création de l'activité d'identification
	 */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		launchWait();
	}

	private void launchWait() {
		// On lance le thread
		Thread t = new Thread(this);
		t.start();
	}

	@Override
	public void run() {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().detectAll().penaltyLog().build());
		// Test de connection au serveur

		try {
			Thread.sleep(1500);
		} catch (InterruptedException e) {
			//
			e.printStackTrace();
		}
		handler.sendEmptyMessage(0);

	}
}


text:
            <button class="prev"><</button>
            <button class="next">></button>


text:
package opticnav.ardd.ard;

/**
 * Information about instances being queried from the {@link ARDConnected} broker.
 *
 * @author Danny Spencer
 *
 */
public class InstanceInfo {
    private final int id;
    private final String name;
    private final int numberConnected;
    private final long startTime;

    public InstanceInfo(int id, String name, int numberConnected, long startTime) {
        this.id = id;
        this.name = name;
        this.numberConnected = numberConnected;
        this.startTime = startTime;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getNumberConnected() {
        return numberConnected;
    }

    public long getStartTime() {
        return startTime;
    }

    @Override
    public String toString() {
        return String.format("ID: %d; Name: %s; # Connected: %d; Start Time: %d",
                this.id, this.name, this.numberConnected, this.startTime);
    }

}


text:
using Discord;
using Discord.Commands;
using ImageSharp;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Services;
using System;
using System.IO;
using System.Threading.Tasks;
using Image = ImageSharp.Image;

namespace NadekoBot.Modules.Gambling
{
    public partial class Gambling
    {
        [Group]
        public class FlipCoinCommands : ModuleBase
        {
            private static NadekoRandom rng { get; } = new NadekoRandom();
            private const string headsPath = "data/images/coins/heads.png";
            private const string tailsPath = "data/images/coins/tails.png";

            [NadekoCommand, Usage, Description, Aliases]
            public async Task Flip(int count = 1)
            {
                if (count == 1)
                {
                    if (rng.Next(0, 2) == 1)
                        await Context.Channel.SendFileAsync(File.Open(headsPath, FileMode.OpenOrCreate), "heads.jpg", $"{Context.User.Mention} flipped " + Format.Code("Heads") + ".").ConfigureAwait(false);
                    else
                        await Context.Channel.SendFileAsync(File.Open(tailsPath, FileMode.OpenOrCreate), "tails.jpg", $"{Context.User.Mention} flipped " + Format.Code("Tails") + ".").ConfigureAwait(false);
                    return;
                }
                if (count > 10 || count < 1)
                {
                    await Context.Channel.SendErrorAsync("`Invalid number specified. You can flip 1 to 10 coins.`");
                    return;
                }
                var imgs = new Image[count];
                for (var i = 0; i < count; i++)
                {
                    imgs[i] = rng.Next(0, 10) < 5 ?
                                new Image(File.OpenRead(headsPath)) :
                                new Image(File.OpenRead(tailsPath));
                }
                await Context.Channel.SendFileAsync(imgs.Merge().ToStream(), $"{count} coins.png").ConfigureAwait(false);
            }

            [NadekoCommand, Usage, Description, Aliases]
            public async Task Betflip(int amount, string guess)
            {
                var guessStr = guess.Trim().ToUpperInvariant();
                if (guessStr != "H" && guessStr != "T" && guessStr != "HEADS" && guessStr != "TAILS")
                    return;

                if (amount < NadekoBot.BotConfig.MinimumBetAmount)
                {
                    await Context.Channel.SendErrorAsync($"You can't bet less than {NadekoBot.BotConfig.MinimumBetAmount}{CurrencySign}.")
                                 .ConfigureAwait(false);
                    return;
                }
                var removed = await CurrencyHandler.RemoveCurrencyAsync(Context.User, "Betflip Gamble", amount, false).ConfigureAwait(false);
                if (!removed)
                {
                    await Context.Channel.SendErrorAsync($"{Context.User.Mention} You don't have enough {CurrencyPluralName}.").ConfigureAwait(false);
                    return;
                }
                //heads = true
                //tails = false

                var isHeads = guessStr == "HEADS" || guessStr == "H";
                bool result = false;
                string imgPathToSend;
                if (rng.Next(0, 2) == 1)
                {
                    imgPathToSend = headsPath;
                    result = true;
                }
                else
                {
                    imgPathToSend = tailsPath;
                }

                string str;
                if (isHeads == result)
                {
                    var toWin = (int)Math.Round(amount * NadekoBot.BotConfig.BetflipMultiplier);
                    str = $"{Context.User.Mention}`You guessed it!` You won {toWin}{CurrencySign}";
                    await CurrencyHandler.AddCurrencyAsync(Context.User, "Betflip Gamble", toWin, false).ConfigureAwait(false);
                }
                else
                {
                    str = $"{Context.User.Mention}`Better luck next time.`";
                }

                await Context.Channel.SendFileAsync(File.Open(imgPathToSend, FileMode.OpenOrCreate), new FileInfo(imgPathToSend).Name, str).ConfigureAwait(false);
            }
        }
    }
}


text:
package org.gsm.oneapi.responsebean.mms;

/**
 * Contains the detail of a request to obtain delivery information for MMS messages sent via the OneAPI server
 */
public class DeliveryInfoList implements java.io.Serializable {
	private static final long serialVersionUID = 9214265875910218116L;

	/**
	 * The inner class DeliveryInfo contains pairings of the recipient address and a textual delivery status
	 */
	public static class DeliveryInfo {
		/**
		 * The address of the recipient (normally MSISDN)
		 */
		private String address=null;
		/**
		 * Delivery status may be one of
		 * "DeliveredToTerminal", successful delivery to Terminal.
		 * "DeliveryUncertain", delivery status unknown: e.g. because it was handed off to another network.
		 * "DeliveryImpossible", unsuccessful delivery; the message could not be delivered before it expired.
		 * "MessageWaiting" , the message is still queued for delivery. This is a temporary state, pending transition to one of the preceding states.
		 * "DeliveredToNetwork", successful delivery to the network enabler responsible for routing the MMS
		 */
		private String deliveryStatus=null;

		/**
		 * return the address of the recipient (normally MSISDN)
		 */
		public String getAddress() { return address; }
		/**
		 * return the delivery status for this recipient
		 */
		public String getDeliveryStatus() { return deliveryStatus; }

		/**
		 * set the recipient address. This is called internally to set the contents according to the JSON response.
		 */
		public void setAddress(String address) { this.address=address; }
		/**
		 * set the deliveryStatus. This is called internally to set the contents according to the JSON response.
		 */
		public void setDeliveryStatus(String deliveryStatus) { this.deliveryStatus=deliveryStatus; }

		/**
		 * default constructor
		 */
		public DeliveryInfo() {

		}

		/**
		 * utility constructor to create a DeliveryInfo instance with all fields set
		 * @param address
		 * @param deliveryStatus
		 */
		public DeliveryInfo(String address, String deliveryStatus) {
			this.address=address;
			this.deliveryStatus=deliveryStatus;
		}

		/**
		 * generate a textual representation of the DeliveryInfo contents
		 */
		public String toString() {
			StringBuffer buffer=new StringBuffer();
			buffer.append("address = ");
			buffer.append(address);
			buffer.append(", deliveryStatus = ");
			buffer.append(deliveryStatus);
			return buffer.toString();
		}
	}

	/**
	 * the deliveryInfoList object contains the delivery information for each address that you asked to send the message to, in a deliveryInfo array.
	 */
	DeliveryInfo[] deliveryInfo=null;
	/**
	 * return the array of deliveryInfo pairs of address/ deliveryStatus
	 */
	public DeliveryInfo[] getDeliveryInfo() { return deliveryInfo; }
	/**
	 * set the array of deliveryInfo pairs of address/ deliveryStatus. This is called internally to set the contents according to the JSON response.
	 */
	public void setDeliveryInfo(DeliveryInfo[] deliveryInfo) { this.deliveryInfo=deliveryInfo; }

	/**
	 * resourceURL contains a URL uniquely identifying this DeliveryInfoList request
	 */
	String resourceURL=null;
	/**
	 * return resourceURL containing a URL uniquely identifying this DeliveryInfoList request
	 */
	public String getResourceURL() { return resourceURL; }
	/**
	 * set resourceURL containing a URL uniquely identifying this DeliveryInfoList request. This is called internally to set the contents according to the JSON response.
	 */
	public void setResourceURL(String resourceURL) { this.resourceURL=resourceURL; }

	/**
	 * generate a textual representation of the DeliveryInfoList instance including nested elements and classes
	 */
	public String toString() {
		StringBuffer buffer=new StringBuffer();
		if (deliveryInfo!=null) {
			buffer.append("deliveryInfo = {");
			for (int i=0; i<deliveryInfo.length; i++) {
				buffer.append("[");
				buffer.append(i);
				buffer.append("] = {");
				if (deliveryInfo[i]!=null) buffer.append(deliveryInfo[i].toString());
				buffer.append("} ");
			}
			buffer.append("} ");
		}
		buffer.append(", resourceURL = "+resourceURL);
		return buffer.toString();
	}

}


text:
<?php

namespace app\models;

use yii\helpers\ArrayHelper;
use app\components\{
    CreatorBehavior, DirectoryTrait, TimestampBehavior, DirectoryInterface
};

/**
 * Class Group "Группы исполнителей"
 * @package app\models
 */
class Group extends GroupBase implements DirectoryInterface
{
    // Спавочник
    use DirectoryTrait;

    /**
     * {@inheritdoc}
     */
    public function behaviors(): array
    {
        return [
            'creatorBehavior' => CreatorBehavior::class,
            'timestampBehavior' => TimestampBehavior::class,
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function rules(): array
    {
        return [
            [['name'], 'required'],
            [['enabled'], 'integer'],
            ['enabled', 'in', 'range' => [0, 1]],
            [['enabled'], 'default', 'value' => 1],
//            [['created_at', 'updated_at'], 'safe'],
            [['name'], 'string', 'max' => 64],
            [['name'], 'unique'],
            [
                ['creator_id'],
                'exist',
                'skipOnError' => true,
                'targetClass' => Profiles::class,
                'targetAttribute' => ['creator_id' => 'uid'],
            ],
        ];
    }

    /**
     * Возвращает всех исполнитилей.
     *
     * @return array
     */
    public static function getAllExecutors(): array
    {
        return Profiles::find()->select(['fullname', 'uid'])
            ->indexBy('uid')
            ->innerJoinWith(['user', 'groups'])
            ->where(['user.status' => User::STATUS_ACTIVE])
            ->asArray()
            ->column();
    }

    /**
     * Возвращает id всех членов группы.
     *
     * @return array
     */
    public function getMemberIds(): array
    {
        if (!empty($this->profiles)) {
            return ArrayHelper::getColumn($this->profiles, 'uid');
        }

        return [];
    }

    /**
     * Возвращает всех членов группы.
     *
     * @return array
     */
    public function getMembers(): array
    {
        if (!empty($this->profiles)) {
            return ArrayHelper::map($this->profiles, 'uid', 'fullname');
        }

        return [];
    }

    /**
     * Добавляет испонителей в группу.
     *
     * @param array $ids id исполнителей
     * @return int количество добавленных усполнителей
     * @throws \yii\base\InvalidCallException
     */
    public function addMembers(array $ids): int
    {
        $ret = 0;
        if (\is_array($ids) && 0 < \count($ids)) {
            $newMembers = array_diff($ids, $this->getMemberIds());
            if (!empty($newMembers)) {
                $profiles = Profiles::findAll(['uid' => $newMembers]);
                foreach ($profiles as $profile) {
                    $this->link('profiles', $profile);
                    $ret++;
                }
                $this->profile_count += $ret; // TODO: Эвент при отключении пользователя!
                $this->save(false, ['profile_count']);
            }
        }

        return $ret;
    }

    /**
     * Добавляет испонителя в группы.
     * @param int $profile_id
     * @param array $group_ids
     * @throws \yii\base\InvalidCallException
     */
    public static function addMemberInGroups(int $profile_id, array $group_ids): void
    {
        foreach ($group_ids as $group_id) {
            if (null !== ($group = self::findOne((int)$group_id))) {
                $group->addMembers([$profile_id]);
            }
        }
    }

    /**
     * Удаляет исполнителей из группы.
     *
     * @param array $ids
     * @return int
     * @throws \yii\base\InvalidCallException
     */
    public function removeMembers(array $ids): int
    {
        $ret = 0;
        if (\is_array($ids) && 0 < \count($ids)) {
            $profiles = Profiles::find()->with('groups')->where(['uid' => $ids])->all();
            foreach ($profiles as $profile) {
                $profile->unlink('groups', $this, true);
                $ret++;
            }
            $this->profile_count -= $ret; // TODO: Эвент при отключении пользователя!
            $this->save(false, ['profile_count']);
        }

        return $ret;
    }

    /**
     * Удаляет исполнителя из групп.
     *
     * @param int $profile_id
     * @param array $group_ids
     * @throws \yii\base\InvalidCallException
     */
    public static function removeMemberFromGroups(int $profile_id, array $group_ids): void
    {
        foreach ($group_ids as $group_id) {
            if (null !== ($group = self::findOne((int)$group_id))) {
                $group->removeMembers([$profile_id]);
            }
        }
    }

    /**
     * @return bool
     */
    public function beforeDelete(): bool
    {
        $this->unlinkAll('profileGroups', true);
        return parent::beforeDelete();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="@color/tw_dialog_main_text_color_material_light" android:alpha="@dimen/tw_disabled_alpha_material" />
    <item android:color="@color/tw_dialog_main_text_color_material_light" />
</selector>


text:
// $Id$
// $MpId: AliMpManuGeo.h,v 1.5 2006/05/24 13:58:16 ivana Exp $

/// \ingroup mptrigger
/// \class AliMpLocalBoard
/// \brief Class that manages the properties of the local board
///
/// \author Ch. Finck; Subatech Nantes

#ifndef ALI_MP_LOCAL_BOARD_H
#define ALI_MP_LOCAL_BOARD_H

#include <TNamed.h>

#include "AliMpArrayI.h"
#include "AliMpEncodePair.h"

class TString;

class AliMpLocalBoard : public TNamed
{

 public:
    AliMpLocalBoard(Int_t id, const Char_t* name, Int_t slot);
    AliMpLocalBoard(TRootIOCtor* /*ioCtor*/);
    virtual ~AliMpLocalBoard();

    // detElem
    Bool_t AddDE(Int_t detElemId);
    Int_t  GetNofDEs() const;
    Int_t  GetDEId(Int_t index) const;
    Int_t  GetDEIdByChamber(Int_t chamberId) const;
    Bool_t HasDEId(Int_t detElemId) const;

    // get methods
    //
           /// Return the identifier (unique)
    Int_t  GetId()   const {return fId;}
           /// Return the slot Identifier in the given crate
    Int_t  GetSlot() const {return fSlot;}

    /// set slot
    void   SetSlot(Int_t slot) {fSlot = slot;}

    // Switches
    //
            /// Get switch bit wise (return a inteter for backware compatibility)
    Int_t  GetSwitch(Int_t index) const;
            /// Set switch in a compact way
    void   SetSwitch(UInt_t swit);
            /// Get switch in a compact way
    UInt_t  GetSwitch() const {return fSwitch;}

    // switch enum for local board (see PRR, chpt: 2.4.4)
    enum {kX2d, kX2m, kX2u, ///< (1) indicate a change of strip pitch in Y circuit
	  kOR0, kOR1,  ///< taking into account the different segmentation in Y from MT1 to MT2
	  kENY,        ///< (0) enable communication in Y to n+/-1 board via tranverse connector, (1) disable
	  kZeroAllYLSB,///< (1) reset the LSB for special configuration of board RC2L5B4 & RC2L6B1
	  kZeroDown,   ///< (0) information is expected from n-1 board for X input, (1) not
	  kZeroMiddle, ///< (0) always, not used
	  kZeroUp };   ///< (0) information is expected from n+1 board for X input, (1) not

    // Transverse connector
    //
             /// Set transverse connector
    void     SetTC(Bool_t connect) {fTC = connect;}
             /// Return transverse connector
    Bool_t   GetTC() const {return fTC;}

    // Crate name
    //
             /// Set crate name
    void     SetCrate(TString name) {fCrate = name;}
             /// Return crate name
    TString  GetCrate() const {return fCrate;}

    // Notify
    //
             /// Set notified flag (not copy card)
    void     SetNotified(Bool_t notify) {fNotified = notify;}
             /// Return notified flag (not copy card)
    Bool_t   IsNotified() const {return fNotified;}

    /// given position (line, col)
    MpPair_t GetPosition() const;

    // Id to be copy to or from

    /// Get Id from where the X input are copied
    Int_t GetInputXfrom() const {return fInputXfrom;}
    /// Get Id to where the X input are copied
    Int_t GetInputXto() const   {return fInputXto;}
    /// Get Id from where the Y input are copied
    Int_t GetInputYfrom() const {return fInputYfrom;}
    /// Get Id to where the Y input are copied
    Int_t GetInputYto() const  {return fInputYto;}

    /// Set Id from where the X input are copied
    void SetInputXfrom(Int_t id) {fInputXfrom = id;}
    /// Set Id to where the X input are copied
    void SetInputXto(Int_t id)   {fInputXto   = id;}
    /// Set Id from where the Y input are copied
    void SetInputYfrom(Int_t id) {fInputYfrom = id;}
    /// Set Id to where the Y input are copied
    void SetInputYto(Int_t id)   {fInputYto   = id;}

 private:
  /// Not implemented
   AliMpLocalBoard();
  /// Not implemented
   AliMpLocalBoard(const AliMpLocalBoard& src);
   /// Not implemented
   AliMpLocalBoard& operator = (const AliMpLocalBoard& src) ;

   Int_t GetIndex(Int_t chamberId) const;

   Int_t       fId;       ///< Identifier (unique)
   Int_t       fSlot;     ///< Slot Identifier in the given crate
   Bool_t      fTC;       ///< Transverse connector
   TString     fCrate;    ///< Crate name
   UInt_t      fSwitch;   ///< switches in compact way
   Bool_t      fNotified; ///< notified flag (not copy card)
   AliMpArrayI fDEId;     ///< list of Detection element to which this local board is connected
   Int_t       fInputXfrom;///< local id of x3-4 inputs copied from (zero: not copied)
   Int_t       fInputXto;  ///< local id of x3-4 inputs copied to (zero: not copied)
   Int_t       fInputYfrom;///< local id of y1-4 inputs copied from (zero: not copied)
   Int_t       fInputYto;  ///< local id of y1-4 inputs copied to (zero: not copied)

  ClassDef(AliMpLocalBoard,3) //utility class for the motif type
};

#endif


text:
package org.bremersee.geojson.spring.data.mongodb.convert;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Arrays;
import org.bremersee.geojson.utils.GeometryUtils;
import org.bson.Document;
import org.junit.jupiter.api.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LineString;

/**
 * The line string converter test.
 *
 * @author Christian Bremer
 */
class LineStringConverterTest {

  /**
   * Convert.
   */
  @Test
  void convert() {
    LineString model = GeometryUtils.createLineString(Arrays.asList(
        new Coordinate(2., 3.),
        new Coordinate(6., 7.)));

    LineStringToDocumentConverter toDocumentConverter = new LineStringToDocumentConverter();
    assertNotNull(toDocumentConverter.getConvertHelper());

    Document document = toDocumentConverter.convert(model);
    assertNotNull(document);

    DocumentToLineStringConverter toGeometryConverter = new DocumentToLineStringConverter();

    LineString actual = toGeometryConverter.convert(document);
    assertNotNull(actual);
    assertTrue(GeometryUtils.equals(model, actual));

    DocumentToGeometryConverter converter = new DocumentToGeometryConverter();
    Geometry actualGeometry = converter.convert(document);
    assertNotNull(actualGeometry);
    assertTrue(actualGeometry instanceof LineString);
    assertTrue(GeometryUtils.equals(actual, actualGeometry));
  }

}


text:
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/omnibox/browser/zero_suggest_provider.h"

#include <stddef.h>

#include <string>
#include <utility>

#include "base/bind.h"
#include "base/callback.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/user_metrics.h"
#include "base/strings/escape.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "components/omnibox/browser/autocomplete_input.h"
#include "components/omnibox/browser/autocomplete_match.h"
#include "components/omnibox/browser/autocomplete_match_classification.h"
#include "components/omnibox/browser/autocomplete_provider_client.h"
#include "components/omnibox/browser/autocomplete_provider_listener.h"
#include "components/omnibox/browser/base_search_provider.h"
#include "components/omnibox/browser/omnibox_field_trial.h"
#include "components/omnibox/browser/omnibox_prefs.h"
#include "components/omnibox/browser/remote_suggestions_service.h"
#include "components/omnibox/browser/search_suggestion_parser.h"
#include "components/omnibox/common/omnibox_features.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/search_engines/search_engine_type.h"
#include "components/search_engines/template_url_service.h"
#include "components/url_formatter/url_formatter.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "third_party/metrics_proto/omnibox_event.pb.h"
#include "third_party/metrics_proto/omnibox_focus_type.pb.h"
#include "third_party/metrics_proto/omnibox_input_type.pb.h"
#include "url/gurl.h"

using OEP = metrics::OmniboxEventProto;
using OFT = metrics::OmniboxFocusType;
using OIT = metrics::OmniboxInputType;

namespace {

// Represents whether ZeroSuggestProvider is allowed to display zero-prefix
// suggestions, and if not, why not.
// These values are written to logs.  New enum values can be added, but existing
// enums must never be renumbered or deleted and reused.
enum class Eligibility {
  kEligible = 0,
  // Suggest request without sending the current page URL cannot be made. E.g.,
  // the user is in incognito mode or Google is not set as the DSE.
  kRequestNoURLIneligible = 1,
  // Suggest request with sending the current page URL cannot be made. E.g.,
  // the user has not consented and the suggest endpoint and page URL are not
  // same-origin.
  kRemoteSendURLIneligible = 2,
  // Zero-prefix suggestions are not eligible in the given context. E.g., due to
  // the page classification, focus type, input type, or an invalid page URL.
  kGenerallyIneligible = 3,

  kMaxValue = kGenerallyIneligible,
};

// The provider event types recorded as a result of prefetch and non-prefetch
// requests for zero-prefix suggestions. Each event must be logged at most once
// from when the provider is started until it is stopped.
// These values are written to logs. New enum values can be added, but existing
// enums must never be renumbered or deleted and reused.
enum class Event {
  // Cached response was synchronously converted to displayed matches.
  KCachedResponseConvertedToMatches = 0,
  // Remote request was sent.
  kRequestSent = 1,
  // Remote request was invalidated.
  kRequestInvalidated = 2,
  // Remote response was received asynchronously.
  kRemoteResponseReceived = 3,
  // Remote response was cached.
  kRemoteResponseCached = 4,
  // Remote response ended up being converted to displayed matches. This may
  // happen due to an empty displayed result set or an empty remote result set.
  kRemoteResponseConvertedToMatches = 5,

  kMaxValue = kRemoteResponseConvertedToMatches,
};

void LogEvent(Event event,
              ZeroSuggestProvider::ResultType result_type,
              bool is_prefetch) {
  DCHECK_NE(ZeroSuggestProvider::ResultType::kNone, result_type);
  const std::string result_type_string =
      result_type == ZeroSuggestProvider::ResultType::kRemoteNoURL
          ? ".NoURL"
          : ".URLBased";
  const std::string request_type_string =
      is_prefetch ? ".Prefetch" : ".NonPrefetch";
  base::UmaHistogramEnumeration(
      "Omnibox.ZeroSuggestProvider" + result_type_string + request_type_string,
      event);
}

// Relevance value to use if it was not set explicitly by the server.
const int kDefaultZeroSuggestRelevance = 100;

// Returns whether the current URL can be sent in the suggest request.
// This function only applies to kRemoteSendURL variant.
bool AllowRemoteSendURL(const AutocompleteProviderClient* client,
                        const AutocompleteInput& input) {
  const TemplateURLService* template_url_service =
      client->GetTemplateURLService();
  if (!template_url_service) {
    return false;
  }
  const TemplateURL* default_provider =
      template_url_service->GetDefaultSearchProvider();
  if (!default_provider) {
    return false;
  }
  TemplateURLRef::SearchTermsArgs search_terms_args;
  GURL suggest_url = RemoteSuggestionsService::EndpointUrl(
      search_terms_args, template_url_service);

  return BaseSearchProvider::CanSendRequestWithURL(
      input.current_url(), suggest_url, default_provider,
      template_url_service->search_terms_data(), client,
      /*sending_search_terms=*/false);
}

// Return whether a suggest request can be made without sending the current URL.
// This function only applies to kRemoteNoURL variant.
bool AllowRemoteNoURL(const AutocompleteProviderClient* client) {
  const TemplateURLService* template_url_service =
      client->GetTemplateURLService();
  if (!template_url_service) {
    return false;
  }
  const TemplateURL* default_provider =
      template_url_service->GetDefaultSearchProvider();
  if (!default_provider) {
    return false;
  }
  TemplateURLRef::SearchTermsArgs search_terms_args;
  GURL suggest_url = RemoteSuggestionsService::EndpointUrl(
      search_terms_args, template_url_service);

  const bool allow_remote_no_url = BaseSearchProvider::CanSendRequest(
      suggest_url, default_provider, template_url_service->search_terms_data(),
      client);

  // Zero-suggest on the NTP is allowed only if the user is signed-in. This
  // check is done not for privacy reasons but to prevent signed-out users from
  // querying the server which does not have any suggestions for them.
  bool check_authentication_state = !base::FeatureList::IsEnabled(
      omnibox::kZeroSuggestOnNTPForSignedOutUsers);

  return allow_remote_no_url &&
         (!check_authentication_state || client->IsAuthenticated());
}

// Returns a copy of |input| with an empty text for zero-suggest. The input text
// is checked against the suggest response which always has an empty query. If
// those don't match, the response is dropped. It however copies over the URL,
// as zero-suggest on Web/SRP on Mobile relies on the URL to be set.
// TODO(crbug.com/1344004): Find out if the other fields also need to be set and
// whether this call can be avoided altogether by e.g., not checking the input
// text against the query in the response.
AutocompleteInput GetZeroSuggestInput(
    const AutocompleteInput& input,
    const AutocompleteProviderClient* client) {
  AutocompleteInput sanitized_input(u"", input.current_page_classification(),
                                    client->GetSchemeClassifier());
  sanitized_input.set_current_url(input.current_url());
  sanitized_input.set_current_title(input.current_title());
  sanitized_input.set_prevent_inline_autocomplete(true);
  sanitized_input.set_allow_exact_keyword_match(false);
  return sanitized_input;
}

// Called in OnURLLoadComplete() or OnPrefetchURLLoadComplete() when the
// remote response is received with the input for which the request was made.
//
// Populates |results| with the response if it can be successfully parsed for
// |input|; and stores the response json in the user prefs, if applicable to
// |result_type|. Returns true if the response can be successfully parsed.
bool StoreRemoteResponse(const std::string& response_json,
                         const AutocompleteProviderClient* client,
                         const AutocompleteInput& input,
                         ZeroSuggestProvider::ResultType result_type,
                         bool is_prefetch,
                         SearchSuggestionParser::Results* results) {
  DCHECK(results);
  DCHECK_NE(ZeroSuggestProvider::ResultType::kNone, result_type);

  if (response_json.empty()) {
    return false;
  }

  auto response_data =
      SearchSuggestionParser::DeserializeJsonData(response_json);
  if (!response_data) {
    return false;
  }

  if (!SearchSuggestionParser::ParseSuggestResults(
          *response_data, input, client->GetSchemeClassifier(),
          kDefaultZeroSuggestRelevance,
          /*is_keyword_result=*/false, results)) {
    return false;
  }

  // Update the relevant prefs in the cache, based on |result_type|.
  if (result_type == ZeroSuggestProvider::ResultType::kRemoteNoURL) {
    client->GetPrefs()->SetString(omnibox::kZeroSuggestCachedResults,
                                  response_json);
    LogEvent(Event::kRemoteResponseCached, result_type, is_prefetch);
  } else if (result_type == ZeroSuggestProvider::ResultType::kRemoteSendURL) {
    if (base::FeatureList::IsEnabled(omnibox::kZeroSuggestPrefetchingOnSRP) ||
        base::FeatureList::IsEnabled(omnibox::kZeroSuggestPrefetchingOnWeb)) {
      omnibox::SetUserPreferenceForZeroSuggestCachedResponse(
          client->GetPrefs(), input.current_url().spec(), response_json);
      LogEvent(Event::kRemoteResponseCached, result_type, is_prefetch);
    }
  }

  return true;
}

// Called in Start() with an input ensured to be appropriate for zero-suggest.
//
// Returns true if the response stored in the user prefs is applicable to
// |result_type| and can be successfully parsed for |input|. If so, populates
// |results| with the stored response.
bool ReadStoredResponse(const AutocompleteProviderClient* client,
                        const AutocompleteInput& input,
                        ZeroSuggestProvider::ResultType result_type,
                        SearchSuggestionParser::Results* results) {
  DCHECK(results);
  DCHECK_NE(ZeroSuggestProvider::ResultType::kNone, result_type);

  std::string response_json;

  if (result_type == ZeroSuggestProvider::ResultType::kRemoteNoURL) {
    response_json =
        client->GetPrefs()->GetString(omnibox::kZeroSuggestCachedResults);
  } else if (result_type == ZeroSuggestProvider::ResultType::kRemoteSendURL) {
    if (base::FeatureList::IsEnabled(omnibox::kZeroSuggestPrefetchingOnSRP) ||
        base::FeatureList::IsEnabled(omnibox::kZeroSuggestPrefetchingOnWeb)) {
      response_json = omnibox::GetUserPreferenceForZeroSuggestCachedResponse(
          client->GetPrefs(), input.current_url().spec());
    }
  }

  if (response_json.empty()) {
    return false;
  }

  std::unique_ptr<base::Value> response_data =
      SearchSuggestionParser::DeserializeJsonData(response_json);
  if (!response_data) {
    return false;
  }

  if (!SearchSuggestionParser::ParseSuggestResults(
          *response_data, input, client->GetSchemeClassifier(),
          kDefaultZeroSuggestRelevance,
          /*is_keyword_result=*/false, results)) {
    return false;
  }

  return true;
}

}  // namespace

// static
ZeroSuggestProvider::ResultType ZeroSuggestProvider::ResultTypeToRun(
    const AutocompleteProviderClient* client,
    const AutocompleteInput& input) {
  const auto page_class = input.current_page_classification();
  const auto focus_type_input_type =
      std::make_pair(input.focus_type(), input.type());

  // Android Search Widget.
  if (page_class == OEP::ANDROID_SHORTCUTS_WIDGET) {
    if (focus_type_input_type ==
        std::make_pair(OFT::INTERACTION_FOCUS, OIT::URL)) {
      return ResultType::kRemoteNoURL;
    }
  }

  // New Tab Page.
  if (BaseSearchProvider::IsNTPPage(page_class)) {
    if (focus_type_input_type ==
        std::make_pair(OFT::INTERACTION_FOCUS, OIT::EMPTY)) {
      return ResultType::kRemoteNoURL;
    }
  }

  // The following cases require sending the current page URL in the request.
  // Ensure the URL is valid with an HTTP(S) scheme and is not the NTP page URL.
  if (BaseSearchProvider::IsNTPPage(page_class) ||
      !BaseSearchProvider::CanSendPageURLInRequest(input.current_url())) {
    return ResultType::kNone;
  }

  // Open Web - does NOT include Search Results Page.
  if (BaseSearchProvider::IsOtherWebPage(page_class)) {
    if (focus_type_input_type ==
            std::make_pair(OFT::INTERACTION_FOCUS, OIT::URL) &&
        base::FeatureList::IsEnabled(
            omnibox::kFocusTriggersContextualWebZeroSuggest)) {
      return ResultType::kRemoteSendURL;
    }
    if (focus_type_input_type ==
            std::make_pair(OFT::INTERACTION_CLOBBER, OIT::EMPTY) &&
        base::FeatureList::IsEnabled(
            omnibox::kClobberTriggersContextualWebZeroSuggest)) {
      return ResultType::kRemoteSendURL;
    }
  }

  // Search Results Page.
  if (BaseSearchProvider::IsSearchResultsPage(page_class)) {
    if (focus_type_input_type ==
            std::make_pair(OFT::INTERACTION_FOCUS, OIT::URL) &&
        base::FeatureList::IsEnabled(omnibox::kFocusTriggersSRPZeroSuggest)) {
      return ResultType::kRemoteSendURL;
    }
    if (focus_type_input_type ==
            std::make_pair(OFT::INTERACTION_CLOBBER, OIT::EMPTY) &&
        base::FeatureList::IsEnabled(omnibox::kClobberTriggersSRPZeroSuggest)) {
      return ResultType::kRemoteSendURL;
    }
  }

  return ResultType::kNone;
}

// static
bool ZeroSuggestProvider::AllowZeroPrefixSuggestions(
    const AutocompleteProviderClient* client,
    const AutocompleteInput& input) {
  auto eligibility = Eligibility::kEligible;

  switch (ResultTypeToRun(client, input)) {
    case ResultType::kRemoteNoURL: {
      if (!AllowRemoteNoURL(client)) {
        eligibility = Eligibility::kRequestNoURLIneligible;
      }
      break;
    }
    case ResultType::kRemoteSendURL: {
      if (!AllowRemoteSendURL(client, input)) {
        eligibility = Eligibility::kRemoteSendURLIneligible;
      }
      break;
    }
    default: {
      eligibility = Eligibility::kGenerallyIneligible;
      break;
    }
  }

  base::UmaHistogramEnumeration("Omnibox.ZeroSuggestProvider.Eligibility",
                                eligibility);
  return eligibility == Eligibility::kEligible;
}

// static
ZeroSuggestProvider* ZeroSuggestProvider::Create(
    AutocompleteProviderClient* client,
    AutocompleteProviderListener* listener) {
  return new ZeroSuggestProvider(client, listener);
}

// static
void ZeroSuggestProvider::RegisterProfilePrefs(PrefRegistrySimple* registry) {
  registry->RegisterStringPref(omnibox::kZeroSuggestCachedResults,
                               std::string());
  registry->RegisterDictionaryPref(omnibox::kZeroSuggestCachedResultsWithURL,
                                   base::Value::Dict());
}

void ZeroSuggestProvider::StartPrefetch(const AutocompleteInput& input) {
  AutocompleteProvider::StartPrefetch(input);

  TRACE_EVENT0("omnibox", "ZeroSuggestProvider::StartPrefetch");

  if (!AllowZeroPrefixSuggestions(client(), input)) {
    return;
  }

  ResultType result_type = ResultTypeToRun(client(), input);

  if (prefetch_loader_) {
    LogEvent(Event::kRequestInvalidated, result_type, /*is_prefetch=*/true);
  }

  // Create a loader for the request and take ownership of it.
  TemplateURLRef::SearchTermsArgs search_terms_args;
  search_terms_args.page_classification = input.current_page_classification();
  search_terms_args.focus_type = input.focus_type();
  search_terms_args.current_page_url = result_type == ResultType::kRemoteSendURL
                                           ? input.current_url().spec()
                                           : std::string();
  prefetch_loader_ =
      client()
          ->GetRemoteSuggestionsService(/*create_if_necessary=*/true)
          ->StartSuggestionsRequest(
              search_terms_args, client()->GetTemplateURLService(),
              base::BindOnce(&ZeroSuggestProvider::OnPrefetchURLLoadComplete,
                             weak_ptr_factory_.GetWeakPtr(),
                             GetZeroSuggestInput(input, client()),
                             result_type));

  LogEvent(Event::kRequestSent, result_type, /*is_prefetch=*/true);
}

void ZeroSuggestProvider::Start(const AutocompleteInput& input,
                                bool minimal_changes) {
  TRACE_EVENT0("omnibox", "ZeroSuggestProvider::Start");
  Stop(true, false);

  result_type_running_ = ResultType::kNone;
  if (!AllowZeroPrefixSuggestions(client(), input)) {
    return;
  }

  result_type_running_ = ResultTypeToRun(client(), input);
  set_field_trial_triggered(false);
  set_field_trial_triggered_in_session(false);

  // Convert the stored response to |matches_|, if applicable.
  SearchSuggestionParser::Results results;
  if (ReadStoredResponse(client(), GetZeroSuggestInput(input, client()),
                         result_type_running_, &results)) {
    ConvertSuggestResultsToAutocompleteMatches(results, input);
    LogEvent(Event::KCachedResponseConvertedToMatches, result_type_running_,
             /*is_prefetch=*/false);
  }

  // Do not start a request if async requests are disallowed.
  if (input.omit_asynchronous_matches()) {
    return;
  }

  done_ = false;

  // Create a loader for the request and take ownership of it.
  TemplateURLRef::SearchTermsArgs search_terms_args;
  search_terms_args.page_classification = input.current_page_classification();
  search_terms_args.focus_type = input.focus_type();
  search_terms_args.current_page_url =
      result_type_running_ == ResultType::kRemoteSendURL
          ? input.current_url().spec()
          : std::string();
  loader_ = client()
                ->GetRemoteSuggestionsService(/*create_if_necessary=*/true)
                ->StartSuggestionsRequest(
                    search_terms_args, client()->GetTemplateURLService(),
                    base::BindOnce(&ZeroSuggestProvider::OnURLLoadComplete,
                                   weak_ptr_factory_.GetWeakPtr(),
                                   GetZeroSuggestInput(input, client()),
                                   result_type_running_));

  LogEvent(Event::kRequestSent, result_type_running_, /*is_prefetch=*/false);
}

void ZeroSuggestProvider::Stop(bool clear_cached_results,
                               bool due_to_user_inactivity) {
  AutocompleteProvider::Stop(clear_cached_results, due_to_user_inactivity);

  if (loader_) {
    LogEvent(Event::kRequestInvalidated, result_type_running_,
             /*is_prefetch=*/false);
    loader_.reset();
  }

  if (clear_cached_results) {
    experiment_stats_v2s_.clear();
  }
}

void ZeroSuggestProvider::DeleteMatch(const AutocompleteMatch& match) {
  // Remove the deleted match from the cache, so it is not shown to the user
  // again. Since we cannot remove just one result, blow away the cache.
  // Even though we currently have no easy way of checking the request type
  // after-the-fact, it's safe to always clear the cache even if we are on a
  // different request type.
  client()->GetPrefs()->SetString(omnibox::kZeroSuggestCachedResults,
                                  std::string());
  client()->GetPrefs()->SetDict(omnibox::kZeroSuggestCachedResultsWithURL,
                                base::Value::Dict());
  BaseSearchProvider::DeleteMatch(match);
}

void ZeroSuggestProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
  BaseSearchProvider::AddProviderInfo(provider_info);
  if (!matches().empty())
    provider_info->back().set_times_returned_results_in_session(1);
}

void ZeroSuggestProvider::ResetSession() {
  // The user has started editing in the omnibox, so leave
  // |field_trial_triggered_in_session| unchanged and set
  // |field_trial_triggered| to false since zero suggest is inactive now.
  set_field_trial_triggered(false);
}

ZeroSuggestProvider::ZeroSuggestProvider(AutocompleteProviderClient* client,
                                         AutocompleteProviderListener* listener)
    : BaseSearchProvider(AutocompleteProvider::TYPE_ZERO_SUGGEST, client) {
  AddListener(listener);
}

ZeroSuggestProvider::~ZeroSuggestProvider() = default;

bool ZeroSuggestProvider::ShouldAppendExtraParams(
    const SearchSuggestionParser::SuggestResult& result) const {
  // We always use the default provider for search, so append the params.
  return true;
}

void ZeroSuggestProvider::RecordDeletionResult(bool success) {
  if (success) {
    base::RecordAction(
        base::UserMetricsAction("Omnibox.ZeroSuggestDelete.Success"));
  } else {
    base::RecordAction(
        base::UserMetricsAction("Omnibox.ZeroSuggestDelete.Failure"));
  }
}

void ZeroSuggestProvider::OnURLLoadComplete(
    const AutocompleteInput& input,
    ResultType result_type,
    const network::SimpleURLLoader* source,
    std::unique_ptr<std::string> response_body) {
  TRACE_EVENT0("omnibox", "ZeroSuggestProvider::OnURLLoadComplete");

  DCHECK(!done_);
  DCHECK_EQ(loader_.get(), source);

  const bool response_received =
      response_body && source->NetError() == net::OK &&
      (source->ResponseInfo() && source->ResponseInfo()->headers &&
       source->ResponseInfo()->headers->response_code() == 200);
  if (!response_received) {
    loader_.reset();
    done_ = true;
    return;
  }

  LogEvent(Event::kRemoteResponseReceived, result_type,
           /*is_prefetch=*/false);

  SearchSuggestionParser::Results results;
  const bool response_parsed = StoreRemoteResponse(
      SearchSuggestionParser::ExtractJsonData(source, std::move(response_body)),
      client(), input, result_type,
      /*is_prefetch=*/false, &results);
  if (!response_parsed) {
    loader_.reset();
    done_ = true;
    return;
  }

  loader_.reset();
  done_ = true;

  // For display stability reasons, update the displayed results with the remote
  // response only if they are empty or if an empty result set is received. In
  // the latter case, the displayed results may no longer be valid to be shown.
  const bool empty_matches = matches().empty();
  const bool empty_results =
      results.suggest_results.empty() && results.navigation_results.empty();
  if (!empty_matches && !empty_results) {
    return;
  }

  // Convert the response to |matches_| and notify the listeners.
  ConvertSuggestResultsToAutocompleteMatches(results, input);
  LogEvent(Event::kRemoteResponseConvertedToMatches, result_type,
           /*is_prefetch=*/false);
  NotifyListeners(/*updated_matches=*/true);
}

void ZeroSuggestProvider::OnPrefetchURLLoadComplete(
    const AutocompleteInput& input,
    ResultType result_type,
    const network::SimpleURLLoader* source,
    std::unique_ptr<std::string> response_body) {
  TRACE_EVENT0("omnibox", "ZeroSuggestProvider::OnPrefetchURLLoadComplete");

  DCHECK_EQ(prefetch_loader_.get(), source);

  const bool response_received =
      response_body && source->NetError() == net::OK &&
      (source->ResponseInfo() && source->ResponseInfo()->headers &&
       source->ResponseInfo()->headers->response_code() == 200);
  if (response_received) {
    LogEvent(Event::kRemoteResponseReceived, result_type, /*is_prefetch=*/true);

    SearchSuggestionParser::Results unused_results;
    StoreRemoteResponse(SearchSuggestionParser::ExtractJsonData(
                            source, std::move(response_body)),
                        client(), input, result_type,
                        /*is_prefetch=*/true, &unused_results);
  }

  prefetch_loader_.reset();
}

AutocompleteMatch ZeroSuggestProvider::NavigationToMatch(
    const SearchSuggestionParser::NavigationResult& navigation) {
  AutocompleteMatch match(this, navigation.relevance(), false,
                          navigation.type());
  match.destination_url = navigation.url();

  match.fill_into_edit +=
      AutocompleteInput::FormattedStringWithEquivalentMeaning(
          navigation.url(), url_formatter::FormatUrl(navigation.url()),
          client()->GetSchemeClassifier(), nullptr);

  // Zero suggest results should always omit protocols and never appear bold.
  auto format_types = AutocompleteMatch::GetFormatTypes(false, false);
  match.contents = url_formatter::FormatUrl(navigation.url(), format_types,
                                            base::UnescapeRule::SPACES, nullptr,
                                            nullptr, nullptr);
  match.contents_class = ClassifyTermMatches({}, match.contents.length(), 0,
                                             ACMatchClassification::URL);

  match.description =
      AutocompleteMatch::SanitizeString(navigation.description());
  match.description_class = ClassifyTermMatches({}, match.description.length(),
                                                0, ACMatchClassification::NONE);
  for (const int subtype : navigation.subtypes()) {
    match.subtypes.insert(SuggestSubtypeForNumber(subtype));
  }
  return match;
}

void ZeroSuggestProvider::ConvertSuggestResultsToAutocompleteMatches(
    const SearchSuggestionParser::Results& results,
    const AutocompleteInput& input) {
  matches_.clear();
  suggestion_groups_map_.clear();
  experiment_stats_v2s_.clear();

  if (!field_trial_triggered()) {
    set_field_trial_triggered(results.field_trial_triggered);
  }
  if (!field_trial_triggered_in_session()) {
    set_field_trial_triggered_in_session(results.field_trial_triggered);
  }

  // Add all the SuggestResults to the map. We display all ZeroSuggest search
  // suggestions as unbolded.
  MatchMap map;
  for (size_t i = 0; i < results.suggest_results.size(); ++i) {
    AddMatchToMap(results.suggest_results[i], std::string(), input,
                  client()->GetTemplateURLService()->GetDefaultSearchProvider(),
                  client()->GetTemplateURLService()->search_terms_data(), i,
                  false, false, &map);
  }

  const int num_query_results = map.size();
  const int num_nav_results = results.navigation_results.size();
  const int num_results = num_query_results + num_nav_results;
  base::UmaHistogramCounts1M("ZeroSuggest.QueryResults", num_query_results);
  base::UmaHistogramCounts1M("ZeroSuggest.URLResults", num_nav_results);
  base::UmaHistogramCounts1M("ZeroSuggest.AllResults", num_results);

  if (num_results == 0) {
    return;
  }

  for (MatchMap::const_iterator it(map.begin()); it != map.end(); ++it) {
    matches_.push_back(it->second);
  }

  const SearchSuggestionParser::NavigationResults& nav_results(
      results.navigation_results);
  for (const auto& nav_result : nav_results) {
    matches_.push_back(NavigationToMatch(nav_result));
  }

  // Update the suggestion groups information from the server response.
  for (const auto& entry : results.suggestion_groups_map) {
    suggestion_groups_map_[entry.first].MergeFrom(entry.second);
  }

  // Update the list of experiment stats from the server response.
  for (const auto& experiment_stats_v2 : results.experiment_stats_v2s) {
    experiment_stats_v2s_.push_back(experiment_stats_v2);
  }
}


text:
title: Indented
order: 3
---

In indented tree layout, each node takes a row or a column.

## Usage

Indented is an appropriate layout method for tree data structure. Please use it with TreeGraph. As the demo below, you can deploy it in `layout` while instantiating Graph.

You can set different configurations for different nodes if the parameter is Function type. Please refer to the ducuments for more information.