text:
package com.amazonaws.services.cloudtrail.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetChannelRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The ARN or UUID of a channel.
     *

     */
    private String channel;

    /**
     *

     * The ARN or UUID of a channel.
     *

     *
     * @param channel
     *        The ARN or UUID of a channel.
     */

    public void setChannel(String channel) {
        this.channel = channel;
    }

    /**
     *

     * The ARN or UUID of a channel.
     *

     *
     * @return The ARN or UUID of a channel.
     */

    public String getChannel() {
        return this.channel;
    }

    /**
     *

     * The ARN or UUID of a channel.
     *

     *
     * @param channel
     *        The ARN or UUID of a channel.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetChannelRequest withChannel(String channel) {
        setChannel(channel);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getChannel() != null)
            sb.append("Channel: ").append(getChannel());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetChannelRequest == false)
            return false;
        GetChannelRequest other = (GetChannelRequest) obj;
        if (other.getChannel() == null ^ this.getChannel() == null)
            return false;
        if (other.getChannel() != null && other.getChannel().equals(this.getChannel()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getChannel() == null) ? 0 : getChannel().hashCode());
        return hashCode;
    }

    @Override
    public GetChannelRequest clone() {
        return (GetChannelRequest) super.clone();
    }

}


text:
_[www.codever.land/bookmarks/t/indexeddb](https://www.codever.land/bookmarks/t/indexeddb)_
---
#### [Client-side storage - Learn web development | MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage)
_https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage_

Modern web browsers support a number of ways for web sites to store data on the user's computer — with the user's permission — then retrieve it when necessary. This lets you persist data for long-term...
* **tags**: [local-storage](../tagged/local-storage.md), [client](../tagged/client.md), [browser](../tagged/browser.md), [caching](../tagged/caching.md), [cacheapi](../tagged/cacheapi.md), [indexeddb](../tagged/indexeddb.md)
---
#### [Working with quota on mobile browsers](https://www.html5rocks.com/en/tutorials/offline/quota-research/)
_https://www.html5rocks.com/en/tutorials/offline/quota-research/_

As web apps get richer and richer, more and more developers are using browser-side storage. However, there hasn't been a major study comparing the limitations of the various storage mechanisms. It is ...
* :calendar: **published on**: 2014-01-28
* **tags**: [html](../tagged/html.md), [local-storage](../tagged/local-storage.md), [indexeddb](../tagged/indexeddb.md)
---
#### [IndexedDB API - Web APIs | MDN](https://developer.mozilla.org/en/docs/Web/API/IndexedDB_API)
_https://developer.mozilla.org/en/docs/Web/API/IndexedDB_API_

IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data. While Web...
* **tags**: [indexeddb](../tagged/indexeddb.md), [web-api](../tagged/web-api.md)
---
#### [Moving beyond localStorage – Standard Journal](https://journal.standardnotes.org/moving-beyond-localstorage-991e3695be15)
_https://journal.standardnotes.org/moving-beyond-localstorage-991e3695be15_

WebCrypto and IndexedDB are the one-two punch to a new era of encrypted, offline, and privacy centric web applications.
* **tags**: [offline-first](../tagged/offline-first.md), [indexeddb](../tagged/indexeddb.md), [webcrypto](../tagged/webcrypto.md)
---
#### [Basic concepts - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB)
_https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB_

IndexedDB is a way for you to persistently store data inside a user's browser. Because it lets you create web applications with rich query abilities regardless of network availability, these applicati...
* **tags**: [offline-first](../tagged/offline-first.md), [indexeddb](../tagged/indexeddb.md)
---
#### [Using IndexedDB - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
_https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB_

This tutorial walks you through using the asynchronous API of IndexedDB. If you are not familiar with IndexedDB, you should first read [Basic Concepts About IndexedDB](https://developer.mozilla.org/en...
* **tags**: [offline-first](../tagged/offline-first.md), [indexeddb](../tagged/indexeddb.md)
---

redpajama_set_name: RedPajamaGithub


text:
package chatty.util.api;

import chatty.gui.HtmlColors;
import java.awt.Color;
import java.util.regex.Pattern;

/**
 *
 * @author tduva
 */
public class CheersUtil {

    public static final Pattern PATTERN = Pattern.compile("(?<=^|\\s)cheer(\\d+)(?=$|\\s)");

    public enum CHEER {

        GRAY("gray", 1, HtmlColors.decode("#979797"), "1 or more bits"),
        PURPLE("purple", 100, HtmlColors.decode("#9c3ee8"), "100 or more bits"),
        GREEN("green", 1000, HtmlColors.decode("#1db2a5"), "1,000 or more bits"),
        BLUE("blue", 5000, HtmlColors.decode("#0099fe"), "5,000 or more bits"),
        RED("red", 10000, HtmlColors.decode("#f43021"), "10,000 or more bits");

        public int min;
        public Color color;
        public String image;
        public String info;

        CHEER(String image, int min, Color color, String info) {
            this.image = image;
            this.min = min;
            this.color = color;
            this.info = info;
        }
    }

    public static CHEER getCheerFromBits(int bits) {
        CHEER result = null;
        for (CHEER c : CHEER.values()) {
            if (bits < c.min) {
                break;
            }
            result = c;
        }
        return result;
    }

}


text:
'use strict';

var _getFormNames = require('../getFormNames');

var _getFormNames2 = _interopRequireDefault(_getFormNames);

var _plain = require('../../structure/plain');

var _plain2 = _interopRequireDefault(_plain);

var _expectations = require('../../structure/plain/expectations');

var _expectations2 = _interopRequireDefault(_expectations);

var _immutable = require('../../structure/immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _expectations3 = require('../../structure/immutable/expectations');

var _expectations4 = _interopRequireDefault(_expectations3);

var _addExpectations = require('../../__tests__/addExpectations');

var _addExpectations2 = _interopRequireDefault(_addExpectations);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var describeGetFormNames = function describeGetFormNames(name, structure, expect) {
  var getFormNames = (0, _getFormNames2.default)(structure);

  var fromJS = structure.fromJS,
      getIn = structure.getIn;

  describe(name, function () {
    it('should return a function', function () {
      expect(getFormNames()).toBeA('function');
    });

    it('should get the form names from state', function () {
      expect(getFormNames()(fromJS({
        form: {
          foo: {
            values: {
              dog: 'Snoopy',
              cat: 'Garfield'
            }
          },
          bar: {
            values: {
              dog: 'Fido',
              cat: 'Whiskers'
            }
          }
        }
      }))).toEqualMap(['foo', 'bar']);
    });

    it('should use getFormState if provided', function () {
      expect(getFormNames(function (state) {
        return getIn(state, 'someOtherSlice');
      })(fromJS({
        someOtherSlice: {
          foo: {
            values: {
              dog: 'Snoopy',
              cat: 'Garfield'
            }
          },
          bar: {
            values: {
              dog: 'Fido',
              cat: 'Whiskers'
            }
          }
        }
      }))).toEqualMap(['foo', 'bar']);
    });
  });
};

describeGetFormNames('getFormNames.plain', _plain2.default, (0, _addExpectations2.default)(_expectations2.default));
describeGetFormNames('getFormNames.immutable', _immutable2.default, (0, _addExpectations2.default)(_expectations4.default));


text:
package es.cenobit.struts2.json.example.objects;

public class Foo {

    private Long id;
    private String name;
    private Bar bar;

    public Foo(Long id, String name, Bar bar) {
        super();
        this.id = id;
        this.name = name;
        this.bar = bar;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Bar getBar() {
        return bar;
    }

    public void setBar(Bar bar) {
        this.bar = bar;
    }

}


text:
package com.rimbit.rimbit.uri;

/**
 *
Exception to provide the following to {@link RimbitURI}:

 *

 *
Provision of parsing error messages

 *

 *
This base exception acts as a general failure mode not attributable to a specific cause (other than
 * that reported in the exception message). Since this is in English, it may not be worth reporting directly
 * to the user other than as part of a "general failure to parse" response.

 */
public class RimbitURIParseException extends Exception {
    public RimbitURIParseException(String s) {
        super(s);
    }

    public RimbitURIParseException(String s, Throwable throwable) {
        super(s, throwable);
    }
}


text:
<?php
namespace Pronit\ParametrizacionGeneralBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

/**
 * Description of SociedadFIAdmin
 *
 * @author gcaseres
 */
class ConversionSistemaMedicionAdmin extends Admin
{
 // Fields to be shown on create/edit forms
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('desde', 'sonata_type_model', array('label' => 'Sistema Medición Desde', 'property' => 'nombre'))
            ->add('hasta', 'sonata_type_model', array('label' => 'Sistema Medición Hasta', 'property' => 'nombre'))
            ->add('factor', 'number', array('label' => 'Factor'))
        ;
    }

    // Fields to be shown on lists
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('desde')
            ->add('hasta')
            ->add('factor')
        ;
    }
}


text:
define(["require", "exports"], function(require, exports) {
    var UrlService = (function () {
        function UrlService() {
            this.BASE_URL = "/api";
            this.AUTHENTICATION_URL = this.BASE_URL + "/security/authenticate";
        }
        return UrlService;
    })();

    return UrlService;
});
//# sourceMappingURL=UrlService.js.map


text:
/* -*-Mode: c++;-*- (Tell emacs to use c++ mode) */

#ifndef mempool_allocator_INCLUDED
#define mempool_allocator_INCLUDED

#ifndef mempool_INCLUDED
#include "mempool.h"
#endif

template <class T>
class mempool_allocator {
private:
  MEM_POOL* pool;
  template <class U> friend class mempool_allocator;

public:
  typedef size_t    size_type;
  typedef ptrdiff_t difference_type;
  typedef T*        pointer;
  typedef const T*  const_pointer;
  typedef T&        reference;
  typedef const T&  const_reference;
  typedef T         value_type;

  template <class U> struct rebind {
    typedef mempool_allocator<U> other;
  };

  mempool_allocator() : pool(Malloc_Mem_Pool) {} // The default value.
  mempool_allocator(MEM_POOL* p) : pool(p) {}
  mempool_allocator(const mempool_allocator& a) : pool(a.pool) {}
  template <class U> mempool_allocator(const mempool_allocator<U>& a)
    : pool(a.pool) {}
  ~mempool_allocator() {}

  pointer address(reference x) const { return &x; }
  const_pointer address(const_reference x) const { return &x; }

  pointer allocate(size_type n, const void* = 0)
    { return n != 0 ? TYPE_MEM_POOL_ALLOC_N(T, pool, n) : pointer(0); }

  void deallocate(pointer p, size_type /* n */) {
    if (p)
      MEM_POOL_FREE(pool, p);
  }

  size_type max_size() const { return size_t(-1) / sizeof(T); }

  void construct(pointer p, const T& val) { new(p) T(val); }
  void destroy(pointer p) { p->~T(); }

#if (__GNUC__ >= 4)
  inline bool operator!=(const mempool_allocator& b) const {
    return pool != b.pool;
  }
#endif

};

template<>
class mempool_allocator<void> {
public:
  typedef size_t      size_type;
  typedef ptrdiff_t   difference_type;
  typedef void*       pointer;
  typedef const void* const_pointer;
  typedef void        value_type;

  template <class U> struct rebind {
    typedef mempool_allocator<U> other;
  };
};
#endif //  mempool_allocator_INCLUDED


text:
<!DOCTYPE html>

    <title>Write an expression that checks if given positive integer number n (n ≤ 100) is prime. E.g. 37 is prime.</title>
    <link href="styles/js-console.css" rel="stylesheet" />

    Number:
    <input type="text" id="tb-number" />
    <button type="button" onclick="IsPrime()">Is prime?</button>


text:
<?php

namespace Spin\Template\Engine;

use Dwoo\Core;

class DwooEngine implements EngineInterface
{
    /**
     * The template engine.
     *
     * @var Core
     */
    protected $engine;

    /**
     * Constructor.
     *
     * @param Core $engine
     */
    public function __construct(Core $engine)
    {
        $this->engine = $engine;
    }

    /**
     * Render the template.
     *
     * @param string $file
     * @param array  $vars
     *
     * @return string
     */
    public function render($file, array $vars)
    {
        return $this->engine->get($file, $vars);
    }
}


text:
set -e

function cleanup {
    set +e
    echo "Removing resource groups"
    $(az group delete -n custodian-function-test-rg -y)
    $(az group delete -n custodian-function-test-dedicated -y)
    $(az group delete -n custodian-function-test-consumption -y)
}
trap cleanup EXIT

echo "Logging to Azure"
az login --service-principal -u $AZURE_CLIENT_ID -p $AZURE_CLIENT_SECRET -t $AZURE_TENANT_ID -o none
az account set -s $AZURE_SUBSCRIPTION_ID -o none

echo "Running Cloud Custodian"
custodian run -s=/dev/null policy_timer_dedicated.yaml
custodian run -s=/dev/null policy_event_dedicated.yaml
custodian run -s=/dev/null policy_timer_consumption.yaml
custodian run -s=/dev/null policy_event_consumption.yaml

echo "Creating new resource group"
az group create -l westus -n custodian-function-test-rg -o none

result=1
max_attempts=60

echo "Waiting for the 'custodian-function-test: passed' tag..."
for i in $(seq 1 ${max_attempts})
do
    sleep 30s
    echo "Attempt ${i}/${max_attempts}..."
    tags=$(az group show -n custodian-function-test-rg --query 'tags' -o json)
    echo ${tags}
    if [[ $(echo $tags | grep -o 'custodian-function-' | wc -l) -eq 4 ]]; then
        result=0
        echo "Found all expected tags."
        break
    fi
    echo "Tag not found, retrying in 30 seconds."
done

echo "Exiting... Status:${result}"
exit ${result}


text: export { default } from './PermissionsList';


text:
import React from 'react'

function NotFoundPage () {
  return (

Doh! 404!

These are not the droids you are looking for!

  )
}

export default NotFoundPage


text:
namespace APPCA {
    function VeiculosModel(): IVeiculos {
        let Model = {
            combustivel: "",
            imagem: "",
            marca: "",
            modelo: "",
            placa: "",
            valor: 0
        };

        function getModel() {
            return angular.copy(Model);
        }

        return {
            model: getModel
        };
    }

    angular
        .module("AppContaAzul")
        .factory("VeiculosModel", VeiculosModel);
}


text:
import { TestBed } from '@angular/core/testing';
import { UserActions } from '../user.actions';
import { UserType, User } from '../../Models/user';

describe('Actions: User', () => {
  it('should create a LOGIN action', () => {
    let email = 'email';
    let password = 'password';
    let remember = '1';
    let expected = {
      type: 'USER_LOGIN',
      payload: {
        email: email,
        password: password,
        remember_me: remember
      }
    };

    let actual = UserActions.userLogin(email, password, remember);

    expect(actual).toEqual(expected);
  });

  it('should create a LOGIN_SUCCESS action', () => {
    let user: User = {
      id: 33639,
      type: UserType.STUDENT,
      first_name: "Mireille",
      last_name: "Buckridge",
      email: "estelle@hotmail.com"
    };

    let expected = {
      type: 'USER_LOGIN_SUCCESS',
      payload: user
    }
    let actual= UserActions.userLoginSuccess(user);

    expect(actual).toEqual(expected);
  });

  it('should create a LOGIN_FAIL action', () => {
    let expected = {
      type: 'USER_LOGIN_FAIL'
    }

    let actual = UserActions.userLoginFail();

    expect(actual).toEqual(expected);
  });

  it('should create a LOGOUT action', () => {
    let expected = {
      type: 'USER_LOGOUT'
    };

    let actual = UserActions.userLogout();

    expect(actual).toEqual(expected);
  });

  it('should create a LOGOUT_SUCCESS action' , () => {
    let expected = {
      type: 'USER_LOGOUT_SUCCESS'
    };

    let actual = UserActions.userLogoutSuccess();

    expect(actual).toEqual(expected);
  });

  it('should create a LOGOUT_FAIL action' , () => {
    let expected = {
      type: 'USER_LOGOUT_FAIL'
    };

    let actual = UserActions.userLogoutFail();

    expect(actual).toEqual(expected);
  });
});


text:
#ifndef _STLLOADER_HH_
#define _STLLOADER_HH_

#include <stdint.h>
#include <string>

#include "common/MeshLoader.hh"

#define LINE_MAX_LEN 256
#define COR3_MAX 200000
#define ORDER_MAX 10
#define FACE_MAX 200000

namespace gazebo
{
  namespace common
  {
    /// \addtogroup gazebo_common Common
    /// \{

    /// \class STLLoader STLLoader.hh common/common.hh
    /// \brief Class used to load STL mesh files
    class STLLoader : public MeshLoader
    {
      /// \brief Constructor
      public: STLLoader();

      /// \brief Destructor
      public: virtual ~STLLoader();

      /// \brief Creates a new mesh and loads the data from a file
      /// \param[in] _filename the mesh file
      public: virtual Mesh *Load(const std::string &_filename);

      /// \brief Reads an ASCII STL (stereolithography) file.
      /// \param[in] _filein the file pointer
      /// \param[out] _mesh the mesh where to load the data
      /// \return true if read was successful
      private: bool ReadAscii(FILE *_filein, Mesh *_mesh);

      /// \brief Reads a binary STL (stereolithography) file.
      /// \param[in] _filein the file pointer
      /// \param[out] the mesh where to load the data
      /// \return true if read was successful
      private: bool ReadBinary(FILE *_filein, Mesh *_mesh);

      /// \brief Compares two strings for equality, disregarding case.
      /// \param[in] _string1 the first string
      /// \param[in] _string2 the seconf string
      /// \return true if the strings are equal (same content)
      private: bool Leqi(char* _string1, char* _string2);

      /// \brief Finds if a vector occurs in a table. This is done using
      /// floating point comparison with the default tolerance of 1e-6
      /// \param[in] _a the vector data
      /// \param[in] _m the number of columns in the table
      /// \param[in] _n the number of rows in the table
      /// \return The column index of the vector
      private: int RcolFind(float _a[][COR3_MAX], int _m, int _n, float _r[]);

      /// \brief Reads a long int from a binary file.
      /// \param[in] _filein the file pointer
      /// \return the value
      private: uint32_t LongIntRead(FILE *_filein);

      /// \brief Reads a short int from a binary file.
      /// \param[in] _filein the file pointer
      /// \param[out] _value the value read
      /// \return true
      private: bool ShortIntRead(FILE *_filein, uint16_t &_value);

      /// \brief Read 1 double precision float from a binary file.
      /// \param[in] _filein the file pointer
      /// \param[out] the value
      /// \return true
      private: bool FloatRead(FILE *_filein, double &_value);
    };
    /// \}
  }
}
#endif


text:
module SiteUiHelper

  # ea. app should define a after_sign_in_path method

  # must define this method!
  def conditionally_authenticate_user!
    authenticate_user!
  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jy.repository.system.account.AccountDao">
    <!--  com.jy.entity.system.account.Account -->
    <resultMap id="base" type="BaseAccount">
        <id column="ID" jdbcType="VARCHAR" property="accountId"/>
        <association property="loginLog" column="ID" javaType="LoginLog" select="getLoginLogById"/>
        <collection property="poss" column="ID" ofType="basePos" select="getPoss"/>
    </resultMap>
    <resultMap id="LoginLog" type="LoginLog"></resultMap>
    <resultMap id="ZNodes" type="com.jy.common.utils.tree.entity.ZNodes"></resultMap>
    <resultMap id="basePos" type="BasePos"></resultMap>
    <!-- 防止密码外泄,取消密码列 -->
    <select id="find" resultMap="base" parameterType="BaseAccount">
        SELECT t.id,
        t.loginName,
        t.roleId,
        jbr.name as roleName,
        t.name,
        t.department,
        t.orgid,
        t.picUrl,
        t.email,
        t.isValid,
        t.createTime,
        t.updateTime,
        t.skin,
        t.description
        FROM JY_BASE_ACCOUNT t
        LEFT JOIN JY_BASE_ROLE jbr
        ON jbr.id=t.roleId
        WHERE 1=1
        <if test="loginName != null and loginName!='' ">
            and t.loginName=#{loginName}
        </if>
        <if test="roleId != null and roleId!='' ">
            and t.roleId=#{roleId}
        </if>
        <if test="accountId != null ">
            and t.id=#{accountId}
        </if>
        <if test="company != null and company!=''">
            AND t.cid=#{company}
        </if>
    </select>
    <!--  防止密码外泄,取消密码列 -->
    <select id="findByPage" resultMap="base" parameterType="BaseAccount">
        SELECT t.id,
        t.loginName,
        t.roleId,
        jbr.name as roleName,
        t.name,
        t.picUrl,
        t.email,
        t.orgid,
        t.department,
        t.isValid,
        t.createTime,
        t.updateTime,
        t.skin,
        t.description FROM JY_BASE_ACCOUNT t
        LEFT JOIN JY_BASE_ROLE jbr
        ON jbr.id=t.roleId
        WHERE 1=1
        <if test="param.loginName != null and param.loginName!='' ">
            AND t.loginName LIKE CONCAT('%',#{param.loginName},'%')
        </if>
        <if test="param.keyWord!= null and param.keyWord!= ''" >
            AND (
            t.loginName LIKE CONCAT('%',#{param.keyWord},'%')
            OR t.name LIKE CONCAT('%',#{param.keyWord},'%')
            OR t.email LIKE CONCAT('%',#{param.keyWord},'%')
            )
        </if>
        <if test="param.roleId != null ">
            AND t.roleId=#{param.roleId}
        </if>
        <if test="param.orgid != null ">
            AND t.orgid=#{param.orgid}
        </if>
        <if test="param.company != null and param.company!=''">
            AND t.cid=#{param.company}
        </if>
        <if test="param.isValid != null ">
            AND t.isValid=#{param.isValid}
        </if>
        ORDER BY t.createTime desc
    </select>
    <select id="count" resultType="int" parameterType="BaseAccount">
       SELECT count(*) FROM JY_BASE_ACCOUNT t  WHERE 1=1
    </select>
    <insert id="insert" parameterType="BaseAccount">
 	<![CDATA[

	INSERT INTO JY_BASE_ACCOUNT(
	id,loginName,name,password,salt,roleId,skin,email,isValid,createTime,description,cid,department,orgid
	) VALUES (#{accountId},#{loginName},#{name},#{password},#{salt},#{roleId},#{skin},
	#{email},#{isValid},#{createTime},#{description},#{company},#{department},#{orgid}
	)

        ]]>
	</insert>
    <delete id="delete" parameterType="BaseAccount">
	delete from JY_BASE_ACCOUNT
	WHERE id=#{accountId}
	</delete>
    <delete id="deleteBatch" parameterType="java.util.List">
        DELETE FROM JY_BASE_ACCOUNT WHERE id in(
        <foreach item="o" collection="list" open="" separator="," close="">
            #{o.accountId}
        </foreach>
        )
    </delete>
    <update id="update" parameterType="BaseAccount">
		UPDATE JY_BASE_ACCOUNT
		SET name =#{name},
			email =#{email},
			isValid =#{isValid},
			roleId =#{roleId},
			updateTime =#{updateTime},
			description =#{description},
			department=#{department},
			orgid=#{orgid}
		WHERE id=#{accountId}
	</update>
    <!-- 这方法能获取密码和盐 -->
    <select id="findFormatByLoginName" resultMap="base" parameterType="String">
    	<![CDATA[

       SELECT a.* FROM JY_BASE_ACCOUNT a WHERE a.isvalid='1'
       AND a.loginname=#{loginName,jdbcType=VARCHAR}

        ]]>
    </select>

    <select id="findFormatByLoginNameAndCompany" resultMap="base" parameterType="String">
		<![CDATA[

       SELECT a.* FROM JY_BASE_ACCOUNT a WHERE a.isvalid='1'
       AND a.loginname=#{loginName,jdbcType=VARCHAR}
       AND a.cid = #{company,jdbcType=VARCHAR}

        ]]>
	</select>
    <!-- 这方法不能能获取密码和盐 -->
    <select id="findAccountById" resultMap="base" parameterType="String">
       SELECT  t.id,
       		  t.loginName,
       		  t.roleId,
       		  jbr.name as roleName,
       		  t.name,
       		  t.picUrl,
       		  t.email,
       		  t.isValid,
       		  t.createTime,
       		  t.updateTime,
       		  t.skin,
       		  t.department,
       		  t.description
       	FROM JY_BASE_ACCOUNT t
       	LEFT JOIN JY_BASE_ROLE jbr
        ON jbr.id=t.roleId
        WHERE t.accountId=#{accountId}
    </select>
    <update id="setSetting" parameterType="BaseAccount">
		UPDATE JY_BASE_ACCOUNT
		SET   skin =#{skin}
		WHERE id=#{accountId}
	</update>
    <select id="getPerData" resultMap="base" parameterType="String">
		   SELECT t.id,
		   	  t.loginName,
       		  t.roleId,
       		  t.picUrl,
       		  t.name,
       		  t.email,
       		  		  t.department,
       		  t.createTime,
       		  t.updateTime,
       		  t.description,
       		  jbr.name as roleName
       		  FROM JY_BASE_ACCOUNT t
       	   LEFT JOIN  JY_BASE_ROLE jbr
       	   ON jbr.id=t.roleId
       	   WHERE t.isValid=1 and t.id=#{accountId}
	</select>
    <update id="setPerData" parameterType="BaseAccount">
		UPDATE JY_BASE_ACCOUNT
		SET   name =#{name},
			  email =#{email},
			  updateTime =#{updateTime}
		WHERE id=#{accountId}
	</update>
    <update id="setHeadpic" parameterType="BaseAccount">
		UPDATE JY_BASE_ACCOUNT
		SET   picUrl =#{picUrl},
			  updateTime =#{updateTime}
		WHERE id=#{accountId}
	</update>
    <select id="getRoles" resultMap="ZNodes">
		SELECT jbo.id,
			   jbo.pId,
			   jbo.name,
			   'o' as other
		FROM JY_BASE_ORG jbo
		UNION ALL
		SELECT CONCAT('role',jbr.id) as id,
			   jbr.orgId as pId,
			   jbr.name,
			   'r' as other
		FROM JY_BASE_ROLE jbr
	</select>
    <select id="getCompanyRoles" resultMap="ZNodes" parameterType="string">
		SELECT jbo.id,
		jbo.pId,
		jbo.name,
		'/whale/static/plugins/zTree/3.5/img/diy/group.png' as icon,
		'o' as other
		FROM JY_BASE_ORG jbo where jbo.cid=#{company}
		UNION ALL
		SELECT CONCAT('role',jbr.id) as id,
		jbr.orgId as pId,
		jbr.name,
		'/whale/static/plugins/zTree/3.5/img/diy/user.png' as icon,
		'r' as other
		FROM JY_BASE_ROLE jbr where jbr.cid=#{company}
	</select>

    <select id="getSingleRoles" resultMap="ZNodes" parameterType="string">
        SELECT CONCAT('role',jbr.id) as id,
        jbr.orgId as pId,
        jbr.name,
        '/whale/static/plugins/zTree/3.5/img/diy/user.png' as icon,
        'r' as other
        FROM JY_BASE_ROLE jbr where jbr.cid=#{company}
    </select>
    <select id="findCountByLoginName" resultType="int">
       SELECT COUNT(*)
       		  FROM JY_BASE_ACCOUNT t
       WHERE  t.loginName=#{loginName}
    </select>

    <select id="findCountByLoginNameAndCompany" resultType="int">
		SELECT COUNT(*)
		FROM JY_BASE_ACCOUNT t
		WHERE  t.loginName=#{loginName} AND t.cid=#{company}
	</select>

    <update id="resetPwd" parameterType="BaseAccount">
		UPDATE JY_BASE_ACCOUNT
		SET   password =#{password},
			  salt =#{salt}
		WHERE id=#{accountId}
	</update>

    <select id="getLoginLogById" parameterType="string" resultMap="LoginLog">
	SELECT
    t.loginTime, t.loginIP FROM JY_BASE_LOGIN_LOG t WHERE t.accountId = #{ID}  ORDER BY t.loginTime DESC LIMIT 1 ;
	</select>
    <select id="getPoss" parameterType="string" resultMap="basePos">
	  SELECT jbp.* FROM JY_BASE_ACCOUNT_POSITION jbap
	  LEFT JOIN JY_BASE_POSITION jbp
	  ON jbp.id=jbap.posId
	  WHERE jbap.accountId=#{ID}
	  ORDER BY jbap.posId
    </select>
</mapper>


text:
ReferenceParser
===============

Scripture Reference Parser is a library to parse data, including book, chapter, verse, and index, from references from various scriptures


text:
ActiveRecord::Schema.define(version: 2019_09_30_024200) do

  create_table "test_records", force: :cascade do |t|
    t.integer  "state",            default: nil, null: false
  end
end


text:
<?php

namespace JydFsm\Entity;

use Doctrine\ORM\Mapping as ORM;

class Test
{
    private $firstName;

    public function getFirstName()
    {
        return $this->firstName;
    }

    public function setFirstName($name)
    {
        $this->firstName = $name;
    }
}


text:
from collections import OrderedDict
from typing import Dict, Type

from .base import EventarcTransport
from .grpc import EventarcGrpcTransport
from .grpc_asyncio import EventarcGrpcAsyncIOTransport

# Compile a registry of transports.
_transport_registry = OrderedDict()  # type: Dict[str, Type[EventarcTransport]]
_transport_registry["grpc"] = EventarcGrpcTransport
_transport_registry["grpc_asyncio"] = EventarcGrpcAsyncIOTransport

__all__ = (
    "EventarcTransport",
    "EventarcGrpcTransport",
    "EventarcGrpcAsyncIOTransport",
)


text:
@interface MOBProjectionEPSG3065 : MOBProjection

@end


text:
module Handler.TaxSpec (spec) where

import TestImport

spec :: Spec
spec = withApp $ do

    describe "getTaxR" $ do
        error "Spec not implemented: getTaxR"

    describe "postTaxR" $ do
        error "Spec not implemented: postTaxR"


text:
#include <stdarg.h>
#include "Arduino.h"
#include "SIMCommunication.h"
#include <SoftwareSerial.h>

extern SoftwareSerial SIM900;

/*
    Constructor
*/
SIMCommunication::SIMCommunication(unsigned long baud, uint8_t powerPin)
{
    _powerPin = powerPin;
    _baud = baud;

    pinMode(_powerPin, OUTPUT);
    digitalWrite(_powerPin, LOW);

    SIM900.begin(_baud);
}

/*
    Toggles the power of SIM900 module.
    Holds PWR pin high for 2 seconds.
    Does not use AT+CPOWD
*/
void SIMCommunication::togglePower() {
    DEBUG_PRINT(F("Toggling Power..."));
    digitalWrite(_powerPin, HIGH);
    delay(2000);
    digitalWrite(_powerPin, LOW);
    delay(2000);
    DEBUG_PRINTLN(F("Done"));
}

/*
    Restarts the SIM900 module. Turns it on if it's off.
*/
void SIMCommunication::restartModule() {
    if (isOn()) {
        togglePower();
    }

    togglePower();
}

/*
    Checks if SIM900 module is powered on.

    Returns true if its on. False otherwise.
*/
bool SIMCommunication::isOn() {
    /*
        Sends the AT command to the module.
        If it's on, it'll respond with OK.
        If it's off, it won't respond.
    */
    String response = sendCommand("AT", 500);

    return response.indexOf("OK") >= 0;
}

/*
    Sends AT commands to SIM900 module.

    Parameter   Description
    command     String containing the AT command to send to the module
    timeout     A timeout, in milliseconds, to wait for the response

    Returns a string containing the response. Returns NULL on timeout.

*/
String SIMCommunication::sendCommand(String command, int timeout) {
    // Clear read buffer before sending new command
    while(SIM900.available()) { SIM900.read(); }

    SIM900.println(command);

    if (responseTimedOut(timeout)) {
        //DEBUG_PRINT("sendCommand Timed Out: ");DEBUG_PRINTLN(command);
        return NULL;
    }

    String response = "";

    while(SIM900.available()) {
        response.concat((char)SIM900.read());
        delayMicroseconds(500);
    }

    return response;
}

/*
    Sends the necessary commands to connect to the network.
*/
bool SIMCommunication::connectToNetwork() {
    if (!fancySend("AT+CREG=1", 10, 1000, 1, "OK")) goto error;
    if (!fancySend("AT+CREG?", 10, 1000, 2, ",1", ",5")) goto error;
    if (!fancySend("AT+CGATT=1", 5, 1000, 1, "OK")) goto error;
    if (!fancySend("AT+CGATT?", 1, 1000, 1, ": 1")) goto error;
    if (!fancySend("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"", 5, 1000, 1, "OK")) goto error;
    // TODO: Determine APN automatically. Use "phone" for ATT LTE. "wap.cingular" for other ATT
    if (!fancySend("AT+SAPBR=3,1,\"APN\",\"wap.cingular\"", 5, 1000, 1, "OK")) goto error;
    // if bearer is not connected, connect it.
    if (sendCommand("AT+SAPBR=2,1", 2500).indexOf("1,3") >= 0) {
        if (!fancySend("AT+SAPBR=1,1", 5, 2000, 1, "OK")) goto error;
    }
    // Check that we have an IP address
    if (!fancySend("AT+SAPBR=2,1", 5, 2000, 1, "1,1")) goto error;

    return true;

    error:
        return false;
}

String SIMCommunication::HTTPRequest(uint8_t type, String url, String parameters) {
    /*
        Setup HTTP
    */
    sendCommand("AT+HTTPINIT", 1000);

    // if (!fancySend("AT+HTTPINIT", 1, 1000, 1, "OK")) {
        // DEBUG_PRINTLN("INIT fail");
    // }

    sendCommand("AT+HTTPPARA=\"CID\",\"1\"", 2000);
    sendCommand("AT+HTTPPARA=\"URL\",\"" + url + "\"", 1000);
    sendCommand("AT+HTTPPARA=\"REDIR\",\"1\"", 1000);

    switch (type) {
        case 0:
            sendCommand("AT+HTTPACTION=0", 1000);
            break;
        case 1: {
            // if (!fancySend("AT+HTTPPARA=\"CONTENT\",\"application/x-www-form-urlencoded\"", 1, 1000, 1, "OK")) {
                // DEBUG_PRINTLN("CONTENT fail");
            // }
            // if (!fancySend("AT+HTTPPARA=\"TIMEOUT\",\"45\"", 1, 1000, 1, "OK")) {
                // DEBUG_PRINTLN("TIMEOUT fail");
            // }
            sendCommand("AT+HTTPPARA=\"CONTENT\",\"application/x-www-form-urlencoded\"", 1000);
            sendCommand("AT+HTTPPARA=\"TIMEOUT\",\"45\"", 1000);

            uint8_t dataLen = parameters.length();
            sendCommand("AT+HTTPDATA="+(String)dataLen+",5000", 5000);
            // DEBUG_PRINTLN("AT+HTTPDATA="+(String)dataLen+",5000");
            // if (!fancySend("AT+HTTPDATA="+(String)dataLen+",5000", 1, 10000, 1, "DOWNLOAD")) {
                // DEBUG_PRINTLN("httpdata fail");
            // }

            sendCommand(parameters, 1000);

            sendCommand("AT+HTTPACTION=1", 1000);

            break;
        } default:
            DEBUG_PRINTLN(F("Invalid type in HTTP Request"));
            break;
    }

    // After HTTPACTION we have to wait for a HTTP Status Code.
    if (responseTimedOut(10000)) {
        DEBUG_PRINTLN(F("Didn't get HTTP Status Code"));
        sendCommand("AT+HTTPTERM", 1000);
        return NULL;
    }
    delay(1000);
    while (SIM900.available()) { SIM900.read(); }

    delay(1000);
    String response = "";

    SIM900.println("AT+HTTPREAD");
    if (responseTimedOut(10000)) {
        DEBUG_PRINTLN(F("Didn't get HTTP data"));
        sendCommand("AT+HTTPTERM", 1000);
        return NULL;
    }

    // Capture only data between braces (JSON)
    bool begin = false;
    while (SIM900.available()) {

        char in = SIM900.read();
        if (in == '{') {
            begin = true;
        }

        if (begin) response += (in);

        if (in == '}') {
            break;
        }

        delay(1);
    }

    delay(1000);

    sendCommand("AT+HTTPTERM", 1000);
    // if (!fancySend("AT+HTTPTERM", 1, 5000, 1, "OK")) {
        // DEBUG_PRINTLN("TERM fail");
    // }

    return response;
}

/*
    Sends a command to SIM900 and waits for one of the acceptable responses.

    Parameter       Description
    command         String containing the AT command to send to the module
    attempts        Number of times to re-send <command> if nothing in <OKResponses> matches response
    timeout         A timeout, in milliseconds, to wait for the response from SIM900 per <attempt>
    num             Number of acceptable responses
    ...             Strings of substrings of the acceptable responses.
                    The function will look for each of these substrings in the response.
                    It should be specific enough to determine success.

    Returns true if something in <OKResponses> matched response from SIM900. False otherwise.
*/
bool SIMCommunication::fancySend(String command, uint8_t attempts, int timeout, uint8_t num, ...) {
    va_list arguments;

    String response;
    bool done = false;

    for (uint8_t i = 0; i < attempts; i++) {
        response = sendCommand(command, timeout);
        va_start(arguments, num);
        for (uint8_t j = 0; j < num; j++) {
            String comp = va_arg(arguments, char*);
            if (response.indexOf(comp) >= 0) {
               done = true;
               break;
            }
        }
        va_end(arguments);

        if (done) break;
        delay(500);
    }

    return done;
}

/*
    Waits for a response from SIM900 for <ms> milliseconds

    Returns true if timed out without response. False otherwise.
*/
bool SIMCommunication::responseTimedOut(int ms) {
    int counter = 0;
    while(!SIM900.available() && counter < ms) {
        counter++;
        delay(1);
    }

    // Timed out, return null
    if (counter >= ms) {
        return true;
    }
    counter = 0;
    return false;
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Rottboellia pubescens Bertol.

### Remarks
null


text:
"""
This script tests other routines related to localized spectral analyses
"""

# standard imports:
import os
import sys
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

# import shtools:
sys.path.append(os.path.join(os.path.dirname(__file__), "../../.."))
import pyshtools as shtools

# set shtools plot style:
sys.path.append(os.path.join(os.path.dirname(__file__), "../Common"))
from FigStyle import style_shtools
mpl.rcParams.update(style_shtools)

def main():
    test_LocalizationWindows()
    # test_LocalizationBias()
    # test_Other()

def test_LocalizationWindows():

    print '\n---- testing SphericalCapCoef ----'
    lmax = 15
    theta = 50.
    print 'generating {:2.1f} degrees cap:'.format(theta)
    coeffsm0 = shtools.SphericalCapCoef(np.radians(theta), lmax)
    print coeffsm0

    print '\n---- testing SHBias ----'
    winpower = coeffsm0**2
    ldata = 20
    globalpower = np.random.rand(ldata)
    localpower = shtools.SHBias(winpower, globalpower)
    print localpower[:min(ldata, 20)]

    print '\n---- testing Curve2Mask ----'
    # defines lat/lon square (bug!?)
    nlat = 100
    dlat = 180. / nlat
    npoints = 4
    points = np.empty((npoints, 2))
    points[0] = [40., 20.]
    points[1] = [40., 50.]
    points[2] = [80., 50.]
    points[3] = [80., 20.]
    hasnorthpole = False
    dhmask = shtools.Curve2Mask(nlat, points, hasnorthpole)
    # compute covered area as a check
    thetas = np.linspace(0 + dlat / 2., 180. - dlat / 2., nlat)
    weights = 2 * np.sin(np.radians(thetas))
    maskarea = np.sum(dhmask * weights[:, None] * dlat**2)
    globearea = 4 * np.pi * (180 / np.pi)**2
    print 'mask covers {:2.2f}%% of the globe'.format(100 * maskarea / globearea)
    # plt.imshow(dhmask)
    # plt.show()

    print '\n---- testing ComputeDMap ----'
    nlat = 180
    lmax = 20
    dlat = 180. / nlat
    lats = np.linspace(90. - dlat / 2., -90. + dlat / 2., nlat)
    lons = np.linspace(0. + dlat, 360. - dlat / 2., nlat)
    latgrid, longrid = np.meshgrid(lats, lons, indexing='ij')
    dh_mask = np.logical_and(5. < latgrid, latgrid < 20.)
    print 'dij matrix[0,:lmax={:d}]:'.format(lmax)
    dij_matrix = shtools.ComputeDMap(dh_mask, lmax)
    print dij_matrix[0, :lmax]

    print '\n---- testing SHReturnTapersMap ----'
    tapers, evalues = shtools.SHReturnTapersMap(dh_mask, lmax, Ntapers=1)
    print 'best taper concentration: {:2.2f}'.format(evalues[0])

#==== EXECUTE SCRIPT ====
if __name__ == "__main__":
    main()


text:
Sign in

				<form data-ng-submit="signin()" autocomplete="off">

						<input type="text" id="username" name="username" class="form-control input-lg" data-ng-model="credentials.username" placeholder="{{ 'USERNAME_PLACEHOLDER' | translate }}">

						<input type="password" id="password" name="password" class="form-control input-lg" data-ng-model="credentials.password" placeholder="{{ 'PASSWORD_PLACEHOLDER' | translate }}">

						<button type="submit" class="btn btn-default btn-lg btn-block">

						</button>

				</form>


text:
package org.chromium.content.browser;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.IBinder;
import android.os.ResultReceiver;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;

import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.content.browser.ImeAdapter.AdapterInputConnection;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper;
import org.chromium.content.browser.test.util.DOMUtils;
import org.chromium.content.browser.test.util.TestCallbackHelperContainer;
import org.chromium.content_shell_apk.ContentShellTestBase;

import java.util.concurrent.Callable;

public class ImeTest extends ContentShellTestBase {

    private static final int INVALID_SELECTION = -2;
    private static final int INVALID_COMPOSITION = -2;
    private static final String DATA_URL = UrlUtils.encodeHtmlDataUri(
            "<meta name=\"viewport\"" +
            "content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0\" />" +
            "<form action=\"about:blank\">" +
            "<input id=\"input_text\" type=\"text\" />" +
            "<input id=\"input_radio\" type=\"radio\" />" +
            "</form>");

    private TestAdapterInputConnection mConnection;
    private ImeAdapter mImeAdapter;
    private ContentView mContentView;
    private TestCallbackHelperContainer mCallbackContainer;
    private TestInputMethodManagerWrapper mInputMethodManagerWrapper;

    @Override
    public void setUp() throws Exception {
        super.setUp();

        launchContentShellWithUrl(DATA_URL);
        assertTrue("Page failed to load", waitForActiveShellToBeDoneLoading());

        mInputMethodManagerWrapper = new TestInputMethodManagerWrapper(getContentViewCore());
        getImeAdapter().setInputMethodManagerWrapper(mInputMethodManagerWrapper);
        assertEquals(0, mInputMethodManagerWrapper.mShowSoftInputCounter);
        getContentViewCore().setAdapterInputConnectionFactory(
                new TestAdapterInputConnectionFactory());

        mContentView = getActivity().getActiveContentView();
        mCallbackContainer = new TestCallbackHelperContainer(mContentView);
        // TODO(aurimas) remove this wait once crbug.com/179511 is fixed.
        assertWaitForPageScaleFactor(1);
        DOMUtils.clickNode(this, mContentView, mCallbackContainer, "input_text");
        assertWaitForKeyboardStatus(true);

        mConnection = (TestAdapterInputConnection) getAdapterInputConnection();
        mImeAdapter = getImeAdapter();

        assertWaitForSetEditableCallback(1, mConnection);
        assertEquals("", mConnection.mText);
        assertEquals(0, mConnection.mSelectionStart);
        assertEquals(0, mConnection.mSelectionEnd);
        assertEquals(-1, mConnection.mCompositionStart);
        assertEquals(-1, mConnection.mCompositionEnd);
        assertEquals(1, mInputMethodManagerWrapper.mShowSoftInputCounter);
    }

    @MediumTest
    @Feature({"TextInput", "Main"})
    public void testKeyboardDismissedAfterClickingGo() throws Throwable {
        mImeAdapter.checkCompositionQueueAndCallNative("hello", 1, false);
        assertWaitForSetEditableCallback(2, mConnection);
        assertEquals("hello", mConnection.mText);
        assertEquals(5, mConnection.mSelectionStart);
        assertEquals(5, mConnection.mSelectionEnd);
        assertEquals(0, mConnection.mCompositionStart);
        assertEquals(5, mConnection.mCompositionEnd);

        performGo(getAdapterInputConnection(), mCallbackContainer);

        assertWaitForSetEditableCallback(3, mConnection);
        assertEquals("", mConnection.mText);
        assertEquals(0, mConnection.mSelectionStart);
        assertEquals(0, mConnection.mSelectionEnd);
        assertEquals(-1, mConnection.mCompositionStart);
        assertEquals(-1, mConnection.mCompositionEnd);
        assertWaitForKeyboardStatus(false);
    }

    @SmallTest
    @Feature({"TextInput", "Main"})
    public void testGetTextUpdatesAfterEnteringText() throws Throwable {
        mImeAdapter.checkCompositionQueueAndCallNative("h", 1, false);
        assertWaitForSetEditableCallback(2, mConnection);
        assertEquals("h", mConnection.mText);
        assertEquals(1, mConnection.mSelectionStart);
        assertEquals(1, mConnection.mSelectionEnd);
        assertEquals(0, mConnection.mCompositionStart);
        assertEquals(1, mConnection.mCompositionEnd);
        assertEquals(1, mInputMethodManagerWrapper.mShowSoftInputCounter);

        mImeAdapter.checkCompositionQueueAndCallNative("he", 1, false);
        assertWaitForSetEditableCallback(3, mConnection);
        assertEquals("he", mConnection.mText);
        assertEquals(2, mConnection.mSelectionStart);
        assertEquals(2, mConnection.mSelectionEnd);
        assertEquals(0, mConnection.mCompositionStart);
        assertEquals(2, mConnection.mCompositionEnd);
        assertEquals(1, mInputMethodManagerWrapper.mShowSoftInputCounter);

        mImeAdapter.checkCompositionQueueAndCallNative("hel", 1, false);
        assertWaitForSetEditableCallback(4, mConnection);
        assertEquals("hel", mConnection.mText);
        assertEquals(3, mConnection.mSelectionStart);
        assertEquals(3, mConnection.mSelectionEnd);
        assertEquals(0, mConnection.mCompositionStart);
        assertEquals(3, mConnection.mCompositionEnd);
        assertEquals(1, mInputMethodManagerWrapper.mShowSoftInputCounter);

        mImeAdapter.checkCompositionQueueAndCallNative("hel", 1, true);
        assertWaitForSetEditableCallback(5, mConnection);
        assertEquals("hel", mConnection.mText);
        assertEquals(3, mConnection.mSelectionStart);
        assertEquals(3, mConnection.mSelectionEnd);
        assertEquals(-1, mConnection.mCompositionStart);
        assertEquals(-1, mConnection.mCompositionEnd);
        assertEquals(1, mInputMethodManagerWrapper.mShowSoftInputCounter);
    }

    @SmallTest
    @Feature({"TextInput"})
    public void testImeCopy() throws Exception {
        mImeAdapter.checkCompositionQueueAndCallNative("hello", 1, true);
        assertWaitForSetEditableCallback(2, mConnection);
        assertEquals("hello", mConnection.mText);
        assertEquals(5, mConnection.mSelectionStart);
        assertEquals(5, mConnection.mSelectionEnd);

        mImeAdapter.setEditableSelectionOffsets(2, 5);
        assertWaitForSetEditableCallback(3, mConnection);
        assertEquals("hello", mConnection.mText);
        assertEquals(2, mConnection.mSelectionStart);
        assertEquals(5, mConnection.mSelectionEnd);

        mImeAdapter.copy();
        assertClipboardContents(getActivity(), "llo");
    }

    @SmallTest
    @Feature({"TextInput"})
    public void testImeCut() throws Exception {
        mImeAdapter.checkCompositionQueueAndCallNative("snarful", 1, true);
        assertWaitForSetEditableCallback(2, mConnection);
        assertEquals("snarful", mConnection.mText);
        assertEquals(7, mConnection.mSelectionStart);
        assertEquals(7, mConnection.mSelectionEnd);

        mImeAdapter.setEditableSelectionOffsets(1, 5);
        assertWaitForSetEditableCallback(3, mConnection);
        assertEquals("snarful", mConnection.mText);
        assertEquals(1, mConnection.mSelectionStart);
        assertEquals(5, mConnection.mSelectionEnd);

        mImeAdapter.cut();
        assertWaitForSetEditableCallback(4, mConnection);
        assertEquals("sul", mConnection.mText);
        assertEquals(1, mConnection.mSelectionStart);
        assertEquals(1, mConnection.mSelectionEnd);

        assertClipboardContents(getActivity(), "narf");
    }

    @SmallTest
    @Feature({"TextInput"})
    public void testImePaste() throws Exception {
        ThreadUtils.runOnUiThreadBlocking(new Runnable() {
            @Override
            public void run() {
                ClipboardManager clipboardManager =
                        (ClipboardManager) getActivity().getSystemService(
                                Context.CLIPBOARD_SERVICE);
                clipboardManager.setPrimaryClip(ClipData.newPlainText("blarg", "blarg"));
            }
        });

        mImeAdapter.paste();
        assertWaitForSetEditableCallback(2, mConnection);
        assertEquals("blarg", mConnection.mText);
        assertEquals(5, mConnection.mSelectionStart);
        assertEquals(5, mConnection.mSelectionEnd);

        mImeAdapter.setEditableSelectionOffsets(3, 5);
        assertWaitForSetEditableCallback(3, mConnection);
        assertEquals("blarg", mConnection.mText);
        assertEquals(3, mConnection.mSelectionStart);
        assertEquals(5, mConnection.mSelectionEnd);

        mImeAdapter.paste();
        assertWaitForSetEditableCallback(5, mConnection);
        assertEquals("blablarg", mConnection.mText);
        assertEquals(8, mConnection.mSelectionStart);
        assertEquals(8, mConnection.mSelectionEnd);

        mImeAdapter.paste();
        assertWaitForSetEditableCallback(6, mConnection);
        assertEquals("blablargblarg", mConnection.mText);
        assertEquals(13, mConnection.mSelectionStart);
        assertEquals(13, mConnection.mSelectionEnd);
    }

    @SmallTest
    @Feature({"TextInput"})
    public void testImeSelectAndUnSelectAll() throws Exception {
        mImeAdapter.checkCompositionQueueAndCallNative("hello", 1, true);
        assertWaitForSetEditableCallback(2, mConnection);
        assertEquals("hello", mConnection.mText);
        assertEquals(5, mConnection.mSelectionStart);
        assertEquals(5, mConnection.mSelectionEnd);

        mImeAdapter.selectAll();
        assertWaitForSetEditableCallback(3, mConnection);
        assertEquals("hello", mConnection.mText);
        assertEquals(0, mConnection.mSelectionStart);
        assertEquals(5, mConnection.mSelectionEnd);

        mImeAdapter.unselect();
        assertWaitForSetEditableCallback(4, mConnection);
        assertEquals("", mConnection.mText);
        assertEquals(0, mConnection.mSelectionStart);
        assertEquals(0, mConnection.mSelectionEnd);

        assertWaitForKeyboardStatus(false);
    }

    @SmallTest
    @Feature({"TextInput", "Main"})
    public void testUpdatesGetIgnoredDuringBatchEdits() throws Throwable {
        mConnection.beginBatchEdit();
        assertWaitForSetIgnoreUpdates(true, mConnection);

        mImeAdapter.checkCompositionQueueAndCallNative("h", 1, false);
        assertWaitForSetEditableCallback(2, mConnection);
        assertEquals("h", mConnection.mText);
        assertEquals(1, mConnection.mSelectionStart);
        assertEquals(1, mConnection.mSelectionEnd);
        assertEquals(0, mConnection.mCompositionStart);
        assertEquals(1, mConnection.mCompositionEnd);
        assertTrue(mConnection.isIgnoringTextInputStateUpdates());

        mImeAdapter.checkCompositionQueueAndCallNative("he", 1, false);
        assertWaitForSetEditableCallback(3, mConnection);
        assertEquals("he", mConnection.mText);
        assertEquals(2, mConnection.mSelectionStart);
        assertEquals(2, mConnection.mSelectionEnd);
        assertEquals(0, mConnection.mCompositionStart);
        assertEquals(2, mConnection.mCompositionEnd);
        assertTrue(mConnection.isIgnoringTextInputStateUpdates());

        mImeAdapter.checkCompositionQueueAndCallNative("hel", 1, false);
        assertWaitForSetEditableCallback(4, mConnection);
        assertEquals("hel", mConnection.mText);
        assertEquals(3, mConnection.mSelectionStart);
        assertEquals(3, mConnection.mSelectionEnd);
        assertEquals(0, mConnection.mCompositionStart);
        assertEquals(3, mConnection.mCompositionEnd);

        assertEquals(0, mConnection.mUpdateSelectionCounter);
        assertTrue(mConnection.isIgnoringTextInputStateUpdates());
        mConnection.endBatchEdit();
        assertWaitForSetIgnoreUpdates(false, mConnection);
    }

    @SmallTest
    @Feature({"TextInput", "Main"})
    public void testShowImeIfNeeded() throws Throwable {
        DOMUtils.focusNode(this, mContentView, mCallbackContainer, "input_radio");
        assertWaitForKeyboardStatus(false);

        performShowImeIfNeeded();
        assertWaitForKeyboardStatus(false);

        DOMUtils.focusNode(this, mContentView, mCallbackContainer, "input_text");
        assertWaitForKeyboardStatus(false);

        performShowImeIfNeeded();
        assertWaitForKeyboardStatus(true);
    }

    private void performShowImeIfNeeded() {
        ThreadUtils.runOnUiThreadBlocking(new Runnable() {
            @Override
            public void run() {
                mContentView.getContentViewCore().showImeIfNeeded();
            }
        });
    }

    private void performGo(final AdapterInputConnection inputConnection,
            TestCallbackHelperContainer testCallbackHelperContainer) throws Throwable {
        handleBlockingCallbackAction(
                testCallbackHelperContainer.getOnPageFinishedHelper(),
                new Runnable() {
                    @Override
                    public void run() {
                        inputConnection.performEditorAction(EditorInfo.IME_ACTION_GO);
                    }
                });
    }

    private void assertWaitForPageScaleFactor(final float scale) throws InterruptedException {
        assertTrue(CriteriaHelper.pollForCriteria(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return getContentViewCore().getScale() == scale;
            }
        }));
    }

    private void assertWaitForKeyboardStatus(final boolean show) throws InterruptedException {
        assertTrue(CriteriaHelper.pollForCriteria(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return show == getImeAdapter().mIsShowWithoutHideOutstanding &&
                        (!show || getAdapterInputConnection() != null);
            }
        }));
    }

    private void assertWaitForSetEditableCallback(final int callbackNumber,
            final TestAdapterInputConnection connection) throws InterruptedException {
        assertTrue(CriteriaHelper.pollForCriteria(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return callbackNumber == connection.mSetEditableTextCallCounter;
            }
        }));
    }

    private void assertClipboardContents(final Activity activity, final String expectedContents)
            throws InterruptedException {
        assertTrue(CriteriaHelper.pollForCriteria(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        ClipboardManager clipboardManager =
                                (ClipboardManager) activity.getSystemService(
                                        Context.CLIPBOARD_SERVICE);
                        ClipData clip = clipboardManager.getPrimaryClip();
                        return clip != null && clip.getItemCount() == 1
                                && TextUtils.equals(clip.getItemAt(0).getText(), expectedContents);
                    }
                });
            }
        }));
    }

    private void assertWaitForSetIgnoreUpdates(final boolean ignore,
            final TestAdapterInputConnection connection) throws Throwable {
        assertTrue(CriteriaHelper.pollForCriteria(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return ignore == connection.isIgnoringTextInputStateUpdates();
            }
        }));
    }

    private ImeAdapter getImeAdapter() {
        return getContentViewCore().getImeAdapterForTest();
    }

    private ImeAdapter.AdapterInputConnection getAdapterInputConnection() {
        return getContentViewCore().getInputConnectionForTest();
    }

    private static class TestAdapterInputConnectionFactory extends
            ImeAdapter.AdapterInputConnectionFactory {
        @Override
        public AdapterInputConnection get(View view, ImeAdapter imeAdapter,
                EditorInfo outAttrs) {
            return new TestAdapterInputConnection(view, imeAdapter, outAttrs);
        }
    }

    private static class TestAdapterInputConnection extends ImeAdapter.AdapterInputConnection {
        private int mSetEditableTextCallCounter = 0;
        private int mUpdateSelectionCounter = 0;
        private String mText;
        private int mSelectionStart = INVALID_SELECTION;
        private int mSelectionEnd = INVALID_SELECTION;
        private int mCompositionStart = INVALID_COMPOSITION;
        private int mCompositionEnd = INVALID_COMPOSITION;

        public TestAdapterInputConnection(View view, ImeAdapter imeAdapter, EditorInfo outAttrs) {
            super(view, imeAdapter, outAttrs);
        }

        @Override
        public void setEditableText(String text, int selectionStart, int selectionEnd,
                int compositionStart, int compositionEnd) {
            mText = text;
            mSelectionStart = selectionStart;
            mSelectionEnd = selectionEnd;
            mCompositionStart = compositionStart;
            mCompositionEnd = compositionEnd;
            mSetEditableTextCallCounter++;
            super.setEditableText(
                    text, selectionStart, selectionEnd, compositionStart, compositionEnd);
        }

        @Override
        protected void updateSelection(
                int selectionStart, int selectionEnd,
                int compositionStart, int compositionEnd) {
            mUpdateSelectionCounter++;
        }
    }

    private static class TestInputMethodManagerWrapper extends InputMethodManagerWrapper {
        private ContentViewCore mContentViewCore;
        private InputConnection mInputConnection;
        private int mShowSoftInputCounter = 0;

        public TestInputMethodManagerWrapper(ContentViewCore contentViewCore) {
            super(null);
            mContentViewCore = contentViewCore;
        }

        @Override
        public void restartInput(View view) {
            mInputConnection = mContentViewCore.onCreateInputConnection(new EditorInfo());
        }

        @Override
        public void showSoftInput(View view, int flags, ResultReceiver resultReceiver) {
            mShowSoftInputCounter++;
            if (mInputConnection != null) return;
            mInputConnection = mContentViewCore.onCreateInputConnection(new EditorInfo());
        }

        @Override
        public boolean isActive(View view) {
            if (mInputConnection == null) return false;
            return true;
        }

        @Override
        public boolean hideSoftInputFromWindow(IBinder windowToken, int flags,
                ResultReceiver resultReceiver) {
            boolean retVal = mInputConnection == null;
            mInputConnection = null;
            return retVal;
        }

        @Override
        public void updateSelection(View view, int selStart, int selEnd,
                int candidatesStart, int candidatesEnd) {
        }
    }
}